Repository navigation
improve: reduce Gateway stalls during compaction rewrites - #202547
Conversation
Use the internal read-only branch boundary for rewrite matching and replay so hydrated payloads remain shared through preparation and publication. Preserve writable SDK and opaque graph isolation in the existing snapshot owner. Add mutation regression coverage and a synthetic compaction transcript benchmark.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review in progressClawSweeper is reviewing this revision. This supersedes any previous blocked status. |
Codex Review Summary: ✅ CompletedThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4a004a3342
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
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".
|
@clawsweeper re-review Please review final head |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review Final head is now |
|
🦞👀 Re-review progress:
|
|
Codex review: needs maintainer review before merge. What this changesThis PR uses the existing internal read-only transcript accessor during rewrite matching and replay to avoid unnecessary history copies. Example: Rewrite a tool result near the end of a persisted 1,700-message conversation.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this useful, maintainer-authored PR open: the earlier performance hold is resolved, and the focused change has no actionable findings. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherCompaction and transcript-maintenance callers submit message replacements to the embedded runner, which prepares a detached SessionManager branch and commits it through the existing persistence owner. flowchart TD
A[Compaction or maintenance] --> B[Transcript rewrite]
B --> C[Internal branch reader]
C --> D[Detached rewrite snapshot]
D --> E[Replay changed suffix]
E --> F[Existing persistence commit]
Technical reviewBest possible solution: Use the existing internal branch reader at both read-only rewrite sites while retaining the snapshot owner's mutation isolation and atomic commit. Do we have a high-confidence way to reproduce the issue? Current main's rewrite calls the writable accessor, whose implementation detaches hydrated payloads; the supplied regression and persisted-owner benchmark exercise this path, but no target code was run during this read-only review. Is this the best way to solve the issue? The two accessor substitutions are the smallest complete repair: they remove unnecessary writable exposure without adding state, changing public APIs, or moving persistence responsibility. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against f845db254767. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +2, Tests +39, Other +209. Total +250 across 3 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed November 20, 2026, 11:27 AM ET / 16:27 UTC (Revision 2). |
|
Item 1 — Resolved: the performance owner explicitly accepted the tail limitation. The Team perf-loop lead accepted it as an agent acting under Peter's standing unattended-operations instruction, not as Peter. The acceptance and rationale are now recorded in the PR body and were verified by readback. It releases the performance hold only; exact-head CI and this re-review still gate merge. Rationale: the rewrite path identified in production as a 2.5-second main-thread stall drops synthetic CPU 95.1% and allocation 96.5%, with all 320 measured output comparisons identical. The two read-only substitutions are at transcript-rewrite.ts:164 and transcript-rewrite.ts:180. The initial-context clone at session-manager-codec.ts:298 is unchanged because its projection borrows mutable SDK data. Its median latency and allocation are effectively unchanged; the roughly +20 ms p95 (67.5 → 87.7 ms) on that untouched path at small n is accepted as unattributed. Production delta: +2 lines. The evidence remains explicitly scoped to the real persisted transcript rewrite owner on a synthetic 1,700-message fixture. It does not claim a measured whole-Gateway or provider-inference latency improvement. The accepted initial-context optimization question is a separate follow-up, not part of this landing. @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…02547) * perf(agents): preserve sealed history during transcript rewrites Use the internal read-only branch boundary for rewrite matching and replay so hydrated payloads remain shared through preparation and publication. Preserve writable SDK and opaque graph isolation in the existing snapshot owner. Add mutation regression coverage and a synthetic compaction transcript benchmark. * test(agents): await rewrite regression seed persistence * test(agents): require seeded transcript entry IDs
* perf(agents): preserve sealed history during transcript rewrites Use the internal read-only branch boundary for rewrite matching and replay so hydrated payloads remain shared through preparation and publication. Preserve writable SDK and opaque graph isolation in the existing snapshot owner. Add mutation regression coverage and a synthetic compaction transcript benchmark. * test(agents): await rewrite regression seed persistence * test(agents): require seeded transcript entry IDs (cherry picked from commit 018e2fb) Co-authored-by: RomneyDa <[email protected]> (cherry picked from commit 39782333d63dbb44633bd9b955f99a7948866e59) (cherry picked from commit b0b733aa06dd55aecbabfa132df431bdc2779938)
What Problem This Solves
Rewriting a few messages during compaction copies unchanged conversation history on the Gateway thread, delaying other chats and creating avoidable garbage.
User Impact
Compaction transcript rewrites retain immutable history instead of making it writable and copying it again. Saved messages, replacement output, SDK mutation behavior, and commit checks stay unchanged. No configuration or migration is needed.
Why This Change Was Made
Matching and replay only read the branch, but both used the public writable accessor. On hydrated histories that detaches every payload before the rewrite snapshot can share it. Both reads now use the existing internal branch reader. The snapshot owner still copies mutable SDK data and private navigation containers; no new sharing policy or cache is introduced. Production delta is +2 lines (an import and ownership comment).
The initial-context projection still needs its clone: its fresh array borrows nested entries and SDK data. Freezing it in place would violate mutation isolation. This PR changes only the proven redundant writable exposure in the rewrite path.
Evidence
The regression fails on the exact base at the unchanged-payload identity assertion and passes with the fix. It also rejects mutation of shared history and proves subsequent writable SDK edits cannot change retained model context or durable history. All 92 focused tests pass, including existing opaque aliases, stale commit, metadata, notifications, plugin reads, and prompt-prefix stability. Isolated Codex autoreview through P2 is clean.
The committed benchmark exercises initial-context publication and a real two-entry rewrite/commit on a 1,700-message, 21,158,679-byte synthetic persisted history. Five counterbalanced A/A and five A/B pairs use five measured operations per process; allocation is measured in separate collected-inclusive sampling runs. All 200 measured outputs match an independently constructed expected result and have identical iteration-specific complete-context digests across arms. SQL setup/hydration is excluded; commit is included. This is owner-boundary proof, not whole-Gateway or provider-inference performance.
Rewrite CPU improves 95.1% and allocation 96.5%. A/A rewrite CPU differs 0.84%, allocation 0.41%. Separate CPU profiles support the owner diagnosis: inclusive
cloneTranscriptViewsamples fall from 626.28 to 34.84 ms, and rewrite preparation from 206.61 to 11.94 ms, across one warmup and one measured operation.Accepted tail limitation: original pooled initial-context p95 was 66.166 → 90.280 ms (+36.4%), despite this code being unchanged. An additional A/A control and five counterbalanced A/B pairs, now ten measured operations per process, retain this concern: initial-context pooled p95 67.471 → 87.750 ms (+30.1%), mean CPU 61.051 → 62.532 ms (+2.4%), median wall 61.017 → 61.320 ms (+0.5%). Rewrite pooled p95 improves 364.983 → 40.632 ms and mean CPU 323.445 → 15.886 ms in that qualification. All additional outputs match. Shared-host scheduling contributes to some spikes (135 ms wall / 71 ms CPU), but this is not proof that the tail difference is harmless. No samples were discarded. The initial-context clone is retained, and no first-stall elimination claim is made.
The Team perf-loop lead accepted this limitation as an agent acting under Peter's standing unattended-operations instruction, not as Peter. Rationale: this fixes the rewrite path identified in production as a 2.5-second main-thread stall; synthetic proof reduces rewrite CPU 95.1% and allocation 96.5%, with all 320 measured output comparisons identical. The initial-context path is unchanged because its projection borrows mutable SDK data. Its median latency and allocation are effectively unchanged; the roughly +20 ms p95 (67.5 → 87.7 ms) on that untouched path at small sample size is accepted as unattributed. Production delta is two lines. Acceptance removes only the performance hold; exact-head CI and final-head ClawSweeper must still pass.
Focused command:
node scripts/run-vitest.mjs src/agents/embedded-agent-runner/transcript-rewrite.test.ts src/agents/embedded-agent-runner/transcript-rewrite-metadata.test.ts src/agents/embedded-agent-runner/transcript-rewrite-plugin-reads.test.ts src/agents/embedded-agent-runner/transcript-rewrite-notifications.test.ts src/agents/sessions/session-manager-maintenance-async.test.ts src/agents/sessions/session-manager-codec.test.ts src/agents/agent-tools.prefix-stability.test.ts --maxWorkers=1(92 tests; 176.30 s including compilation and four shards).pnpm check:changedcompleted: all guards pass except the original proof-code type/lint errors (both corrected and rechecked successfully) and an unrelated unusedCronScheduleexport introduced by #202416 at the exact base44ec89e71877ef2194e18a028ab828b995203844. The same dead-export guard reproduces both findings in a clean worktree on that exact parent with frozen dependencies (exit 1). This remains a reported main regression, not a green full-check claim. Final-head CI run 44770160216 passed. ClawSweeper re-review on8c72a97b5d3a4728e5c3f9bf3f4bad1c040c8f11has no findings and zero open before-merge items; it acknowledges the performance acceptance. Nativescripts/prmerged that exact head as018e2fb364bb977d8f537a671b8df0fa35933910, verified reachable from main. The regression fixture was corrected to await async open/appends after hosted Codex feedback; that final fixture fails on the exact base at the intended identity assertion and passes at final head8c72a97b5d3a4728e5c3f9bf3f4bad1c040c8f11. CI caught missing narrowing of async append IDs in the first fixture correction; existingexpectDefinedassertions now establish that contract. The affected test typecheck and regression pass, the assertion correction has a clean isolated Codex review, and the hosted thread is resolved. Production/benchmark source is unchanged. No browser-runtime module or visual behavior changes; import search underui/srcfound no changed-module consumers.