Skip to content

feat: detachable turns — re-attach to a running turn after mocactl quits (#471) - #481

Merged
pdettori merged 42 commits into
rossoctl:mainfrom
pdettori:docs/471-turn-reattach-spec
Oct 10, 2026
Merged

pdettori merged 42 commits into
rossoctl:mainfrom
pdettori:docs/471-turn-reattach-spec

Conversation

@pdettori

@pdettori pdettori commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

Closes #471.

Problem

If you quit mocactl while a turn is streaming, the harness aborts that turn. That is what the SSE spec's §3.6 says a disconnect does. When you reopen and resume, the reply is cut off and you have to type "go on". #472 added a notice saying the turn isn't running. This PR keeps the turn running instead.

What it does

Detachable turns, opted into per turn. They are honoured only when all three hold: SH_TURN_DETACH=1, a session token, and SSE. Everything else keeps today's behaviour.

  • Harness (harness/src/turn-registry.ts): a new TurnRegistry.
    • Lease: a per-session lease (SET NX, renewed by a Lua compare-and-set). A session has one live turn; a second gets 409 turn_in_progress. The owner aborts before its lease can lapse, so two processes never both own a session.
    • Frame log: every frame goes to a per-turn Redis Stream. The SSE id is <turnId>:<entryId>. Finished turns can be replayed for SH_TURN_LOG_TTL_S (24 h).
    • Watching: each attached reader refreshes a watch key. A turn nobody watches is aborted after SH_TURN_DETACHED_MAX_S (30 min).
    • Cancel: sent over Pub/Sub, with a lease flag as the fallback.
    • Crashed owner: an attacher writes a terminal owner_lost frame, exactly once.
  • Server (packages/knative-server):
    • POST /v1/turn accepts detachable: true. Its first frame is turn, every logged frame carries an id:, and a disconnect detaches instead of aborting.
    • GET /v1/turn?sessionId= re-attaches: it replays from Last-Event-ID, then follows live. A cursor at a finished turn's terminal gets turn with ended: true.
    • POST /v1/turn/cancel cancels.
    • Both new routes are in routes.ts and docs/api/harness-openapi.yaml.
    • P6 workers keep a detached turn counted until it ends. Fifteen seconds into a drain they end each one with a "harness restarting" terminal.
  • mocactl:
    • The TUI sends detachable. Headless does not.
    • Frame ids go into the transcript.
    • Resume catches up on the last turn: what you missed, then live.
    • A dropped stream re-attaches on its own: 5 tries, backoff starting at 0.5 s.
    • Esc cancels on the server. That includes an Esc pressed before the turn's first frame.
    • Quit or switch with a running turn asks: k keep it running · c cancel it · esc stay.
    • A 409 from another device's turn shows that turn, then sends your prompt. Esc there withdraws your prompt and does not touch the other device's turn.
  • Deploy: the feature is on for compose, vm and k8s (P6). Knative keeps today's behaviour, see the spec §3. The compose live smoke has two new claims: re-attach (no repeats and nothing missed) and cancel.

Spec: docs/specs/2026-10-09-turn-reattach-design.md · ADR-0040 (amends ADR-0029's disconnect rule for detachable turns).

Compatibility

Client \ harness P6 with SH_TURN_DETACH=1 Older harness, or Knative
Older mocactl, curl Unchanged, except a 409 while a detachable turn of the same session runs Unchanged
New mocactl Full feature No turn frame → today's behaviour. Attach 404 → nothing to attach. The #472 notice stands.

Testing

  • make typecheck, make lint, make test: all pass on the rebased head. Package counts: mocactl 751, knative-server 449 (including openapi-contract), harness 629, control-plane 602, supervisor 215.
  • Harness: registry tests against real Redis cover the lease, renew, a hung or failed renew, re-arm after an outage, TTLs, cancel through each path, the unwatched cap, attach replay and follow, a cursor at or past the terminal, and owner_lost written once under concurrent attaches.
  • Server: route tests cover detach, 409, peek fail-open, attach, cancel, error codes, and no raw error text in bodies or the replay log.
  • Cross-task: packages/mocactl/test/turn-reattach-seams.test.ts checks the end-to-end flows the final review found: resume after a finished turn, catch-up mid-tool, Esc before the turn frame, and Esc during a conflict attach.
  • Not run: the compose live smoke (COMPOSE_LIVE_SMOKE=1 ./deploy/compose/smoke.sh, claims 8 and 9). It needs Docker and a model key. Please run it before merging.

Known issues

🤖 Generated with Claude Code

Quitting mocactl mid-turn aborts the turn: the harness ties a turn's life
to its SSE connection (turn SSE spec §3.6) and replays nothing.

The spec adds opt-in detachable turns on the P6 runtime: a per-turn Redis
Stream log whose entry ids are the SSE ids, GET /v1/turn to replay from
Last-Event-ID and follow live, POST /v1/turn/cancel as the explicit cancel,
one live turn per session under a renewed lease, and a 30-minute cap on
unwatched turns. mocactl asks at quit whether to keep the turn running,
re-attaches on resume, and reconnects after a dropped stream. Knative keeps
today's behavior.

ADR-0040 records the decision; the streaming spec points at the amendment.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…pses, expires orphaned logs (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…se lapses (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…an orphan (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…rn frame keeps the client's cursor (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…nnot stall /v1/turn (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…cancel body (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…h and cancel (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…irst stream after its first frame (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…d-frames check (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…oke (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…ch-up on resume (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…r attach job; remint and de-duplicate cancels (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…ailed create after keep is shown; stay clears the pending leave (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… no second terminal after owner_lost (rossoctl#471)

The attach route marks its synthesized turn frame ended when the cursor is at
or past a finished turn's terminal. mocactl stops reading there and ends the
resume's attach step quietly (attach-none, missed: false) instead of reading
the EOF as a drop and re-attaching five times into a false lost-turn error.

END_LUA no longer appends a terminal to a log that already ends on one (an
attach wrote owner_lost while the owner stalled); it returns that terminal's id.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…-up (rossoctl#471)

fromTranscript no longer finalizes the reply or marks the tools interrupted
of a last turn that is open-detachable: the attach step replays the tool
result and the rest of the reply into it. useSession settles that turn when
the attach step ends without its terminal (attach-none, or a turn-end with
no terminal frame). Earlier turns settle as before.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…thdrawn, not cancelled (rossoctl#471)

- A detachable turn is pending from its request to its first frame and counts
  as running, so quit/switch asks. Esc (or the leave overlay's cancel) while
  pending waits for the first frame: a turn frame gets a server-side cancel;
  any other frame, or none within PENDING_CANCEL_MS (2 s), aborts the fetch.
- Esc or cancel on a 409's attach stops following the other client's turn and
  drops the held-back prompt; it never cancels a turn this client did not start.
- A resume attach that fails on a network error or 503 before any frame, when
  nothing was expected to run, ends quietly (attach-none, missed: false).
- The cancel bound aborts the cancel request (CancelTurnArgs.signal).
- The shared in-flight cancel is keyed by turnId.
- An attach job losing its turn after frames reports LOST_TURN_MESSAGE.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…he supervisor's grace ends (rossoctl#471)

Under compose and k8s the supervisor is PID 1, so its exit SIGKILLs the
workers and the IPC disconnect path never writes the "harness restarting"
terminal. On drain the worker now arms an unref'd DETACHED_DRAIN_MS (15 s,
below the supervisor's 20 s SHUTDOWN_GRACE_MS) timer that calls
abortDetachedTurns('restarting'). The disconnect path stays.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… codes (rossoctl#471)

After the rebase onto rossoctl#474/ddc02d1: the detachable path's pre-first-frame
failure uses the one-argument turnErrorCode, so an unclassified failure answers
internal_error (logged, never echoed); the attach and cancel catch-alls go
through internalError rather than writing String(err); writeAuthError reuses
retryHeaders for its 503. A bare GET /v1/turn now routes (400
sessionId_required) instead of falling through to 404.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… frame, frame ids (rossoctl#471)

Registers GET /v1/turn (attachTurn) and POST /v1/turn/cancel (cancelTurn) in
ROUTES as session-auth client routes, and documents them in
harness-openapi.yaml: the detachable body field and when it is honoured, the
turn frame (turnId, sessionId, truncated, ended), the id: <turnId>:<entryId>
on every frame, abortReason on the error frame, 409 turn_in_progress /
turn_mismatch, and the redis_unavailable 503s with Retry-After.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… turn log; log begin failures (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori requested a review from cwiklik as a code owner October 9, 2026 20:29
@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Oct 9, 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.

REQUEST_CHANGES. This is a solid, carefully specified feature, and CI is fully green at 635ef7f. Two client-side issues should block merge, because they undercut the PR's own promises about cancel and transcript correctness:

  1. An Esc (or the leave overlay's c) before the turn frame detaches the turn instead of cancelling it once the 2 s deferral expires (session-manager.ts:201). The turn then keeps running unwatched for up to 30 min, and the next prompt hits a 409.
  2. A 409 conflict attach writes the other device's turn into this prompt's transcript, and the following turn is then mis-classified as finished on resume (session-manager.ts:515, blocks.ts:220).

The remaining inline comments are suggestions. Most are about robustness under a slow or partitioned Redis: lease fencing of appends, lease-clock start, slot adoption racing begin(), unbounded Redis calls. There are also two re-attach gaps: the per-turn retry budget, and the id of a truncated SSE block at EOF.

Smaller test notes (not inline):

  • harness/test/turn-registry.test.ts lease-lost timing asserts are measured from brokenAt, not from the last successful renew, so a late abort would still pass.
  • The truncated attach test uses a fabricated cursor and never trims the stream.
  • detachable-turn-route.test.ts has no coverage for cancel with another session's token, for attach/cancel with SH_TURN_DETACH off, or for begin() → 503.

The PR body says the compose live smoke (claims 8/9) was not run. Please run it before merge.

Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (harness turn registry + Lua, knative-server routes/worker, mocactl session manager/SSE/transcripts/TUI), Docs (OpenAPI, spec, ADR-0040), Deploy (compose/k8s/vm, smoke.sh), tests
Agent/IDE config (.claude/.vscode): none
Commits: 29 commits, all signed-off: yes
CI status: passing on 635ef7f (all checks green); merges cleanly with current main

const timer = setTimeout(() => {
if (this.deferred?.promise !== promise) return;
this.deferred = undefined;
this.controller?.abort();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix — An Esc before the turn frame can leave the server turn running.

When no frame arrives within PENDING_CANCEL_MS (2 s), this timer only aborts the fetch. On a detachable request, closing the connection detaches the turn; it does not cancel it (spec §4.1). The server takes the lease in begin() but writes the turn frame lazily, with the first real event (server.ts send). Sandbox placement or a slow first token easily takes longer than 2 s.

Result: the user sees "■ cancelled", but the turn keeps running, tools included, unwatched for up to SH_TURN_DETACHED_MAX_S (30 min). The next prompt gets a 409 and shows that "cancelled" turn as if another device owned it. The leave overlay's c goes through cancelRemote → deferCancel and resolves true the same way, so the user quits believing the turn was cancelled. turn-reattach-seams.test.ts ("Esc with no frame for the deadline") asserts harness.cancels is [], which codifies this.

Possible fixes, either works: (a) have the detachable route write the turn frame right after begin() succeeds. Failures after begin are already in-stream for this opt-in path. (b) On the deadline, keep the request open until the turn frame or a refusal arrives, or follow the abort with a turnId-less POST /v1/turn/cancel (retrying briefly on 404, since the cancel can land before begin()).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 2d1f1e9, with follow-ups in aa3bb29 and e28bedd. I chose option (b) over (a). An eager turn frame would make pre-first-frame failures in-stream errors: a 503 when the sandbox pool is full, a 410 for a missing config bundle. mocactl's Retry-After retry and the status-code handling depend on those staying real statuses.

  • When PENDING_CANCEL_MS expires with no frame, the client aborts the request and then sends POST /v1/turn/cancel without a turnId. It retries on turn_not_found (3 tries, 1.5 s apart, each bounded by the 5 s cancel timeout), because the cancel can land before begin().
  • A 202 that names the session's previous, already-ended turn doesn't count as success, so retrying continues. The 202 now also carries outcome (requested | ended), and the client keeps retrying on ended (e28bedd).
  • If every try finds no turn, nothing holds the session, so the client reports success quietly. That happens on Knative or an older harness (whose bare 404 now also reads as turn_not_found), where the abort stopped the turn, and on P6, where the turn never began (4bf246e: the server no longer begins a turn for a client that has already left).
  • The leave overlay's c resolves true only on an accepted cancel.
  • The next queued prompt is held until that cancel settles, so a late retry can't cancel this client's own next turn.
  • The seams test now expects the turnId-less cancel.

One risk remains, and I accept it. If our request never reached begin(), another device starting a turn on the same session inside that short window could be the one cancelled.

// Another device's turn holds the session: show it, then send this prompt (spec §6.5).
// Only a detachable session attaches: headless fails the turn, as it always has.
const resend: PromptJob = { ...job, resend: true, conflicts: job.conflicts + 1 };
this.queue.unshift({ kind: 'attach', expectOpen: false, conflict: { resend } }, resend);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix — A 409 writes the other device's turn into this prompt's transcript.

runTurn has already called appendPrompt(P) before the request is sent. On turn_in_progress, the conflict attach's consume appends every frame of the other device's turn T1, terminal included, under P. The resend then skips appendPrompt. The file ends up as prompt P, turn T1, T1 frames, T1 terminal, turn T2, T2 frames.

  • On reload, T1's reply renders as the answer to P, and T1's usage counts toward this session.
  • lastTurnState (render/blocks.ts:220) only treats a turn entry as open when it follows a prompt, so T2 reads as finished. Quit with k mid-T2 and the resume closes T2 (its running tools are marked interrupted) instead of re-attaching it as open.

This contradicts the PR's "the transcript and the server state are correct". Fix: keep the conflict attach's frames out of the transcript, or record the prompt only once its own turn is accepted. Also let a turn entry after a terminal open a new turn in lastTurnState.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in f4c1a1c.

  • The prompt is now recorded only once its own turn is accepted. That happens on the request's first frame, or in finally for any outcome other than a 409 that leads to a conflict attach. A 409 therefore records the other device's turn on its own, then the prompt, then our turn.
  • lastTurnState treats a turn entry after a terminal as opening a new detachable turn, so quitting with k during T2 re-attaches it instead of closing it.
  • I traced every path for exactly-once recording: refusal before a frame, 503 retry, token remint, Esc before a frame, re-login resend, and the conflict cap.
  • Older transcripts and the feat(mocactl): note an unfinished last turn on resume (#471) #472 notice are unchanged.

* when the turn ended cancelled.
*/
private async reattach(controller: AbortController, ids: Cursor): Promise<boolean> {
for (let attempt = 0; attempt < REATTACH_TRIES; attempt++) {

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 — The re-attach budget covers the whole turn, not each drop. attempt is never reset after a re-attach that delivered frames. A long turn behind a proxy that cuts idle or long streams, or one spanning a rolling restart, therefore fails with LOST_TURN_MESSAGE after 5 drops in total, and the backoff has grown to 8 s by then. Reset attempt (and the backoff) whenever ids.frames advanced during a try.

A related gap: isDropped only covers network_error/stream_truncated. A gateway 502/503/504, or the harness's own 503 redis_unavailable, on the re-attach GET during a worker drain is rethrown on the first try. Consider treating 5xx as retriable here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 1364651.

  • attempt and the backoff reset whenever a try delivered a frame the client hadn't seen. The turn frame that every re-attach repeats doesn't count as progress; if it did, a harness that drops right after it would be retried forever.
  • A harness 502/503/504, or redis_unavailable, on the re-attach GET is now retried, like network_error/stream_truncated.

try {
for await (const event of readSse(res.body)) {
const frame = toFrame(event);
if (event.id !== undefined) onEventId?.(event.id);

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 — The id of an incomplete event at EOF can make a re-attach skip a frame. readSse ends with parser.flush(), which still dispatches a trailing block that had no closing blank line; the SSE spec says to discard it. The server writes id: before data:. So a body cut mid-data, which is exactly the drop this feature re-attaches after, yields an unknown frame carrying a complete id. onEventId records it, and the re-attach resumes after that id, so the real frame (for example a tool_result) is never delivered. Don't report the id of, or don't dispatch, a block that was not terminated.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 58d8937. Following the SSE spec, readSse now discards a trailing block with no closing blank line, so its id is never reported. A body cut mid-data: therefore ends as stream_truncated and re-attaches from the previous id.

Real harness streams always end each block with a blank line: makeFrameWriter, the keepalive, and the post-first-frame error path all do. contract.test.ts restores the fixture's closing blank line, which the end-of-file-fixer hook trims.

Comment thread harness/src/turn-registry.ts Outdated

async xadd(sessionId: string, turnId: string, frame: TurnStreamFrame): Promise<string> {
await this.open();
return this.client.xAdd(

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 — The owner's frame writes are not fenced by the lease. append is a plain XADD, and END_LUA/OWNER_LOST_LUA check only the tail entry for an existing terminal.

Scenario: the owner loses Redis for more than 30 s. It aborts with lease_lost (~20 s), the lease lapses, and an attacher writes owner_lost. When the owner reconnects, its queued XADDs (node-redis offline queue) land after owner_lost. The tail is then no longer a terminal, so END_LUA appends a second terminal. A cursor between the two terminals then gets frames after a terminal. That breaks the "exactly once" guarantee for owner_lost, and the terminal is no longer the last entry.

Fix: append via Lua, refusing when the lease doesn't name this turn or a terminal marker exists. Have END/OWNER_LOST set a per-turn …:term marker rather than inspecting the tail. A related issue: end() (line 274) returns the caller's own frame even when END_LUA returned an existing owner_lost id, so the original connection can show done under the owner_lost entry's id.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in de7e032 and db5ffda.

  • Owner appends now go through a Lua script that refuses when the lease no longer names this turn, or when the per-turn terminal marker sh:turn:<sid>:<turnId>:term exists.
  • END_LUA and OWNER_LOST_LUA set and check that marker instead of inspecting the tail.
  • end() returns the frame actually logged as the terminal, including an earlier owner_lost, with its id.
  • The marker's TTL now follows the stream's in END and RENEW (db5ffda). The review reproduced a skew that let a second owner_lost through; the log now ends [turn, owner_lost].

Comment thread harness/src/turn-registry.ts Outdated
) {
this.signal = this.controller.signal;
this.ended = new Promise((r) => (this.resolveEnded = r));
this.lastRenewOk = reg.now();

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 — The lease clock starts too late. lastRenewOk is taken when ActiveTurn is constructed, which is after BEGIN_LUA set the lease and after the turn-frame XADD and EXPIRE. If Redis stalls during begin, say 15 s, the owner's "abort one renewal before lapse" deadline is measured from the wrong point. The lease can then lapse while the owner still believes it holds it, which is the double-owner window §5.1 rules out. Take now() before the BEGIN_LUA eval and pass it in.

A related issue at lines 417–421: if the XADD succeeds but the separate expire fails, the catch releases the lease and leaves an events stream with no TTL. Folding the turn-frame XADD + EXPIRE into BEGIN_LUA closes both.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in de7e032.

  • The lease clock is read just before the BEGIN_LUA eval and passed into ActiveTurn.
  • The turn-frame XADD and its EXPIRE are folded into BEGIN_LUA, so begin is one atomic step and can't leave a stream without a TTL.
  • begin({ timeoutMs }) also bounds itself. A BEGIN that lands after the bound is ended at once, so nothing holds the lease.

Comment thread packages/knative-server/src/server.ts Outdated
}
return;
}
const releaseSlot = adoptTurnSlot(res);

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 — The turn slot is adopted only after await turnRegistry().begin() returns. If the client disconnects during begin(), which is a few Redis round trips plus the first subscriber connect, the worker's close listener sees adopted=false and ends the slot. adoptTurnSlot then hands back the already-spent end, so the detached turn runs uncounted for up to 30 min. The supervisor over-admits, and awaitIdle on shutdown can treat the worker as idle before the 15 s "restarting" abort. Line 529 already handles this race for watched. Adopt before begin() and release on a begin failure, or let adoptTurnSlot re-arm a slot that has already ended.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 8156180 and 4bf246e.

  • The slot is adopted before begin() and released on every begin failure.
  • The review also found an earlier window: a client that left during the control-plane credential exchange, before the route was entered. The route now returns without beginning (no lease, nothing written) when the client is already gone.
  • Tested with the exchange held open: no lease is taken, and the counter is back to 0.

Comment thread packages/knative-server/src/server.ts Outdated
signal: turn.signal,
onPlacement: (p) => (placement = p),
});
await chain;

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 — If chain ever rejects (a throw inside send/writeFrame), the await chain in the catch rethrows and turn.end() is never reached. The ActiveTurn renewal timer then keeps the lease alive indefinitely, and the session answers 409 turn_in_progress until the process restarts. The likelihood is low, but the failure is sticky. Use await chain.catch(log) in both places, and make sure a once-only turn.end runs in finally.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 8156180.

  • Each frame-chain link catches its own error. Without that, a failed write was an unhandled rejection mid-turn, which crashes the worker under Node's default mode.
  • The chain is settled with chain.catch(log).
  • A once-only turn.end runs in finally, so the lease is always released.

const PEEK_TIMEOUT_MS = 250;

/** The session's running detachable turn, or null when there is none or Redis cannot answer in time. */
async function peekRunningTurn(sessionId: string): Promise<string | null> {

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 — There are two operational gaps around Redis. (1) The fail-open peek is silent. When Redis is alive but slower than 250 ms, a non-detachable turn runs alongside a live detachable turn on the same session, which is the overlap §4.4 exists to prevent, and nothing records it. Add a console.warn or a counter on timeout or error. (2) begin() (line 501), the first attach read, and cancel() have no time bound (node-redis has no command timeout, as turn-registry.ts notes). Against a blackholed Redis, these requests hang with no bytes instead of the documented 503 redis_unavailable + Retry-After. Reuse the Promise.race pattern here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 8156180.

  1. The fail-open peek logs a console.warn (sanitised with forLog) on a timeout or error.
  2. begin(), the first attach read, and cancel() are each bounded by REGISTRY_TIMEOUT_MS (5 s, overridable with SH_TURN_REGISTRY_TIMEOUT_MS; values ≤ 0 fall back to the default). On expiry they answer 503 redis_unavailable with Retry-After.

The OpenAPI doc and spec §5.6 are updated, and tests cover a never-settling begin, attach, and cancel.

Comment thread deploy/compose/smoke.sh Outdated
[[ -n "$last_id" ]] || { ko "the detachable turn sent no ids: $(head -c 400 "$first")"; return; }
curl -sN --max-time 180 -H @"$TURN_HDR" -H 'Accept: text/event-stream' -H "Last-Event-ID: $last_id" \
"http://127.0.0.1:$SH_PORT/v1/turn?sessionId=$sid" >"$second" || true
if ! grep -q '^event: done' "$second"; then

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 — Claim 8 can fail for the wrong reason. If the model finishes the 200 numbers within ~1 s of the first id, the first stream already holds the terminal. The attach with that Last-Event-ID then correctly answers turn with ended: true and no event: done, and this reports "did not reach done". Accept "ended":true here, or cut the first stream right after its first id.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 707e597. Claim 8 accepts a re-attach that ends on "ended":true when the first stream already holds event: done. It also fixes a blank-line bug that would have reported that case as missed frames.

The live smoke has now run: COMPOSE_LIVE_SMOKE=1 SH_COMPOSE_BUILD=1 at 4bf246e, 9 passed and 0 failed. In claim 8 the client re-attached after 20 frames and got 44 more, with no loss and no repeats. In claim 9 the turn was cancelled with abortReason: cancelled.

… early lease clock; bounded begin (rossoctl#471)

- append is APPEND_LUA: refused once the lease no longer names the turn or the
  per-turn terminal marker sh:turn:<sid>:<turnId>:term exists, so queued
  writes cannot land after an attach's owner_lost.
- END_LUA and OWNER_LOST_LUA set and check the marker (log TTL) instead of
  inspecting the tail; end() returns the terminal actually logged.
- BEGIN_LUA logs the turn frame and sets its TTL in the same step; the lease
  clock (lastRenewOk) is read before BEGIN.
- begin(sessionId, { timeoutMs }) bounds the call and ends a late-landing
  turn; withTimeout(promise, ms) bounds other registry calls.
- Tests: lease-lost bounds measured from the last good renew; the truncated
  attach test really trims the stream.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…iling Redis or write (rossoctl#471)

- Adopt the worker's turn slot before begin(), and release it when begin fails, so a client
  that leaves during begin cannot leave the detached turn uncounted.
- A frame write that throws no longer skips turn.end(): each chain link catches its own failure
  (no unhandled rejection, later frames still logged), the chain is settled with
  `chain.catch(log)` before ending, and a once-only end runs in `finally`.
- Bound begin (its own timeoutMs), the first attach read and cancel (withTimeout) by
  REGISTRY_TIMEOUT_MS = 5000 (SH_TURN_REGISTRY_TIMEOUT_MS overrides); past it, the documented
  503 redis_unavailable with Retry-After. A timed-out attach aborts and returns its reader.
- The fail-open one-live-turn peek now warns, through forLog, on timeout and on error.
- Route tests: cancel with another session's token, attach and cancel with SH_TURN_DETACH off,
  begin() -> 503; OpenAPI and spec §5.6 note the bound.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…ready ended (rossoctl#471)

When the model finishes within the second before the cut, the first stream already holds the
terminal, and the re-attach correctly answers only a turn frame with "ended":true. Accept that
(with the done in the first stream) as reaching the end, and drop the blank line an empty
re-attach adds to the id comparison.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…already left (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…octl#471)

readSse flushed a trailing block that had no closing blank line. The
harness writes id: before data:, so a body cut mid-event surfaced an
unknown frame with a complete id, and a re-attach resumed after it and
never saw the real frame. Per the SSE spec the block is now discarded;
a held-back CR still closes its line.

The contract test restores the fixture's final blank line, which the
end-of-file-fixer hook trims from the file.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…lable harness (rossoctl#471)

The 5 re-attach tries covered the whole turn, so a long turn behind a
proxy that cuts streams failed after 5 drops in total, with the backoff
grown to 8 s. A try that delivered new frames now restarts the count and
the backoff. The turn frame every re-attach repeats does not count, so a
harness that only ever sends it still runs out.

A 502/503/504 or redis_unavailable on the re-attach GET (a worker drain,
a gateway) is now retried like a dropped stream.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…s prompt (rossoctl#471)

runTurn wrote the prompt before sending it. On turn_in_progress the
conflict attach then recorded the other device's whole turn under it,
and the resend skipped the prompt: on reload T1's reply read as P's
answer, and lastTurnState saw T2 as finished, so a resume closed it.

The prompt is now recorded once its own turn is accepted (its first
frame), or when the turn ends without one -- never before a 409 that
leads to a conflict attach; the resend records it. The transcript reads
turn T1 ... T1 terminal, prompt P, turn T2 ...

lastTurnState treats any turn entry, including one after a terminal with
no prompt, as opening a detachable turn, and fromTranscript keeps such a
prompt-less turn open while settling the turns before it. Usage counting
is unchanged.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…r, not detaches it (rossoctl#471)

The server takes the lease in begin() but writes the turn frame with the
first real event. When no frame came within PENDING_CANCEL_MS, Esc only
aborted the fetch, which detaches a detachable turn: the user saw
cancelled while the turn ran on, unwatched, and the leave overlay's c
resolved true the same way.

The deadline now aborts the fetch and then sends POST /v1/turn/cancel
without a turnId, retrying turn_not_found (the cancel can land before
begin()) for 3 tries over about 3 s. cancelRemote resolves true only once
a cancel was accepted; if every try answers 404 (an old or Knative
harness) it resolves false with the couldn't-cancel notice. The queue
holds the next job until that cancel settles, so a late try cannot hit
this client's next turn.

Accepted risk: if the request never reached begin() and another device
started a turn inside that window, the turnId-less cancel can hit it.

The seams test 'Esc with no frame for the deadline' now expects the
turnId-less cancel instead of codifying the detach.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…6 matches the client (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…'s cancel outcome (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori

Copy link
Copy Markdown
Member Author

I've addressed the review in 11 commits (635ef7f..e28bedd). Each inline thread has a reply naming its commit. Below are the points from the summary that have no thread of their own.

Test notes

  • Lease-lost timing: these asserts are now measured from the last successful renew instead of from brokenAt, so a late abort fails them (de7e032).
  • truncated attach test: it now really trims the stream. It uses a registry with maxLen: 10 and 300 appends, and asserts that the cursor's entry is gone (de7e032).
  • detachable-turn-route.test.ts: added coverage for:
    • cancel with another session's token (400 session_mismatch);
    • attach and cancel with SH_TURN_DETACH off (exact 404 bodies);
    • begin() → 503 with Retry-After and no secret text (8156180).

Live compose smoke: I ran COMPOSE_LIVE_SMOKE=1 SH_COMPOSE_BUILD=1 ./deploy/compose/smoke.sh against images built from 4bf246e, under Podman with docker-compose v2.32.4. The result was 9 passed, 0 failed:

  • Claim 8: re-attached after 20 frames and received 44 more, with no loss and no repeats.
  • Claim 9: cancelled with abortReason: cancelled.

The commits after 4bf246e touch only mocactl, plus the cancel route's new outcome field (e28bedd). The smoke runs no mocactl, and claim 9 checks only for a 202. On head e28bedd, make typecheck, make lint and make test all exit 0.

Also found while fixing:

  • A detached turn could run uncounted. This happened when the client left during the control-plane credential exchange, before the route was entered. The server no longer begins a turn for a client that is already gone (4bf246e).
  • A second owner_lost could be written. The terminal marker could expire before the turn log. The marker's TTL now follows the log (db5ffda).
  • Wrong "couldn't cancel" notice. An early Esc against an older harness, which answers a bare 404, could show "couldn't cancel" even though the abort had stopped the turn. That 404 now reads as turn_not_found. The cancel's 202 also carries outcome (requested | ended), so the client can tell an already-ended turn from an accepted cancel (aa3bb29, e28bedd).

Still open, tracked separately:

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

APPROVE. Thanks for the thorough follow-up. I checked every item from the 635ef7f review against the code at e28bedd, and all are addressed:

  • Early Esc: a turnId-less cancel with retries, the queue held until it settles, and no begin() for a client that already left.
  • 409 transcript: the prompt is recorded only once its own turn is accepted, and a prompt-less turn entry opens a turn.
  • Re-attach budget: counted per drop, and 5xx is retried.
  • SSE: an unterminated block is dropped at EOF.
  • Registry: fenced owner appends with a :term marker, an atomic BEGIN with the lease clock read before it, and a bounded begin.
  • Server: the slot is adopted before begin(), the frame chain is settled, end() runs once in finally, there's a warning on fail-open, and the registry calls are bounded.
  • Smoke claim 8 and the test notes are fixed too.

CI is green on e28bedd. Thanks for running the live compose smoke.

One non-blocking suggestion is inline: a timed-out turnId-less cancel can still land later, which weakens the spec's "a late try cannot cancel that prompt's turn". The follow-ups already tracked (#478, #479, #483) are fine as separate work.

Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (harness turn registry Lua + ActiveTurn, knative-server detachable/attach/cancel routes, mocactl session manager / SSE parser / harness client / transcript blocks), Docs (OpenAPI, spec), Deploy (compose smoke.sh), tests. Incremental 635ef7f..e28bedd.
Agent/IDE config (.claude/.vscode): none
Commits: 40 commits (11 new), all signed-off: yes
CI status: passing on e28bedd (all checks green)

if (!authorizeTurnRoute(req, res, sessionId)) return;
if (!detachEnabled()) return turnNotFound(res);
try {
const r = await withTimeout(

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 (non-blocking) — withTimeout's doc (turn-registry.ts:112) says a late landing is harmless for "a cancel request". That held for the conditional cancel, which a turnId fences. It does not quite hold for the new turnId-less cancel from the early-Esc path.

Scenario: worker A's Redis connection is reconnecting, so its CANCEL_LUA sits in node-redis's offline queue. The 5 s bound answers 503 redis_unavailable, or the client's own CANCEL_TIMEOUT_MS gives up first. cancelBySession treats that as a failure: it shows the notice and resolves false, so blindCancel settles and the queue releases the next prompt. That prompt begins on worker B, whose Redis connection is healthy. When A reconnects, the queued turnId-less cancel lands and cancels the user's next turn. That is exactly what spec §6.4 says can't happen ("The queue holds the next prompt until it settles, so a late try cannot cancel that prompt's turn").

The likelihood is low: it needs a worker-local Redis stall plus a second worker. A cheap fence would close it. For example, handleCancel captures its receipt time, and for an empty turnId CANCEL_LUA skips a lease whose startedAt is later than that, with a small skew margin, since startedAt is the owner's clock. Alternatively, startedAt could come from redis.call('TIME') in BEGIN. Or, at minimum, list it next to the existing accepted risk in §6.4 and fix the withTimeout comment.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in b3eb544, with spec wording in 39835f2.

The fence

  • handleCancel takes its receipt time as its first statement, before reading the body, auth, or any Redis await.
  • TurnRegistry.cancel(sessionId, turnId?, { issuedAt }) passes that time to CANCEL_LUA.
  • For a cancel with no turnId, the script treats a lease whose startedAt > issuedAt + CANCEL_SKEW_MS (2000 ms) as no running turn: no flag set, no publish, the same answer as the no-lease branch.
  • CANCEL_SKEW_MS absorbs the skew between the owner's clock (startedAt) and the receiving worker's clock (issuedAt).
  • A conditional cancel is unchanged; its turnId already fences it.

Effect on your scenario. The queued cancel was received at t0. The next prompt is released no earlier than about t0+5 s, so its turn's startedAt is past t0+2 s and the late cancel no longer touches it.

Docs. The withTimeout comment now says what fences each kind of late cancel. Spec §6.4 claims the fence only when the cancel reaches the server well inside the 5 s bound, which is the normal case. It lists two residual accepted risks:

  • Late arrival. A slow token refresh or slow delivery, combined with a reconnecting worker's offline queue, can still let a late cancel through.
  • Last try. On the final early-Esc try, a fenced outcome: ended reads as success.

Tests

  • A turn started past the margin is not cancelled.
  • A turn at or before the margin is cancelled, including the exact boundary.
  • A conditional cancel ignores issuedAt.
  • The route passes a receipt time.

On 39835f2, make typecheck, make lint and make test all pass.

…nnot cancel the next turn (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… name the residual cases (rossoctl#471)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori merged commit e4925c7 into rossoctl:main Oct 10, 2026
14 checks passed
@pdettori
pdettori deleted the docs/471-turn-reattach-spec branch October 10, 2026 13:36
pdettori added a commit to pdettori/moca that referenced this pull request Nov 16, 2026
Sixteen ADRs still said Proposed although their decisions are in code
on main. Each status line now names the merged PRs that implemented it
and the date the core landed (format of ADR-0042), and notes what is
still owed where only part is built:

- 0028 (rossoctl#170, rossoctl#201, rossoctl#340; its KEDA transport removed by ADR-0041)
- 0029 (rossoctl#171), 0030 (rossoctl#214), 0031 (rossoctl#214, rossoctl#225)
- 0032 (rossoctl#249, rossoctl#350, as amended by MI1)
- 0035 (rossoctl#251; ADR-0048 adds lease mode beside it)
- 0036 (rossoctl#347), 0038 (rossoctl#458), 0039 (rossoctl#467), 0040 (rossoctl#481)
- 0043 (rossoctl#560, rossoctl#588, rossoctl#600, rossoctl#615), 0044 (rossoctl#563), 0045 (rossoctl#620)
- 0046 (phase 1: rossoctl#630, rossoctl#641, rossoctl#646; phase 2 owed)
- 0047 (M1 and M3: rossoctl#704, rossoctl#713, rossoctl#717, rossoctl#765; M2 owed)
- 0048 (rossoctl#706, rossoctl#763, rossoctl#802, rossoctl#808, rossoctl#814; off by default until the
  security review's lease sections are signed off)

The README index follows, and its 0033 row, which still said Proposed
after rossoctl#249 accepted the ADR, is corrected.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
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.

mocactl: re-attach to a running turn after quitting, instead of the disconnect aborting it

2 participants