Skip to content

refactor(host-kit): settle deadline races via settleWithin with R87 race ratchet - #4766

Merged
thymikee merged 7 commits into
mainfrom
t3/q7-hostkit-settlewithin
Nov 20, 2026
Merged

thymikee merged 7 commits into
mainfrom
t3/q7-hostkit-settlewithin

Conversation

@thymikee

@thymikee thymikee commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

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) in packages/host-kit/src/internal/retry.ts beside Deadline/sleep, exported via the existing @agent-device/host-kit/retry subpath. 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.
  • Daemon-local settleWithinBudget removed; all deadline races use settleWithin (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).
  • New layering ratchet R87: 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 manual clearTimeout. 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 --head receipt run-EfSWzy/receipt.json (exactCommit: true, base eeff795f47): format, lint, typecheck, layering (R87 OK), build, package, vitest-related + 8 more passed; unit failed only — Base-blocked (same pnpm test:unit on 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 format run (daemon races 5 -> 1, repo 45 -> 41). CI owns full coverage, device lanes (none needed), provider integration. Risk: unit needs a green rerun on a quieter host.


Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

View guided diff Turn on auto-fix

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 2 new findings on 9bdc4eb. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

The idle-expiry sweep now holds the daemon's event loop for its whole deadline, which the old code avoided on purpose.

The removed budgetElapsedAfter() called timer.unref(), and its comment said a ref'd timer there is a daemon that cannot exit. settleWithin arms a ref'd setTimeout (retry.ts#L404), and expireIdleSession now uses it (daemon-session-idle-expiry.ts#L286). If settleIdleSessionUnderLock hangs with no other ref'd handles, a daemon with closed servers cannot exit until resolveDaemonSessionTeardownTimeoutMs elapses (5 s base, up to 46 s for web plus recording sessions). The daemon has no process.exit and relies on its other background timers being unref'd. The rule is: a deadline awaited by a background sweep must not hold the event loop. Please give settleWithin an option such as { keepAlive: false } that unrefs the timer, and pass it from expireIdleSession. Keep the default ref'd for shutdown callers, where an unref'd timer could let the process exit mid-report. Add a host-kit test that the timer is unref'd when the option is set. The real impact depends on whether the hung expiry holds ref'd handles itself; it was not reproduced live.

Not blocking, take or leave: in provider-lease-expiry.ts#L411 the AbortController and its .finally(() => deadline.abort()) only cancelled the old sleep, so nothing reads the signal now and retryPending can be passed directly. The ownerFailed/ownerFailure locals in daemon-runtime.ts#L804 only move emitDaemonDiagnostic out of the catch, so awaiting it inside the catch drops both. The cost line in the ratchet header says 63 + 90 LOC while the files are 78 and 66 lines. The rule also counts the literal text Promise.race(, so it misses Promise.race ( and aliases. Counting CallExpression nodes with the parser the layering scan already uses would fix that, or the header could state the textual limit.

Main already defines R87 as unique-exported-type-names (#4757), so this rule needs the next free id (R88) in the rule, its test, the check.ts comments and the success line.

The PR has merge conflicts with main in scripts/layering/check.ts, where both sides append a rule id and summary sentence. Keep both rules when you resolve it.

Of the open inline threads, the unref'd timer one still applies and is the same issue as above. The Promise.race( text count one also still applies. Its impact is low because base text nets out.

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 check.ts conflict and renumber the rule off R87.

@thymikee
thymikee force-pushed the t3/q7-hostkit-settlewithin branch from 9bdc4eb to 36bdfc5 Compare November 19, 2026 19:05
@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.43 MB 6.43 MB -283 B
Package (unpacked) 6.43 MB 6.43 MB -283 B
Package (download) 1.95 MB 1.95 MB -144 B

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 24.7 ms 20.3 ms -4.4 ms
CLI --help 51.0 ms 40.3 ms -10.7 ms

@thymikee

Copy link
Copy Markdown
Member Author

Review follow-ups applied — head 36bdfc5b37dec5743012fd8a5ee03458ec67fd5e

Rebased onto current main (96a2813c55); the scripts/layering/check.ts conflict is resolved keeping both rules — R87 unique-exported-type-names (main, #4757) and this PR's race ratchet, renumbered R88 in the rule, its test, the check.ts comments and the success line.

Blocking

  1. Unref'd idle-expiry deadline restored. settleWithin(work, timeoutMs, options?) now accepts { keepAlive: false }, which unrefs the deadline timer (packages/host-kit/src/internal/retry.ts); expireIdleSession passes it (daemon-session-idle-expiry.ts), so a hung idle expiry can no longer hold a daemon with closed servers for up to the 46 s teardown budget — the invariant the removed budgetElapsedAfter() held. Default stays ref'd for shutdown callers (an unref'd timer there could let the process exit mid-report). New host-kit test asserts the timer is unref'd only with keepAlive: false.
  2. R87 → R88 renumbered everywhere for the race ratchet (see above).
  3. Rebase done, both rules kept; PR is MERGEABLE at the new head.

Recommended (all applied)

  • provider-lease-expiry.ts: dead AbortController/deadline.abort() dropped — retryPending() passed directly (it takes no signal).
  • daemon-runtime.ts: ownerFailed/ownerFailure locals dropped; emitDaemonDiagnostic is awaited inside the catch.
  • Ratchet header LOC figures corrected (116 rule / 84 test).
  • The rule now counts Promise.race CallExpression nodes via the shared layering parser (oxc-parser + layering-ast.ts, memoized by source text so the merge-base pass parses each identical file once) instead of the literal text — comments, strings, aliases and spacing no longer count, and violations blame the actual call's file:line. New test covers comment/string/alias/spacing cases.

Validation at 36bdfc5b37: pnpm build, pnpm typecheck, pnpm lint, pnpm format:check, pnpm check:layering all green (success line reports R88, 41 remaining — same count as the old textual baseline at the merge-base); focused tests: host-kit retry 15/15 (incl. the new unref test), daemon server suites 334/334, layering ratchet tests 7/7. CI owns the full gate at the pushed head.

Both open inline threads (unref'd timer, textual count) are answered and resolved.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 2 new findings on 36bdfc5. The verdict and the full list are in the summary comment.

Comment on lines +408 to +411
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));

@apex-sentinel-staging apex-sentinel-staging Bot Nov 19, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment on lines +254 to +269
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);
},
);

@apex-sentinel-staging apex-sentinel-staging Bot Nov 19, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@thymikee

Copy link
Copy Markdown
Member Author

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 Promise.race calls.

Not blocking: the header comment in scripts/layering/check.ts and the success line near line 471 still say "Promise.race( occurrences" and "counts", but the rule now counts call expressions, so "Promise.race(...) calls" would be accurate. Take it or leave it.

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 actions/cache download race on the runner ("Directory not empty", missing action.yml), not this change, and it has been rerun. The unref test uses fake timers, and no daemon-level test pins the keepAlive:false call site; one would guard the idle-expiry wiring. No conflicts.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 19, 2026
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Still ready at f189c1b. The only change since 36bdfc5 is one fix plus its test: the provider-lease drain now reports a release that fails inside the budget as pending instead of throwing past the bounded window, and the settleWithin doc states the zero-budget case. CI is green, and the label stays.

@thymikee

Copy link
Copy Markdown
Member Author

This now conflicts with main. Please rebase. The code verdict at f189c1b stands, so a clean rebase gets the label back without a new review.

@thymikee thymikee removed the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 20, 2026
thymikee and others added 7 commits November 20, 2026 07:55
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.
@thymikee
thymikee force-pushed the t3/q7-hostkit-settlewithin branch from f189c1b to 844e719 Compare November 20, 2026 07:03
@thymikee

Copy link
Copy Markdown
Member Author

Rebased onto 115c83a8e1 after #4779 (R89) merged; new head 844e719685 (conflicts were the shared scripts/layering registries — kept both ratchets; the wiring test pinned the rule-id order). Validation at the rebased head: layering 512/512, check.ts OK (R88 race counts hold at merge-base 41; R89 383/383), host-kit+daemon vitest 5248 pass, oxlint/oxfmt clean; the 10 tsc errors are the known __OWNER_FILES__ codegen artifact, identical on untouched checkouts at this base.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 20, 2026
@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 844e719

Since the review of f189c1b: 0 new · 0 still open · 0 no longer raised

No open findings.

1 finding below minor hidden (user_settings.min_severity).

Reviewed with this repository's own Sentinel configuration (115c83a8e121).

💬 Talking to Sentinel

In a finding's thread, reply with:

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.

@thymikee

Copy link
Copy Markdown
Member Author

Ready again at 844e719. The rebase onto main is clean: the patch is identical to f189c1b, with only the race ratchet commits re-applied over the new R89 rule. The earlier code verdict stands.

@thymikee
thymikee merged commit 505a913 into main Nov 20, 2026
19 checks passed
@thymikee
thymikee deleted the t3/q7-hostkit-settlewithin branch November 20, 2026 10:15
thymikee added a commit to pcbeingused333/agent-device that referenced this pull request Nov 20, 2026
* 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)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant