Skip to content

fix(daemon-contracts): bound stale-claim recovery disposal - #4952

Merged
thymikee merged 4 commits into
callstack:mainfrom
samanyudas:fix/4106-bound-stale-claim-disposal
Nov 23, 2026
Merged

thymikee merged 4 commits into
callstack:mainfrom
samanyudas:fix/4106-bound-stale-claim-disposal

Conversation

@samanyudas

@samanyudas samanyudas commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Stale-claim recovery awaited gateway.shutdown() with no time limit, so a never-settling runtime owner load held open, startup reconciliation, and device release --stale open past the 5 s acquisition deadline.

Now createOwnerScopedDeviceClaimReconciler bounds disposal with settleWithin (5 s, dynamically imported) and requires trackDisposal so every recovery transaction is owned from gateway composition through disposal settlement and late diagnostic flush (device_claim_recovery_dispose_settled / device_claim_recovery_dispose_failed with afterBudget: true). Daemon close drains tracked disposals under ownerMs (re-draining after root shutdown, keeping platformOwners: pending / hasUnfinishedWork() true on deadline). Daemonless device release --stale writes outcomes at the bound and keeps Node alive until tracked disposals drain before exit.

Closes #4106.

Before / after

# Before (b03e32bf7): composed recovery with hung owner load after 5 s deadline
releaseProvenStaleDeviceClaims(...) -> never settles

# After (8986f58a0): same composed recovery + required process-owner tracking
releaseProvenStaleDeviceClaims(...) -> writes retained outcome at 5 s budget; CLI stays alive until late shutdown + diagnostic finish; daemon close drains under ownerMs and retains registration while pending

Validation

Head 8986f58a077053b4e2168c1e9995d0259aa45d53, base b03e32bf7a363b3aa91258dbe8e66af022d94f05.

  • On 8986f58a0: format, lint (0 warnings/errors), typecheck, fallow (0 issues in 26 files), build, 6 recovery/daemon-close suites (73/73), and 11 touched suites including eager-closure-budgets (1,020/1,020). Full check:affected passed on eae9e563d; CI validates 8986f58a0.

Reviewed with sol-loop: 3 rounds with gpt-6.2-sol. Sol verdict: approved.

Created with Claude Opus 5.5 and Gemini 4 Neon in T3 Code.

A recovery transaction awaited its gateway's shutdown with no bound. After
the durable acquisition deadline or a cancellation abandoned an owner load
that never settles, gateway.shutdown() stays pending by design, so the
stale-claim caller (open, startup reconciliation, device release --stale)
hung forever.

createOwnerScopedDeviceClaimReconciler now waits at most 5 s for disposal
through settleWithin. When the budget expires it emits
device_claim_recovery_dispose_pending, keeps an earlier retained reason or
primary error, and turns a reconciled outcome into the typed
recovery-dispose-pending retention so the claim file stays on disk. A late
disposal failure is still reported as device_claim_recovery_dispose_failed
with afterBudget: true and never replaces the returned outcome.

Closes callstack#4106

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@thymikee

Copy link
Copy Markdown
Member

Thanks for working on this.

At 3672be2 the bound works, but the pending disposal is left with no owner after the budget. device-claim-owner-recovery.ts:116 detaches the promise, and nothing in the process awaits it or reports it. Two routes are affected. In daemonless agent-device device release --stale (platform-runtime-claim-recovery.ts:52), the outcome returns at the bound and exitAfterFlush(0) calls process.exit (process-entry.ts:17, process-exit.ts:18). A late-loaded owner's shutdown and its rejection diagnostic never run, while the base waited for both. In daemon open and startup reconciliation, a hung recovery used to stay in flight, so drainInFlightRequests counted it as abandoned and hasUnfinishedWork() kept the registration (daemon-runtime.ts:860). Now the request finishes, and a later close sees abandonedRequests=0 and platformOwners='closed' (only the main gateway is tracked). It then releases the registration and clears the lock configuration while the recovery gateway may still be loading or shutting down. Issue #4106 forbids abandoning late cleanup and forbids a false cleanup confirmation. On the CLI route this can leak owner-held processes. On the daemon route a successor can start recovery for the same claim while the old disposal is still running. The rule the code must satisfy: every disposal that outlives its budget is owned by the process owner, and that owner awaits or reports it before it exits. The sites follow from who calls createOwnerScopedDeviceClaimReconciler: the daemon close must await the tracked disposals under its existing owner budget and count a deadline as platformOwners pending or unfinished work, and runStaleDeviceClaimRelease must drain them after it writes output and before it exits. One test per route would prove it: the CLI does not exit before a released late load shuts down, and daemon close with a pending recovery disposal keeps hasUnfinishedWork() true.

Could the bound and the outcome mapping stay as written, and only the ownership move? For example, createOwnerScopedDeviceClaimReconciler could take a trackDisposal(promise) sink or return { reconcile, drain() }. No smaller design was found that also meets the issue's "do not abandon late cleanup" requirement.

Not blocking, and fine to take or leave: the disposal wait at device-claim-owner-recovery.ts:106 ignores scope.signal and scope.checkDeadline, so a canceled open still waits the full 5 s (race it against the signal, or document that the budget adds to cancellation); a disposal that fulfills after the budget logs nothing after device_claim_recovery_dispose_pending (use disposal.then(onLateClose, onLateFailure) and emit device_claim_recovery_dispose_settled with afterBudget: true); and the ClaimRecoveryRetentionReason doc at device-claim-reconciliation.ts:98 should say that recovery-dispose-pending comes only from the transaction, never from device status.

The required evidence is present. The two non-passing checks are cancelled Body rules runs, which lint the PR description, and this diff touches only daemon-contracts sources and tests, so they look unrelated. There are no conflicts. Not verified here: tests and check:affected were not run. Not verified here: whether a late-loaded owner holds external child processes on each platform. Not verified here: whether the daemon process exits right after close in every route while a recovery disposal is pending. Before merge, the post-budget disposals need a process-lifetime owner on both routes, with a regression test for each.

@samanyudas

Copy link
Copy Markdown
Contributor Author

Note

🤖 Gemini 4 Neon responding on behalf of samanyudas

Updated in eae9e563d to give every recovery disposal a process-lifetime owner on both routes while keeping the 5 s per-transaction bound and outcome mapping intact:

  • Tracker & late observation (packages/daemon-contracts/src/device-claim-owner-recovery.ts): Added createClaimRecoveryDisposalTracker() and trackDisposal on createOwnerScopedDeviceClaimReconciler. Each recovery transaction is tracked from gateway composition through disposal settlement and late diagnostic flush, emitting device_claim_recovery_dispose_settled (level: 'info', afterBudget: true) on late fulfillment as well as device_claim_recovery_dispose_failed (afterBudget: true) on late rejection. Documented that the 5 s disposal grace runs even after scope.signal cancellation so normal fast gateway shutdown finishes synchronously inside the transaction.
  • Daemon route (daemon-runtime.ts, request-router.ts, request-execution-scope.ts): Wired startup reconciliation, top-level requests, handler context, and same-session replay child scopes into one daemon-owned tracker. closeSteps awaits claimRecoveryDisposals.drain() alongside deviceRuntimeGateway.shutdown() under ownerMs and re-drains after root shutdown completes; a deadline takes precedence in platformOwners = 'pending' (preserving daemon_shutdown_platform_owner_failed if root shutdown also rejected) so hasUnfinishedWork() stays true and registration, lock configuration, and runtime state remain held.
  • Daemonless CLI route (src/platform-runtime-claim-recovery.ts, src/cli/commands/device.ts): runStaleDeviceClaimRelease writes command output at the 5 s bound via afterOutcomes, then keeps Node's event loop alive with a ref'd interval while awaiting disposals.drain() before returning to exitAfterFlush(0).
  • Retention reason doc (packages/daemon-contracts/src/device-claim-reconciliation.ts): Documented that recovery-dispose-pending comes only from the reconciliation transaction, never from device status.
  • Regression tests:
    • CLI route: src/__tests__/platform-runtime-claim-recovery-disposal.test.ts covers output-at-bound before late shutdown/diagnostics finish, plus a real Node subprocess test proving an .unref()-backed late disposal completes before the CLI process exits.
    • Daemon route: packages/daemon/src/server/http/daemon-runtime-bounded-close.test.ts covers startup post-budget disposal keeping platformOwners: 'pending' and registration/lock/state held, clean close waiting for disposal before plugin/runner finalization, HTTP close during an active request's disposal grace, HTTP close where recovery disposal starts after root shutdown begins, and deadline precedence over root gateway failure.
  • Validation on eae9e563d: format, lint, typecheck, layering, fallow, build, vitest-related (388/388), and unit (21,514 passed; scripts/fuzz/harness.test.ts re-verified 14/14). CI is running on the updated head.

@thymikee

Copy link
Copy Markdown
Member

Thanks for the follow-up. The PR is ready: the earlier findings from 3672be2 are fixed, and nothing from that review remains. At eae9e56, late disposals now drain through one tracker per process on both routes: daemon close under the owner budget, reporting pending work at the deadline, and the CLI drain before exit. Each route has tests. CI is green, with 15 checks and none failing, and there are no conflicts. Not blocking, and fine to take or leave: the disposal outcome flags and the late re-check in device-claim-owner-recovery.ts guard a race that cannot drop a report, because a handler attached to an already-settled promise still runs, so attaching the late handlers directly on deadline would remove that state; and trackDisposal is optional at line 105 and in the router deps, so a future construction that omits it compiles but leaves its late disposal without a process owner, and making it required would enforce that rule. Not verified here: tests, mutations and check:affected were not run, and the CLI tests call runStaleDeviceClaimRelease directly, so the output, drain and exit ordering was checked by reading the code. Not verified here: whether the daemon executable exits right after a close that reports pending platform owners, which matches the existing root gateway shutdown handling and is outside this change.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 22, 2026
@samanyudas

Copy link
Copy Markdown
Contributor Author

Note

🤖 Gemini 4 Neon responding on behalf of samanyudas

Applied both non-blocking nits in 8986f58a0:

  • Simplified device-claim-owner-recovery.ts by removing the disposalOutcome / budgetExpired flags and re-check, attaching the late settlement/failure .then handlers directly on deadline.
  • Made trackDisposal required on createOwnerScopedDeviceClaimReconciler and trackClaimRecoveryDisposal required on RequestRouterDeps and createRequestExecutionScope (updating the shared test router fixture and direct test call sites).
  • Verified on 8986f58a0: format, lint (0 warnings/errors), typecheck, fallow (0 issues), build, 6 recovery/daemon-close suites (73/73), and 11 touched suites including eager-closure-budgets (1,020/1,020).

@thymikee thymikee removed the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 22, 2026
@thymikee

Copy link
Copy Markdown
Member

Thanks for the follow-up change.

The delta at 8986f58 keeps every stale-claim recovery disposal tracked, and the earlier clean review still applies to the simplified code. All 15 checks pass at this commit, and no conflicts are known.

Not verified here: the tests were not run locally, so the claim that both the daemon and CLI routes still drain every active recovery disposal rests on reading the code and on the passing checks. Please confirm that with a local run of the bounded-close tests before merge.

Not blocking: the re-drain test at daemon-runtime-bounded-close.test.ts#L669 waits until the reconciler has registered its lifecycle before it calls close, so the first drain already sees the pending lifecycle and the test still passes if the second drain is removed; gating gateway composition until root shutdown starts would cover it, and this can be taken or left.

Could daemon-runtime.ts await the root gateway shutdown attempt and then drain the claim-recovery tracker once within the same owner budget? Registration already observes each lifecycle as it runs, so the initial drain does not start any cleanup.

@samanyudas

Copy link
Copy Markdown
Contributor Author

Note

🤖 Gemini 4 Neon responding on behalf of samanyudas

Applied the single-drain simplification in 99da454d0 and confirmed the local test run:

  • packages/daemon/src/server/http/daemon-runtime.ts now awaits deviceRuntimeGateway.shutdown() and then calls claimRecoveryDisposals.drain() once within the ownerMs budget (removing the redundant parallel drain() call).
  • Verified locally on 99da454d0: pnpm format, pnpm lint (0 warnings/0 errors), pnpm typecheck, and pnpm vitest run packages/daemon/src/server/http/daemon-runtime-bounded-close.test.ts packages/daemon-contracts/src/device-claim-owner-recovery.test.ts src/__tests__/platform-runtime-claim-recovery-disposal.test.ts (38/38 passed in 3.64 s). CI is running on 99da454d0.

@thymikee

Copy link
Copy Markdown
Member

Thanks for the update. This PR is ready on review at 99da454, and the re-drain change fixes what the earlier review left open. The re-drain test note on daemon-runtime-bounded-close.test.ts is moot now that the re-drain is gone, and tests at :553 and :689 still hold under sequential shutdown-then-drain, as checked by reading them. CI shows 14 checks with none failing, and there are no conflicts. Not verified here: the exact-head CI result, since the author comment says CI was still running when it was written, and the 38/38 local run, which is the author's claim. Not blocking, and fine to take or leave: the late-compose fixture at https://github.com/callstack/agent-device/blob/99da454/packages/daemon/src/server/http/daemon-runtime-bounded-close.test.ts#L669 calls runtime.close() only after recovery bind has started, by which point the gateway is already composed. The case would pass with only an early parallel drain, so gating progress before gateway composition and releasing it after root shutdown has entered would make it test the drain order. A disposal composed after the final drain returns is still not covered, as in earlier heads. The only step left before merge is the exact-head CI result.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 22, 2026
@thymikee
thymikee merged commit 65ba7bb into callstack:main Nov 23, 2026
14 checks passed
@samanyudas
samanyudas deleted the fix/4106-bound-stale-claim-disposal branch November 23, 2026 13:30
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.

Bound stale-claim recovery waiting for unfinished runtime disposal

2 participants