Repository navigation
fix(daemon): report Windows SIGTERM daemon exits as forced - #4659
Conversation
|
I reviewed 6e1b790 and found one change to make before merge. The RPC-first stop route itself looks well owned.
Not blocking, take or leave: The only reported check was skipped, so nothing yet attributes a pass or failure to this head. The full CI, including the Linux/macOS suites, |
|
Thanks @thymikee for the review — addressed the blocking issue and the follow-ups in
Could a maintainer approve the fork CI run for |
|
This PR is ready at b04b6bb. The findings from the earlier review (6e1b790, #4659 (comment)) are fixed, and I found nothing new that needs a change. Not blocking, and you can take or leave these: readReusableLocalDaemon passes settings.host for every non-reuse decision, including an unreachable daemon, so a TCP-hung daemon waits out the 2s RPC timeout and the 3s term window before SIGKILL (https://github.com/callstack/agent-device/blob/b04b6bb/packages/daemon-client/src/daemon-client-startup.ts#L146); passing host only when decision.cause is not unreachable would match the rule in your stopDaemonForTakeover comment. The new No checks have reported on b04b6bb yet because fork CI is waiting for maintainer approval. The new tests, wire-compat and layering gates have not run yet, and the Windows results rest on your report. A maintainer needs to approve the CI run so the full suites, wire-compat and layering gates can run before merge. There are no conflicts. |
|
Thanks for approving the CI run. The full suite has now run at b04b6bb, and one gate fails on this PR's own code, so I removed the ready-for-human label until it is fixed. The Fallow complexity audit in Repo Guards & Compatibility (job) flags two functions over the threshold:
Please reduce both below the threshold rather than adding a baseline entry. The force-mode guard that duplicates |
|
[Gemini 4 Hydrogen] responding on behalf of @GaspardIV Thanks @thymikee! Fixed both Fallow complexity findings in
|
|
Thanks for the rework. 876b1bf fixes the two functions that failed the Fallow complexity audit at b04b6bb, and no baseline entry or exemption was added. Daemon shutdown is part of the trust boundary we review most strictly, so this head also got a separate security cross-check. It found four problems that need fixing before merge:
Not blocking: the No checks have run on this fork head yet, so a maintainer still needs to approve CI. Items 1 and 3 point toward the same design: a local control channel bound to the daemon instance, instead of the tenant RPC port. That channel would fix both, and probably make the RPC-first stop simpler. |
|
Thank you so much for the thorough security cross-check @thymikee! Every single one of those 4 points hit a real bug, and I reproduced each of them live against Live reproductions before the fix (
|
|
Thanks for the update. The earlier findings from 876b1bf are fixed at 5490b79, but one new problem remains in the HTTP deadline change, and a separate security cross-check found two more in the control route (below). sendHttpRequest no longer clears the request deadline when the response body arrives. It now clears it only when resolveOnce or rejectOnce runs. For a remote daemon, resolveDaemonHttpResult calls resolveOnce only after materializeRemoteArtifacts finishes (daemon-client-transport.ts:273-276). That step downloads every response artifact, each with its own 90 s bound. The envelope leaves only about 30 s of margin after the daemon budget, minus the health probe and upload time. So a remote screenshot, recording or record stop can now reject with daemon_transport_timeout even though the command ran and the download was still within its own budget. The CLI reports a timeout, the artifact is lost, and the download keeps running unobserved. This worked before this change, and remote devices are the main use of the product. The rule the code must satisfy: the request deadline bounds the daemon answer and the error conversion, and it does not bound artifact materialization of an answered request. The smallest fix is to clear the deadline before materializeRemoteArtifacts on the ok path, for example with a clearDeadline callback passed to handleDaemonHttpResponseBody. Keep it armed for rejectDaemonHttpRpcError, which needs it to bound remote error localization (boundary-fault-transport.test.ts:291). Please add a test where a slow artifact download on an answered request settles successfully past the original deadline. Our earlier review asked to keep the deadline until settlement, so this narrows that request. Security cross-check, item 2: the control listener accepts the tenant bearer. The control listener authenticates with the same bearer that direct HTTP tenants present after the auth hook attests their tenant ID (daemon-runtime.ts:675, http-server.ts:579-608). A tenant with that bearer and loopback access, for example a client under another OS account on the daemon host, can stop a detached daemon that still has active sessions or leases. Host control needs its own authority: a separate per-instance control secret stored owner-only, or OS peer credentials on an owner-restricted local socket. Please add a test that a hook-attested tenant with the HTTP bearer cannot stop the daemon, while the host still can stop an HTTP-only daemon. Security cross-check, item 3: a managed takeover can force an active drain. After an accepted shutdown, closeSteps closes the socket and HTTP listeners before request, session and provider cleanup (daemon-runtime.ts:751-764), while the control listener still reports draining. A same-version managed command arriving in that window sees the data transport as unreachable and passes no host at daemon-client-startup.ts:150, so retirement skips the control RPC and can escalate to a signal before the term budget. Please ask the control listener before graceful retirement on every takeover path, wait the term budget when it reports draining or its state is uncertain, and keep the identity check before escalation. Add a test where a managed command arrives after the data listeners close and before the drain finishes. Not blocking, and fine to take or leave: daemon-control.ts:10 re-exports two constants from daemon-resolution.ts while daemon-idle-reap.ts imports one from each, so import both from one place; leave() in daemon-idle-reap.ts:275 is only called with requireIdle: true, so its shutdown message arm cannot run; and the CLI smoke test at smoke-daemon-http.test.ts:176 also passes when daemon stop falls back to SIGTERM on Linux and macOS, so asserting something only the control route produces (such as the daemon log showing the lifecycle drain with no signal-initiated close) would make it prove the route. No checks have been reported on 5490b79 yet, so a maintainer needs to approve the fork workflow runs. The diff touches daemon lifecycle, daemon-client transport and wire-compat ledger routes, which unit-core, integration smoke and wire-compat exercise. Once the deadline fix and its test are in and CI is green, this is ready for another look. |
|
Thank you for the follow-up review and cross-check @thymikee! I have addressed all three blocking items, the three non-blocking notes, and a source-guard regression caught when running the broader daemon suites locally in Changes in
|
|
The follow-up at d409073 separates the shutdown proof key from the HTTP bearer, but the findings below remain. CI is pending: zero checks are reported at this commit, and historical failures do not establish the current gate state. There are no conflicts. Before merge, close both tenant shutdown routes, honor the full drain wait during takeover, verify Windows provider release, and run the required checks at the new head. On Windows, a custom state directory with inherited read access can expose the control secret to another local account, which can then shut down the host even with active sessions or leases. The staging file inherits directory permissions, and file modes cannot restrict Windows readers. Require owner-only access before the registration owner first writes the key, using an ACL-protected credential location or authenticated peer transport, and fail closed if that access cannot be established. Registration owner, Node.js file modes. An attested HTTP tenant with loopback access, the bearer and daemon fence can still drain an idle dual-mode daemon through legacy quiesce on the data port. Route both lifecycle operations exclusively through host control when the daemon publishes it, and retain client quiesce fallback only for older daemons without control. Idle reap. A managed contender can send SIGKILL after the three-second signal budget while a control drain is still within its five-second request cancellation period, before provider release or report publication. Private replay cleanup shares this default, and takeover can truncate an explicit stop. Give accepted or uncertain control drains a lifecycle-owned grace budget shared by takeover and cleanup through the existing bounded drain wait; reserve the signal budget for signal fallback. Startup. Could a connected control probe that times out before authentication remain an uncertain outcome and receive the identity-fenced drain wait? With data listeners closed, the current two-second timeout can classify a draining daemon as unavailable and cause immediate SIGTERM on Windows. A definite connection refusal can remain eligible for signal fallback. Lifecycle request. A separate cross-check of this head also found that a checked JSON-RPC error keeps the RPC deadline armed while the client fetches diagnostics and, for a failed batch, settles script artifacts from completed steps (daemon-client-rpc.ts:39). If the timer expires during either step, the caller gets The HTTP smoke hook rejects shutdown before lifecycle admission, so the test would still pass if the runtime data-plane shutdown refusal were removed. Have the hook attest shutdown too, assert lifecycle admission returns UNAUTHORIZED, and prove the daemon remains available. HTTP smoke. The reported head smoke has no active provider allocation, and the runtime test expects no released provider IDs; the older mock WebDriver run was on b04b6bb. On Windows at the corrected head, close a BrowserStack or equivalent WebDriver app while retaining its device lease, start daemon stop, and issue a managed request after the data port closes while provider release is pending. Record the authenticated control path, provider DELETE and release confirmation, the released lease ID in the shutdown report, original process exit and replacement startup, with no premature signal. Also prove a separate local account with the HTTP bearer cannot read the control credential or invoke either lifecycle operation. Runtime. Could the registration owner parse one optional owner-protected control endpoint and pass it to quiesce and shutdown, validate the server credential at construction, and use the existing drain wait for both operations including unanswered connected probes? This would first require cross-platform owner-only credentials and an accepted-drain budget owned by the existing lifecycle wait; the old-record quiesce decision would remain in the client. Not blocking: the unused shutdown host parameter and takeover forwarding can be removed by accepting DaemonPaths; take or leave this cleanup. The linked Windows report confirms the symptoms but does not establish SIGTERM as the cause. Unit-core, daemon CLI smoke, wire compatibility and repository guards exercise the changed code and need results at the new head. |
|
Thanks for the Windows comparison. Please open an agent-device issue with the exact-main Windows reproduction and link the e2e report. For the BrowserStack failure, please try awaiting the final release of the e2e-owned lease before daemon stop and show the provider DELETE and release result. This PR now changes host control authority and remote HTTP response handling, so please split out the Windows stop-mode reporting correction. If graceful stop with active leases is still needed for independently managed Windows daemons, bring that case to the issue so we can agree on the smallest owner-only close path and its drain budget before another implementation. |
|
This branch now conflicts with main after recent merges. Please rebase onto main; the earlier review points still apply, and the next review will cover the rebased head. |
d409073 to
3e4fe63
Compare
|
Thanks @thymikee — split this PR onto
|
|
Thanks for the fix. At 3e4fe63 the code change looks right, but the docs now promise something Windows cannot do. The versioned help at cli-help.ts:422 says CI shows 1 check, passing, at this commit. The fork's full Linux and macOS suites need maintainer approval and have not run yet. The daemon-exit-wait, daemon-registration-owner and daemon-process-takeover unit suites overlap this change, so they matter once they run. There is no Windows lane in CI, so the win32 expectation in daemon-registration-owner.test.ts only runs on a Windows host. The live Windows 11 run was not reproduced here, so the win32 branch rests on the platform-mocked unit tests and the author-reported run. The earlier points about the control-secret ACL, tenant shutdown routes and drain wait no longer apply, because this head removed that code. Before merge, the fork CI needs approval and the full daemon suites need to pass at 3e4fe63. The docs fix above needs no other code change. |
|
Thanks @thymikee — updated both |
|
Thanks for the update. The two fixes from the earlier review are in at 5380f1b: the help string and the docs line now match what the code does on Windows, and the review found nothing else to change. There are no conflicts. No checks have reported on this head: the workflows for this fork need maintainer approval to run. Once CI reports green here, this is ready. Not verified here: nothing was run on Windows. That SIGTERM ends the process immediately rests on Node's documented win32 |
|
This head (5380f1b) now conflicts with main. Please rebase onto main and push; the open evidence item from the earlier review still applies to the rebased head. |
5380f1b to
0252850
Compare
|
Rebased onto Re-verified on Windows 11 ( |
|
Thanks for the update. The code at 0252850 looks good, and the conflict from the earlier review (#4659 (comment)) is resolved. No conflicts remain. No code change is needed. The hosted checks that ran are green. The fork's full Linux and macOS suites need maintainer approval and have not run at this commit, so the daemon-exit-wait, daemon-registration-owner and daemon-process-takeover suites that overlap daemon-process.ts have not yet run in hosted CI. Not verified here: anything on Windows, because there is no Windows CI lane and the review only read the code. The win32 branch of daemon-registration-owner.test.ts runs only on a Windows host, daemon-exit-wait.test.ts covers win32 through a mocked process.platform, and the live Windows 11 result is author-reported. Before merge, a maintainer needs to approve the fork CI run, and the full daemon suites need to pass at 0252850. |
|
This head (0252850) now conflicts with main. Please rebase onto main and push; the rebased head gets a delta review. |
On Windows, cross-process SIGTERM triggers TerminateProcess immediately without running Node signal handlers or flushing a graceful shutdown report. Map SIGTERM on win32 to 'forced' in stopDaemonProcess and preserve previousExitMode if the daemon exits before SIGKILL so callers report forced shutdown and unknown cleanup confidence.
0252850 to
c47c1af
Compare
|
Rebased onto |
|
Thanks for the update. The Windows SIGTERM exit fix at c47c1af looks right in the code, and the earlier conflict is resolved. Checks are green, but they cover only 2 jobs. Not verified here: the live win32 SIGTERM behavior and the smoke-daemon-clean result were not run on Windows, so they rest on the PR body and the rebase comment. Not verified here: the daemon-exit-wait, daemon-registration-owner and daemon-process-takeover suites at this head, because the fork CI suites need maintainer approval to run. Before merge, a maintainer needs to approve that run. |
* origin/main: fix(auth): send a stored CLI session only to the cloud that issued it (#4921) refactor(reasons): declare the daemon reasons in ReasonTable rows (#4936) fix(cli): drop --remote-config from auth and skip reading it for unsupported commands (#4957) refactor(snapshot): deduplicate system-surface projections and warnings (#4959) fix(find): enforce offscreen and non-hittable guarantees on focus (#4954) feat(auth): store a rotated CLI session credential and show the login code (#4833) fix(daemon): report Windows SIGTERM daemon exits as forced (#4659) # Conflicts: # packages/capture-kit/src/snapshot-quality-verdict.ts # packages/command-runtime/src/commands/interaction/runtime/target-visibility-stages.ts # packages/contracts/src/device-inventory.ts # packages/daemon/src/execution/interaction/internal/__tests__/find.test.ts # packages/daemon/src/execution/interaction/internal/find-target-capture.ts # packages/replay-port/src/daemon-port/session-replay-runtime-failure-response.ts # website/docs/docs/error-reasons.md
Summary
On Windows,
process.kill(pid, 'SIGTERM')callsTerminateProcessimmediately without running Node signal handlers or writingdaemon-shutdown.json, yetstopDaemonProcessreported'graceful'.packages/daemon-contracts/src/daemon-process.ts:signalExitMode()mapsSIGTERMonwin32to'forced'and preservespreviousExitModeif the daemon exits beforeSIGKILL.src/__tests__/daemon-exit-wait.test.tsandsrc/__tests__/daemon-registration-owner.test.ts: parameterizelinux/win32signal exit modes and match manual stop expectations onwin32(forced/unknowncleanup confidence).src/commands/schema/cli-help.tsandwebsite/docs/docs/commands.md: qualify the 75 sdaemon stopteardown grace as non-Windows and state that Windows force-terminates (mode: "forced",cleanupConfidence: "unknown").Touched files: 5 (
+69 / -14). Rebased ontoorigin/main(d1ace8139atc47c1af00); earlier prototype archived at archive/pr-4659-rpc-shutdown (d409073d1). Context: e2e-inc/e2e#1723 (client release in e2e-inc/e2e#1900; Windows graceful shutdown tracked in #4822).Before / after
Windows 11
session list --json->daemon stop --json:bfc09800b):"mode": "graceful","cleanupConfidence": "unknown","The graceful shutdown report is unavailable..."c47c1af00):"mode": "forced","cleanupConfidence": "unknown","The daemon was force-killed before provider lease state could be finalized..."Validation
Tested at
c47c1af00on Windows 11 (globalSetupskipped due tops not found in PATH):daemon-exit-wait.test.ts33/33,cli-help-topics.test.ts23/23,cli-help.test.ts29/29,command-doc-coverage.test.ts6/6.check:quick,check:production-exports,check:bundle-owner-files,check:daemon-wire-compat,layering,di-seams,check-doc-prose,command-docs --check,pnpm build,smoke-daemon-clean.test.ts3/3.daemon-exit-wait.test.tsmocksprocess.platform; livewin32exit verified by CLI andsmoke-daemon-clean.test.ts.