Skip to content

fix(daemon-client): name a sandbox-denied connect and leave that daemon alone - #5095

Merged
thymikee merged 8 commits into
mainfrom
t3/classify-sandbox-daemon-connect
Nov 26, 2026
Merged

thymikee merged 8 commits into
mainfrom
t3/classify-sandbox-daemon-connect

Conversation

@thymikee

@thymikee thymikee commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Summary

A reachability probe answered a boolean, so a loopback connect the host refused (EPERM or EACCES under a Codex workspace-write sandbox around the client) read exactly like a daemon that answers nothing. The client judged a healthy daemon dead, tried to replace it, and failed with "Daemon replacement could not be confirmed." That attempt killed the daemon this client could not reach.

Probes now answer a verdict, and a refusal by EPERM or EACCES is a denial rather than evidence about the daemon. The takeover ladder answers a new connectDenied decision; each client hearing it fails with details.reason: daemon-connect-denied, the errno, transport, port, daemon identity, and the host-access hint the denied listen already used. Nothing is spawned, retired, or signaled on that answer. The probe layer moves to daemon-client-loopback-probe.ts, which owns the denial set.

Before / after

$ codex sandbox -- agent-device devices   # healthy daemon, pid 67030, port 58269
Base: Daemon replacement could not be confirmed.
      --json: reason startup-exited, startError EPERM .../daemon.log,
              cleanup retirement-unconfirmed on EPERM .../daemon.reclaim.lock
      ps: pid 67030 gone — the healthy daemon was killed
Head: The host denied this client a connect to the daemon's loopback endpoint
      on 127.0.0.1:58269.  details.reason daemon-connect-denied, errno EPERM,
      hint naming the sandbox and host access
      ps: pid 67030 alive; the next unsandboxed devices reused it

Validation

Head 19fccace43. typecheck, lint, format, gate fallow, check:layering, check:doc-prose, check:command-docs clean. packages/daemon-client 385 tests pass, plus packages/daemon 4779 and test/repo-guards 181. Suppressing the classifier or the ladder branch fails the new cases. Reproduced with the Codex sandbox CLI, no device. CI owes the full lane. Risk: a denial errno besides EPERM/EACCES still reads as unreachable.


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

View guided diff Turn on auto-fix

…on alone

A reachability probe answered a boolean, so a loopback connect the host
refused (EPERM or EACCES under a sandbox around the client) read exactly like a
daemon that answers nothing. The client then judged a healthy daemon dead and
tried to replace it, and reported "Daemon replacement could not be confirmed."
The replacement attempt could also kill the daemon it could not reach.

Probes now answer a verdict, and a refusal carried by EPERM or EACCES is a
denial, not an answer about the daemon. The takeover ladder answers a new
connectDenied decision for it, and every client that hears it throws
details.reason daemon-connect-denied with the errno, transport, port, and daemon
identity, plus the host-access hint the denied listen already used. Nothing is
spawned, retired, or signaled on that answer.

The probe layer moves to daemon-client-loopback-probe.ts, which owns the
denial set, so the transport module stays under the lint file-size limit.
@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.61 MB 6.59 MB -18.6 kB
Package (unpacked) 6.61 MB 6.59 MB -18.6 kB
Package (download) 2.02 MB 2.01 MB -5.1 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 31.0 ms 36.5 ms +5.5 ms
CLI --help 59.0 ms 63.6 ms +4.6 ms

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

All reported issues were addressed across 16 files

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread src/commands/schema/cli-help.ts Resolved
Comment thread website/docs/docs/configuration.md Resolved
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

At 19fccac, some routes can still retire a daemon whose connect the host refused, or can lose the daemon-connect-denied reason. The changes below are needed before merge.

Older-version, missing-version and code-mismatch decisions return replace without a reachability probe. Managed SDK and proxy calls can then signal a live daemon and end its sessions, including a startup-race winner after a denial was already observed. A managed client pinned to an unadvertised transport also gets replace without a usable connect attempt. CLI/MCP ensure and attach can report incompatibility, a transport failure or lifecycle-contended instead of the documented host-access recovery. The shortcut predates this PR but breaks its rule. Every replace decision without usable connect evidence should first probe an advertised endpoint with denial detection and keep any denial already observed. The help and configuration text should match the resulting routes. Validation should run managed SDK and CLI ensure against a live older or code-mismatched daemon with connects denied, and show daemon-connect-denied, a surviving PID and no new spawn.

For a daemon the client launched itself, readReadyLaunchedDaemon turns a denial into null. The stall or ceiling path then retires that live daemon and reports the wrong reason. A denial during startup should end the attempt with the typed error, outside the catch that retires failed startups. A launch that can listen but cannot connect should show daemon-connect-denied and a surviving daemon.

The fresh HTTP and socket liveness checks turn EPERM or EACCES into false, the same as silence. After a request timeout, a quiesce timeout or an exceeded drain wait, this can force-retire a running daemon. This also predates the PR. Both checks should classify these errors the same way as the reachability probe and stop retirement with the typed denial, while any response still proves the daemon answered. Tests should deny the connect on each of those timeout routes and show that nothing is signaled.

Can the local HTTP reachability probe reuse a pooled keep-alive socket and miss a refusal of new connects? A reused or stale socket never exposes the connect error, and the later RPC then reports an ordinary transport failure. The local probe should force a fresh connection, as the liveness check does, with remote health and RPC behavior unchanged. A test should prime the pool, deny new connects and show the denial.

When the first leg is denied and the fallback succeeds after the outer deadline, this return drops the denial and can end in a startup failure. Only an in-budget fallback success should replace the first denial. Every other outcome should keep a denial from either leg, covered by a late-fallback test.

The rule that a client never treats an EPERM or EACCES refusal as silence and retires the registered daemon does not hold yet on the routes above. The help and configuration additions also promise the typed reason and an untouched daemon more widely than the code delivers. Please fix those routes or explain why they are outside the rule.

Would it be simpler for resolveDaemonTakeover to make one onAnyAdvertisedTransport probe before every replace answer and return connectDenied on a denial? That decides it in one place before quiesce, retire or spawn on those routes, for one extra loopback probe of under 500 ms on the replace path.

Not blocking: these can be taken or left: add an ensureDaemon denial test that checks the reason and zero spawns; use a daemon fixture that passes the retirement check (or assert retirement is never called), fix its comment, and exercise attach and real HTTP errors; share one errno check for these codes with the listen path; and reword the helper comment to say a refusal leaves daemon reachability unknown.

These high-priority threads still apply: launched daemon denial, help errno condition and CLI replace route. Five lower-priority threads also still apply. The pooled socket thread can be resolved for a process refused from the start, since reuse needs an earlier successful connect; a later policy change is the pooled socket question above.

The Repo Guards & Compatibility check fails because of this PR: the test naming guard finds no module for daemon-client-connect-denied.test.ts. Rename it, for example to daemon-client-loopback-probe.test.ts, or to index-connect-denied.test.ts for a cross-module case. The cause of the Coverage failure is unclear: its log ends after this PR's connect-denied test output with no failure line.

Not verified here: the sandbox reproduction and the test suite were not rerun, and the regression tests were judged by reading their mocks and assertions. The managed SDK kill assumes the sandbox allows signaling a daemon outside it, as the base run in the PR description shows; that was not rerun on this route.

A host-denied loopback connect (EPERM or EACCES) reached `daemon-connect-denied`
only on the one ladder branch that probed. Every other path to a replacement
judged the daemon from the record alone, so a client that cannot see a daemon
still retired it, and a launch whose own readiness probe was refused fell into
the startup cleanup that signals the launched process.

The ladder now probes the advertised endpoints before ANY `replace` answer, for a
version mismatch and a code mismatch alike, so `connectDenied` is the verdict
wherever a replacement was about to be decided. A launch-time refusal is terminal
and names the typed reason before the stalled and ceiling cleanup paths. The
liveness probe classifies its legs' errnos too: a refused leg settles as a denial,
so neither the drain wait, a timed-out quiesce, nor a reset-eligible timeout can
retire on a connect this client was refused. The HTTP reachability leg asks on a
fresh connection, and the first leg's refusal survives a late answer on the second.

The probe implementation moves behind the function-scoped `await import` its one
caller already uses, and `readDaemonHttpHealth` returns to the shape the wire
ledger records: a probe now proves a refused connect with its own connect rather
than by carrying an errno in a health payload, so no wire declaration changes.

Docs name the two errnos the reason covers, and the connect-denied test is named
for the module it pins.
@thymikee

Copy link
Copy Markdown
Member Author

Everything below is on 2b30ec4. The invariant holds on every path now: a loopback connect refused with EPERM or EACCES becomes details.reason daemon-connect-denied and nothing is spawned, retired, quiesced or signaled.

1. Probe an advertised endpoint with denial detection before ANY replace. Fixed at the decision owner, resolveDaemonTakeover (packages/daemon-client/src/daemon-launch-spec.ts): the version-mismatch and code-mismatch branches now probe onAnyAdvertisedTransport and answer connectDenied before returning replace, so no caller can reach a retirement unprobed. That covers the race-winner route through readReusableLocalDaemon and observeLocalDaemon, and it is what makes ensureOnce's existing connectDenied branch reachable for a mismatched daemon. cli-help.ts and configuration.md name the two errnos and say another errno stays ordinary unreachability.

2. A denial at launch time is terminal. readReadyLaunchedDaemon keeps the verdict and throws the typed error outside the probe's try/catch, so retireStartupAttempt is never reached. The liveness legs are classified too: probeDaemonResponsive returns a verdict instead of a boolean and reports a refused leg as a denial, so awaitDrainedDaemon, quiesceOrRetireUnresponsive and the reset-eligible timeout route stop instead of retiring.

3. Fresh connection on the HTTP reachability leg. The probe no longer borrows the health reader: probeHttpEndpoint in daemon-client-loopback-probe.ts makes its own request with agent: false, and the first leg's denial is kept when the fallback leg answers late.

4. The two failing checks. The connect-denied test is renamed to daemon-client-loopback-probe-connect-denied.test.ts, which is the name the test-colocation guard expects. The eager-closure growth is fixed by making the probe module lazy (await import at its one call site) and type-only to its other readers, so all three entry closures return to their merge-base shape. readDaemonHttpHealth is byte-identical to the merge-base again — a probe now proves a refused connect with its own connect rather than by carrying an errno in a health payload — so the wire ledger needs no new digest or ack.

@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: 1 new finding on 2b30ec4. The verdict and the full list are in the summary comment.

The guard every replacement now takes out was run through the reachability probe, and that probe is
built for a different question: it sends a health request and retries with waits, so a mismatched
daemon cost a takeover one request and one extra wait step it had never paid. What a retirement has to
check is narrower — whether the HOST lets this client reach the registered ports at all — so it asks
that directly: `readAdvertisedConnectDenial` makes one bare loopback connect per advertised port, at
once, with no health request and no retries. A sandbox that blocks local ports refuses the connect
itself, which is the evidence the guard needs; a busy daemon's silence stays no evidence at all.

A reset-eligible timeout whose liveness probe the host refused also stops reporting a timeout. That
hint promised a session the caller could not have reached, when the client's real finding is that the
host refused the connect: the refusal now answers with `daemon-connect-denied` and the shared
host-access hint. `handleRequestTimeout` is split at its own owners — the probe, the recovery decision,
the diagnostic, and the failure — so the decision reads as one step per function and the file is back
under the complexity threshold.

The reason table now carries the EPERM/EACCES wording where the generated reasons page reads it, which
is what made `website/docs/docs/error-reasons.md` stale.
…imitive

The HTTP reachability leg loaded `node:http` under a hand-rolled `Promise.race` against an abort
listener, which is the third such race in this package (R88 counts two at the merge-base) and the one
shape the rule exists for: a timer racing work, cleared only where the author remembered. It now waits
on `settleWithin`, which clears its own timer on every settle path, and the loader's spend is taken out
of the request's window so the probe's budget stays absolute across both steps.
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

This PR is ready at f4793a2. Every point from the earlier review that could retire a daemon because of a refused connect is now fixed. Three smaller points remain and can go to a follow-up issue.

Not blocking: these can be taken or left: when a pinned transport is not advertised, the unreachable branch could ask refusedByHost if onClientTransport returned no denial, before it answers replace, because that managed path still retires the daemon without a connect; the denied timeout, new in 3beb513, drops requestSent, so a sent request could carry daemonRequestSent on that error and keep the "may have dispatched" disclosure for daemon-connect-denied (or keep the timeout error and attach the denial); and route tests could cover each of the launch-time, late-fallback, drain/quiesce and pooled-socket reachability-probe denials, asserting the reason and that nothing is signaled.

These threads no longer apply and can be resolved: launched daemon survives denial; HTTP probe uses its own connection; help names the errno codes; mismatch branches check refusal first; attach case is tested; configuration and error docs aligned; fixture doc corrected; transport, errno and port tested; probe doc corrected; denied timeout reports host access, with the requestSent side effect noted above.

All 21 checks pass, including Repo Guards, which the test rename fixed.

The sandbox reproduction in the PR description ran on the earlier commit, was not rerun on this one, and did not cover a mismatched or newly launched daemon. Not verified here: tests were not run locally, and their regression value was judged by reading the mocks and assertions. Not verified here: whether any real setup allows a request to connect and then refuses the later probe in the same process, which the timeout point depends on.

No further change is required before merge.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 25, 2026
…spatch visible

Three follow-ups from the ready review:

- The takeover's unreachable branch now asks `refusedByHost` before it answers
  `replace`, so a managed client pinned to a leg the daemon does not serve no longer
  retires a daemon it was never allowed to reach.
- A denial that replaces a timed-out request's reason carries `daemonRequestSent`,
  and the transport's failure classifier discloses dispatch from it, so a request
  written before the host refused the probe is still reported as one that may have run.
- Route coverage for each route that can act on a refusal: the launch-time readiness
  probe, the reachability probe's late fallback leg and its pooled-socket case, the
  quiesce-timeout route, and the drain-escalation route. Each asserts the reason and
  that nothing is signaled or spawned.
@thymikee

Copy link
Copy Markdown
Member Author

Took all three notes, plus the thread cleanup, at fdbb7fb.

  1. Unreachable branch — resolveDaemonTakeover now asks refusedByHost after onClientTransport answers silence, before it answers replace (daemon-launch-spec.ts:186). daemon-launch-spec.test.ts covers it with a reachability triple whose client leg is silent and whose guard is refused; dropping the new refusedByHost call turns that case red.
  2. Denied timeout and requestSent — the denial now carries daemonRequestSent: true when the request had been written, and the transport's failure classifier treats a refusal that states it like a timeout, so the dispatched: 'unknown' disclosure lands on the denied error too (daemon-client-timeout.ts:166, daemon-client-transport.ts:468). Kept the denial as the reason rather than attaching it to the timeout error: a caller that switches on the reason should see "your sandbox refused this", not "the daemon was slow". The reason's row in the generated table now documents the field, and the route test asserts both details. A refusal found BEFORE the request goes out still records nothing, which the classifier leaves as dispatched: 'no'.
  3. Route tests — four, each asserting daemon-connect-denied and that nothing is signaled or spawned:
    • launch-time: a launched daemon whose readiness connect the host refused is left running — the launch seam starts a registration-owning child over a silent endpoint, so this is the client's own startup watch reading its own publication and being refused (new case in the denial suite).
    • late fallback: a fallback leg answering past the deadline still reports the first leg as a denial — clock-driven, so "late" is settled and not raced.
    • pooled socket: a fresh connect the host refused is not answered around by a pooled socket — the global keep-alive pool is primed first with the same module object the probe loads, then every fresh connect is refused; a verdict of reachable could only come from the pooled socket. net.Socket.prototype.connect is the seam: a deferred emit('error') is swallowed by the agent (ERR_SOCKET_CLOSED), which is why it destroys with the errno, as a refusing host does.
    • drain/quiesce: one in daemon-client-ensure-drain.test.ts on the existing virtual-clock drain harness (asserts drain.signals stays empty), one in daemon-client-ensure-explicit-lifecycle.test.ts for the quiesce-timeout route.
  4. Stale threads — all ten you listed were already resolved, checked again just now.

Locally I ran only the six suites this touches (107 tests), pnpm typecheck, oxlint on the package, and the wire-compat and eager-closure ledgers. Not run locally: the full gate.

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

This comment has been minimized.

The Coverage lane runs the file's cases in a shuffled order, and two cases added for
the denial shapes patched process globals: Date.now frozen to a counter, and every
net.Socket connect refused. Anything still in flight from an earlier case was refused
too, and a keep-alive socket left in the global agent was handed to a later case whose
server the OS had just given the same port. The late-leg case now spends a real budget,
the refusal is scoped to the probed port, and the primed socket is destroyed.
@thymikee

Copy link
Copy Markdown
Member Author

Coverage failure root cause: the two reachability-shape cases added in fdbb7fb patched process globals inside this file. One froze Date.now to a counter, the other refused every net.Socket connect and left the primed keep-alive socket in http.globalAgent. Under the lane's shuffled order, anything still in flight from an earlier case got refused or read a frozen clock, and a later case whose server the OS handed the same port rode the free socket and lost its request — which is the shape of all five reports (Remote daemon is unavailable vs a timeout, the two 5 s timeouts, and the request-limit byte count reading 0).

Fixed in d93f600: the late-leg case spends a real budget instead of faking one, the refusal is scoped to the probed port (comparing numbers, since Node hands connect its normalized-args array with a string port), and the primed socket is destroyed. Both cases still discriminate: dropping the deadline check in answeredWithinDeadline, or production's agent: false, turns them red. Shuffled runs and the whole packages/daemon-client project under coverage are green locally.

@apex-sentinel-staging

This comment has been minimized.

…hrough the fixture plan

Two Coverage failures on this head:

The repo guard reads the launch seam as a daemon-fixture family member: its launcher mock
must be a bare vi.fn() with the launch plan installed on it, and its fixture teardown must
run through the shared family cleanup. The mock was built in a hoisted block instead.

The pooled-socket case hung and then reported an error thrown after it completed. Two
shared-state faults made that possible: it primed the process-wide agent and emptied it in
teardown, so every socket another case was still using went with it, and it issued the prime
without clearing the entry this endpoint already had, so a keep-alive socket a previous file
had left for a port the OS just reused answered the write with nothing and the request had no
bound to end the wait. The case now clears only this endpoint's pooled sockets, before and
after, and the prime has its own deadline.
@apex-sentinel-staging

This comment has been minimized.

The case refused every connect made while its patch was installed, and a worker runs the
cases of one file in one process: a connect another case was still waiting on was refused
too, and the errno surfaced as an unhandled error once that case had finished. Vitest gives
every file a worker, so the patch now reaches only this case.

The refusal also lands later. Destroying a socket synchronously inside its connect reports a
closed socket rather than the errno, and it fires before the requester has a listener on the
socket. The real connect runs, so the socket has its handle, and the errno arrives on the
next turn, when the request owns it. The case pins that the prime really did leave an idle
socket in the pool, so the verdict cannot come from an empty pool, and it drops only this
endpoint's pooled sockets.
@thymikee
thymikee force-pushed the t3/classify-sandbox-daemon-connect branch from 2071fc7 to 411ad6e Compare November 25, 2026 14:45
@thymikee

Copy link
Copy Markdown
Member Author

Coverage fix (round 3), head 411ad6e: the pooled-socket probe case now has its own file, packages/daemon-client/src/__tests__/daemon-client-loopback-probe-pooled-socket.test.ts (named for daemon-client-loopback-probe.ts, so R84 holds). Vitest isolates each file in its own worker, so the Socket.prototype.connect patch and the keep-alive pool it leans on can no longer reach a case in daemon-client-transport.test.ts that is mid-request on a shared socket — that was the unhandled EPERM and the 5 s timeout.

Two adjustments made it stable in the isolated file: the refusal is emitted asynchronously on the next turn (a synchronous destroy inside connect fires before the requester has a listener and reports ERR_SOCKET_CLOSED, not the errno), and the case asserts the prime really left an idle socket in the pool for its endpoint, so a reachable: false verdict cannot come from an empty pool. afterEach restores the prototype. The case still discriminates: dropping production's agent: false turns it red. Five shuffled coverage runs of the new file + daemon-client-transport.test.ts + the denial file + the fixture-launch guard are green, as is packages/daemon-client + test/repo-guards (69 files / 585 tests).

@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 411ad6e

Since the review of 49b48b0: 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 (f1c5f3dc3ed1).

💬 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

The code at 411ad6e has no findings, which matches the earlier review of f4793a2. Nothing remains to fix, and the required evidence is in place.

This earlier thread no longer applies: at this commit, a denied connect returns daemon-connect-denied and does not retire the daemon.

CI is green, with all 22 checks passing at this commit.

Not verified here: tests were not run locally, and the test isolation claim for the pooled-socket test file rests on the green CI run.

Nothing else needs to happen before merge.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 25, 2026
@thymikee
thymikee merged commit 2d29b6d into main Nov 26, 2026
22 of 23 checks passed
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