Skip to content

fix(daemon): bound upload ingress and finalization - #4721

Merged
thymikee merged 21 commits into
mainfrom
t3/ingress-finalization-review-fix
Nov 20, 2026
Merged

thymikee merged 21 commits into
mainfrom
t3/ingress-finalization-review-fix

Conversation

@thymikee

@thymikee thymikee commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Apply the daemon’s upload time budget from HTTP admission through artifact registration. Accepted JSON chunks and completed file writes renew the inactivity timer. After body completion, the original aggregate deadline still applies. Cancellation joins owned work and cleans up unregistered artifacts. Incomplete finalize preserves the ticket’s original expiry.

Refs #4441.

Validation

Head 52e3437eb9. Local pnpm check:affected --run passed all runnable checks with exactCommit=true, including unit, daemon-wire-compat (against v0.21.41) and docs. Hosted checks restart at this head. The live evidence below is from cdd3c1d791; this head changes only the JSON body refusal path and the failure-answer commit.

  • Live at cdd3c1d791: a real daemon and agent-device proxy were tested with the real remote upload client. All 40 of 40 single-request runs (20 direct, 20 proxy) read the mid-stream 308 and resumed at offset 1048576 with 2 PUTs and no reset. All 20 pipelined direct runs passed. A single-shot upload that stalls 125 s gets the typed 500, a FIN and no reset when direct. A pipelined streaming PUT through the proxy fails before this PR too; that limit is in the proxy, which this PR does not change.
  • Each review fix has a test that failed on the code it fixed: the gaps from 142a2c9, 4130732, f9628fb, 267495c, bea8886 and cdd3c1d (an oversized JSON body now gets its 400 and a clean close).
  • Risk: the live runs used loopback only. WAN and Windows clients are not tested.

Earlier evidence at 142a2c93bb: slow JSON bodies over 180 s, a stalled PUT at exactly 120,000 ms, and finalize after 150 s of hash work.


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

thymikee and others added 3 commits November 18, 2026 22:02
…ingress)

Daemon ingress/upload-ticket residual layer of #4441, on current main:

- Explicit Node ingress ceilings at the daemon HTTP constructor: 30s to
  receive request headers, 600s to receive a request body, replacing the
  Node defaults. Ingress-only; RPC execution keeps its own deadlines.
- Upload routes (/upload, /upload/preflight, /upload/direct/*,
  /upload/finalize) admit a finite 600s aggregate at the request callback
  plus a 120s body-inactivity ceiling, renewed only by accepted body
  progress and never resetting the aggregate. Expiry and client disconnect
  abort owned work through the request stream with typed reasons
  (transfer_phase_timeout / transfer_ingress_deadline_exceeded).
- The single-shot upload runs one joined pipeline (request -> byte cap ->
  file) owned by the ingress link: the signal destroys every stream with
  its typed reason, accepted (flushed) bytes renew only the inactivity
  ceiling, and the earliest failure is reported via resolveIngressFailure
  so an abort-owned generic AbortError maps back to the owner's typed
  reason without losing an earlier classified failure. Hash and extract
  phases check the owner and are provably bounded by the byte cap.
- Resumable ticket idle timer renews on completed (flushed) body bytes, not
  only after a whole chunk appends. Finalize disarms the idle timer only
  after the incomplete/stat validation, so an incomplete finalize keeps the
  original idle lifetime and expiry cannot fire during an active valid
  finalize; terminal paths still clean up through closeEntry.
- The direct chunk pipeline maps an aborted signal's owned typed reason
  deterministically (resolveIngressFailure) and rolls back to the
  pre-chunk offset on failure.

Tests: constructed server settings, fake-timer ingress/ticket behavior,
real loopback request-route evidence for progress (308/range/x-upload-offset
framing preserved, idle lifetime renewed) and client cancellation
(rollback, on-schedule expiry cleanup) with controlled timers installed
before ticket creation, abort-reason mapping matrix, and regression tests
that fail on the previous candidate code.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
 residual)

Threads the existing per-request ingress signal through the real finalize
route and into the owned post-body pipeline, closing the residual where
finalize hash/extraction/registration ran unbounded behind the ticket:

- upload-http.ts: /upload/finalize passes ingress.signal through
  finalizeResumableUpload into serialized admission, post-body hash, owned
  extraction and materialization, and the artifact registration boundary
  (sendUploadedArtifactResponse refuses to register an aborted owner).
  Inactivity now stops at body completion on every route (bodyComplete()),
  so valid post-body work observes only the 600s aggregate.
- resumable-upload.ts: finalize admission checks the owner after the
  close/cancel race check, preserving the close side's typed expiry error;
  incomplete finalizes still keep the original idle timer; terminal
  failures keep joined cleanup and rethrow the typed first failure via
  resolveIngressFailure.
- resumable-upload-transfer.ts: computeUploadHash takes the owner signal
  (abort destroys the read stream with the typed reason); chunk receive
  reports body completion.
- upload.ts: single-shot hash and extraction run under the same signal
  instead of only phase-boundary checks behind the byte cap.
- artifact-archive.ts: extraction forwards the signal into
  extractArchiveSafely's owned stream; inherently synchronous fs calls
  (statSync, open/read/close, rename, existsSync/rmSync) are guarded by
  owner checks immediately before them.

Tests: bodyComplete inactivity/aggregate split, pending-finalize admission
abort with ticket recovery, mid-hash abort with typed reason and semantic
cleanup (registry closed, temp dir removed), owned single-shot success and
post-body cancellation, plus the existing ingress/ticket suites. Wire
ledger digests and rationale updated for the changed upload-http handlers.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.43 MB 6.43 MB +4.6 kB
Package (unpacked) 6.43 MB 6.43 MB +4.6 kB
Package (download) 1.95 MB 1.95 MB +1.5 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 24.6 ms 25.5 ms +0.9 ms
CLI --help 53.7 ms 54.7 ms +1.0 ms

@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: 3 new findings on a9aec49. The verdict and the full list are in the summary comment.

@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 finding moved to a new line on 63c5d0d. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

I found no defect in the code at 63c5d0d, but the tests do not yet prove the new route wiring. Both loopback tests in upload-http-ingress.test.ts look like they pass on base: base already refreshed the ticket per chunk and already rolled back on cancel. If ingress.bodyComplete() is removed from handleUploadFinalize, or onBodyComplete is dropped, every test still passes, and a finalize longer than 120 s would fail with transfer_phase_timeout. Please add one createDaemonHttpServer loopback test with faked setTimeout. It should stall a partial PUT and see the connection close at 120 s with the ticket offset rolled back. It should then run a finalize after the body completes, with a hash blocked for more than 120 s, and see it succeed.

17 of 17 checks pass at 63c5d0d, and there are no conflicts. Before merge, the new loopback test above should land, and the reuse question below should be answered.

Could upload-ingress.ts shrink to about 40 lines? createTransferPhaseWatchdog(AbortSignal.any([typedAggregate.signal, responseDisconnectSignal(req, res)])) in host-kit already owns the body-inactivity timer. It would arm('request-body', TRANSFER_BODY_INACTIVITY_TIMEOUT_MS) at admission, touchBody() from observeCompletedRequestWrites, and suspend() at bodyComplete. That would drop the copied transfer_phase_timeout reason constant, the hand-built error and observeAcceptedWrites, and would leave one owner for every transfer-phase timeout, as #4441 asks. It needs observeCompletedRequestWrites generalized from ClientRequest to Writable, and the transfer-phase error builder or phase exported so a daemon-side post-body phase can be named. If that does not fit, what stops it?

Not blocking, and fine to take or leave: many of the ten throwIfIngressAborted checkpoints repeat a check that already runs (for example resumable-upload.ts:159 repeats the runExclusive admission check, and computeUploadHash and extractTarInstallableArtifact already honor the signal), so keeping admission and the registration handoff would be enough, and the narration comments could go; DAEMON_HTTP_REQUEST_TIMEOUT_MS (http-server.ts:88) and UPLOAD_TRANSFER_AGGREGATE_TIMEOUT_MS are two literals for one limit, so exporting the aggregate and deriving requestTimeout from it (or asserting the order in a test) would link them; and the PR body still names a9aec49 and 13 files, while the head is 63c5d0d with 14 files and later production changes.

The open thread on the unlinked timeout literals does not apply as written: the aggregate usually fires before requestTimeout, and the typed reason does not reach the client either way, so please resolve it and use the note above for the link. The rmSync thread (here) was withdrawn correctly because the directory is not registered yet at that point. The isGenericAbortError thread (here) is fixed in a69fb5e, so those two can be resolved too.

How the 600 s per-request budget composes with the proxy route stays with #4441. The Node requestTimeout timing above follows Node 22 behavior and was not measured here.

thymikee added a commit that referenced this pull request Nov 19, 2026
…s stall and post-body finalize

Add the createDaemonHttpServer loopback regression requested on #4721: with
faked setTimeout and real loopback I/O, a stalled partial PUT sees its
connection close at exactly the 120 s body-inactivity ceiling and the ticket
offset rolls back (a restart from byte 0 completes with 200), then a
finalize whose post-body hash spends >120 s of fake time still succeeds
under the 600 s aggregate, proving bodyComplete() suspends the inactivity
ceiling on the real route. Fails on the base wiring (no 120 s close) and on
a bodyComplete()-less finalize mutation (finalize answers 500
transfer_phase_timeout).

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
@thymikee

Copy link
Copy Markdown
Member Author

Pushed 07e9122cda with the requested loopback proof through createDaemonHttpServer. The stalled PUT stays open at 119,999 ms, closes at 120,000 ms and can retry from offset zero. Finalize still succeeds after 150 seconds of post-body hashing. The test waits for the actual file write and hash read before advancing the fake clock. Removing bodyComplete() changes finalize from HTTP 200 to HTTP 500.

I kept the current ingress owner. The host-kit watchdog would cover inactivity, but the route still needs a separate aggregate timer, request teardown and typed failure mapping. Reusing the completed-write observer would also require generalizing its client request interface to file streams.

All three earlier inline threads are resolved. The three loopback tests, typecheck and focused lint passed. Exact affected validation is queued on the shared lock.

…s stall and post-body finalize

Add the createDaemonHttpServer loopback regression requested on #4721: with
faked setTimeout and real loopback I/O, a stalled partial PUT sees its
connection close at exactly the 120 s body-inactivity ceiling and the ticket
offset rolls back (a restart from byte 0 completes with 200), then a
finalize whose post-body hash spends >120 s of fake time still succeeds
under the 600 s aggregate, proving bodyComplete() suspends the inactivity
ceiling on the real route. Fails on the base wiring (no 120 s close) and on
a bodyComplete()-less finalize mutation (finalize answers 500
transfer_phase_timeout).

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
@thymikee
thymikee force-pushed the t3/ingress-finalization-review-fix branch from 07e9122 to d7e485d Compare November 19, 2026 08:38
@thymikee

Copy link
Copy Markdown
Member Author

The size report was generated for 07e9122cda, whose ancestry included three unrelated Android IME commits. I moved the same loopback test onto the original upload head, 63c5d0d86a. The corrected head, d7e485d4b0, adds only the upload ingress test. CI is running on the corrected head.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks for the update. At d7e485d the loopback proof I asked for is in and fails without the fix, the reuse question has an answer, and the abort-error matching is fixed. All 18 checks pass and there are no conflicts. One defect remains before merge.

The request-body inactivity timer on the two JSON routes can close a request that is still making progress (upload-http.ts:289). Preflight and finalize arm the 120-second timer and read the body with readRestJsonBody, which accumulates chunks without reporting accepted bytes. A valid JSON body that is still arriving at 120 seconds is destroyed as stalled, even if its last chunk arrived 30 seconds earlier. So POST /upload/preflight and POST /upload/finalize can drop a progressing request before the 600-second aggregate deadline. The same body completes on the merge base, which has no 120-second timer on these routes. Please let the bounded body reader report each nonempty chunk after the size check. Then renew the ingress inactivity timer from that callback on both JSON upload routes, and keep the existing bodyComplete call after the read. A loopback test that sends a JSON body in slow chunks across the 120-second mark and still gets a 200 would prove it.

Could upload-ingress.ts own the per-request aggregate and the HTTP teardown, and delegate body-phase timing and its typed reason to host-kit's createTransferPhaseWatchdog? It would be fed from the existing bounded JSON reader and the two file writers. All four routes mark body completion, and only the two file routes report progress.

The open inline thread on the abort cleanup near upload-http.ts:274 can be resolved: that rmSync runs only before artifact registration, so it cannot remove a finalized artifact (#4721 (comment)). The thread on isGenericAbortError can be resolved: it now matches only the error name or code, fixed in a69fb5e (#4721 (comment)). The thread on http-server.ts:88 can be resolved: the 600-second ingress aggregate is armed at the request callback and normally fires first, and neither typed reason reaches the client (#4721 (comment)).

Not blocking: The new loopback test arms the admission timer and the post-write re-arm at the same fake time, so it would not catch a route that drops onAcceptedBytes to onAcceptedBodyBytes (upload-http.ts:199). Renewal is covered only at unit level in upload-ingress.test.ts:50. The single-shot POST /upload onBodyComplete wiring has no loopback proof either. How the 600-second budget composes with the proxy route stays with #4441.

@thymikee

Copy link
Copy Markdown
Member Author

Pushed 142a2c93bb. The bounded JSON reader reports nonempty chunks after the byte-limit check, and preflight and finalize renew their inactivity timers from that callback. Both still stop the inactivity timer at body completion. The loopback test sends each JSON body over 180 seconds with 90-second gaps. Both routes return HTTP 200. Removing either callback closes that request before the last chunk. All 61 focused tests and the release-tag wire check passed.

The shared phase watchdog could own the 120-second phase and its typed reason. All four routes now have a progress signal that can call touchBody(), and completion can call suspend(). The ingress owner would still hold the 600-second timer and use the combined abort signal to destroy the request and tear down on disconnect, while preserving the first typed failure. I kept that refactor separate from the progress fix.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The earlier JSON-route finding from d7e485d (#4721 (comment)) is fixed at 142a2c9: bounded JSON reads now renew the request-body deadline, and a loopback regression covers that route. No new code problems were found, and an independent check confirmed the new test exercises the real routes. CI is green, with 17 of 17 checks passing on 142a2c9, and there are no conflicts. Nothing else from this review must happen before merge.

Not blocking, and you can take or leave it: armInactivity in upload-ingress.ts repeats the resettable request-body deadline and transfer_phase_timeout reason that createTransferPhaseWatchdog already provides. Could upload-ingress.ts keep ownership of the per-request aggregate and HTTP teardown, and use host-kit transport's createTransferPhaseWatchdog for the request-body inactivity phase, with both bounded JSON reads and successful file writes feeding its progress hook?

Of the three open inline threads, the abort-cleanup rmSync thread (#4721 (comment)) does not apply: that call runs only before artifact registration, so it cannot remove a finalized artifact. The isGenericAbortError thread (#4721 (comment)) is fixed in a69fb5e and still holds at head, so you can resolve it. The http-server.ts:88 thread (#4721 (comment)) does not apply: the 600 s ingress aggregate normally fires before the server requestTimeout, and neither typed reason reaches the client.

@thymikee

Copy link
Copy Markdown
Member Author

An independent second pass over 142a2c9 found four cancellation and timeout gaps on the upload routes. Remote clients can reach these routes, so please fix them before merge, even though each needs specific timing.

  1. A cancelled tar extraction can produce an unhandled rejection (archive-extraction-tar.ts:36). If an app-bundle upload times out or disconnects while extraction awaits an entry's filesystem operation (:52), the signal can reject the tar pipeline before that operation returns. That promise has no handler until the entry loop exits (:55-58). The daemon treats an unhandled rejection as fatal (src/daemon.ts:59), so a cancelled upload can shut the daemon down before cleanup finishes. Please observe the pipeline outcome as soon as it starts, in both inspection and extraction. On failure, join the pipeline and the current entry, and keep the original typed cancellation reason.

  2. A queued finalize can wait past its aggregate deadline (resumable-upload.ts:274). A finalize whose body is already read waits on entry.tail behind active work on the ticket, and its signal is checked only after that tail settles. Destroying the already-consumed request (upload-ingress.ts:74) neither closes the response nor releases the wait. A disconnected waiter is held the same way, and queued PUTs omit the admission signal entirely (:116). Please make ticket admission abortable for both PUT and finalize. Release an expired or disconnected waiter without waiting for a predecessor it doesn't own, keep serialization intact, and still clean up any work the request started.

  3. A resumable chunk can advance its offset after cancellation (resumable-upload-transfer.ts:67). After the append pipeline closes, the final stat runs outside the rollback block. A disconnect or deadline during that stat still returns the new offset and refreshes the ticket (resumable-upload.ts:130). The next request then sees bytes from a chunk whose handler was cancelled before it committed. Please keep the final offset check and the cancellation check inside the rollback boundary, or derive the offset from the joined writer and the validated byte count. Check cancellation before committing the offset and refreshing the ticket.

  4. An early response can leave the request body outside the ingress budget (upload-http.ts:217). A PUT with an offset mismatch answers 308 without reading its body, and header or auth refusals can also answer early. Each route then disposes its timers. On a keep-alive connection, Node drains the unread body under its own coarse request timeout, so a slowly sent discarded body can outlive the 600 s deadline. Please close the connection after an early response to an unfinished body, keep the ingress timer able to close it while the response is pending, and preserve the 308 and its offset headers.

Not blocking, take or leave:

  • At resumable-upload.ts:125 each write refreshes the five-minute ticket before the chunk is validated, so a run of failed chunks can keep a ticket alive.
  • The authorization hook (http-authorization.ts:188) is awaited without the ingress signal.
  • Archive entry names are kept without a cumulative metadata cap (archive-extraction-tar.ts:90).
  • At upload-http.ts:272 a failed cleanup of an unregistered directory is dropped in favor of the abort. Record the cleanup failure while keeping the cancellation reason.

The JSON-route fix from the last review holds, and CI is green at 142a2c9.

… routes

- Observe the tar pipeline outcome at once and keep the typed cancellation reason.
- Make ticket admission abortable for PUT and finalize without breaking serialization.
- Keep the final chunk offset check inside the rollback boundary.
- Close the connection after an early answer to an unfinished request body.
@thymikee

thymikee commented Nov 19, 2026 •

Copy link
Copy Markdown
Member Author

Fixes for the four gaps in the second-pass review. Head: 5455fedf89.

The tests are in e42492db98. Each test failed on 142a2c9 for the stated reason. Then the fix went in fd71357cae.

  1. Tar cancellation. The tar pipeline outcome now has a handler from the start, in inspection and in extraction. A cancelled walk reports the signal's typed reason. A classified archive error stays as it is.
    Test: archive-extraction-tar.test.ts › "a tar extraction cancelled during an entry filesystem operation…". On 142a2c9, an unhandledRejection fired with the AbortError.
  2. Queued admission. PUT and finalize admission now stop when the request's signal aborts (deadline or disconnect). The waiter leaves the queue with the typed reason. Its listener is removed. The next waiter still waits for both the predecessor and the released operation, so serialization stays intact.
    Tests: loopback upload-http-ingress.test.ts › "a finalize queued behind a held ticket answers at its own deadline". This test returns 500 with transfer_ingress_deadline_exceeded at 600 s. On 142a2c9, no response came. Unit resumable-upload.test.ts › "an aborted queued PUT releases at once…". This test gives request_canceled at once, and the finalize queued after it still waits.
  3. Chunk offset. The final stat and a last cancellation check now run inside the rollback scope. A cancelled chunk rolls back and does not change the committed offset or the ticket timer.
    Test: resumable-upload.test.ts › "a chunk cancelled during its final offset check…". On 142a2c9, the chunk resolved with offset 4 and did not reject.
  4. Early answer. If the body is unread, a 308 or an error answer now sends Connection: close. Each route closes the socket after the answer flushes, and that includes authorization refusals. The ingress timers stop when the socket closes. They do not stop at the end of the handler. The 308 range and x-upload-offset headers did not change.
    Test: loopback upload-http-ingress.test.ts › "an early answer to an unfinished body closes the connection…". This test covers a 308 offset mismatch and a 401. On 142a2c9, the keep-alive socket stayed open.

The four route digests changed, so ledger.json has new acks for them (5455fedf89). The status codes, headers, and bodies did not change.

Validation: pnpm check:affected --run passed at 5455fedf89 with exactCommit=true. I did not take the non-blocking notes in this round.

… pass the ingress signal to authorization

- A per-socket close owner lingers while any request on the socket has an unread
  body; requests only register their interest, so a pipelined upload no longer
  restores the hard close under a later 308.
- The tar entry writer checks the signal after each filesystem await and runs its
  pipeline under it, so no writer opens after cancellation.
- Upload authorization and the auth hook context get the ingress signal; the hook
  await stops with the typed reason and a late result is not applied.
@thymikee

Copy link
Copy Markdown
Member Author

This round fixes the two Sentinel minor findings and the three gaps from the review at 4130732. Head: f9628fbd1d.

Each new test failed on the 4130732 production code for its stated reason. Each one passes now.

  1. Abort classification (r4622377722) (a87cd8037b). resolveIngressFailure uses only the signal state. If the signal is aborted, its typed reason replaces every failure that is not an AppError. An earlier AppError stays. The name and code check is removed.
    Test: upload-ingress.test.ts › "resolveIngressFailure lets the aborted signal own every unclassified failure, whatever its name". On 4130732, an error with no abort marker came back as the raw error.
  2. Socket ceiling order (r4629041193) (a87cd8037b). requestTimeout is now UPLOAD_TRANSFER_AGGREGATE_TIMEOUT_MS plus a named 30 s margin. The aggregate constant has one owner.
    Test: http-server-ingress-limits.test.ts checks requestTimeout > aggregate. On 4130732, both values were 600,000.
  3. Pipelined 308 (f9628fbd1d). Each socket now has one close owner. While any request on the socket still has an unread body, the owner only half-closes. Requests only register their interest, and no request restores the original close.
    Test: upload-http-socket-ownership.test.ts › "the second of two pipelined uploads reads its early 308 while it is still streaming". The test sends two PUTs on one raw keep-alive socket. The second PUT keeps sending 16 MiB after its 308 arrives, for 20 attempts. On 4130732, it failed with write EPIPE. When I removed only the restore call on 4130732, the test passed, so the restore was the cause.
  4. Tar entry writer (f9628fbd1d). The entry writer checks the signal after the parent mkdir. The entry pipeline runs under the signal and joins its writer before it settles. createExtractedDirectory checks the signal between its mutations.
    Test: the held-mkdir test in archive-extraction-tar.test.ts now also asserts that the output root is empty after the typed rejection, and that no unhandledRejection fired. On 4130732, payload.bin was there.
  5. Authorization signal (f9628fbd1d). AuxiliaryHttpAuthorizer gets signal, and all four routes pass ingress.signal. authorizeAuxiliaryHttpRequest passes the signal to the hook context (HttpAuthHookContext.signal). The await stops with the typed reason. A late result is not applied (signal.throwIfAborted() runs after the hook). The abandoned hook promise has a handler attached. security-trust.md documents the new field.
    Tests: upload-http-socket-ownership.test.ts › "a held auth hook sees the upload ingress deadline through its signal" (transfer_phase_timeout at 120 s) and "… a client disconnect …" (request_canceled). In both tests, the hook never resolves. On 4130732, the hook got no signal.

The wire ledger has new digests and acks for the four upload routes, AuxiliaryHttpAuthorizer, authorizeAuxiliaryHttpRequest, and HttpAuthHookContext. No request, response, or status framing changed. I also narrowed the ingress doc to "answers sent before the body is consumed", as the review suggested. I did not change transferPhase.

Validation: pnpm check:affected --run passed at f9628fbd1d with exactCommit=true. It ran format, lint, typecheck, layering, fallow, build, vitest-related, unit, daemon-wire-compat, docs-links, and docs-prose. I answered and resolved both Sentinel threads. No review threads are open.

@thymikee

Copy link
Copy Markdown
Member Author

I reran the live 308 test on head f9628fbd1d. This run covers that head. I built from a clean checkout and used the same setup: a real daemon and agent-device proxy from the branch CLI, a 64 MiB file, and 1 MiB already stored on the server before each run.

The single-request test uses the real client streamFileToHttpRequest. Each run sends a PUT from offset 0, gets a 308 mid-stream, and resumes. 20 runs went direct and 20 went through the proxy:

     20 direct requests=2 putRequests=2 socketErrors=0 resets=0 attemptOffsets=[0,1048576] finalize=200
     20 proxy requests=2 putRequests=2 socketErrors=0 resets=0 attemptOffsets=[0,1048576] finalize=200

The pipelined test sends two PUTs on one keep-alive socket: #1 is a valid 1 MiB chunk, and #2 is a chunked PUT from offset 0. The client keeps sending 16 MiB after #2's 308, and then resumes with a ranged PUT:

[pipelined-direct-1] +   58ms <- #1 308 x-upload-offset=1048576 connection=-
[pipelined-direct-1] +   58ms <- #2 308 x-upload-offset=1048576 connection=close
[pipelined-direct-1] +   58ms client sent 16777216 body bytes after the second answer; socket closed cleanly
[pipelined-direct-1] +  194ms -> #3 PUT content-range=bytes 1048576-67108863/67108864 <- 200
     20 pipelined-direct SUMMARY pipelined puts=3 answers=308@1048576,308@1048576 resumeOffset=1048576 resets=0 finalize=200
     20 pipelined-proxy socket error EPIPE

Pipelined through the proxy fails, and the cause is in the proxy. The same failure occurs before this PR. With the pre-PR merge base 6e18ea3 as both proxy and daemon, the result is the same (5 base-pipelined-proxy socket error EPIPE). The proxy sends no answer at all, not even #1's. This PR does not change packages/proxy. Two pipelined GETs and two pipelined Content-Length PUTs through the proxy each get both answers, so only a streaming pipelined body stalls in the proxy. In the direct runs at the base, the leftover body bytes are read as a third request (400). At this head, the half-close ends the connection cleanly.

The raw logs are in .tmp/live-4721/f9628fb/, with tokens redacted. The proxy and both daemons are stopped. I made no code changes.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

At f9628fb the three gaps from the earlier review are fixed and covered by tests. CI is green (18 checks) and there are no conflicts. A second, independent correctness pass over the upload routes found four more timing gaps, each reproduced with a scaled loopback or in-memory probe against the head's ingress owner. These routes are reachable by remote clients, so they need fixing before merge.

  1. Node can time out a progressing body before the upload owner does. The native request timeout at http-server.ts:91 is the aggregate plus 30 s, but Node starts that clock when the parser starts the message, while the upload owner starts after headers. Node checks header expiry only at its connectionsCheckingInterval, so a header block can take longer than 30 s and still reach the callback. A request-timeout poll after 630 s from message start but before 600 s from admission then sends 408 or closes the socket, and the ingress sees a disconnect. The configuration test compares durations, not start times. Please derive the native ceiling from the aggregate plus a bound on pre-admission header time that includes Node's polling, or have one owner enforce header and upload budgets on a shared clock. Add a loopback case with slow headers and a progressing body.
  2. A queued 308 can time out and close a different in-budget upload. On a keep-alive socket, pipeline a complete finalize for ticket A and a stale-offset PUT for ticket B with an unfinished body. If A's post-body hash takes longer than 120 s, B's 308 queues behind A, and B's dispose (upload-ingress.ts:98) leaves its inactivity timer armed while waiting for finish. That timer destroys the shared socket before either response flushes and cancels A, which still had time left. The two-PUT test covers only the case where the first upload finishes promptly. Please tie pipelined admission and timeout handling to response order, so a later request cannot destroy an earlier in-budget response, and cover a 308 queued behind post-body work longer than the inactivity ceiling.
  3. A timeout does not end the exchange once Node has finished reading the request. After normal EOF, a single POST or resumable PUT can still be waiting on a file write callback. The inactivity timer aborts the pipeline, but req.destroy(error) at upload-ingress.ts:110 does nothing on a finished request, and the file stream waits for the pending write before closing. The client stays connected and the handler stays pending until the write settles. The aggregate has the same gap during a completed finalize whose hash read, rename or cleanup is still pending. Please make the timeout end the HTTP exchange regardless of IncomingMessage state: send a typed terminal response when it is safe to write, otherwise close the connection. Keep owning the in-flight filesystem operation through cleanup or rollback, and test the client outcome with the write callback held.
  4. An overdue deadline can be cleared after a successful registration. Registration and the final resumable offset check (upload-http.ts:276) look only at signal.aborted. If a filesystem completion or a synchronous filesystem call crosses the deadline before the timer callback runs, the continuation publishes success and dispose clears the overdue timer. Late accepted-byte progress can likewise replace an overdue inactivity timer. Please record monotonic aggregate and inactivity deadlines at admission, and check elapsed time before renewing on progress, committing a chunk offset, creating a preflight ticket, or registering an artifact, with the same expiry reason and cleanup as the timer path.

Not blocking: the tar regression at archive-extraction-tar.test.ts:35 covers cancellation before the writer opens, not with a write already in flight. The held-hook tests in upload-http-socket-ownership.test.ts assert the signal fires but not that the route's wait settles. The comment in http-server.ts:86 says the upload owner answers an expired body with a typed reason, but for an unfinished body it destroys the socket. The ledger rationale at ledger.json:571 still says "30s/600s header and body ceilings" instead of the derived request ceiling.

These hold at this head: all four routes arm one ingress owner at admission; accepted bytes renew inactivity and body completion disarms it; byte caps are fixed and PUT ranges stay within the preflight size; ordinary cancellation joins the pipeline, restores the PUT's pre-chunk size and removes unregistered directories. The four earlier inline threads are settled and can be resolved: r4622377719, r4622377722, r4628305643, r4629041193.

…rded deadlines

- One ingress budget owner derives the native request ceiling from the header
  ceiling, the connections-checking interval, the upload aggregate and a margin,
  so Node never closes a progressing upload body before its owner does.
- Expiry ends the exchange whatever the request stream state: a typed answer
  when none started, and a connection close only after this request's own answer
  flushes, so a queued pipelined request never closes the socket under an earlier
  answer. The handler keeps owning its filesystem work through rollback.
- Aggregate and inactivity deadlines are recorded on the monotonic clock and
  checked before progress renewal, chunk offset commit, ticket creation, finalize
  steps and artifact registration, with the same typed expiry as the timers.
@thymikee

Copy link
Copy Markdown
Member Author

This round answers the review at f9628fb. Head: 267495c2cb.

Each item has a test that failed on the f9628fb production code. The red run is saved locally in the validation checkout.

  1. Node can time out before the upload owner. The new http/ingress-budget.ts is the one owner of the header ceiling (30 s), the connections-checking interval (now 5 s, set explicitly), the upload aggregate (600 s) and a 30 s margin. requestTimeoutBehindUploads adds all four, so the native request ceiling is 665 s. It covers the worst admitted header time plus one polling interval before the 600 s from admission.
    • Test: http-server-ingress-limits.test.ts checks requestTimeout > headersTimeout + connectionsCheckingInterval + aggregate. On f9628fb this failed (630,000 vs 660,000).
    • Test: the new http-server-slow-headers.test.ts scales the owner module (400 ms headers, 200 ms polling, 1000 ms aggregate) and uses real Node timers. Slow headers and a progressing body get the owner's 500 transfer_ingress_deadline_exceeded. If the formula drops the header and polling terms, Node closes the request first, and the test failed 3 of 3 times.
  2. A queued 308 closes the socket under another upload. On expiry, the ingress now closes an unread-body connection only after this request's own answer flushes. Node writes answers in order, so a queued request never closes the socket under an earlier answer that is still owned.
    • Test: upload-http-deadline.test.ts › "a queued 308 behind a long finalize never closes the socket under the earlier answer". A pipelined finalize A has its hash held past 150 s. A stale-offset PUT B with an unfinished body comes after it. The socket survives, and A gets 200 before B gets 308. On f9628fb, the socket was destroyed.
  3. A timeout does not end a finished request. Expiry now ends the exchange whatever the state of the request stream: it sends a typed answer if no answer has started, otherwise it closes the connection in response order. The handler keeps owning the file write and rolls back when the write settles. Route failure answers are skipped once the ingress has answered.
    • Test: "a timeout ends the exchange with a typed answer while a chunk write is still pending". The write callback is held after EOF, and the client gets 500 transfer_phase_timeout at 120 s. When the write is released, the chunk rolls back, and a retry from offset 0 gets 200. On f9628fb, no answer came.
  4. A deadline can pass without being enforced. The aggregate and inactivity deadlines are recorded on performance.now() at admission. ingress.ensureActive() expires an overdue request through the same path as its timer. The checks run before progress renewal, chunk offset commit (inside rollback), preflight ticket creation, each finalize step, and artifact registration (which removes the unregistered directory). dispose() does not clear an overdue deadline.
    • Test: "a finalize whose hash crosses the deadline never publishes success". The clock jumps 600 s inside the held hash read, and the answer is 500 transfer_ingress_deadline_exceeded. On f9628fb, the answer was 200.
    • Test: upload-ingress.test.ts › "late progress after an overdue inactivity ceiling expires instead of renewing it". On f9628fb, the progress renewed the ceiling.

Recommended items (done):

  • A new tar test cancels with an entry write in flight. It asserts that the extraction waits for that write, gives the typed reason, leaves no stray file after cleanup, and fires no unhandled rejection.
  • The held-hook deadline test now asserts that the exchange ends with 500 transfer_phase_timeout.
  • The inaccurate http-server.ts comment is gone; ingress-budget.ts now explains the derivation. The ledger.json rationale now names the derived ceiling and no longer says "30s/600s".
  • The four upload routes share runUploadRoute and authorizeUpload. Fallow had flagged their duplicated setup. authorizeUpload is listed in the wire surface.
  • The ledger has new digests and acks. No request, response or status framing changed.

Security pass:

  • Slow headers: each connection's header phase is bounded at about 35 s (30 s ceiling plus 5 s polling). The native ceiling is 665 s from message start.
  • Slow bodies: accepted bytes renew the 120 s inactivity ceiling, and an overdue ceiling is not renewed. The 600 s aggregate starts at admission and progress never renews it. Byte caps did not change.
  • Socket ownership with pipelined requests: each socket has one close owner, so a request does not restore or hard-close another request's linger. An expired queued request closes the socket only after its own answer.
  • Late success after a deadline: nothing commits or publishes after a recorded deadline passes, even before the timer callback runs. An expired exchange gets the typed answer once, and later handler writes are skipped, so a double write cannot become an unhandled rejection.
  • Residual: a client can pipeline many requests behind one long finalize. Each queued request stays bounded by its own budget, and the socket closes no later than the earlier answer's own 600 s aggregate. The connection count is not capped; that limit existed before this PR and is out of scope here.

Live 308 rerun at 267495c2cb:

     20 direct requests=2 putRequests=2 socketErrors=0 resets=0 attemptOffsets=[0,1048576] finalize=200
     20 proxy requests=2 putRequests=2 socketErrors=0 resets=0 attemptOffsets=[0,1048576] finalize=200
     20 pipelined-direct SUMMARY pipelined puts=3 answers=308@1048576,308@1048576 resumeOffset=1048576 resets=0 finalize=200

In every pipelined run, the client sent 16 MiB after the second 308 and the socket closed cleanly. I did not run pipelined through the proxy, because it fails before this PR too (see the earlier comment). The proxy and the daemon are stopped.

The four settled threads (r4622377719, r4622377722, r4628305643, r4629041193) were already resolved.

Validation: pnpm check:affected --run passed at 267495c2cb with exactCommit=true. It ran format, lint, typecheck, layering, fallow, build, vitest-related, unit, daemon-wire-compat, docs-links, and docs-prose. The first unit run had two 5 s timeouts under load (daemon-entrypoint.test.ts, macos-helper-package-contents.test.ts). Both pass in isolation in under 1 s, and the rerun passed.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

At 267495c the four gaps from the previous review have targeted regressions: slow headers at the native server boundary, a held finalize answered before the queued 308, a typed timeout before a pending final write is released, and recorded deadlines checked at the success boundaries. Transfer caps and ordinary cancellation ownership hold. A second, independent correctness pass still found four more ways to commit after a deadline, each reproduced with a scaled clock probe, so no label yet.

Three of them share one shape: a deadline that has passed but whose timer callback has not run yet is missed at the point where something becomes externally visible.

  • Body completion. upload-ingress.ts:165: if a chunked terminator, or a final file-stream close, is processed after 120 s without accepted bytes and before the timer fires, bodyComplete drops the inactivity deadline and the next ensureActive allows success.
  • Preflight. upload-http.ts:175 checks the deadline before beginResumableUpload, whose synchronous mkdtemp and writeFile can cross 600 s, then commits a 200 and leaves the new ticket live.
  • Ignored PUT. resumable-upload-transfer.ts:25: if the initial payload stat finishes after a deadline, a mismatched-range or un-ranged retry returns the offset and a 308 goes out before dispose sees the expiry.

Rather than add a check at each site, please make the ingress owner the only way to commit: one owner.commit(fn) (or similar) that compares the recorded monotonic deadlines before it sends a response, publishes a ticket, registers an artifact or clears a deadline, and otherwise runs the shared expiry and rollback path. Then any new commit point is covered by construction. Preflight also needs a provisional-ticket cleanup path, so an expired preflight removes its new directory while keeping an existing ticket returned for the same attempt.

The fourth is different:

  • Ticket expiry closes an earlier response. resumable-upload.ts:272: a finalize is hashing while a valid PUT for a nearly expired ticket is pipelined behind it, waiting for its first accepted write. The ticket's idle timer can fire first, and expireEntry destroys the IncomingMessage directly. Node then destroys the shared socket, and the earlier in-budget finalize loses its response. Please signal the active PUT with RESOURCE_EXPIRED through its request owner instead, keep ticket invalidation and the joined rollback, and let the ingress owner end the exchange in response order. The existing queued-308 test uses an ignored PUT that has already released activeReceive, so add a case with a held first write on a nearly expired ticket behind a held finalize.

Please cover each with a clock-driven test that holds the timer callbacks.

Not blocking:

  • resumable-upload.ts:129 renews the ticket idle timer before onAcceptedBodyBytes checks the request deadline, so an overdue write that ingress then rejects still extends the ticket. Renewing after the check, or through the same commit path, closes it.
  • Node's header timeout (http-server.ts:254) still closes the shared socket when a later pipelined header block expires before admission. That is pre-admission and socket-wide by design, so a note in the code is enough.

@thymikee

Copy link
Copy Markdown
Member Author

Two more items at 267495c, from the line-by-line review that finished after the comment above:

  1. An expired request can reset the socket under an earlier answer. On expiry with an unread body, endExchange (upload-ingress.ts:209) calls req.destroy right after the response's finish. IncomingMessage._destroy then destroys the socket outright and skips the lingering half-close that holdLingeringClose and socketCloseOwner provide. With a pipelined B released after an early 308 while the client is still sending, B's unread bytes are still in the kernel buffer, so the close sends an RST microseconds after A's 200 and B's 308 were written. As this file's own comment (lines 63-67) says, a still-sending client then loses the answer, so an in-budget finalize can register its artifact while the client never reads its 200. It needs pipelining, a finalize longer than 120 s and a client still sending, so it is narrow, but it is the same response-order rule as the ticket-expiry item above. Once this request's answer has flushed, leave the unread-body socket to the existing close owner's lingering close (socket.destroySoon through socketCloseOwner), bounded by a short grace timer. With the single owner.commit path suggested above, that close can live in the same place.
  2. Two commit-point checks have no test. Only the finalize hash test and the progress-renewal unit test skew performance.now. Deleting the recorded-deadline check before the chunk offset commit (resumable-upload-transfer.ts:66), the one before preflight ticket creation (upload-http.ts:174), or the overdue branch in dispose (upload-ingress.ts:111-117) leaves the suite green. One skewed-clock case per commit point, following the finalize test's pattern, would pin them.

…d end ticket expiry in response order

- The ingress owner's commit() is the only way to answer, publish a ticket,
  register an artifact, commit a chunk offset or clear a deadline. It compares
  the recorded monotonic deadlines first and runs the shared expiry path when one
  passed before its timer callback ran.
- A preflight ticket is provisional until its answer commits; a refused commit
  removes the new ticket and keeps an existing one for the same attempt.
- Ticket expiry aborts the active receive through its own controller, and the
  chunk pipeline no longer owns the request stream, so a pipelined socket is
  never closed under an earlier answer.
- An expired request with an unread body hands the socket to its close owner's
  lingering close after its own answer flushes, bounded by a short grace.
- The ticket idle timer renews only after the request deadline check.
@thymikee

Copy link
Copy Markdown
Member Author

This round answers the review at 267495c and its addendum. Head: bea8886ff4.

The ingress owner is now the only committer. UploadTransferIngress.commit(work) first compares the recorded monotonic deadlines. If one has passed before its timer callback ran, it runs the shared expiry path and refuses the work with the typed expiry. These all go through it: every success answer (preflight 200, PUT 200 and 308, finalize and upload 200), ticket publish, artifact registration, the chunk offset commit (inside rollback), each finalize step, and bodyComplete (which clears a deadline). dispose keeps its overdue branch. I swept for other commit points: only failure answers and authorization refusals remain outside commit, and they publish no work.

Each item has a test that failed on the 267495c production code. On each line below, the part in parentheses is the result on 267495c.

Item Fix Test (on 267495c)
Body completion bodyComplete commits through commit and throws the typed expiry when the deadline is overdue upload-ingress.test.ts › "body completion after an overdue inactivity ceiling expires instead of clearing it" (no exception)
Preflight after the synchronous mkdtemp A new ticket stays provisional until its 200 commits. A refused commit removes the new ticket and its directory. An existing ticket for the same attempt is kept. upload-http-deadline.test.ts › "a preflight whose ticket creation crosses the deadline …" (200, ticket kept)
Ignored PUT 308 after a late stat The 308 commits through commit "an ignored PUT whose offset check crosses the deadline answers the expiry, not a 308" (308)
Ticket expiry under a pipelined PUT expireEntry aborts the active receive through its own controller with RESOURCE_EXPIRED. The chunk pipeline no longer owns the request stream: it reads the body through a forwarder, so an abort never destroys the request. Ticket invalidation and the joined rollback did not change. "a ticket expiring under a held first write never closes the socket under an earlier finalize". A held finalize hash, a held first write, and a ticket 1 s from expiry give A 200, then B 404 RESOURCE_EXPIRED (socket destroyed)
Expired unread body resets an earlier answer (addendum 1) After this request's own answer flushes, endExchange hands the socket to the close owner's lingering close (destroySoon), discards the rest of the body, and bounds the wait with a 5 s grace. It no longer calls req.destroy. "an expired queued request with an unread body never resets the earlier answer". The client keeps sending 8 MiB after B expires, and reads 200, 308 before a clean close, for 5 attempts (write EPIPE)

Addendum 2, coverage for the existing commit points. These checks already existed at 267495c, so the tests pass there. I removed each check at the new head, and each test then failed:

  • Chunk offset commit: "a chunk whose final offset check crosses the deadline rolls back instead of committing".
  • Preflight ticket creation: "a preflight whose body completes past the deadline creates no ticket". The ticket count stays 0. The gate is the bodyComplete commit in the same turn, so I removed the separate pre-creation check.
  • dispose overdue branch: upload-ingress.test.ts › "a release after an overdue aggregate expires the request instead of clearing it".

Recommended items (done):

  • The ticket idle timer now renews only after the request's own deadline check. An overdue write that the ingress rejects no longer extends the ticket.
  • http-server.ts has a note: Node's header timeout acts before admission and per socket, so it closes the whole socket by design.

Security pass:

  • Late success: no answer, ticket, registration, offset or deadline clear happens after a recorded deadline, even before the timer callback runs. A refused preflight leaves no new ticket behind.
  • Socket ownership: three things can end a connection: the close owner's lingering close, an expired request's grace timer, and Node's own pre-admission ceilings. Ticket expiry and pipeline aborts no longer destroy a request. A queued request never closes the socket before its own answer flushes, so an earlier answer is not cut off.
  • Slow bodies after expiry: the remaining body is discarded for at most 5 s after the answer, and then the socket closes.
  • Behavior change: after a pipeline failure (limiter overflow or expiry), the request body is drained through the lingering close and not reset. The client now reads the typed answer.
  • Residual risks did not change: the header phase is about 35 s per connection, the connection count is uncapped (as before this PR), and a pipelined streaming PUT through agent-device proxy fails before this PR too.

Live 308 rerun at bea8886ff4:

     20 direct requests=2 putRequests=2 socketErrors=0 resets=0 attemptOffsets=[0,1048576] finalize=200
     20 proxy requests=2 putRequests=2 socketErrors=0 resets=0 attemptOffsets=[0,1048576] finalize=200
     20 pipelined-direct SUMMARY pipelined puts=3 answers=308@1048576,308@1048576 resumeOffset=1048576 resets=0 finalize=200

In every pipelined run, the client sent 16 MiB after the second 308 and the socket closed cleanly. The proxy and the daemon are stopped.

The wire ledger has new digests and acks for the four route handlers and sendUploadedArtifactResponse. Status codes, headers and bodies did not change.

Validation: pnpm check:affected --run passed at bea8886ff4 with exactCommit=true. It ran format, lint, typecheck, layering, fallow, build, vitest-related, unit, daemon-wire-compat, docs-links, and docs-prose.

@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 bea8886. The verdict and the full list are in the summary comment.

Comment thread packages/daemon/src/server/upload.ts Resolved
@thymikee

Copy link
Copy Markdown
Member Author

At bea8886 every change asked for since 267495c is in, each with a clock-driven test that fails without it: one owner check of the recorded deadlines before anything becomes visible, provisional-ticket cleanup, ticket expiry reported through the request in response order, and the lingering close on the resumable path. No success answer or ticket is published outside that check. CI is green.

A second, independent correctness pass found one remaining gap, on the route the resumable work did not touch, so no label yet:

Single-shot POST /upload still resets the connection when an upload is cut off mid-body. receiveUploadBody hands req straight to pipeline (upload.ts:111). When the 600 s deadline, the 120 s inactivity timer or a disconnect ends the exchange, Node destroys the request and detaches its socket, so lingerThenClose returns early with no socket and the request's close frees the socket's close owner at once. The socket closes while the client is still sending: a scaled reproduction of the ingress driven the way receiveUploadBody drives it got ECONNRESET or EPIPE in 4 of 5 runs. On loopback the answer still arrived first, but over a real network a reset can lose it, which is exactly what the ingress comment says must not happen. The upload client still uses this route as its fallback. Please feed the request through forwardRequestBody, as the resumable PUT path already does, and add a test where the client keeps streaming through the deadline and expects the typed answer and a clean close. This also settles the open thread at upload.ts:111.

Not blocking:

  • When forwardRequestBody stops for a reason the ingress does not own (byte-limit overflow, a content-range or length mismatch, an expired ticket), req stays paused with its body unread, and the unread-body branch in dispose waits for the 120 s inactivity timer. Calling the same lingerThenClose there would bound it.
  • answerUploadFailure (upload-http.ts:280) and the auth-hook rejection (http-authorization.ts:207-212) answer without the deadline check, so a hash mismatch found just past the deadline returns 400 instead of the deadline error. Nothing is registered, so only the reported reason is off.
  • The 308/200 answer is re-checked at upload-http.ts:204 microseconds after the offset is saved; crossing the deadline there gives an error but keeps the bytes. State stays consistent and the next PUT corrects the offset.
  • An auth hook slower than 120 s is reported as "Upload body stalled", which blames the client; a JSON body over 64 KiB gets the same reset on close (this predates the PR).
  • The forwarder comment says a pipeline owning req would close the socket under an earlier answer; on current Node it detaches the socket instead, so the real job of the forwarder is keeping req.socket attached for the lingering close. Rewording it that way matches the blocker above.

…ate failure answers

- POST /upload reads its body through the same forwarder as the chunk pipeline
  (pipeRequestBody), so a deadline, an inactivity expiry, a disconnect or a byte
  cap fails the pipeline without destroying the request. The request keeps its
  socket, and the ingress answers and ends the exchange with its lingering close.
- Release of an unread body (a byte cap, a length mismatch, an expired ticket, an
  early answer) uses the same lingering close with its short grace.
- Failure answers and auth-hook or tenant-trust refusals go through the commit
  gate, so a deadline that passed first answers with its own typed expiry.
@thymikee

Copy link
Copy Markdown
Member Author

This round answers Sentinel r4633504073 and the CoS review at bea8886. Head: cdd3c1d791.

The fix is in 69cd253a6a. cdd3c1d791 merges main, because the new v0.21.41 tag made the released-surface gate compare PublishOutcome against code that this branch did not have yet. I merged and did not rebase, so the push stays fast-forward.

Blocker: single-shot POST /upload owns req. The body now goes through the shared pipeRequestBody forwarder. The chunk path uses the same helper. Any cutoff fails the pipeline but keeps req.socket attached, so the ingress answers and ends the exchange with its lingering close.

  • Test: "a single-shot upload that expires mid-body answers a client that is still sending". The client streams through the deadline and reads the typed 500. Then it sends 4 MiB more, and the server half-closes with a FIN and no reset. On bea8886, this got ECONNRESET/EPIPE.
  • Test: "a single-shot upload expiring behind a long finalize never closes the socket under it". The earlier 200 arrives, then B's typed 500. This test also passes on bea8886, because Node does not attach the socket to a queued request.

Recommended items (all done):

  • dispose now uses lingerThenClose for an unread body (a byte cap, a length mismatch, an expired ticket, an early answer). Test: "a chunk refused by its byte cap lingers only for the grace, not the inactivity ceiling". The server connection closes after the 5 s grace. On bea8886, it stayed open until the 120 s ceiling.
  • answerUploadFailure and the auth-hook and tenant-trust refusals now go through commit. A deadline that passed first is reported as itself. Test: "a hash mismatch found past the deadline answers the deadline expiry". On bea8886, the answer was a 400 for the hash mismatch.
  • The forwarder comment now explains its real job: it keeps req.socket attached for the lingering close.

Live at cdd3c1d791:

     20 direct requests=2 putRequests=2 socketErrors=0 resets=0 attemptOffsets=[0,1048576] finalize=200
     20 proxy requests=2 putRequests=2 socketErrors=0 resets=0 attemptOffsets=[0,1048576] finalize=200
     20 pipelined-direct SUMMARY pipelined puts=3 answers=308@1048576,308@1048576 resumeOffset=1048576 resets=0 finalize=200
[stall-direct-1] +120017ms <- HTTP/1.1 500 Internal Server Error
[stall-direct-1] +120018ms <- server FIN (half-close)
[stall-direct-1] +126015ms SUMMARY single-shot-stall status=500 reason=transfer_phase_timeout serverFin=true resets=0 sentAfterStall=4194304
[stall-proxy-1] +120017ms <- HTTP/1.1 500 Internal Server Error
[stall-proxy-1] +131006ms socket error EPIPE

The new single-shot case uses real daemon timers: 64 KiB, a 125 s stall, then 4 MiB more. Direct, the client reads the typed 500, gets a FIN, and sees no reset. Through agent-device proxy, the client also reads the 500. The proxy's own front-end then closes the connection about 6 s after the client resumes sending, which gives EPIPE. This PR does not change the proxy's front-end, so that close is not from this change. The proxy and the daemon are stopped.

Security pass: every upload pipeline now keeps req out of the stream chain. A connection ends only through the close owner's lingering close (with a 5 s grace after the answer) or through Node's pre-admission ceilings. Failure answers and refusals cannot report the wrong reason after a deadline. The other residual items did not change.

The wire ledger has new digests and acks for authorizeAuxiliaryHttpRequest, AuxiliaryHttpAuthorizer and authorizeUpload. Only an optional commit callback was added. No status codes or bodies changed.

Validation: pnpm check:affected --run passed at cdd3c1d791 with exactCommit=true, including daemon-wire-compat against v0.21.41. I answered and resolved the Sentinel thread.

@thymikee

Copy link
Copy Markdown
Member Author

At cdd3c1d the single-shot POST /upload fix is in: the request now goes through pipeRequestBody and stays out of the pipeline, so its socket stays attached for the lingering close. The new test streams through the 600 s deadline and gets the typed answer, more accepted bytes and a clean close with no reset. Failure answers and auth-hook or tenant rejections now pass the deadline check. A second, independent correctness pass re-confirmed both timers on all four routes, cancellation cleanup, finalize bounds and constant-only limits. The line-by-line review has no blocking findings.

One small last item, the same kind of close as the upload fix, so no label yet:

An oversized JSON body on /upload/preflight or /upload/finalize still resets the client. Both routes read the body with for await (const chunk of req) in readNodeHttpRequestBody. When the body passes 64 KiB the throw ends the loop, Node destroys the request and sets req.socket = null, and dispose() then has no socket for the lingering close (upload-ingress.ts:125). A client streaming a large body gets EPIPE instead of the typed 400. This was noted last round as predating the PR. It now sits next to the fixed upload route and is a one-line change: read with req.iterator({ destroyOnReturn: false }) (optionally refusing a declared length over 64 KiB first), and add a test where the client keeps streaming and gets the 400 and a clean close.

Not blocking:

  • answerUploadFailure (upload-http.ts:294) calls commit(() => undefined) as a checkpoint and then sends the answer outside it, while the ingress contract (upload-ingress.ts:36-42) says answers commit through commit(work). Sending inside the commit would match the contract.
  • The test "a single-shot upload expiring behind a long finalize never closes the socket under it" (upload-http-deadline.test.ts:679) also passes on bea8886, because a queued request has no socket attached yet. The new streaming test is the one that guards the fix; this one could go or be reworded.
  • The 665 s request timeout applies to the whole server, so /rpc and other bodies get it too (Node's default was 300 s). The 5 s post-answer grace ends in a hard close by design.

@apex-sentinel-staging

This comment has been minimized.

…ngering close

readNodeHttpRequestBody refuses a declared length over its bound before reading
and reads with req.iterator({ destroyOnReturn: false }), so a refusal no longer
destroys the request and detaches its socket. The upload ingress answers the 400
and ends the exchange with its lingering close. Failure answers now send inside
commit(work), and the pipelined single-shot test is reworded as a guard.
@thymikee

Copy link
Copy Markdown
Member Author

This round answers the review at cdd3c1d. Head: 52e3437eb9.

Oversized JSON body on preflight or finalize. readNodeHttpRequestBody now refuses a declared Content-Length over the bound before it reads any byte. It reads with req.iterator({ destroyOnReturn: false }), so a refusal leaves the request and its socket attached. The upload ingress answers the 400 and ends the exchange with its lingering close: a FIN, then a full close after the 5 s grace.

  • Test: upload-http-deadline.test.ts › "an oversized JSON body on /upload/preflight …" and "… on /upload/finalize …". Each test sends a chunked body with no declared length and keeps sending 2 MiB past the refusal. The client reads the 400, gets a FIN with no reset, and the server closes after the grace. On cdd3c1d, both tests failed: the request was destroyed and its socket detached, and the client's sending stalled.
  • Test: transport.test.ts has a new case: a declared length over the bound is refused before any byte is read. The existing limit case now also asserts that the request is not destroyed.
  • The human-control admin route uses the same reader. After a refusal, Node's keep-alive handling now ends that connection, and the route no longer resets it.

Optional items (both done):

  • answerUploadFailure now sends inside commit(work), as the ingress contract says.
  • The :679 test is renamed to "guard: a single-shot upload expiring behind a long finalize keeps the earlier answer first", with a note in the code. It also passes before the forwarder change, because Node attaches no socket to a queued request. It pins the response order and does not prove the fix. The streaming single-shot test proves the fix.

No wire digest changed. I did not rebase and did not merge main again.

Validation: pnpm check:affected --run passed at 52e3437eb9 with exactCommit=true, including daemon-wire-compat against v0.21.41.

@thymikee

Copy link
Copy Markdown
Member Author

This PR is ready at 52e3437. The last item is fixed: readNodeHttpRequestBody refuses a declared Content-Length over the limit before reading, and otherwise reads with req.iterator({ destroyOnReturn: false }), so refusing a body no longer destroys the request or detaches its socket. On /upload/preflight and /upload/finalize a client that keeps streaming now gets the typed 400 and a clean FIN, and the new test streams 2 MiB past the refusal and checks for the 400, the FIN, no socket errors and no open connections. The line-by-line review is clean, and a second, independent correctness pass found no remaining abrupt close of a socket with unread request bytes on any upload route, apart from the documented 5 s grace close. CI is green.

Not blocking, for a follow-up if you like:

  • The human-control and host-lease PUT routes share the same reader, but their error answers do not set Connection: close. A chunked oversize body now gets the 400 (it used to get a reset with no answer) followed by a reset when the keep-alive timeout fires, and a declared oversize length is read and discarded up to the request timeout instead of stopping early. Both routes check the daemon token before reading, so this is limited to authenticated callers; setting Connection: close on those error answers would match the upload routes.
  • The declared-length refusal is covered only by the host-kit unit test, not on an upload route.
  • The new test's final "no reset" check depends on the server having read every client byte before the grace close, so it could flake under load.
  • readNodeHttpRequestBody is a public host-kit export whose refusal no longer destroys the request; the JSDoc says so, which is enough.

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

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 52e3437

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

No open findings.

Reviewed with this repository's own Sentinel configuration (0b9186494f80).

💬 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
thymikee merged commit 9b0bf9f into main Nov 20, 2026
19 checks passed
@thymikee
thymikee deleted the t3/ingress-finalization-review-fix branch November 20, 2026 07:35
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