Repository navigation
Conversation
|
🦞👀 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: needs real behavior proof before merge. What this changesScope fallback token estimates to the compaction summary, retained entries, and subsequent messages while preserving measured usage. Example: A JSONL artifact contains a 4000-character archived message, a retained 2000-character message, a 500-character summary, and a 15-character live tail.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 2 items remain Keep open: this PR fixes a distinct JSONL diagnostic overestimate still present on current main; no blocking correctness defect was found. Priority: P2 Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherAuthorized raw reply diagnostics read legacy JSONL artifacts through the transcript usage seam and render the resulting usage snapshot in reply payloads. flowchart TD
A[Raw reply diagnostic] --> B[Reply finalization]
B --> C[Transcript usage seam]
C --> D[JSONL artifact reader]
D --> E[Usage accumulator]
E --> F[Rendered session usage]
Technical reviewBest possible solution: Keep the focused boundary-aware estimate in the existing accumulator and retain one diagnostic integration suite alongside the distinct reader regressions. Do we have a high-confidence way to reproduce the issue? Current-main source demonstrably sums superseded JSONL messages; contributor-reported red/green results cover the same failure, but no target code was executed during this read-only review. Is this the best way to solve the issue? The production change repairs the estimate at its existing owner, preserves snapshot precedence, and leaves SQLite behavior unchanged; the redundant builder-level tests can be removed. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 6c57f5a9cfd5. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +61, Tests +344, Other +6. Total +411 across 8 files. Added test files: 3. 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. Review metrics
LabelsLabel changes: No label 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 (19 earlier review cycles; latest 8 shown)
Reviewed November 15, 2026, 6:46 AM ET / 11:46 UTC (Revision 20). |
c102fb1 to
a1fedb4
Compare
a1fedb4 to
e0eae47
Compare
e0eae47 to
8de22e7
Compare
8de22e7 to
7467d58
Compare
|
CI note on the |
|
CI refresh on 44bc990 (merged current main in to clear the stale-plan drift behind the The merge needed one real repair, and I want it on record: main's accumulator refactor (
Evidence (macOS arm64, Node 22, merged tree): the previously red plan test ( |
|
Runtime follow-up on a real compacted session (after-fix, redacted). Setup: isolated Artifact: the session's real transcript events from the canonical store, serialized back to the legacy JSONL shape (11 lines: session header, three 16,258-char user messages, compaction #1, a user message, a short assistant tail, a bootstrap event, compaction #2). Nothing hand-authored. A redacted variant drops the usage fields and the model-snapshot event so the chars estimate is what gets measured (older transcripts genuinely lack usage). After-fix reader output on the real file: The estimate now covers only the live window after the latest compaction: empty here, so no 4065 tokens of superseded history read as live context on a twice-compacted session: that is the misfire, and it is gone after the fix. The aggregate side is untouched: on the usage-carrying artifact the reader still reports the real provider totals (49,037 input / 1 output / $0.0126), confirming that usage snapshots aggregate across boundaries by design while only the estimate restarts. [AI-assisted] — session driven and outputs captured locally as described. |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. |
|
The first hosted run on Current main @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Correction to my previous ratchet note: slack 561 came from a non-staged sparse-worktree count that omitted 566 tracked test lines. The full-index command reproduces hosted CI exactly: Shipped diagnostic proof on Boundary-terminal artifact, ending at the real compaction whose 464-char summary names the 91-char retained user message, with usage fields removed: Full artifact with usage fields removed: Full measured control, preserving the real provider usage fields: The estimates still match ceil((464 + 91) / 4) = 139 and ceil((464 + 91 + 56 + 90) / 4) = 176. The measured control is unchanged. The PR body now records this shipped-path evidence. @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
The reviewer asked for a shipped request path, not only the reader in process. Drive buildReplyDiagnosticsPayload with an absolute JSONL sessionFile and read the rendered "Usage (Session Total)" block, which is what a raw trace reply shows.
|
@clawsweeper re-review Addressed the remaining "real behavior proof" item with a shipped request path rather than more in-process output.
Two cases, both on the real artifact reader with no mocks:
Red-green on this head: with the boundary handling in
Still not covered: a live Gateway session against a real provider. This host has no channel credentials, so the proof is the shipped diagnostic builder over a real JSONL artifact rather than a recorded production session. Saying so plainly rather than implying more. |
|
🦞👀 Re-review progress:
|
The reviewer asked for a shipped CLI or Gateway diagnostic request, not the reader in process. The previous test drove buildReplyDiagnosticsPayload directly, which is the composition step, not the request a user issues. Drive finalizeReplyAgentRun instead. That is the exported entry the reply pipeline calls, and it reaches the diagnostic through prepareReplyAgentPayloads and accountAgentTurn rather than by naming the builder. Read the rendered "Usage (Session Total)" block out of the returned payloads. Two cases, same contract as the reader-level test: the retained window and compaction summary are estimated while the superseded archive is not, and a later per-call snapshot still wins over any estimate. Red-green through the shipped path: dropping the boundary's window reset in session-transcript-derived-readers.ts makes the first case render total=1,504 tok instead of total=629 tok and fail; restoring it passes. The production file is byte-identical to its committed state afterwards. agent-runner-result.shipped-diagnostic-usage.test.ts 2 passed agent-runner-result-diagnostics.artifact-usage.test.ts 2 passed agent-runner-result.usage-diagnostics.test.ts 1 passed oxlint and oxfmt clean on the new file. The repo-wide oxlint wrapper cannot run in this checkout: its plugin-sdk boundary step rejects a node_modules realpath that resolves into a sibling worktree, so the binary was invoked directly on the changed file instead. Test-lines ratchet passes with a 112-line allocation registered for the new file.
|
The shipped-request gate is now addressed on
Two cases through that path:
Red-green through the shipped path, not just the reader: dropping the boundary's window reset in Getting the shipped path to actually reach the artifact reader took two corrections worth recording, since they are properties of the path rather than of the fixture: the reply context carries a concrete Tests: 2 passed in the new file, 2 in the builder-level file, 1 in the existing silent-reply usage test. oxlint and oxfmt clean on the new file. The repo-wide oxlint wrapper cannot run in this checkout because its plugin-sdk boundary step rejects a @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@vincentkoc @steipete Could I get a human review of The usage estimate should cover the live model window across compaction boundaries: the compaction summary, the retained tail named by Could you check that ownership against the current transcript accumulator and the shipped diagnostic reply path? The PR includes a real compacted-session reproduction and shipped-entry tests. The current rollup still has one failure and two cancellations, so this is a request for the correctness and ownership decision, not a merge-ready claim. |
|
This pull request has been automatically marked as stale after 7 days without qualifying human activity. |
Refs #150579
What Problem This Solves
A compacted session's transcript usage report (the JSONL artifact seam behind diagnostic reads) counted the whole append-only archive as live context. Content superseded by a compaction or reset stays in the file, and the chars-based estimate summed every user/assistant message ever written, so the reported total kept growing across clean compactions while the model's actual context stayed small.
A second gap sat next to it: once the estimate restarted at a boundary, eligibility was re-derived only from model-tagged assistant entries in the retained window. A summary-only window (the cut names an entry outside the message window) or a retained-user-only window (overflow compaction with a pending user message as its tail) lost the estimate until the next assistant reply, even though the summary and retained text were sitting in the model context.
Root cause
aggregateSessionTranscriptUsagefillstotalTokensfrom a chars estimate when no per-call usage snapshot provides one.readLatestSessionUsageFromTranscriptFileAsyncfeeds it the full JSONL transcript, and the estimate accumulatedestimatedTranscriptCharsover the whole scanned set with no notion of boundary markers or the retained window they name. The boundary restart also resetsawEstimateModelIdentityfrom the retained entries alone, whilefinish()requires that flag, so any window without a surviving model-tagged assistant reported no estimate at all.Fix
compaction/resetboundary records through with theirsummary/firstKeptEntryIdfields, and forwards each entry's id, instead of skipping markers.firstKeptEntryIdplus the compaction summary, matching the model-context contract (compactionSummary + retained entries + post-boundary messages) and the transcript tree selector's fallback (an unknown kept target drops the pre-boundary window). The previous revision restarted the estimate at zero, which undercounts a compacted session that retains a large summary or window.totalTokenssnapshot still wins over any estimate, unchanged.Scope
This change lives entirely in the JSONL artifact seam:
readLatestSessionUsageFromTranscriptFileAsyncreads bounded transcript artifacts and its callers are diagnostic paths. The live budget-preflight path from #150579 reads the SQLite seam, which already scopes to the active context and is untouched here; that preflight symptom stays with #150579 and the PRs addressing it directly. This branch does not close the issue.Evidence
session-usage-estimate.test.ts: a compaction keeps its 500-char summary plus the 2000-char retained message named byfirstKeptEntryIdwhile dropping the 4000-char superseded prefix; a reset keeps its named retained tail; an unknown kept target drops the pre-boundary window but still counts the summary. Three further regressions end the transcript right at the boundary (summary-only window, compaction retaining only user messages, reset retaining only user text), covering the read between the boundary and the next assistant reply; earlier versions of these tests appended that reply, which masked the eligibility drop.context_length_exceeded, one committed auto-compaction, then one more turn. The committed marker carries a 464-char summary and names a retained 91-char user message asfirstKeptEntryId, so the boundary leaves a summary-plus-retained-user window. The artifact is the session's real settled transcript events serialized back to legacy JSONL, with redacted variants that drop usage fields and the model-snapshot entry so the chars estimate is what gets measured. The after-fix reader reportstotalTokens: 139on the redacted prefix ending at the boundary (ceil((464 + 91) / 4), the summary plus the retained user text) and176on the full redacted artifact (ceil((464 + 91 + 56 + 90) / 4), adding the post-boundary assistant and user text). On the usage-carrying artifact the reader still reports the real provider aggregates (input 105 / output 25, latest context snapshot 120 total and available), so the estimate path and the snapshot path stay separate.dcfc49a70dfb, including upstream main3f2e7078de23:node scripts/test-projects.mts src/gateway/session-usage-estimate.test.ts src/gateway/session-transcript-derived-readers.usage.test.ts src/gateway/session-utils.fs.test.ts src/gateway/session-utils.transcript-usage.test.ts --maxWorkers=1passes 4 files and 50 tests. oxfmt and direct type-aware oxlint pass on the consolidated test; the net PR diff passesgit diff --check.591ef68b2e9: the real settled Gateway compaction events drive the productionbuildReplyDiagnosticsPayloadraw diagnostic path throughreadLatestSessionUsageFromTranscriptAsync, not just a direct reader call. With usage fields removed, the boundary-terminal artifact emitstotal=139and the full artifact emitstotal=176. The measured control emitsinput=105,output=25,cacheRead=0,cacheWrite=0,total=120. The probe prints only the session usage block, with no transcript text, credentials or endpoints.1ea8830335d8:agent-runner-result.shipped-diagnostic-usage.test.tsdrivesfinalizeReplyAgentRun, the exported entry the reply pipeline calls, and reads the renderedUsage (Session Total)block out of the returned payloads. The diagnostic is reached throughprepareReplyAgentPayloadsandaccountAgentTurn, not by naming the builder. Two cases: the retained window plus compaction summary is estimated while the superseded archive is not (total=629 tokagainst a 4000-char archived prefix that would otherwise inflate it), and a later per-call snapshot still wins (total=1,234 tok). Red-green through that same shipped path: dropping the boundary's window reset insession-transcript-derived-readers.tsrenderstotal=1,504 tokand fails the first case; restoring it passes, and the production file is byte-identical to its committed state afterwards. 2 + 2 + 1 tests pass across the new file, the builder-level file and the existing silent-reply usage test. oxlint and oxfmt are clean on the new file; the repo-wide oxlint wrapper cannot run in this checkout because its plugin-sdk boundary step rejects a node_modules realpath resolving into a sibling worktree, so the binary was invoked directly on the changed file. A 112-line allocation is registered and the test-lines ratchet passes with slack 0.config/test-lines-allocations/session-usage-active-window.txtgrants exactly those 145 added lines. The full-index ratchet on current headdcfc49a70dfb, using hosted CI's current main3f2e7078de23with--no-merge-base, reportsTest lines OK: 6561328; ceiling: 6561328; slack: 0.An earlier sparse local run omitted 566 tracked test lines and produced a false slack result; materializing those files reproduced hosted CI's over-10 failure before this consolidation.[AI-assisted] prepared with Kimi K3; verified locally as described above and reviewed line by line.