Repository navigation
fix: keep a slow first turn frame from tripping a proxy idle timeout - #533
Conversation
/turn wrote nothing until the first real frame, so a middlebox with a 50 s idle timeout (IBM Cloud VPC LB) cut turns whose first frame was slower than that; mocactl rendered it as "cannot reach the harness: fetch failed". harness: makeFrameWriter flushes SSE headers at a first-frame deadline (SH_TURN_STREAM_FIRST_FRAME_FLUSH_MS, default 15000, 0 disables) - the detachable turn's `turn` frame, else a keepalive comment - and arms the heartbeat. Failures faster than the deadline keep their HTTP status; later ones end with a terminal error frame. (Writing the turn frame right after begin() would have dropped the 404/410/503 parity executeTurn failures rely on, so the deadline is used on the detach route too.) mocactl: a connection closed under the request is now connection_dropped, not network_error, with an honest message. On a detachable session a POST cut before any frame attaches by session to follow the running turn, never re-sending the prompt; a finished or already-seen turn is not mistaken for it, and the original error stands when nothing is found. Fixes rossoctl#531 Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Summary
The server half is sound. makeFrameWriter's one-shot timer is cleared by the first real frame and by stop(). It bails on headersSent/writableEnded/destroyed. In handleTurnStream, the !res.headersSent check in the catch runs synchronously after executeTurn rejects, so the timer can't slip between them. The detachable preamble sets started before it emits turn.start, so send can't write the turn frame twice. Frames still in chain are written after the preamble, so ordering holds. The mocactl recovery path never re-sends the prompt, and a turn_not_found/ended/old-turn first frame falls back to the original error, as described. I also checked every network_error consumer on the PR head: isDropped, runAttach's "nothing to show", and classify (which keys on status === 0) all treat connection_dropped like network_error. subagent.ts branches on causeCode, so it isn't affected.
The comments below are non-blocking. One is a transcript-ordering bug in the new recovery path, one is about an error message that is wrong for mid-stream drops, and the rest are docs that still state unconditional status parity.
Not in the diff, so noted here: docs/api/harness-openapi.yaml createTurn (L75-77, and L106-108 "The lazy flush is unchanged … a failure before the first frame is the sync path's status and JSON") and docs/reference/http-api.md §Streaming frames still describe the old behaviour. docs/reference/configuration.md doesn't list SH_TURN_STREAM_FIRST_FRAME_FLUSH_MS (or the existing SH_TURN_STREAM_KEEPALIVE_MS). Also worth a line in the openapi: after the deadline, a 503 that carries Retry-After arrives as an error frame, so mocactl's 503 retry (session-manager.ts:687) no longer applies to it. That should be rare, since selection throws fast, but it's part of the trade-off §3.4 now describes.
Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (knative-server, mocactl), tests, docs
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit, all signed-off: yes
CI status: passing (all checks)
| err instanceof ApiError && | ||
| err.code === 'connection_dropped' | ||
| ) | ||
| return await this.recoverDroppedStart(controller, ids, err); |
There was a problem hiding this comment.
suggestion: on this path the prompt reaches the transcript after the recovered turn. consume → appendFrame writes the turn record and every frame during reattach, and record() (appendPrompt) only runs in runTurn's finally (L707). So the saved transcript reads answer-then-question, and the auto title is derived late. The normal path records on the first frame (L622). Suggest recording when recovery accepts the first turn frame, e.g. an onAccept callback in recovering that the wrapper in attachStream calls before yield. A transcript assertion in the new "attaches by session" test would pin it.
| function describe(err: unknown): string { | ||
| if (err instanceof ApiError) { | ||
| // Reached, then cut: not "cannot reach" (a proxy's idle timeout closes a turn with no output yet). | ||
| if (err.code === 'connection_dropped') |
There was a problem hiding this comment.
suggestion: networkError is also what frames() throws when the body read fails (harness.ts:193), and undici reports a socket closed mid-stream as UND_ERR_SOCKET. So a non-detachable turn cut after frames have shown now reads "dropped before the response began", which is false there. The same applies to attach, cancel and every control-plane call. Suggest dropping "before the response began" (e.g. "the harness closed the connection (a proxy idle timeout?)"), or setting connection_dropped only on the pre-response fetch catch.
| @@ -85,7 +85,9 @@ An unknown `sessionId` or a missing `prompt` still returns a real HTTP `404`/`40 | |||
| body as the non-streaming path — the `200` + SSE headers are only sent once the first frame is ready. | |||
There was a problem hiding this comment.
nit: "the 200 + SSE headers are only sent once the first frame is ready" no longer holds unconditionally. With the new deadline, they go out after 15 s even with no frame, and a failure after that is an error frame. Suggest qualifying this the way §3.4 now does.
| { Authorization: `Bearer ${mint(sessionId)}` }, | ||
| ); | ||
| expect(res.status).toBe(404); | ||
| await new Promise((r) => setTimeout(r, 400)); // a leaked timer would throw on the ended response |
There was a problem hiding this comment.
nit: a leaked timer wouldn't throw here. The callback returns early on res.headersSent || res.writableEnded, so this test passes with or without the clearTimeout. If you want to pin it, spy on res.writeHead/count writes, or use fake timers and assert vi.getTimerCount(). Separately, each test deletes the env var only on success. A failed assertion leaks SH_TURN_STREAM_FIRST_FRAME_FLUSH_MS into later tests, so move the cleanup to an afterEach.
- mocactl: record the prompt when recovery accepts the turn, so the transcript reads question-then-answer; pin it in the test. - mocactl: connection_dropped says "closed the connection (a proxy idle timeout?)", which is also true for a stream cut mid-body, attach, cancel and control-plane calls. - tests: move the flush env cleanup to afterEach; assert the flush timer is actually cleared (verified to fail without the clearTimeout). - docs: qualify the "headers only after the first frame" statements in the README, OpenAPI and http-api reference; list SH_TURN_STREAM_FIRST_FRAME_ FLUSH_MS and SH_TURN_STREAM_KEEPALIVE_MS in the configuration reference; note that a Retry-After 503 after the deadline arrives as an error frame. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Follow-up on 5f88046: all four earlier comments are addressed. I checked each against the code. The prompt is now recorded on recovery accept, before any frame reaches the transcript (record is idempotent, so the finally call is a no-op). The connection_dropped message no longer claims "before the response began". The docs (README-kind, openapi, http-api, configuration.md incl. both stream knobs and the Retry-After note) are qualified. The test cleanup is in afterEach and the flush timer is pinned. One optional nit inline. CI is green.
| spy.mockRestore(); | ||
| expect(res.status).toBe(404); | ||
| expect(flushTimers).toHaveLength(1); | ||
| expect(flushTimers[0]!._destroyed).toBe(true); |
There was a problem hiding this comment.
nit: _destroyed is an undocumented Node Timeout internal. A spy on clearTimeout that asserts it was called with the captured timer would pin the same thing through public API. Not blocking.
Fixes #531
Problem
/turnwrote nothing until the first real frame, so a middlebox with a 50 s idle timeout (IBM Cloud VPC LB) cut turns whose first frame was slower than that. mocactl showed it ascannot reach the harness: fetch failed.Changes
Harness
makeFrameWriterflushes SSE headers at a first-frame deadline (SH_TURN_STREAM_FIRST_FRAME_FLUSH_MS, default 15000,0disables): the detachable turn'sturnframe, else a: keepalivecomment. The heartbeat is armed from there.errorframe (§3.4 updated).turnframe right afterbegin()would drop the 404/410/503 parity forexecuteTurnfailures (pinned bydetachable-turn-route.test.ts), so the deadline is used on the detach route too.mocactl
UND_ERR_SOCKET/ECONNRESET/EPIPE) is nowconnection_dropped, with message "the harness connection was dropped before the response began (a proxy idle timeout?)". Refused/DNS staynetwork_error.turnframe that is still running and is not the last turn this client saw.Testing
make typecheck, mocactl suite (930), detachable-turn-route (35) pass.🤖 Assisted-By: Claude Code