Skip to content

Follow a Codex delivery's turn on the connection that started it - #841

Merged
max-sixty merged 3 commits into
mainfrom
fix-772-turn-follower-bound
Sep 19, 2026
Merged

max-sixty merged 3 commits into
mainfrom
fix-772-turn-follower-bound

Conversation

@max-sixty

@max-sixty max-sixty commented Sep 19, 2026 •

Copy link
Copy Markdown
Owner

leaf codex start carried every delivery through one observing connection. The adapter's main loop handed a payload to that connection's thread over a queue and waited on a reply queue with no timeout, and the answer came back only once a notification's items parsed back to the delivery id. So a turn this process had just started was indistinguishable from one it merely watched, and a turn whose notifications never carried the id back ran to completion with its reply unbound and its caller still blocked.

A delivery now opens a connection of its own. start_delivery_turn resumes the thread, reads its status, starts the turn, and hands the socket to one follower that reads it to its reply. thread/resume subscribes the connection that asked for as long as it lives and turn/start neither subscribes nor unsubscribes, so that socket carries everything the turn will say, and losing it is the turn ending rather than a gap to read across. The turn id comes from the response, so nothing recovers a binding the starter already had. This is the model #834 landed for the hosted carrier, which the merged change named as a deliberate exemption for this one.

Two connections may resume one thread and both then receive everything it says. Measured against App Server 0.155, in a throwaway thread since deleted: a second connection resumed a thread the first already held, its turn/start came back with a turn id, and that connection received its own turn's whole stream — turn/started, item/started, item/agentMessage/delta, item/completed, turn/completed. TaskObserver therefore holds a delivery this process is carrying from before its turn/start goes out, and passes over that turn; without it one delivery would have two reply writers. The observer keeps what only it can do: the user's own turns in the terminal, a queued pointer the task picks up by itself, and their activity on the page.

That deleted the cross-thread scheduler — waiters, requests, deferred, _next_delivery, _defer_delivery, _answer_delivery, _fail_pending, available, start_delivery, and _read's defer_answer. It is not a net deletion. Counting statements without comments or docstrings, codex_adapter goes 826 to 869 and codex gains 29 for the moved stream, against 25 out of worker/server: a turn object that owns its own lifetime costs about what the scheduler did. What changes is that a turn has exactly one owner for its whole life.

TurnStream moves to codex.py, which both carriers already share, and takes its silence bound as a parameter. The website gives 120 seconds because nobody is at that task; the adapter gives none, because a turn waiting on a terminal approval is silent for as long as the person takes to answer it.

A turn ends the same way however it ended: DeliveryTurn.commit closes the Leaf turn and takes the activity reading off the page from a finally, because DeliveryReply guards only the commit of a completed answer and a fault in the rest would otherwise leave the page saying the agent is working until the claim's fifteen-minute grace expired. worker/server.py's HostedTurn.commit already did this; the near-copy did not.

Only active is a status worth waiting for. notLoaded and systemError are not states a task comes out of by being left alone, so they raise onto the delivery loop's retry ladder, where the failure is reported once and backed off rather than read as an ordinary busy task. That reaches the adapter's log and no further: this carrier has no writer that tells a reader no answer is coming — write_failure_receipt is the website's alone — so a task stuck in one of those states still leaves the move unanswered until someone reads codex.log. Closing that needs a receipt policy for a carrier whose whole model is to retry, and it is not closed here. Holding back costs no connection either: the loop reads the observer's own fold of turn/started and turn/completed rather than reconnecting once a second to ask the task, and that fold now records a turn id only when the resume names one — the word "active" standing in for an unnamed turn was something no turn/completed could ever clear.

The idle rule is unchanged and now authoritative. turn/start against a running turn steers into it rather than refusing — App Server says of turnTrigger that it is "Ignored when this request steers an already-active turn" — so the status is read on the starting connection one request before the start, rather than from a fold another connection left behind. That narrows the race without closing it. turn/steer's expectedTurnId would close it, and using it is a reply-routing decision rather than a transport change, because a steered turn has one final answer and two deliveries would share it. notes/codex-integration.md records that as the open question, and corrects its claim that the API has no such precondition.

Reviewing. skills/leaf/scripts/leaf/codex_adapter.py holds the whole change: TaskObserver is the old client with the delivery role removed, start_delivery_turn and DeliveryTurn are new. worker/server.py only loses TurnStream and recv_notification to codex.py. The test diff is large because the suite around the deleted scheduler went with it.

Tests: a delivery turn streams and commits its reply on its own connection, a busy task keeps its delivery for a later turn, a refused start gives up the seat it reserved while an unacknowledged one keeps it, a turn this process carries is not adopted by its observer, a dropped connection ends the turn it was carrying, a stopping adapter leaves a running turn to a later carrier, a delivery already being carried holds back the next one, and a connection failure in the delivery loop is retried. Each behaviour was checked against a reverted fix.

Everyday suite 1163 passed with thread exceptions promoted to errors, tests/test_website_server.py 86, pre-commit across the tree.

This was written by Claude Code on behalf of max-sixty

🤖 Generated with Claude Code

max-sixty and others added 2 commits September 19, 2026 00:14
`leaf codex start` carried every delivery through one observing connection. The adapter's main loop handed a payload to that connection's thread over a queue and waited on a reply queue with no timeout, and the answer came back only once a notification's items parsed back to the delivery id. So a turn this process had just started was indistinguishable from one it merely watched, and a turn whose notifications never carried the id back ran to completion with its reply unbound and its caller still blocked.

A delivery now opens a connection of its own. `start_delivery_turn` resumes the thread, reads its status, starts the turn, and hands the socket to one follower that reads it to its reply. `thread/resume` subscribes the connection that asked for as long as it lives and `turn/start` neither subscribes nor unsubscribes, so that socket carries everything the turn will say, and losing it is the turn ending rather than a gap to read across. The turn id comes from the response, so nothing recovers a binding the starter already had.

Two connections may resume one thread and both then receive everything it says, measured against App Server 0.155. `TaskObserver` therefore holds a delivery this process is carrying from before its `turn/start` goes out, and passes over that turn; without it one delivery would have two reply writers. The observer keeps what only it can do: the user's own turns in the terminal, a queued pointer the task picks up by itself, and their activity on the page.

That deleted the cross-thread scheduler — `waiters`, `requests`, `deferred`, `_next_delivery`, `_defer_delivery`, `_answer_delivery`, `_fail_pending`, `available`, `start_delivery`, and `_read`'s `defer_answer`. It is not a net deletion. Counting statements without comments or docstrings, `codex_adapter` goes 826 to 869 and `codex` gains 29 for the moved stream, against 25 out of `worker/server`: a turn object that owns its own lifetime costs about what the scheduler did. What changes is that a turn has exactly one owner for its whole life.

`TurnStream` moves to `codex.py`, which both carriers already share, and takes its silence bound as a parameter. The website gives 120 seconds because nobody is at that task; the adapter gives none, because a turn waiting on a terminal approval is silent for as long as the person takes to answer it.

The idle rule is unchanged and now authoritative. `turn/start` against a running turn steers into it rather than refusing — App Server says of `turnTrigger` that it is "Ignored when this request steers an already-active turn" — so the status is read on the starting connection one request before the start, rather than from a fold another connection left behind. That narrows the race without closing it. `turn/steer`'s `expectedTurnId` would close it, and using it is a reply-routing decision rather than a transport change, so `notes/codex-integration.md` records it as the open question and corrects that note's claim that the API has no such precondition.

Tests: a delivery turn streams and commits its reply on its own connection, a busy task keeps its delivery for a later turn, a refused start gives up the seat it reserved while an unacknowledged one keeps it, a turn this process carries is not adopted by its observer, a dropped connection ends the turn it was carrying, a stopping adapter leaves a running turn to a later carrier, a delivery already being carried holds back the next one, and a connection failure in the delivery loop is retried. Each behaviour was checked against a reverted fix.

Everyday suite, pre-commit.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Two findings, both on how a delivery turn ends or fails to start.

DeliveryTurn.commit closes the page unguarded. DeliveryReply.finish wraps only its _commit call: the _set_state and _release_binding that follow it, and the whole non-completed branch — the path a dropped connection, an interrupted turn and the failed terminal all take — open a PageTransaction with nothing catching an OSError or RuntimeError from it. When one fires, close_stream_turn and clear_stream_activity never run, so the Leaf turn stays open and the "working" reading stays on the page until the fifteen-minute claim grace clears it. worker/server.py's HostedTurn.commit already runs those two from a finally and names the reason — "closing the turn re-reads the page, which the turn's own work may have left unopenable" — and that guard didn't come across with the model. Suggestion inline.

Every non-idle status is deferred forever. notes/codex-integration.md gains the line that thread/status/changed reports idle, active, notLoaded or systemError, and start_delivery_turn reads all three non-idle values as "busy, try the next pass". A task in systemError will not become idle, so the delivery is re-offered for the adapter's life, the reader's comment never reaches Codex, and no receipt or error says so. Deferring active is the rule the PR argues for; the other two arrive at it by default. The same line also makes the busy check cost a fresh connect, handshake and thread/resume once a second for as long as the user's turn runs, since the status is only reachable by opening a connection — TaskObserver already folds that status off its standing subscription, and gating the attempt on the fold would skip the reconnect without moving the authoritative read off the starting connection.

… what the observer already knows

Three things the review found, each about how a delivery turn ends or fails to start.

`DeliveryTurn.commit` wrote the reply and then closed the Leaf turn and took the activity reading off the page, in sequence. `DeliveryReply` guards only the commit of a completed answer: `_set_state` and `_release_binding` open page transactions of their own and catch nothing but `FileNotFoundError`, and the turn's own work may have left that page unopenable. A fault there skipped both closes, so the page went on telling its reader the agent was working until the claim's fifteen-minute grace expired. They run from a `finally` now, which is what `worker/server.py`'s `HostedTurn.commit` already did and this near-copy did not.

`start_delivery_turn` treated every status that was not `idle` as a task to wait for. `active` is; `notLoaded` and `systemError` are not states a task comes out of by being left alone, so a delivery was re-offered for the adapter's life with the reader's move picked up, unanswered and unexplained. Only `active` waits now, and the rest raise onto the delivery loop's retry ladder where they reach the log.

Holding back also cost a connection a second. Status is only readable by opening one, so while the user's own turn ran the loop reconnected, handshook and resumed once a pass to ask. The observer is already subscribed and already folds every `turn/started` and `turn/completed`, so the loop reads `working()` off that instead. The fold can lag, which is why it only holds a delivery back: the status that lets one start is still read on the starting connection, one request before the start.

That fold had to be made worth reading. A resume reporting the task active without naming its running turn — full history is deprecated for paginated threads, so `turns` need not carry it — recorded the word "active" as the turn id. No `turn/completed` matches that, so both the page's activity reading and this fold stood until the next reconnect. An unnamed turn is now recorded as no turn, and the delivery loop falls back to asking the task.

Tests: a reply that cannot be written still closes its turn, a task that will never take a turn is reported rather than waited on, a running turn holds a delivery back without asking the task, and an active task whose turn is not named records no turn. Each was checked against a reverted fix.

Everyday suite, pre-commit.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

My earlier pass on this commit read past one thing on the new status route.

Nothing reaches the reader on notLoaded or systemError. The raise lands in the delivery loop's except Exception, which prints one line to codex.log, sleeps the retry ladder, and offers the same delivery again on the next pass. No page write happens anywhere on that path: the raise is before reserve_delivery_reply, capture_batch writes only the state-home queue, and the adapter has no receipt writer at all — write_failure_receipt exists solely in worker/server.py. So the reader's comment is still unanswered and unexplained for the adapter's life, which is the thing the description says this stops: "they raise onto the delivery loop's retry ladder rather than holding the reader's move unanswered for the adapter's life." The commit message has it right — "where they reach the log" — and the description is the text that merges. Either scope the claim to the log, or give the adapter the receipt HostedTurn._receipt_unanswered writes for a turn that ended with nothing to say.

Worth weighing while that is decided: time.sleep(retry_delay(failures)) sits in the same except that continues past read_watch_pass, so a task in systemError also stops the page watch for up to thirty seconds a pass. _offer_queued_delivery's own comment states the opposite rule for the deferral beside it — "the loop goes on watching pages meanwhile" — and the return None branch keeps it. Nothing expires, since thirty seconds is well inside PICKUP_GRACE; it is capture latency that moves, on a task that cannot answer anyway.

@max-sixty
max-sixty merged commit 7625290 into main Sep 19, 2026
8 checks passed
@max-sixty
max-sixty deleted the fix-772-turn-follower-bound branch September 19, 2026 07:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants