Repository navigation
fix(agents): honor account-scoped history limits instead of silently ignoring them - #119326
Conversation
|
Codex review: needs maintainer review before merge. Reviewed August 28, 2026, 10:28 PM ET / August 29, 2026, 02:28 UTC. ClawSweeper reviewWhat this changesThis PR makes embedded-agent history selection and compaction honor channel account and peer policy, preserves provider replay checkpoints, and adds tests and documentation. Regression provenancePossible regression — suspected (reviewed change). No predecessor PR is attributed. Merge readinessKeep open: current main still lacks account-aware history selection, while the branch has coherent source and gateway-boundary coverage. Exact-head integration checks and the latest ClawSweeper rank-up requirements need confirmation before merge. Priority: P1 Review scores
Verification
How this fits togetherThe embedded agent runner selects transcript history and compacts conversations before sending context to model providers. Channel and Gateway route facts determine the account policy; the selected or compacted checkpoint is persisted for the next model request. flowchart LR
A[Channel or Gateway session] --> B[Account and peer facts]
B --> C[Embedded agent history]
C --> D[Provider compaction]
D --> E[Persisted checkpoint]
E --> F[Next model request]
Before merge
Agent review detailsSecurityNone. Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Merge only after exact-head checks pass and the current ClawSweeper rank-up requirements are confirmed satisfied or explicitly waived. Do we have a high-confidence way to reproduce the issue? Yes, from source: current main resolves history policy without account and peer facts, while the branch passes those facts through the prompt and compaction owners. Is this the best way to solve the issue? Yes: the repair places account and peer policy resolution in the shared history owner and forwards authoritative route facts through each caller instead of adding downstream fallbacks. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 0b0a64e7e30e. LabelsLabel changes:
Label justifications:
EvidenceAcceptance criteria:
What 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 (44 earlier review cycles; latest 8 shown)
|
82be71f to
f5243ec
Compare
|
The P1 is correct and my PR body was wrong. I wrote that there was a single production call site; there are two, and I missed the second because I truncated my own call-site enumeration with
Fixed by forwarding the account id that file already had in scope (it passes getHistoryLimitFromSessionKey(params.sessionKey, params.config, params.agentAccountId),For coverage I exposed the history mock the compaction harness was already installing ( I checked the test actually pins the wiring by reverting the one-line fix and rerunning: then restored it for 125/125. Current state on the rebased branch: I have corrected the "single production call site" claim in the PR body rather than leaving it there. |
|
The identical failure is happening on two of my open PRs whose diffs have nothing in common:
Both fail the same way, in the same suite: There is no single change that is simultaneously in the embedded agent runner and in a QQBot command string, so a shared real-Gateway PTY end-to-end suite timing out on 30s RPCs is the far more likely explanation than either diff. Supporting detail: the string I am not pushing speculative commits to retrigger, and I cannot rerun jobs myself ( |
|
I dug into this properly rather than repeating my earlier "looks flaky", because you are right that So I ran the exact failing suite locally on this branch head ( It passes. And the durations explain the CI failure: Those are individual test durations on a fast local machine, against the 150000ms per-test cap that CI reports hitting. A single test already consumes about 58% of the timeout budget when nothing else is competing for the box. On a loaded CI runner that margin disappears, which is exactly the failure signature in the log: The other reasons I do not think this diff is the cause:
I am not pushing a speculative commit, per your instruction. I cannot rerun the job myself ( Separately, that margin looks worth a maintainer eye on its own: a real-backend suite whose slowest test sits at 87s against a 150s cap will keep producing red on unrelated PRs. Happy to file that as its own issue if useful. |
f5243ec to
4c74b49
Compare
|
The P1 is real and fixed, and it was a good catch on a subtlety I got wrong. I had copied the exact-key lookup style from Now using the shared normalized lookup, the same way const accountConfig = trimmedAccountId
? resolveNormalizedAccountEntry(
providerConfig.accounts,
normalizeAccountId(trimmedAccountId),
normalizeAccountId,
)
: undefined;Note that plain Coverage for the human-form key, as requested, across channel, DM, and per-DM precedence: for (const accountId of ["work-team", "Work Team", "WORK TEAM"]) {
expect(getHistoryLimitFromSessionKey("telegram:channel:c1", config, accountId)).toBe(40);
expect(getHistoryLimitFromSessionKey("telegram:dm:999", config, accountId)).toBe(41);
expect(getHistoryLimitFromSessionKey("telegram:dm:123", config, accountId)).toBe(42);
}I confirmed that test fails against the old exact-key lookup ( On the real-behavior proof, being straight about what I have and have not got. I added coverage that drives the real resolver and the real What I have not produced is a live channel transcript. The built Gates on the new head: One local note in case it bites anyone else: right after rebasing onto current |
7cf55cf to
af7f052
Compare
|
@clawsweeper re-review Improved the original repair in 38a5767eed9: authoritative route-peer disambiguation, queue propagation, numeric/colon peer regressions, and real endpoint message-input coverage. Configured Gateway and independent source-blind proof now cover 12 Telegram turns, whole-request account windows, actual sessions.compact, saved-checkpoint summary readback, and post-compaction prompt continuity. The updated body records both earlier failures and final passing evidence, exact production/test LOC, and the two deliberately preserved compatibility/product follow-ups. No native-runtime parity or authenticated external-service proof is claimed. |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
38a5767 to
1c087b9
Compare
|
@clawsweeper re-review Rewritten head Final local proof completed: full normal build and changed-file gates, independent Codex review, source-blind 19-turn/two-checkpoint Gateway continuity, visible no-provider-call The broader checkpoint repair was necessary to prevent short-window eviction from losing provider context. Complete output validation and replay stay with the provider/history owners. Deliberate transcript rewrite copies bypass only the already-checked ingestion lookup; ordinary ingestion remains deduplicated. Unsupported legacy checkpoints fail with the native recovery instruction rather than generic session-reset advice. Contributor credit is preserved. Exact-head hosted CI is pending; no merge is being claimed. |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Update: repaired and now rebased/pushed at The installed OpenAI 7.5.0 regression first reproduced four failures, then all 83 focused tests across five files passed, including nine real HTTP/lifecycle controls. A stalled body now settles at 107 ms for a 100 ms deadline, with all fixture sockets closed. The embedded compaction safety owner remained bounded before and after. Authenticated OpenAI was repeated after the repair: two compact calls and six continuations, all HTTP 200, with exact complete-output hashes across reopen and eviction. The preceding head passed changed-file checks and normal Original pre-land finding: the rewrite's |
Honor admitted account and peer policy, retain complete bounded provider checkpoints across short history windows, and recover unsupported replay from durable conversation history. Co-authored-by: ayaangazali <[email protected]>
Bound compaction response bytes before SDK parsing so request deadlines, body retries, and typed cancellation retain their canonical owner. Co-authored-by: ayaangazali <[email protected]>
…ization Co-authored-by: ayaangazali <[email protected]>
Co-authored-by: ayaangazali <[email protected]>
|
Merged via squash.
|
What Problem This Solves
Fixes an issue where channel users received the wrong amount of conversation history when the active account or peer policy differed from the channel default. Fixes connected cases where a short history window evicted a provider compaction checkpoint, causing context loss or replay rejection on later turns.
Related: #129599. This is a maintainer rewrite of the existing account-history PR, preserving @ayaangazali's contribution and covering the checkpoint lifecycle exposed by realistic short-window testing.
Why This Change Was Made
Account policy now uses normalized account configuration and admitted route facts, including peer and conversation kind. Manual Gateway compaction reads the existing current-primary conversation registry; it does not infer routing from a possibly ambiguous session key or create another routing store. Explicit zero and whole-map per-peer replacement retain their existing semantics.
Provider replay owns checkpoint continuity. The existing v1 assistant-owned envelope retains the complete validated OpenAI compact output, or the complete native xAI item, and preserves the opaque field for old readers. A transient projection carries at most one eligible original owner across history trimming, after identity/auth checks and before pairing. It neither copies checkpoints into later durable messages nor resurrects covered prelude messages. Prompt pressure measures the canonical checkpoint plus uncovered tail once and does not trust context totals that lack checkpoint/auth lineage. The actually prepared outgoing request determines checkpoint authority.
The complete output is bounded to 16 MiB, including serialized-envelope escaping/duplication; raw successful HTTP bodies are bounded before JSON parsing, with depth capped at 64. Capture falls back to ordinary client compaction if current payload/image/redaction policy would alter the checkpoint. Later redaction or a legacy retained-user checkpoint without its complete output requires explicit
/compactrecovery from full durable history. Provider/model/endpoint/session/auth fences remain intact. Anthropic replay uses its existing canonical resolved-key classifier, passing only a prepared eligibility boolean into core.The compact-only fetch wrapper bounds successful response bytes before the ordinary OpenAI SDK parser consumes them. The SDK still owns per-attempt body deadlines, retries and typed caller cancellation. This replaces the rewrite's raw
.asResponse()reader, which bypassed those SDK lifecycle guarantees; ordinary streaming and non-success HTTP responses retain their existing paths.No database schema/version, index, protocol, dependency, or new configuration setting changes. The additive persisted checkpoint field is an explicitly approved data contract, not a claim of zero persistence impact. Existing database newer-schema guards remain enforced.
User Impact
Per-account and per-peer history limits are applied consistently through ordinary turns, queued turns, and explicit compaction. Tight limits no longer silently discard valid provider context. Unsupported or redacted legacy checkpoint state fails visibly with a recovery action rather than sending a misleading partial transcript. Existing durable messages remain available for explicit recovery.
Telegram's native-ID supplemental history and linked-peer embedded turn history remain distinct documented policies. This does not change native Codex behavior, add Buzz multi-account support, or implement Buzz DM/reaction/media features.
Evidence
Land-ready candidate:
bb3d9a22eeb79362f9f58f2f6a9e36d9eeb8bea6, rebased ontof93be5b5fe56be6293a5517bd57ddcc135375fdaafter checkout-cleanup repairs #132169, #132204 and #132203 landed. The six-commit range-diff preserves the patch, with only context around upstream's isolated compaction-test workspace changed. All 154 compaction-hook tests and nine real HTTP lifecycle controls passed on this head. Normal and private-QA builds passed, including the UI budget (344732 B below 345947 B); the canonical build stamp matches the full candidate SHA. Exact-head CI run 33228608553 passed, includingopenclaw/ci-gate.The final compiled-boundary repeat also passed: both Gateway client/endpoint compaction cases (12 and 18 turns respectively, two endpoint generations with exact checkpoint hashes), 27 provider-replay tests and seven transcript-rewrite tests using real SQLite. Command:
OPENCLAW_VITEST_MAX_WORKERS=1 node scripts/run-vitest.mjs test/gateway-account-history.e2e.test.ts packages/ai/src/transports/provider-compaction-replay.test.ts src/agents/embedded-agent-runner/transcript-rewrite.test.ts --reporter=verbose; three shards completed in 245.79 seconds. Source remained clean and the build stamp was checked before and after. This is actual compiled Gateway behavior with controlled channel/model services, not authenticated Telegram/OpenAI. Current native review baseline5d8ef653has no overlapping production, test or documentation changes since the pinned base; only unrelated assertion-ratchet entries overlap by filename.The preceding
aa463aaacandidate passed final local changed checks and normalpnpm build, including the UI budget (346606 B below 347037 B), but CI run 33222068278 failed in the main-introduced checkout-cleanup test. This rebase incorporates the existing repairs; no duplicate cleanup patch or relaxed assertion was added. The older70382159812587afc4f9c00240449b6f1190987erun is not proof for the SDK-lifetime repair.The preceding failed merge job reported cleanup-failure fatal125 in the process-boundary assertion (small47, job99018176316). That test was introduced on main by #132105 and was absent from the pre-rebase
aa463aaahead. A separate isolated Linux diagnostic completed 80 cases and 568 boundary checks with 264 later ENOENT probes, all passing including the original implementation; this is not a local RED/GREEN reproduction and does not classify the failed CI processes as zombies or active writers. Diagnostic details and coordination are recorded with the existing repair owner./compactwithout a provider call. Publicsessions.compactmade one client-summary request containing first and later durable markers, with zero endpoint calls or opaque checkpoint bytes. A further Gateway restart and continuation retained the resulting summary. The deterministic summary derives only from the actual model request; this proves persistence/continuation, not model semantic quality./newresponse, then proved that only the native precheck error selects the fixed/compactinstruction; mutated, serialized, and spoofed errors do not become trusted copy.3270b4d3e6e35a4980757e5bdff535d120697f35opened the candidate database, retained the additive v1 field on read, and dropped only that field during its real rewrite. Exactly three intentional message appends preserved seven original rows byte-for-byte. Final-candidate reopen retained all six ordinary messages, added no rows, and required explicit/compactrecovery. Both revisions use unchanged state/agent schema guards 13/18. This is matching-schema pre-change-reader proof, not certification of a released older version; public full-history recovery is tested separately.Production/tooling LOC: +1021/-233 (net +788); tests/support: +2675/-146; docs: +40/-3; assertion inventory +1/-1. The production growth is primarily the complete-output validator/bounds and shared replay projection/pressure owner needed for a lossless provider contract; caller plumbing reuses the existing route and conversation owners. A lossy single-item projection, copy-forward checkpoint writes, or downstream retry would not repair the demonstrated lifecycle failure.
Provenance: account-history introduction is not reliably traceable through the available shallow boundary. The endpoint implementations carried the incomplete-output assumption forward: #123622 (xAI, merged 2026-08-14, author/merger @steipete) and #124974 (retained Responses messages, merged 2026-08-18, author/merger @steipete). This does not attribute the original account bug to the author at the shallow boundary. Actual upstream Codex source was inspected at d47e5cc0e2bbd35774dff15c83570519735d2ac4; complete-vector ownership informed the review, without claiming native-runtime parity.
Both rank-up moves from the earlier review are addressed: Gateway compaction consumes the persisted current-primary peer/chat-kind facts, and a real compiled RPC trace distinguishes the peer override from the account default. The latest ClawSweeper review, updated August 29 at 02:30 UTC for this exact head, reports no code or security findings. Its requests for final-head compatibility/session validation and confirmation of rank-up requirements are satisfied by the final compiled-boundary, persistence and CI results above; no requirement was waived. The previous review's 30-second runner interruption was not a terminal product failure; the Linux and final local executions completed.
Release context: