Repository navigation
refactor(host-kit): settle deadline races via settleWithin with R87 race ratchet - #4766
Conversation
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Apex Sentinel: 2 new findings on 9bdc4eb. The verdict and the full list are in the summary comment.
|
The idle-expiry sweep now holds the daemon's event loop for its whole deadline, which the old code avoided on purpose. The removed Not blocking, take or leave: in provider-lease-expiry.ts#L411 the Main already defines R87 as The PR has merge conflicts with main in Of the open inline threads, the unref'd timer one still applies and is the same issue as above. The CI is green: 7 checks, none failing at 9bdc4eb. Before merge, restore the unref'd deadline for idle-expiry, then rebase on main, resolve the |
9bdc4eb to
36bdfc5
Compare
Size Report
Startup median (7 runs, lower is better):
|
Review follow-ups applied — head
|
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Apex Sentinel: 2 new findings on 36bdfc5. The verdict and the full list are in the summary comment.
| drain: async (timeoutMs) => { | ||
| // Shutdown gets one final, bounded attempt at every pending release. A | ||
| // provider call that hangs must not keep the daemon alive indefinitely. | ||
| const deadline = new AbortController(); | ||
| await Promise.race([ | ||
| retryPending().finally(() => deadline.abort()), | ||
| sleep(Math.max(0, timeoutMs), deadline.signal), | ||
| ]); | ||
| await settleWithin(() => retryPending(), Math.max(0, timeoutMs)); |
There was a problem hiding this comment.
No longer raised on f189c1b: the code it pointed at changed.
🆕 🟡 Minor · provider-lease drain no longer swallows a hanging release: settleWithin rejects past the deadline
createExpiredProviderLeaseReleaser(...).drain(timeoutMs) throws instead of returning its report whenever a pending release rejects after the deadline elapses. settleWithin rejects a work rejection that arrives after the deadline was reported.
Suggested change
Await settleWithin(() => retryPending(), Math.max(0, timeoutMs)) inside a try/catch (or on a catch-returning work thunk) so a late rejection from retryPending cannot propagate out of drain after the deadline was already reported.
Details
persona: maintainability
Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.
Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if it is wrong — I will re-check the cited code.
There was a problem hiding this comment.
Fixed at f189c1b: drain now awaits settleWithin(...).catch(() => undefined), so a pending release that fails inside the budget is reported as pending instead of throwing past the bounded window. Regression test: 'a shutdown drain reports its result when a pending release fails inside the budget' (provider-lease-expiry.test.ts, 20/20 green).
| Promise.resolve() | ||
| .then(work) | ||
| .then( | ||
| (value) => { | ||
| if (settled) return; | ||
| settled = true; | ||
| clearTimeout(timer); | ||
| resolve({ kind: 'settled', value }); | ||
| }, | ||
| (error: unknown) => { | ||
| if (settled) return; | ||
| settled = true; | ||
| clearTimeout(timer); | ||
| reject(error); | ||
| }, | ||
| ); |
There was a problem hiding this comment.
No longer raised on f189c1b.
🆕 🔵 Nit · settleWithin's spent-budget path rests on timer-vs-microtask order, not the work
With a 0 budget the outcome depends on setTimeout(0) firing before the work's first microtask continuation rather than on the work itself: settleWithin(() => Promise.reject(e), 0) stays pending until that timer runs in a manually-advanced-timer harness, while under real timers it resolves 'deadline' and the rejection is dropped. Every migrated call site catches or ignores the rejection, so no production value or state goes wrong, but the ordering assumption inside a new deadline primitive should be made explicit.
Suggested change
Either state in the settleWithin doc comment that a rejection arriving after the deadline is swallowed, or add an onLateSettle/diagnostic hook so a shutdown caller can still log a late failure.
Details
persona: maintainability, javascript
Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.
Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if it is wrong — I will re-check the cited code.
There was a problem hiding this comment.
Addressed at f189c1b: the settleWithin doc comment now states the ordering explicitly — a rejection arriving after the deadline is swallowed (the outcome is already deadline, and the rejection stays observed here), and a caller that must see the work's own failure at a spent budget has to await the work, not the wrapper. No hook added: every current caller either catches or treats the deadline as its own verdict, so a diagnostic channel would be vocabulary no one reads.
|
The PR is ready at 36bdfc5. The findings from the earlier review (#4766 (comment)) are fixed: the keepAlive:false path now unrefs its timer, and the race ratchet counts only real Not blocking: the header comment in scripts/layering/check.ts and the success line near line 471 still say " Of the earlier inline threads, the two on #4766 (comment) and #4766 (comment) do not apply, so please resolve them. The first describes a rejection after the deadline, which is dropped on purpose. The second describes a 0 budget, where an immediately rejecting work still propagates. The two threads #4766 (comment) and #4766 (comment) are fixed at this commit, so please resolve them too. The Runner Build (tvOS + visionOS + watchOS) failure is the parallel |
This comment has been minimized.
This comment has been minimized.
|
This now conflicts with |
Adds settleWithin(work, timeoutMs) beside Deadline/sleep/pollUntilSettled and
exports it through the existing ./retry subpath. The typed outcome is
{ kind: 'settled', value } | { kind: 'deadline' }; the deadline timer is
cleared on every settle path, and the doc comment states it does not cancel
the work (a late rejection stays observed, a rejection that beats the
deadline propagates).
Removes the daemon-local settleWithinBudget and migrates every hand-rolled deadline race in the daemon to settleWithin: closeDaemonServers and session teardown in server-shutdown, the request drain and platform-owner/plugin closes in daemon-runtime, the lease-release drain in provider-lease-expiry, and the idle-expiry settle budget in daemon-session-idle-expiry (dropping its bespoke budgetElapsedAfter timer). Races that are not deadlines (the abort race in artifact-tracking, TTL/retry timers) are untouched.
New layering rule promise-race-ratchet (R87): Promise.race( occurrences per package over production sources must not grow past the merge-base with origin/main, measured by the shared merge-base ratchet machinery. Deadline races belong to settleWithin in @agent-device/host-kit/retry, which clears its own timer on every settle path; non-deadline races are out of scope for the count. Registered in LAYERING_RULES with a unit test.
A deadline awaited by a background sweep must not hold the event loop:
the removed budgetElapsedAfter() unref'd its timer on purpose. settleWithin
now takes { keepAlive: false } to unref the deadline timer, and
expireIdleSession passes it (a hung idle expiry could otherwise keep a
daemon with closed servers alive for up to the 46s teardown budget). The
default stays ref'd for shutdown callers, where an unref'd timer could let
the process exit mid-report. Host-kit test covers the unref'd case and the
ref'd default.
Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
retryPending() takes no signal, so the AbortController in the lease drain only cancelled the old sleep; pass retryPending directly. Awaiting emitDaemonDiagnostic inside the owner-shutdown catch drops the ownerFailed/ownerFailure locals. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
…odes Main defines R87 as unique-exported-type-names (#4757), so the promise-race ratchet takes R88 in the rule, its test, the check.ts comments and the success line. The count now parses each source with the shared layering parser and counts Promise.race CallExpression nodes, so comments, strings and spacing cannot move the count; the header's LOC figures are corrected. Conflict with main in check.ts resolved keeping both rules. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
… budget settleWithin rejects a work rejection that arrives while the deadline has not yet been reported, so a pending release failing inside the drain window threw out of drain instead of returning its report. The drain bounds shutdown; a failed release is a pending release, so the report stands. settleWithin's doc now states the spent-budget ordering explicitly: a rejection after the deadline is swallowed, and a caller that must see the work's own failure awaits the work.
f189c1b to
844e719
Compare
|
Rebased onto |
Apex Sentinel · ✅ Approve · review of
|
| Command | What it does |
|---|---|
@apex-sentinel-staging note <context> |
Adds context; Sentinel re-checks the cited code |
@apex-sentinel-staging pivot <why> |
Says the finding is wrong; Sentinel re-checks the cited code |
@apex-sentinel-staging like |
Marks the finding as useful |
@apex-sentinel-staging dislike <why> |
Marks it as not useful, so it is not raised again |
On this conversation, comment @apex-sentinel-staging review to run a full review once again.
* origin/main: (70 commits) refactor(apple-runner): one RUNNER_ERROR_CODES row per runner error code with parity/docs gates (callstack#4774) fix(android): require acknowledgements for test IME typing (callstack#4722) feat(scroll): add scroll refresh for pull-to-refresh (callstack#4770) refactor(host-kit): add request Scope and use it for the wait capture deadline (callstack#4794) fix(android): let permission all change nothing on an app that declares no permissions (callstack#4796) fix(cli): replace the CLI session and generated remote config instead of rewriting them in place (callstack#4797) fix(host-kit): accept a group-writable script directory the user owns (callstack#4799) fix(cli): escape control characters at the CLI's stdout and stderr writes (callstack#4778) fix(audit): do not report rows under a persistent bar that scrolling reveals (callstack#4775) fix(daemon): refuse an unsafe state directory before first use (callstack#4783) refactor: settle remaining single-deadline races through settleWithin (callstack#4788) refactor(host-kit): settle deadline races via settleWithin with R87 race ratchet (callstack#4766) fix(android): authenticate and bound persistent snapshot helper sessions (callstack#4729) fix(daemon): bound upload ingress and finalization (callstack#4721) chore(gates): ratchet wire-published reason literals by value (R89) (callstack#4779) feat(audit): evaluate role-less clickable views on Android (callstack#4780) fix(mutation): keep umask-setting tests out of Stryker's thread pool (callstack#4785) feat(audit): report controls that share one accessible name (callstack#4771) fix(contracts): pair open runtime hints with their apply operation (callstack#4754) refactor(daemon): report startup progress over the launch channel instead of marker files (callstack#4777) ...
Summary
Moves the daemon's deadline-settle helper into host-kit; all daemon deadline races now use it. 15 files touched; 334 insertions / 115 deletions.
settleWithin(work, timeoutMs)inpackages/host-kit/src/internal/retry.tsbesideDeadline/sleep, exported via the existing@agent-device/host-kit/retrysubpath. Typed outcome{ kind: 'settled', value } | { kind: 'deadline' }; doc comment states it does not cancel the work; the deadline timer is cleared on every settle path. Additive only.settleWithinBudgetremoved; all deadline races usesettleWithin(server-shutdown.ts,daemon-runtime.ts,provider-lease-expiry.ts,daemon-session-idle-expiry.ts). Non-deadline races untouched (abort race, TTL timers,process-exit.ts).Promise.race(count per package must not grow past the merge-base (rule +LAYERING_RULES+ unit test).BEFORE: daemon-owned helper + 4 hand-rolled race blocks;
Promise.race(in packages/daemon = 5, each relying on manualclearTimeout. AFTER: one host-kit primitive; daemon count = 1 (non-deadline abort race); R87 blocks regrowth. SIZE: removes 4 race blocks + 1 bespoke timer, adds 1 helper + gate. PERF: deadline timers can no longer outlive settled work. COLLOCATION: deadline settling sits with the other deadline machinery in host-kit. No wire impact.Validation
Tested SHA:
9bdc4eb854e4c8cdb2237c5d841873ee652e4e03.check:affected --run --headreceiptrun-EfSWzy/receipt.json(exactCommit: true, baseeeff795f47): format, lint, typecheck, layering (R87 OK), build, package, vitest-related + 8 more passed;unitfailed only — Base-blocked (samepnpm test:uniton unchanged base fails 145 tests under current host load; here 5-8, all in untouched files, green in isolation). Focused: host-kit 674 passed (4 new tests); 18 daemon suites 157 passed; layering/package/production-exports/lint/typecheck green;pnpm formatrun (daemon races 5 -> 1, repo 45 -> 41). CI owns full coverage, device lanes (none needed), provider integration. Risk:unitneeds a green rerun on a quieter host.Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.