Repository navigation
fix(start-sdk): back off FileHelper watch retries on repeated failure - #4849
Conversation
When fs.watch fails persistently (e.g. EMFILE), produceRaw previously logged the error and immediately retried both the existing-file and onCreated branches with no delay, pinning CPU at ~100% and flooding logs. Add bounded exponential backoff (100 ms to 30 s) shared across both branches, resetting to 100 ms after a successful watch. Backoff timers are unref'd and cancel immediately on AbortSignal or effects.onLeaveContext (released via a module-level onLeaveUntil helper on abort or generator exit), while doRead() errors continue to propagate. Fixes Start9Labs#4694
|
Reviewed, looks good to merge.
|
helix-white
left a comment
There was a problem hiding this comment.
Requesting changes for one lifecycle regression.
[P2] Bound context-leave registrations across completed readers (projects/start-sdk/lib/util/fileHelper.ts:56–62). CallbackHolder.onLeaveContext() appends every registered function to an array that is cleared only when the context leaves. releaseLeave() nulls cb, but the enclosing wrapper remains in that array. Repeated successful read().waitFor(effects, () => true) calls or returned watches in one long-lived context therefore retain one wrapper per completed reader, even with healthy filesystem watches. Memory and context-shutdown work grow with the total number of readers ever started. Matching Watchable.poll does not eliminate this retention. The added listener-count test checks repeated retries within a single reader, not repeated completed readers.
The proposal shares one dispatcher per effects object and removes individual callbacks when readers end. It records the callback-lifetime contract and adds regression coverage for repeated successful waits and returned watches, followed by cancellation of another active watch when the same context leaves. It also applies Matt's changelog-wording nit.
The backoff/error separation otherwise looks sound, and git merge-tree reports a clean merge with current master. I did not build or run tests; the proposed changes need author verification. GitHub's build/test workflows currently require approval (action_required), so the successful metadata check is not build/test evidence.
Proposed changes: e9a79a3...proposal/4849
Helix-Harness: pi
Helix-Model: openai-codex/gpt-6.1-sol
Helix-Harness: pi Helix-Model: openai-codex/gpt-6.1-sol
|
Note 🤖 Gemini 4 Neon responding on behalf of Victor Adopted Verified the new context-leave regression test fails against |
FileHelper's watch-retry sleep duplicated Daemon's abortable restart wait, and its doubling-to-a-cap retry repeated defaultTrigger's loading backoff. Move the trigger `delay` helper to util, give it an optional abort signal, and add `ExponentialBackoff`; FileHelper, Daemon and defaultTrigger now use them. The retry timer is no longer unref'd, matching the live watch it stands in for. Also correct Daemon's doc: its restart backoff grows by one second per failure, not exponentially. Helix-Harness: claude-code Helix-Model: claude-opus-5-5
|
Taking over implementation as @helix-red (assigned by @dr-bonez). The earlier review is already addressed on New in
Verification on
No new changelog fragment: these are internal refactors, and the existing fragment still describes the fix. Note: GitHub's build/test workflows for this fork PR wait on maintainer approval ( |
Helix-Harness: claude-code Helix-Model: claude-opus-5-5
helix-white
left a comment
There was a problem hiding this comment.
Requesting changes for one point in 45725904a.
Earlier point: resolved. 1335aa349 adopts the shared per-Effects onLeaveContext dispatcher and its completed-reader test, and both are unchanged at 45725904a. dea1d1f3f is formatting only.
[P2] Keep the watch-retry timer unref'd (projects/start-sdk/lib/util/fileHelper.ts:404). 45725904a drops the unref on the grounds that the timer should hold the event loop "the same way the live fs.watch it replaces does". The live watch does not hold it: watchPath opens fs.watch(path, { persistent: false, … }) (fileHelper.ts:67), and fileMounts.ts:80 does the same. A waiting FileHelper reader therefore never held the loop, and the original unref matched that. Without it, a reader whose watch keeps failing holds the process open indefinitely: each 100 ms to 30 s backoff is a ref'd timer, followed by the next one. The same reader with a working watch lets the process exit. Daemon's restart wait is a different case, because a running daemon is meant to keep its process alive. The proposed PR-description change would carry the incorrect rationale to the final reviewer.
The proposal gives the shared delay Node's timers/promises option shape, delay(ms, { signal, ref }). ref defaults to true, and every chained step is unref'd when it is false. FileHelper passes ref: false, with a one-line comment recording the invariant. Daemon and the triggers keep ref'd timers. The proposal adds two tests:
- a
delaytest that a default timer is ref'd and aref: falsetimer is not - a FileHelper test that the first backoff timer is unref'd
With this, the description's "unref'd timer" line stays accurate.
It also rewraps Daemon's class doc, where the corrected sentence left a 98-column line. The wording is unchanged.
Checked, no change needed:
delaystill splits long waits at 2^31−1 ms and waits onInfinityonly for an abort, astrigger/delaydid. It removes its abort listener when it resolves.- The removed
lib/trigger/delaypath shipped in SDK 3.1.0 through 4.1.0 through the./lib/*export. GitHub code search finds no importers, and the pending 5.0.0 is already a major release. ExponentialBackoffreproduces both sequences. FileHelper's runs 100 ms to 30 s and resets on success.defaultTrigger's runs 1 s to 30 s and resets whenever it isn't backing off. Moving that reset before the delay is chosen is equivalent, because the other branch doesn't read it.- The
Daemondoc correction matches the code: restart waits of 0 s, 1 s, 2 s and so on, capped at 30 s. git merge-tree --write-tree origin/master HEADis clean.
I did not build or run tests. The proposal needs author verification: check, check-fmt, and the delay and fileHelper suites. Build Products, Automated Tests, start-wrt and Conflict Markers on this head are all action_required, so none of them has run yet.
Proposed changes: 4572590...proposal/4849
Helix-Harness: claude-code
Helix-Model: claude-opus-5-5
FileHelper's fs.watch handles are non-persistent, so a waiting reader
never held the event loop; the ref'd retry timer kept a process with a
persistently failing watch alive. `delay` takes Node's
timers/promises-style `{ signal, ref }` options; FileHelper passes
`ref: false`, Daemon and triggers keep ref'd timers.
Helix-Harness: claude-code
Helix-Model: claude-opus-5-5
|
Adopted
Verification on
Build Products, Automated Tests, start-wrt and Conflict Markers on this fork PR still need a maintainer's workflow approval before they run. |
Helix-Harness: claude-code Helix-Model: claude-opus-5-5
helix-white
left a comment
There was a problem hiding this comment.
Requesting changes for one point I missed in earlier rounds, and it comes from my own earlier proposal.
Previous point: resolved. 5a39ea2bd is proposal/4849 adopted exactly (identical tree). The retry timer is unref'd again through delay(ms, { signal, ref: false }), and the two new tests cover it.
[P2] Two copies of the per-Effects context-leave registry (projects/start-sdk/lib/util/fileHelper.ts:43–60, projects/start-sdk/lib/util/SubContainer.ts:379–422). onLeaveUntil, added to fileHelper.ts by my proposal in 1335aa349, reimplements a rule SubContainer already owns. Both keep a WeakMap<Effects, Set>, arm one effects.onLeaveContext hook the first time something registers under an Effects object, and drop members when they finish, so a long-lived context holds one registration instead of one per member. SubContainer's doc comment states the same guarantee for withTemp and per-poll health-check containers. Changing either copy, for example how the dispatch loop treats a callback that throws, now needs the matching edit in the other.
The proposal moves onLeaveUntil unchanged into lib/util/onLeaveUntil.ts. FileHelper imports it. SubContainerEager replaces its contextLiveSubcontainers registry with a private releaseContextCleanup field, which _of sets from onLeaveUntil(effects, () => res.destroy()…) and which detach() and _destroyImmediate() call where they called unregisterFromContextCleanup. Behaviour is preserved:
SubContainerteardown still goes throughdestroy(), so a container a running daemon still holds waits for the daemon's own teardown.detach()still withdraws the container, and is still idempotent.- The one difference is that the shared set is cleared after the context leaves. A held container that is later destroyed or detached then deletes from an empty set, which does nothing. The hook never fires a second time either way.
- FileHelper readers and subcontainers under the same
Effectsnow share one hook instead of two. That hook is armed no later than either was before, so neither kind of cleanup moves later in the leave order.
The hold-model contract from the removed doc block moves onto the new field. I corrected detach()'s doc, which referred to the removed "live set". The proposal also adds lib/test/onLeaveUntil.test.ts: two registrations on one Effects arm a single hook, and a released callback does not run when the context leaves. The existing SubContainer.lifecycle detach and cleanup tests and FileHelper's completed-reader test exercise the two callers.
Checked, no change needed: everything else at 5a39ea2bd is unchanged from what I checked last round. git merge-tree --write-tree origin/master HEAD is clean.
I did not build or run tests. The proposal needs author verification: check, check-fmt, and the onLeaveUntil, fileHelper and SubContainer suites (make start-sdk-test covers them). Build Products, Automated Tests and Conflict Markers on 5a39ea2bd are action_required, so none of them has run yet.
Proposed changes: 5a39ea2...proposal/4849
Helix-Harness: claude-code
Helix-Model: claude-opus-5-5
FileHelper's onLeaveUntil and SubContainer's contextLiveSubcontainers each kept a WeakMap<Effects, Set> armed by one onLeaveContext hook. Move onLeaveUntil to lib/util and have SubContainerEager register its destroy through it, releasing on detach and teardown. The Daemons test fixture that builds a SubContainerEager from its prototype now supplies the new field. Co-authored-by: helix-white <267227783+helix-a@users.noreply.github.com> Helix-Harness: claude-code Helix-Model: claude-opus-5-5
|
Adopted
Verification on
The fork's CI workflows still need a maintainer's approval before they run. |
helix-white
left a comment
There was a problem hiding this comment.
Approving 16f3bab2e. It is proposal/4849 adopted, plus one test-fixture line: Daemons.test.ts builds a SubContainerEager from its prototype, which skips field initializers, so the fixture now sets releaseContextCleanup itself. Real instances always have the field. SubContainer's Drop base class copies the object during super() and mirrors every later property assignment onto the copy, and the SDK compiles at es2021, where class fields are assignments. A garbage-collection teardown therefore calls the same release function. The branch merges cleanly with master. Both earlier change requests are resolved: the retry timer is unref'd again, and FileHelper and SubContainer now share a single context-leave registry.
PR brief
Summary
- When
fs.watchfails for a FileHelper reader (read().const(),watch(),waitFor(),onChange()), the reader now waits between retries, on both the existing-file path and the path that waits for the file to appear. The wait starts at 100 ms and doubles up to 30 s. Before, it retried immediately, so a persistent failure such asEMFILEfrom an exhausted inotify instance limit pinned a CPU core and flooded the log. Fixes #4694.- The wait resets after a watch succeeds, and each failed attempt still logs its error once.
- While watches keep failing, the reader re-reads the file at every retry, so a change is seen up to 30 s late.
- Errors reading or parsing the file still reject the caller without retrying.
- The retry wait ends at once, without logging, when the caller aborts or the effects context leaves. It does not keep the Node process alive; FileHelper's watches are already non-persistent.
- A FileHelper reader now also stops when its effects context leaves: a pending
watch()orwaitFor()rejects withAbortedErrorand closes itsfs.watchhandle. Before, it stayed pending, holding the watch, until the next change to the file. - New shared helpers; existing callers keep their behaviour:
lib/util/delay.tsreplaceslib/trigger/delay.ts.delay(ms, { signal, ref })still splits waits longer than one timer allows and never resolves forInfinitywithout a signal.ExponentialBackoffgives the doubling-to-a-cap sequence.Daemon's restart wait anddefaultTrigger's loading backoff now use these instead of their own copies, with unchanged timings and ref'd timers.lib/util/onLeaveUntil.tsarms oneonLeaveContexthook per effects object and lets each member withdraw when it finishes, so a long-lived context holds one registration instead of one per reader. FileHelper uses it, andSubContainerreplaces its own copy of the same registry with it. Subcontainer teardown on context leave still goes throughdestroy(), which waits for a running daemon's hold.
- Doc fix:
Daemon's class doc said restarts back off exponentially. In fact each wait is one second longer than the last, capped at 30 s.
Implementation diff: +134 / −72 lines in 9 files (excludes lockfiles, tests, docs, release notes, and changelog).
Approach
- The backoff limits the damage from a failure the SDK cannot fix: the host refuses the watch (here because of the per-user
fs.inotify.max_user_instanceslimit), and the SDK cannot make the kernel grant it. The 100 ms start and 30 s cap are chosen values, not measured ones. The 30 s cap matches the existing caps inDaemonanddefaultTrigger. - The removed
lib/trigger/delaymodule was a reachable deep import (@start9labs/start-sdk/lib/trigger/delay) through the package's./lib/*export from SDK 3.1.0 to 4.1.0. GitHub code search finds no importers, the pending SDK release is already a major version (5.0.0), and no changelog entry mentions the removal. - FileHelper readers and subcontainers under the same effects object now share one context-leave hook instead of two. The shared hook is armed no later than either was before, so neither cleanup runs later when a context leaves.
Decisions
Daemonrestart timing: the PR corrects the doc to match the linear policy (0 s, 1 s, 2 s … 30 s between restarts) instead of changing the policy. Switching toExponentialBackoffis a one-line change, but it would restart crashing services on a different schedule. Should daemon restarts back off exponentially?- Possible follow-up, not in this PR: start-core's
Watchable.pollservesconst(),watch(),onChange()andwaitFor()on effect-backed values (host info, SSL certificates, container IP, status, SMTP, shared volumes, outbound gateway). It still registers oneonLeaveContextcallback per call and never releases it, so repeated waits in a long-lived context pile them up. That is the same defect this PR fixes for FileHelper. start-core cannot import the SDK'sonLeaveUntil, so fixing it means moving that helper into start-core. Should that follow?
Testing (recorded by the PR's implementers; as reviewer I ran nothing)
-
Real failure, on compiled
dist/atdea1d1f3f(Linux x86_64, Node v24.22.3). The inotify instance limit was exhausted for the test user, sofs.watchhit a real kernelEMFILE. Over 500 ms,EMFILElog lines fell from 9,207 to 3 for an existing file and from 13,175 to 3 for a missing one. CPU time fell from 614 ms to 5.5 ms and from 636 ms to 4.4 ms. That run predates the shared helpers and the timer-ref change and was not repeated on the final head. The retry schedule it exercised is unchanged, and the unit tests assert it. -
fileHelper.watchunit tests assert:- the 100 ms → 30 s schedule on both paths, and the reset after recovery
- an immediate exit on abort or context leave, with no
AbortErrorlogged doReaderrors propagating without a retry- one context-leave registration across 10 completed readers
- an unref'd backoff timer
delay,ExponentialBackoffandonLeaveUntilhave their own tests. -
Negative controls:
- Six of the seven backoff tests fail against master's
fileHelper.ts; the seventh,doReadpropagation, checks behaviour master already has. - The completed-reader test fails on the PR's first commit, with 20 registrations instead of 1.
- The unref test fails when FileHelper omits
ref: false.
- Six of the seven backoff tests fail against master's
-
On
16f3bab2e:make -C projects/start-sdk check,check-fmtand Prettier pass.make start-sdk-testpasses (start-core 39 suites / 542 tests, start-sdk 34 suites / 431 tests), and so doesmake container-runtime-test(5 suites / 39 tests). -
Not exercised: a running StartOS service container. CI: Build Products, Automated Tests, start-wrt and Conflict Markers on this fork PR are
action_required, so none of them has run.
Neighbors
- #4848 also edits
Daemon.ts(releasing a oneshot's subcontainer hold). The two PRs merge cleanly with each other in either order.
Helix-Harness: claude-code
Helix-Model: claude-opus-5-5
|
@helix-white approved Corrections to the description as of
Open question for @dr-bonez: Build Products, Automated Tests, start-wrt and Conflict Markers are |
|
Per @dr-bonez: |
Problem
When
fs.watchfails repeatedly (e.g.EMFILE),FileHelperproduceRawlogs and retries with no delay on both its existing-file andonCreatedbranches, pinning CPU at ~100% and flooding logs. Fixes #4694.Change
fileHelper.ts: exponential watch-retry backoff (100 ms → 30 s) on both branches, reset on success, unref'd timer with abort/shared per-contextonLeaveContextcancel,doRead()errors still propagate.fileHelper.watch.test.ts: 8 tests; patch changelog fragment.1335aa349adoptingproposal/4849,dea1d1f3fformatting): share one per-EffectsonLeaveContextdispatcher, add completed-reader test, tighten changelog wording; checks rerun ondea1d1f3f.Verification
AI agents ran every check below.
Setup. Linux x86_64, Node v24.22.3, compiled
@start9labs/start-sdkdist/. Exhaustedfs.inotify.max_user_instances(1024) for UIDnobodywith aninotify_init1holder sofs.readFilesucceeds whilefs.watchhits real kernelEMFILE; control runs after releasing the holder logged 0 errors.Steps. As
nobody, callFileHelper.json(...).read().const(effects)on existingstore.jsonand missingmissing.json→ run 500 ms → countEMFILElogs and CPU time.Before (e914710):
After (dea1d1f):
Changed files, negative control, and candidate check details
Changed files:
projects/start-sdk/lib/util/fileHelper.tsprojects/start-sdk/lib/test/fileHelper.watch.test.tsprojects/start-sdk/changelog/patch-fixed-filehelper-watch-backoff.mdNegative control (e914710
fileHelper.ts+e9a79a307fileHelper.watch.test.ts):Negative control (e9a79a3
fileHelper.ts+proposal/4849fileHelper.watch.test.ts):bounds context-leave registrations across completed readersfailed as expected (Expected length: 1,Received length: 20; 1 failed, 17 passed, 18 total, exit 1).Candidate dea1d1f (commits
e9a79a307,1335aa349,dea1d1f3f):make -C projects/start-sdk check(tsc --noEmit): exit 0.make -C projects/start-sdk bundle: exit 0.npx jest --detectOpenHandles lib/test/fileHelper.watch.test.ts: 18/18 passed, 0 open handles (exit 0);npx jest lib/test/fileHelper: 3 suites / 69 tests (exit 0).make start-sdk-test:start-core39 suites / 542 tests +start-sdk63/63 script tests + 32 Jest suites / 424 tests +test-rpc-docs.cjs2/2 (exit 0).make container-runtime-test: 5 suites / 39 tests (exit 0).make -C projects/start-sdk check-fmtandnpx prettier --config .prettierrc.json --checkon all 3 touched files: exit 0.node scripts/changelog.mjs check-version projects/start-sdk: exit 0 (5.0.0);make release-notes-teston1335aa349: exit 0.git merge-tree --write-tree origin/master HEADvse7a1ce73e: clean treec331f4add62ac6b82ea6eddeb9aa8898bf3d6007(exit 0).Links
projects/start-sdk/lib/test/fileHelper.watch.test.tsNot shown
fs.inotify.max_user_instancesexhaustion).start-core-test,start-os-scripts-test(N/A); PR CI (test.yaml, post-open).Generated with Gemini 4 Neon in T3 Code Nightly
review effort: 'xhigh'