Repository navigation
🤖 refactor: give turn-engine ProviderRequest sole write access to the attempt request - #7483
Conversation
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
🛡️ Codex Security Review · Automatically triggeredSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
82136d1 to
6aa5597
Compare
6aa5597 to
35c7caf
Compare
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
🛡️ Codex Security Review · Automatically triggeredSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
🟢 e2e stories (Haiku): 14 passed27 agent steps · 7 replayed from cache · 33 model calls · 235.5k tokens (77% cached) All 14 tests in 9 files
e2e 0.20.0 · 2m 53s · web · run artifacts 🟢 e2e Electron stories (Haiku): 3 passed3 agent steps · 3 model calls · 8.0k tokens (32% cached) All 3 tests in 3 files
e2e 0.20.0 · 19.7s · electron · run artifacts 🟢 e2e agent repros (Haiku): no tests selectedSpend: $0.00 of the $1.00 cap (proxy ledger) e2e 0.20.0 · 6.1s · 2 targets (web, phone) · run artifacts |
35c7caf to
d2a735c
Compare
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
🛡️ Codex Security Review · Automatically triggeredSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
Layer 5 slice 7, step 2 of 2. StreamManager no longer owns the abort settle that TurnRegistry runs after a hard or soft stop. This commit moves cleanupAbortedStream and its parts, unchanged, into turnEngine/AttemptLoop.ts. Why AttemptLoop: its module comment already says it settles every terminal outcome, and it holds the other two (completeStream for stream-end, persistStreamError for errors). The abort settle runs the same steps on the same state: usage, the reasoning backfill, the session usage settle, the partial, the terminal event, unregistering, then terminalCompletion and the completion settle. Its lost-race guard (terminalCompletion already set) is a contract with those two paths and with settleStreamProcessing, and now all of them live in one file. AttemptLoop already had seven of the eight deps it needs (only the display registry is new). TurnRegistry would have needed six new deps plus a wider turnEvents Pick, type imports of TurnResources, PartialJournal and UsageLedger, and TurnResources built before it in StreamManager. Moved from streamManager.ts: - Methods cleanupAbortedStream (now public: TurnRegistry calls it), persistAbortedStreamUsage and finishAbortedStream. - Module code: AbortedStreamUsage, buildStreamAbortEvent and abortedPartialMetadata. Rewrites outside the moved blocks: - StreamManager wires TurnRegistry's cleanupAbortedStream dep to this.attemptLoop.cleanupAbortedStream. The forward reads the field at call time because AttemptLoop is built after TurnRegistry. TurnRegistry itself does not change, except its module comment. - AttemptLoopDeps gains toolCallDisplayRegistry (Pick "close"). Its partialJournal Pick adds awaitPending, writeAbortPartial and settleAbort, and its turnEvents Pick adds deliver. StreamManager passes its toolCallDisplayRegistry. - AttemptLoop imports hasCommitWorthyParts (historyService), StreamAbortEvent and StreamAbortReason, and the ToolCallDisplayRegistry type. streamManager.ts drops the imports only the moved code used. Lines: 262 added and 262 removed in moved blocks, 32 added and 29 removed outside them. streamManager.ts goes from 1467 to 1185 lines. AttemptLoop.ts goes from 889 to 1173 lines. No turnEngine module imports streamManager.ts. No import cycles. The test-only commit two back pins ten survivors of the unsplit function. Scratch mutations on this commit, against the streamManager, turnEngine, aiService and agentSession suites: 28 of 29 fail a test (one of them, run by hand, makes the TurnRegistry forward a no-op). Not killed: skipping partialJournal.awaitPending before the abort partial write, which is equivalent (see the test commit). Gates: make static-check, make lint-eslint and make dry-check pass. crap-check against the parent passes with coverage (0 violations, 0 warnings). Wide suite: 2774 pass, 0 fail. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
Test-only commit before layer 5 slice 9a moves the stream's unlinkAbortSignal from a post-construction write in TurnEngine into the stream info literal. A scratch edit that drops the write (so the stream never unlinks the caller's signal) survived the existing tests. New test in streamManager.resources.test.ts, "stream resource scope": a stream started with a caller abort signal adds one abort listener to it, and the listener is gone once the stream completes. Scratch mutation on this commit: the edit now fails the test. No production code changes. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
Layer 5 slice 9a, the first of four stacked steps. No behavior change. WorkspaceStreamInfo was one flat interface in types.ts. It now lives in the new turnEngine/turnState.ts and is built from six records. Each record names its owner: the one module that writes its fields after TurnEngine builds the stream info. | Record | Owner | Enforced | |---|---|---| | TurnState | StepApply | 9d | | TurnSlot | TurnRegistry | 9b | | AttemptRequest | ProviderRequest | 9c | | TurnHandles | TurnResources | this commit | | PartialJournalState | PartialJournal | this commit | | UsageLedgerState | UsageLedger | already (#7412) | Enforcement follows #7412: WorkspaceStreamInfo extends an enforced record as Readonly, so a write from another module does not compile. The owner takes `WorkspaceStreamInfo & Record`, which TypeScript lets it write. The view is shallow: it stops reassigning a field, not changing the Map or array the field holds. Changes: - turnState.ts (new): the four new records, plus PartialJournalState and UsageLedgerState moved from types.ts. Fields keep their comments. The record field lists follow the accepted plan's sketch. The 45 fields are the old WorkspaceStreamInfo's, each in exactly one record. - types.ts loses WorkspaceStreamInfo, the two state records and their imports. It stays a leaf: turnState.ts imports it, not the reverse. - Callers import WorkspaceStreamInfo (and the two state records) from turnState.ts. PartialJournal and UsageLedger still re-export their record, and StreamManager still re-exports WorkspaceStreamInfo. - TurnHandles and PartialJournalState are now Readonly in WorkspaceStreamInfo. PartialJournal had no outside writer. TurnHandles had one: TurnEngine set unlinkAbortSignal right after createStreamAtomically returned. TurnEngine now passes it in the registration context, and createStreamInfo puts it in the literal. Nothing ran between the two points. - TurnResources.closeStreamResources takes `WorkspaceStreamInfo & TurnHandles`, since it writes resourceCleanup and unlinkAbortSignal. The parent commit pins the unlink: a scratch edit that drops unlinkAbortSignal from the literal now fails its test. Lines: turnState.ts is 227 lines, and types.ts goes from 540 to 365 lines. No import cycles. Gates: make static-check, make lint-eslint and make dry-check pass. crap-check against the parent passes with coverage (0 violations, 0 warnings). Wide suite: 2775 pass, 0 fail. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
Test-only commit before layer 5 slice 9b moves the attempt loop's TurnSlot writes behind TurnRegistry. Two scratch edits survived the existing tests: - The loop does not set STREAMING when processing starts (the turn stays STARTING). - The failure path does not set ERROR (the turn stays STREAMING while it persists the error). New test in streamManager.completion.test.ts, "stream start": a turn whose provider stream fails reports getStreamState "streaming" at stream-start and "error" at its error event. isStreaming() reads this state. Scratch mutations on this commit: both edits now fail the test. No production code changes. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
…rn slot Layer 5 slice 9b. No behavior change. TurnSlot (state, token, messageId, workspaceName, executionScope, historySequence, startTime, processingPromise, cancelPromise, engineFiber, softInterrupt, completionController, terminalCompletion) is now Readonly in WorkspaceStreamInfo. Only TurnRegistry writes it. The writes that move behind TurnRegistry: - AttemptLoop's three state changes (STREAMING when processing starts, COMPLETED before stream-end, ERROR on failure) call TurnRegistry.setState. Its type takes only those three states: STOPPING stays the stop's own. - AttemptLoop's three terminal outcomes (completed, failed, aborted) call TurnRegistry.recordTerminal. The abort path now builds the completion in a local and settles the handle with that same object. - TurnEngine's processing promise goes through TurnRegistry.trackProcessing. The three methods are static: they only write the record, so neither AttemptLoop nor TurnEngine gains a dep. Each call sits where its assignment was, so no ordering changes. AttemptLoop and TurnEngine now import TurnRegistry as a value (no cycle: TurnRegistry imports neither). TurnRegistry's own writers (cancelStreamSafely, checkSoftCancelStream, superviseEngine, stopEngine) take `WorkspaceStreamInfo & TurnSlot`. The parent commit pins two survivors (the STREAMING and ERROR states). Scratch mutations on this commit, against the streamManager, turnEngine, aiService and agentSession suites: 9 of 10 fail a test. Not killed: dropping recordTerminal on the abort path. It is equivalent: nothing reads terminalCompletion after the abort settle sets it. The cancel latch runs the settle once, and processing has already finished, so the completion handle takes the local object directly. Lines: 56 added and 21 removed in 4 files. Gates: make static-check, make lint-eslint and make dry-check pass. crap-check against the parent passes with coverage (0 violations, 0 warnings). Wide suite: 2776 pass, 0 fail. No import cycles. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
… attempt request Layer 5 slice 9c. No behavior change. AttemptRequest (streamResult, model, metadataModel, thinkingLevel, request, stepTracker, the three didRetry* flags and modelFallback) is now Readonly in WorkspaceStreamInfo. Only ProviderRequest writes it after the record is built. The writes that move behind ProviderRequest: - The four attempt restarts (AttemptLoop's empty-output retry, StreamRetries' previousResponseId and reasoning-replay retries, and RefusalFallback's model hop) call ProviderRequest.beginAttempt. It sets the request first, then the stream result built from that request, the same order the callers used. - The three step-boundary and empty-output retry flags go through ProviderRequest.markRetry. - RefusalFallback's model swap calls ProviderRequest.adoptModel. The thinking level still changes only when the fallback chose one. - TurnEngine's two thinking-override writes call ProviderRequest.setThinkingLevel. The four methods are static: they only write the record, so no caller gains a dep. Each call sits where its assignments were, so no ordering changes. AttemptLoop, RefusalFallback, StreamRetries and TurnEngine now import ProviderRequest as a value (no cycle). Scratch mutations on this commit, against the streamManager, turnEngine, aiService and agentSession suites: 15 of 15 fail a test. Lines: 86 added and 40 removed in 6 files. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
d2a735c to
1595b80
Compare
…state (coder#7487) Layer 5x of the turn-engine split in stack #7398 (based on coder#7483). Layer 5 slice 9, part (d): make the TurnState record read-only outside StepApply, so only StepApply writes the parts, step indices, reasoning state and initial metadata. With this PR each of the six records in `turnEngine/turnState.ts` has one writer. No behavior change on any path that builds the record with `createStreamInfo`. ## What changed ### Commit 1: tests first (`68e032442d`) Test-only commit before layer 5 slice 9d moves the TurnState writes behind StepApply. Scratch edits that survived the existing tests: - The full retry reset keeps the old streamStepOrdinals, reasoningBackfillStartIndex, currentReasoningBlock or terminalFinishReason. - recordStepStart does not set currentStepStartIndex. - The refusal fallback does not apply prepare()'s initialMetadataPatch. Changes: - streamManager.completion.test.ts, "retry reset discards step indices together with discarded parts": the fixture now starts with non-default values for those fields, and the test checks that a reset without preserveParts clears them and sets currentStepStartIndex to 0. - streamManager.refusalFallback.test.ts, new test "the fallback's metadata patch reaches the committed row": a fallback whose patch sets systemMessageTokens commits a row with that value. Scratch mutations on this commit: all six edits now fail a test. No production code changes. ### Commit 2: enforce the owner (`c4653a4608`) Layer 5 slice 9d. No behavior change for a well-formed stream record. TurnState (parts, step and terminal bookkeeping, part timestamps, the pending tool buffers and initialMetadata) is now Readonly in WorkspaceStreamInfo. Only StepApply writes it. With this slice, all six records have one writer each. StepApply's own writers take StepStream (WorkspaceStreamInfo & TurnState). The writes that move behind StepApply: - StreamRetries' retry reset calls StepApply.restartStepNumbering before its first await and StepApply.resetForRetry after it, so the reset order across that await does not change. recordStepStart moves from StreamRetries into StepApply (its only other caller), so StreamRetries can import StepApply without a cycle. - RefusalFallback's three initialMetadata writes and TurnEngine's three (the step tracker's system-section hook, the manual thinking override and Auto thinking escalation) call StepApply.setInitialMetadata. - RefusalFallback's reasoning backfill start calls StepApply.setReasoningBackfillStart. The four methods are static: they only write the record, so no caller gains a dep. RefusalFallback, StreamRetries and TurnEngine now import StepApply as a value (no cycle). TurnEvents (StepApply imports it) and StreamManager initialized pendingNestedCalls and pendingToolExecutionStarts with `??= new Map()`. Both maps are required fields, and TurnEngine's createStreamInfo builds them, so the two writes were dead. They now read the maps directly. A record without the maps, which the type rejects, now throws there. The parent commit pins six survivors. Scratch mutations on this commit, against the streamManager, turnEngine, aiService and agentSession suites: 21 of 21 fail a test. Lines: 94 added and 50 removed in 8 files. Gates: make static-check, make lint-eslint and make dry-check pass. crap-check against the parent passes with coverage (0 violations, 0 warnings). Wide suite: 2777 pass, 0 fail. No import cycles. ## Validation - The tests in commit 1 pass on the parent `82136d1e8e` and kill the 7 scratch mutants that survived there (step ordinal reset at 2 sites, backfill reset, reasoning-block reset, finishReason reset, `currentStepStartIndex` in `recordStepStart`, RefusalFallback's `initialMetadataPatch`). - Scratch mutants on the refactor: 21 of 21 fail a test. - 2352 targeted tests pass here (streamManager*, aiService, turnEngine, continuousCompactor, turnRequestBuilder, coreServicesRoot, serviceContainer, errorRecovery, agentSession), and `make typecheck` passes. The builder's wider run passed 2777 of 2777. - `make static-check`, `make lint-eslint`, `make dry-check` and the CRAP check (with coverage, 0 violations) pass with the parent as the base. No import cycle exists. ## Risks Low. Field writes in StreamRetries, RefusalFallback and TurnEngine become calls to four static StepApply writers that make the same assignments. StreamRetries keeps the order around its `await partialJournal.resetForRetry`: `restartStepNumbering` before it and `resetForRetry` after it. One deliberate change: `TurnEvents` and `streamManager.ts` no longer lazily create `pendingNestedCalls` and `pendingToolExecutionStarts` with `??= new Map()`. Both fields are required by the type, and `createStreamInfo` (`TurnEngine.ts:223-224`) always builds them, so the fallback never ran. A hand-built record without them now fails at those reads instead of silently getting a new map. `WorkspaceStreamInfo` is in-memory only, so no persisted state can lack them. --- _Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking: `high` • Cost: `$82.48`_ <!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high costs=82.48 -->
Layer 5w of the turn-engine split in stack #7398 (based on #7482). Layer 5 slice 9, part (c): make the AttemptRequest record read-only outside ProviderRequest, so only ProviderRequest writes the stream result, request, model, thinking level and retry flags. No behavior change.
What changed
Layer 5 slice 9c. No behavior change. AttemptRequest (streamResult, model,
metadataModel, thinkingLevel, request, stepTracker, the three
didRetry* flags and modelFallback) is now Readonly in
WorkspaceStreamInfo. Only ProviderRequest writes it after the record is
built.
The writes that move behind ProviderRequest:
StreamRetries' previousResponseId and reasoning-replay retries, and
RefusalFallback's model hop) call ProviderRequest.beginAttempt. It
sets the request first, then the stream result built from that
request, the same order the callers used.
ProviderRequest.markRetry.
thinking level still changes only when the fallback chose one.
ProviderRequest.setThinkingLevel.
The four methods are static: they only write the record, so no caller
gains a dep. Each call sits where its assignments were, so no ordering
changes. AttemptLoop, RefusalFallback, StreamRetries and TurnEngine now
import ProviderRequest as a value (no cycle).
Scratch mutations on this commit, against the streamManager, turnEngine,
aiService and agentSession suites: 15 of 15 fail a test.
Lines: 86 added and 40 removed in 6 files.
Validation
make typecheckpasses. The builder's wider run passed 2776 of 2776.make static-check,make lint-eslint,make dry-checkand the CRAP check (with coverage, 0 violations and 0 warnings) pass with the parent as the base. No import cycle exists.Risks
Low. Field writes in AttemptLoop, StreamRetries, RefusalFallback and TurnEngine become calls to four static ProviderRequest writers (
beginAttempt,markRetry,adoptModel,setThinkingLevel) that make the same assignments in the same order.beginAttemptsets the request before it builds the stream result from it, as the old code did. The compiler now rejects any other write to the record.Generated with
xum• Model:anthropic:claude-opus-5-5• Thinking:high• Cost:$80.79