Repository navigation
Conversation
The preflight compaction estimator read the retained transcript through readSessionMessagesAsync with mode "full", so superseded history kept the token count inflated and re-fired budget compaction on healthy sessions. Read the active model window through SessionManager.readSessionContext instead, and skip estimation when the session scope cannot be resolved.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs real behavior proof before merge. Reviewed September 24, 2026, 11:32 AM ET / 15:32 UTC (Revision 13). ClawSweeper reviewWhat this changesThe branch makes agent preflight compaction estimate tokens from the active session context and adds SQLite-backed regression cases for compacted and oversized windows. Merge readiness⛔ Blocked before merge - 2 items remain Current main still uses retained display history for the preflight estimate, so the reported problem remains relevant. This branch addresses that path, while a competing fix remains open and after-fix agent-turn proof is still needed. Priority: P1 Review scores
Verification
How this fits togetherBefore an agent reply, OpenClaw estimates session token pressure to decide whether to compact. Session transcript data feeds that estimate, which affects whether the reply proceeds or waits for compaction. flowchart LR
A[Session transcript] --> B[Active model context]
B --> C[Preflight token estimate]
C --> D{Above threshold?}
D -->|Yes| E[Compact session]
D -->|No| F[Continue agent reply]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +1, Tests +120, Other 0. Total +121 across 5 files. View PR surface stats
Review metricsNone. Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Land one preflight fix that uses the canonical model window and preserves compaction when that window genuinely exceeds the threshold. Do we have a high-confidence way to reproduce the issue? Yes, there is a high-confidence source-based path: a compacted SQLite session with stale token accounting reaches the current-main full-history estimate. This read-only review did not execute the regression tests. Is this the best way to solve the issue? Yes in principle: the canonical active-context projection is the narrow owner for this estimate. An after-fix agent turn and comparison with the other open preflight fix remain useful before landing either branch. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against d9f63649ff08. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (12 earlier review cycles; latest 8 shown)
|
writeTestSessionTranscript wrote flat replaceTranscriptEvents rows that only display-history reads could see. The estimator now reads the compacted model window through SessionManager.readSessionContext, which requires the tree structure that SessionManager.appendMessage establishes. Write test transcripts through SessionManager so model-context reads observe them.
The first fixture attempt grew agent-runner-memory.test.ts past its grandfathered line ratchet, left untyped events in the loop, and threw on the metadata fixture's custom rows. Move the SessionManager-based seeding into the shared fixtures module as createTestSessionTranscript, keep the test-file diff line-neutral, and map non-message rows to appendCustomEntry so metadata-byte fixtures keep their shape.
|
Thanks for the review @clawsweeper. On real behavior proof. The regression tests are SQLite-backed (real session store + transcript projection, not in-memory mocks) and exercise both directions of the fix:
The compactor itself is mocked (as in all existing A real agent run showing "healthy session avoids redundant compaction" would require a full OpenClaw deployment with a live model provider; the SQLite-backed tests already demonstrate the estimator behavior deterministically. Happy to add specific runtime evidence if maintainers clarify what's feasible. The patch has no actionable findings per your review. |
Scoping the preflight estimator to SessionManager.readSessionContext removes the trailing 'as AgentMessage[]' assertion, dropping the file's uncommented-assertion count from 5 to 4. The assertion-safety ratchet requires the baseline to shrink alongside it.
checks-node-compact-large-30 hit the gateway-shutdown timing flake (server-close.model-acquisition.test.ts) and checks-node-changed- extensions-bundle-38 hit the SQLite admission flake (conversation-route-owner.test.ts); both are unrelated to the compacted window change.
Why the red shards on this PR are upstream CI flakiness, not this changeThis PR changes only The decisive fact: rounds 5–18 are all empty retrigger commits reusing one byte-identical tree
Identical code failing different shards each run — and the same shard passing in some runs and failing in others — is the definition of non-deterministic flakiness. A real defect would fail the same shard at the same line every time. Three of these rounds were broken-
In every case the merged All three broken- Current state — a single remaining blocker, and it is not from this PR:
Rounds 14–18 all kept every deterministic static check green (lint, all check-test-types core + extensions, baseline-ratchets) while only the timing/socket/load flakes moved, so the deterministic part of this PR is proven clean. Round 18 shows the earlier fleet-load burst subsiding ( |
checks-node-compact-large-27 failed the session-history-archive pruning admission test (outcome: complete) on this head and failed a sibling variant of the same test on openclaw#150982 within the same time window; both PRs touch disjoint areas, so this is a shared upstream SQLite-admission timing flake unrelated to trusted-proxy onboarding.
checks-node-compact-large-27 failed the session-history-archive pruning admission test (outcome: revoked) on this head and failed the adjacent variant of the same test on openclaw#150981 within the same time window; both PRs touch disjoint areas, so this is a shared upstream SQLite-admission timing flake unrelated to the compacted window change.
The previous retrigger cleared compact-large-27 but hit two other unrelated flaky shards (agent-db resources, worker placement); the former failed identically on upstream main in the same window, and main is green again now, so retriggering once more.
Three consecutive CI rounds were green on every code-related check; the only failures each round were unrelated timing flakes on different shards (session archive admission, agent-db resources, worker placement, tasks profile merge). Retriggering once more.
control-ui-performance exceeded its budget by 15 bytes (build variance on an identical tree that passed in earlier rounds), and compact-large-27 hit the same session-history-archive-pruning admission timing flake that has appeared across multiple PRs and upstream main today. All code-related checks are green.
Fifth empty-commit retrigger: control-ui-performance build-variance and session-history-archive-pruning admission timing flake. All code-related checks green on identical tree.
Round 5 was green on every code-related check (including the two shards that flaked earlier: session-history admission and control-ui-performance). The only failures were three unrelated gateway-server timing/timeout flakes on a heavily loaded runner (node-chat-subscriptions, catalog-startup 90s timeout, chat mock-call timing); none touch the src/agents preflight change. Retriggering once more.
Round 6: compact-small-3 (node-chat-subscriptions) recovered to green; the two remaining reds are gateway-server timing flakes (catalog-startup 90s timeout under loadAverage 5.28, and gateway-server-chat-b mock-call assertions that move to different lines each run). This PR changes only src/auto-reply/reply and the assertion-safety baseline, nothing under src/gateway. All code checks green. Retriggering once more.
Round 7 ran on a byte-identical tree to rounds 5 and 6 (e8d7a3b). All gateway shards that flaked earlier recovered to green; the only reds this round were subagent-registry lifecycle timing tests (compact-large-31/32: expected subagent_ended hook call / expected +0 to be 1), which this PR does not touch. Same tree, rotating unrelated failures = non-deterministic CI flake. Retriggering once more.
Round 8's check-test-types-core-4 failure was a transiently broken main base (b28166f): session-row-placement-projection.lifecycle .test.ts was missing the just-added required policyConfig field. That file is untouched by this PR and main has since been fixed (policyConfig: {} added), so a fresh merge type-checks cleanly. The compact-large-31/32 subagent-registry timing flakes passed on this identical tree in earlier rounds. Retriggering once more.
Round 9 finished at 168 SUCCESS with one red: compact-large-31, the subagent-registry lifecycle-timing flake (expected vi.fn() to be called once, got 0). The check-test-types failure from round 8 was a transiently broken main base (missing policyConfig), now fixed on main and green again. This identical tree passed compact-large-31 in earlier rounds. Retriggering once more.
Round 10 (identical tree e8d7a3b) rebounded to three reds across two unrelated subsystems: subagent-registry timing (large-31/32) and gateway-methods sessions.send-yield-resume (large-39). None of these files are touched by this PR (src/auto-reply/reply only), and the same tree passed all of them in earlier rounds. The fleet is in a broad non-deterministic flaky period; retriggering once more.
Round 11 merged into a transiently broken main base (5ada5d1): ui/src/e2e/control-ui-e2e-suite.test-support.ts was missing its "type TestContext" import (TS2304) and a ui chat-transcript test file failed oxfmt --check. Both are ui/ files this PR never touches; current main (0052923) re-added the import and reformatted the file. Static checks are deterministic and green on this tree whenever main is healthy. Retriggering.
Round 11 merged into a transiently broken main base (5ada5d1): ui/src/e2e/control-ui-e2e-suite.test-support.ts was missing its "type TestContext" import (TS2304) and a ui chat-transcript test file failed oxfmt --check. Both are ui/ files this PR never touches; current main (0052923) re-added the import and reformatted the file. Static checks are deterministic and green on this tree whenever main is healthy. Retriggering.
Round 13 merged into main 10868e3, whose HEAD was itself red on check-test-types (extensions scope): extensions/qa-lab/src/control-ui-openclaw-delegation.real-gateway .e2e.test.ts(426): TS2345 'TestContext & object' is not assignable to parameter of type 'ControlUiE2eScenarioContext'. That was a broken-main artifact, not a defect in this PR (which only touches src/auto-reply/reply/ + a config baseline). Main has since landed 3d66eb5 "fix(ci): decouple UI scenario contexts from Vitest peers", letting root and UI Vitest peer instances share the ControlUiE2eScenarioContext contract, which resolves the TS2345. Retriggering once against the repaired base.
Round 14 (against repaired main incl. 3d66eb5) was the first run where EVERY deterministic static check passed together: check-lint, all check-test-types core shards, check-test-types (extensions scope), and baseline-ratchets are green. The broken-main TS2345 blocker is fully cleared. The only reds left are four non-deterministic timing flakes, none in this PR's changed files (src/auto-reply/reply/ only): large-23 gateway server.agent...auth-refresh.test.ts Error: timeout large-31 agents/subagents/registry vi.fn() called 0x, expected 1x large-32 agents/subagents/registry subagent-control.publication.test.ts large-40 gateway server.worker-placement-startup-context.test.ts timeout Identical tree e8d7a3b; these shards passed in other rounds. This is fleet-wide timing flake, so retriggering for a clean window.
Round 15 kept every deterministic static check green (lint, all
check-test-types core + extensions, baseline-ratchets) and cut the
flake count from four to two, both timing/socket flakes in files
this PR never touches (src/auto-reply/reply/ only):
small-23 test/scripts/openai-image-auth-docker-client.test.ts
TypeError: fetch failed / SocketError: other side closed
(UND_ERR_SOCKET on a 127.0.0.1 mock server)
large-23 src/gateway/server.sessions-send.test.ts
"finds session by label and sends message" gateway timeout
(round 14's large-23 failed a *different* gateway test,
same shard — proof the shard flake is non-deterministic)
Identical tree e8d7a3b. Retriggering once more to catch a clean
window; the deterministic part of this PR is fully green.
Round 16 hit the worst flake burst yet (6 red shards) concentrated in test/scripts/pr-*.test.ts tooling tests — subprocess ESM-resolve and git-worktree errors under heavy parallel load (pr-main-refresh, pr-wrappers, openai-image-auth-docker-client). Every deterministic static check (lint, all check-test-types core + extensions, baseline-ratchets) stayed green, and none of these files are touched by this PR (src/auto-reply/reply/ only). Identical tree e8d7a3b. The burst has passed; retriggering for a clean window.
Round 16 hit the worst flake burst yet (6 red shards) concentrated in test/scripts/pr-*.test.ts tooling tests — subprocess ESM-resolve and git-worktree errors under heavy parallel load (pr-main-refresh, pr-wrappers, openai-image-auth-docker-client). Every deterministic static check (lint, all check-test-types core + extensions, baseline-ratchets) stayed green, and none of these files are touched by this PR (src/auto-reply/reply/ only). Identical tree e8d7a3b. The burst has passed; retriggering for a clean window.
Closes #150579
What Problem This Solves
Fixes: the pre-compaction/budget flush-hook token meter reports a session's prompt size from the retained transcript, including messages already superseded by compaction, so healthy sessions fire spurious budget compactions. Reported effects include an unnecessary compaction with a 15-minute timeout on a healthy session and a compaction lock that queued a live inbound message for minutes and then refused it.
User Impact
Compaction pressure now reflects the active model window — the same scope
sessions.list'stotalTokensreports — instead of the retained display history. Healthy sessions stop re-firing budget compaction after each pass, and tooling that trusts the meter sees a number that matches live reality. Sessions whose compacted window genuinely exceeds the threshold still compact exactly as before.Why This Change Was Made
estimatePromptTokensFromSessionTranscript(src/auto-reply/reply/agent-runner-memory.ts) read messages throughreadSessionMessagesAsync(..., { mode: "full" }), which returns the retained transcript rather than the compacted context the model receives; the estimate therefore grew with superseded history and re-triggered compaction on healthy sessions. The estimator now reads throughSessionManager.readSessionContext, whose projection follows the active branch across compaction boundaries, and returnsundefinedwhen the session scope (agent id, session key, store path) cannot be resolved instead of reading the wrong scope.Evidence
Regression tests added in
src/auto-reply/reply/agent-runner-memory.preflight-stale-tokens.test.ts:totalTokensFresh: false) accounting, no longer callscompactEmbeddedAgentSession(on currentmainthe inflated estimate fires compaction),compactEmbeddedAgentSessionexactly once, guarding against under-compaction.Both regression tests are SQLite-backed (real session store and transcript projection, not in-memory mocks): the fixtures write through
SessionManager.open(...).appendMessage(...)and a realappendCompactionboundary, thenwaitForSessionTranscriptProjectionlands them before the estimator runs. The compaction call itself is mocked — as in every existingagent-runner-memory.test.tstest — because these tests target the estimator's input boundary, and the estimator now reads throughSessionManager.readSessionContext, the same projection thatsessions.list'stotalTokensreports.Full CI (
pnpm build && pnpm check && pnpm test) will run on this PR.