Skip to content

fix: keep a slow first turn frame from tripping a proxy idle timeout - #533

Merged
pdettori merged 2 commits into
rossoctl:mainfrom
pdettori:fix/turn-first-frame-flush
Oct 14, 2026
Merged

pdettori merged 2 commits into
rossoctl:mainfrom
pdettori:fix/turn-first-frame-flush

Conversation

@pdettori

@pdettori pdettori commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

Fixes #531

Problem

/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 showed it as cannot reach the harness: fetch failed.

Changes

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. The heartbeat is armed from there.
  • Failures faster than the deadline keep their HTTP status. Later ones end with a terminal error frame (§3.4 updated).
  • Deviation from the issue's item 1: writing the turn frame right after begin() would drop the 404/410/503 parity for executeTurn failures (pinned by detachable-turn-route.test.ts), so the deadline is used on the detach route too.
  • The attach route is unchanged: it awaits its first frame under the registry timeout and writes immediately.

mocactl

  • A connection closed under the request (UND_ERR_SOCKET/ECONNRESET/EPIPE) is now connection_dropped, with message "the harness connection was dropped before the response began (a proxy idle timeout?)". Refused/DNS stay network_error.
  • On a detachable session, a POST cut before any frame attaches by session with the existing reattach backoff. The prompt is never re-sent. If nothing is found, the original error stands.
  • Attach replays the last turn even if finished, so recovery only accepts a turn frame that is still running and is not the last turn this client saw.

Testing

  • knative-server: new tests for the flush on both routes, error-frame-after-deadline, status-before-deadline, and disable.
  • mocactl: recovery, no-turn, finished-earlier-turn, refused/non-detachable cases; error classification and message.
  • make typecheck, mocactl suite (930), detachable-turn-route (35) pass.

🤖 Assisted-By: Claude Code

/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]>
@pdettori
pdettori requested a review from cwiklik as a code owner October 14, 2026 20:00
@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Oct 14, 2026

@ingpaolodettori-dev ingpaolodettori-dev 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.

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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread deploy/knative/README-kind.md Outdated
@@ -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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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]>
@pdettori
pdettori merged commit 76c6a8a into rossoctl:main Oct 14, 2026
15 checks passed

@ingpaolodettori-dev ingpaolodettori-dev 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.

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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

@pdettori
pdettori deleted the fix/turn-first-frame-flush branch October 14, 2026 22:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

harness: /turn stream is silent until the first frame, so a 50 s idle proxy cuts slow turns (mocactl: "cannot reach the harness: fetch failed")

2 participants