Skip to content

fix(codex): avoid repeated host compaction on native turns - #175256

Merged
obviyus merged 16 commits into
mainfrom
fix/codex-lazy-seed
Oct 17, 2026
Merged

obviyus merged 16 commits into
mainfrom
fix/codex-lazy-seed

Conversation

@obviyus

@obviyus obviyus commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #158044, #126171, #115514, #167916

What Problem This Solves

Fixes repeated host summarization on ordinary Codex turns, including the turn after native /compact, when OpenClaw's transcript mirror exceeds its byte limit.

User Impact

Healthy native Codex threads continue without a host byte-summary request or a following native compaction. OpenClaw bounds the mirror only when it must seed a fresh native thread, attempting one host compaction only if the bounded seed would omit history not already covered by a host summary. The full stored transcript remains available to history, search, export, backups, cold storage, and memory indexing.

Native rollout-size/token fuses, manual native compaction, built-in/CLI behavior, and explicit context-engine ownership are preserved. Fresh seeds can still omit oversized history after the single attempt; an existing bounded-context notice tells the user when history is omitted. This does not add a native SQLite replay boundary or change memoryFlush.forceFlushTranscriptBytes (#126171).

Why This Change Was Made

The guard introduced in #115514 protects fresh-thread bootstrap size, but ran on every turn. Native compaction deliberately produces a display-only note, not a host compaction boundary, so it cannot clear that trigger. The bound and conditional host compaction now live at fresh-thread seed consumption instead. Thanks to @scotthuang for diagnosing the repeated post-/compact work in #158044; this implements the maintainer's lazy-seed direction, not host-first manual compaction.

Removed: the Codex byte-preflight branch, its private WeakMap authority/claim module, projected compaction configuration, queued special-authority handling, post-maintenance latch callback, byte-triggered native follow-up, and tests of those retired paths. Owning engines retain engine-first compaction and their native follow-up. The existing compactor and atomic summary/count writer are reused; #167916's bounded summarization remains unchanged.

Accepted compatibility boundary: Ayaan, the SDK and security owner, approved the optional additive AgentHarnessHostCapabilities.prepareBoundedSeed({ assertCurrent, signal, tokenBudget? }): Promise<readonly AgentMessage[]> capability on 2026-10-17, including the narrowing-only delivery allowance. The host captures session, configuration, source, byte budget, cancellation, and writer fences; callers cannot select another target or widen the captured token budget. Older hosts keep bounded selection without a plugin-side summary request. Explicit context engines retain their projections. The required main integration now supplies the canonical nullable-latch writer contract unchanged: seed commits pass explicit null to clear prior suppression. No schema, stored-row shape, external protocol, or config key changes. Stored Codex latches are ignored on ordinary turns; non-Codex latch behavior is retained.

Evidence

Complete: 57 paired result rows, seven reduced paid-confirmation turns, and supporting manual-compaction/harness-switch campaigns. The final report records no unresolved regressions or coverage gaps. Full local evidence is retained in codex-mirror-lazy-seed/results.md and results.json; private transcript contents and credentials are not published here.

BEFORE executed 7bfde4923e84f67e2961ea24d6a6fb6108680a03; AFTER executed df4c0017e1a8c4971afd8b0819e29923242ba970. Final head 7083100abbdcc77bb9a28ac1afc41e647e299ead is production-identical to df4c: git diff df4c0017 7083100a --stat contains only host-seed.test.ts | 12 (11 additions, one deletion) for its test-table type. The 67 incoming main commits changed none of the seed/compactor/writer/maintenance/harness-capability owners, so the same BEFORE remains applicable. The OpenShell config fingerprint conflict was regenerated canonically.

Paired runtime results

“Op” means a committed host compaction; “calls” means summary-provider requests within that operation. Native history injection is not native compaction.

Scenario Repeats BEFORE host ops / calls AFTER host ops / calls Result
Oversized ordinary turn 5 1 / 1 0 / 0 All three historical facts retained
Below-budget control 5 0 / 0 0 / 0 All three facts retained
Fresh rotation at final history allowance 2 0 / 0 1 / 2 73,678-byte seed; all three facts retained
Subsequent rotation with covering summary 2 0 / 0 0 / 0 No repeat host summary; all three facts retained
8 KiB refresh, compaction disabled 2 0 / 0 0 / 0 20,459 / 20,463-byte seeds retain the active 17,862-byte exchange and task once; older facts omitted with the native-seed notice
Same refresh, compaction enabled 1 paired, plus 2 repair-proof repeats 1 / 1 1 / 1 22,222-byte seed; active exchange and all three facts retained
Forced-cold upgrade, first next turn 2 1 / 2 1 / 1 1,744-byte seed contains persisted summary; settings/auth/history and all facts retained
Same upgrade, second next turn 2 1 / 2 0 / 0 Warm native reuse, no repeat host maintenance
High-byte-cap but token-bounded upgrade 1 0 / 0 1 / 2, then 0 / 0 Deliberately not a below-all-budgets control; all facts retained

Supporting recorded-head campaigns also exercised real native /compact followed by a normal turn, built-in/CLI harness switching, and an owning context engine's engine-first compaction plus native follow-up. Their head identities remain explicit in the full report; they are not mislabeled as current-head executions. The final focused batch passed 74 tests in three owner files, with Oxfmt/Oxlint and independent P0/P1 review clean; the main-integration batch separately passed 136 tests in five files.

Five-repeat latency

Wall times include CLI startup through terminal reply. These are loopback comparisons, not a promise of a fixed live-provider speedup.

Cell BEFORE median [min–max], ms AFTER median [min–max], ms
Oversized ordinary turn, n=5 each 1,714.492 [1,683.089–1,792.939] 1,484.624 [1,462.629–1,495.408]
Control, n=5 each 1,492.385 [1,463.280–1,495.413] 1,523.846 [1,478.522–1,551.325]

Real-provider confirmation

Each rotation entry below is one measured turn. Inputs are provider-reported totals across summary and native requests; model names are redacted as A/B/C. All six rotation turns recalled all three facts with zero errors and zero native thread/compact/start requests.

Model Summary calls BEFORE → AFTER Input tokens BEFORE → AFTER Wall ms BEFORE → AFTER AFTER seed bytes
A 2 → 1 41,896 → 41,700 10,284.090 → 9,766.600 67,614
B 2 → 1 41,855 → 41,602 12,733.944 → 11,388.505 67,174
C 2 → 1 41,873 → 41,639 12,074.490 → 11,443.134 67,368

The seventh confirmation turn was BEFORE model-A ordinary maintenance: 35,518 input tokens and two summary calls. Earlier full three-model campaigns remain supporting evidence. Final confirmation used 286,083 input tokens against a 286,841 forecast; the whole paid campaign used 3,593,931 input / 26,838 output tokens / 280 requests, below the approved 3,650,000-input cap. Credentials were removed.

Authority, compatibility, and limitations

  • The task-owned observer exercised the real host compactor, atomic persistence, and stock native injection: one host operation, two summary calls, nine injected items / 73,678 bytes, and zero native compaction RPCs. The report's legacy nativeSyncAfterHost flag also counts expected injection; it does not mean thread/compact/start.
  • Retained callbacks after completed-source retirement and after public reset rejected with zero additional summary/native effects; transcript-plus-entry hashes stayed identical. Reset during prepared seeding produced zero stale injections; the next turn was healthy with neither old-thread reuse nor stale seed markers. Public reset retires both source and writer; isolated writer-only reassignment is additionally covered by the owner regression.
  • E2E exposed and repaired two real defects: an oversized tail crowded out a fitting persisted summary, and the compactor's default kept tail exceeded the final seed allowance. The seed now reserves a fitting summary and gives the existing compactor the matching retention budget. Negative owner tests fail before these repairs.
  • The upgrade is explicitly forced-cold: native 0.160.0→0.162.0 changes runtime/policy identity. This is not presented as a warm-binding migration. Saved operator settings, authentication, logical history, and real pre-existing latch state were checked.
  • The existing 160,000-CJK-weighted-character summary input cap samples oversized histories and marks gaps. This PR does not promise lossless summaries or hide that pre-existing limitation.
  • With compaction disabled, the configured cap still omits older historical facts with a notice; no-cap defaults and the full saved record are unchanged. In the disabled 8 KiB case, BEFORE recalled three old facts and AFTER recalled none, while preserving the active task/exchange. That is the explicit configured-bound behavior, not an inherited-loss claim.
  • Cleanup removed 98 receipt-owned temporary roots, deferred none, and stopped all test Gateways/providers. Private evidence was retained; no operator Gateway or live state was touched.

Exact-head CI is green. The final build, proof identity, budget ledger, and cleanup receipts are recorded; merge remains gated on ClawSweeper's exact-head readiness.

pr-simplify against merge base 0b64fd18fcdccfa5ef3a1837909e7321ebcbca50: production +460/-362 (+98); tests +487/-602 (-115); docs including generated fingerprints +43/-44 (-1). Total: 36 files, +990/-1008, net -18 lines. No coverage was cut.

The remaining production increase is 295 lines of host-owned seed preparation (authority/cancellation, retained-input budgeting, media costs, summary reservation and atomic persistence), plus 62 net lines of SDK/injection/notice integration, offset by 259 removed lines of eager preflight and private claim machinery. Shared bounds have distinct jobs: avoid restoring discarded media, account for actual media/active input, then reserve notice/summary only when needed. Non-Codex and owning-engine contracts remain intact.

Merge danger: two-way door. Reverting restores eager host byte preflight; any summaries already appended remain valid existing-format transcript events. The main risk is incorrect fresh-thread seed selection or source/writer handoff for Codex sessions with the byte guard enabled. Healthy native reuse and explicit engine ownership are protected separately. No operator Gateway or operator state was touched.

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling extensions: codex size: XL labels Oct 17, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 17, 2026
@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR defers host transcript compaction until a fresh Codex thread needs bounded history.

Example: An ordinary Codex turn has an oversized host transcript mirror.

  • Before: The supplied five-repeat campaign recorded one host compaction and one summary request per turn.
  • After: It recorded zero host compactions and zero summary requests, while retaining all three historical facts.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Approved direction, relevant shipped-path evidence, exact-head gates, and no actionable introduced findings support readiness.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied real CLI/native-runtime results exercise ordinary reuse, bounded fresh seeds, subsequent rotations, manual compaction, refresh input, and forced-cold upgrades; retained callbacks and reset-during-seeding scenarios reject stale summary or injection effects, and the reviewed head is production-identical to the executed after revision.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Ordinary Codex replies can repeatedly wait for host summarization even when the native conversation remains healthy.
Reason: Recorded maintainer direction supports the changed timing and additive capability, and runtime comparisons demonstrate reduced unnecessary work.

Merge readiness

✅ Ready for maintainer review

This PR implements the approved lazy-seeding direction, addresses repeated Codex host compaction, and has no actionable introduced defects after review.

Priority: P1
Reviewed head: 7083100abbdcc77bb9a28ac1afc41e647e299ead

Before merge

None.

Findings

None.

Agent review details

How this fits together

OpenClaw stores conversation history independently of Codex native threads; the host prepares bounded history for fresh threads while Codex owns native compaction.

flowchart TD
 A[Admitted conversation turn] --> B[Codex thread lifecycle]
 B --> C[Reuse healthy native thread]
 B --> D[Prepare fresh history seed]
 D --> E[Host compaction when needed]
 E --> F[Atomic transcript and accounting writer]
 D --> G[Bounded native history injection]
 F --> G
Loading

Technical review

Best possible solution:

Keep host summarization at fresh-seed consumption, preserving native reuse, atomic accounting, active input, and explicit context-engine ownership.

Do we have a high-confidence way to reproduce the issue?

Current main evaluates host transcript byte pressure independently of native compaction, explaining repeated summaries; the supplied before/after runtime campaigns corroborate that path.

Is this the best way to solve the issue?

Moving the guard to fresh-seed consumption addresses its original bootstrap purpose and reuses the existing compactor and atomic writer without competing persistence ownership.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 08b19021512e.

Provenance checked

  • Codex host byte preflight changes intended behavior with a stated reason (4e651a4: Bound host history because it supplies fresh native bootstrap payloads.)
  • Atomic compaction persistence and writer fencing keeps the original intent (9d98269: Commit transcript boundaries, accounting, and latch state together under current writer authority.)
  • Selected native history delivery keeps the original intent (d64c9bb: Deliver selected history without a second silent cutoff and avoid duplicate injection.)
  • Bounded fallback context changes intended behavior with a stated reason (17cc94a: Continue replies with bounded whole-turn history and a visible omission notice when compaction cannot satisfy the bound.)
  • Manual native compaction keeps the original intent (34ddb38: Restore native manual and preflight compaction through the existing authority and settlement owners.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Maintainer direction: The discussion at fix(codex): avoid repeated host compaction after manual compact #158044 (comment) explicitly selects lazy fresh-thread seeding instead of host-first manual compaction and credits scotthuang's diagnosis; this maintainer-authored PR records approval of the additive capability.
  • Current main retains eager preflight: Fetched main still lets Codex sessions evaluate the host byte guard; the introduced diff adds the Codex early return and removes the retired preflight claim machinery. (src/auto-reply/reply/agent-runner-memory.ts:160, 08b19021512e)
  • Bounded seed and atomic persistence: The host captures the target and budget, preserves active refresh input, accounts for restored media, attempts one existing compactor operation, and persists through the existing writer with explicit null latch clearing. (src/agents/harness/host-seed.ts:204, 7083100abbdc)
  • Final-effect authority: Source assertions and writer ownership accompany summary persistence; fresh native injection passes the binding assertion, cancellation signal, and current-authority operation to the transport. (extensions/codex/src/app-server/context-engine-history.ts:309, 7083100abbdc)
  • Native protocol contract inspected: The patch invokes thread/inject_items, making this dependency's contract relevant: the inspected implementation checks direct-input permission and awaits history injection; thread/compact/start separately submits Op::Compact. (codex-rs/app-server/src/request_processors/turn_processor.rs:985, c1382380de69)
  • Supplied runtime and upgrade evidence: The complete body records real CLI/native-runtime comparisons, fresh rotation, repeated rotation, disabled compaction, forced-cold upgrade, and reset/revocation rejection with zero stale effects; private artifacts were not independently inspected. (7083100abbdc)

PR surface

Source +98, Tests -115, Docs -1, Generated 0. Total -18 across 36 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 22 460 362 +98
Tests 8 487 602 -115
Docs 5 41 42 -1
Config 0 0 0 0
Generated 1 2 2 0
Other 0 0 0 0
Total 36 990 1008 -18

Review metrics

Metric Value Why it matters
Production versus test LOC Production +460/-362; tests +487/-602 The increase supplies bounded seed preparation while removing eager preflight machinery; tests move to seed, persistence, media, and authority contracts.

Root-cause cluster

Relationship: canonical
Canonical: #175256
Summary: This PR implements the maintainer-selected replacement for eager host compaction; the memory-flush replay-boundary report remains distinct.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Oversized Codex conversations can repeatedly delay ordinary replies with unnecessary host summarization.
  • merge-risk: 🚨 compatibility: The public host capability gains an optional method and the configured byte guard changes timing; the current PR records owner acceptance and upgrade evidence.
  • merge-risk: 🚨 session-state: Fresh-thread selection and summary persistence affect delivered conversation context; bounded omission is explicitly accepted, and active-input and authority scenarios are covered.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (7 earlier review cycles)
  • reviewed 2026-10-17T07:10:08.161Z sha cbac0e7 :: blocked before merge. :: [P1] [P1] Fit fresh seeds to the final history delivery allowance | [P1] [P1] Preserve the original task when seeding a refresh continuation
  • reviewed 2026-10-17T07:29:21.738Z sha cbac0e7 :: needs real behavior proof before merge. :: [P1] Fit fresh seeds to the final history delivery allowance | [P1] Preserve the original task when seeding a refresh continuation
  • reviewed 2026-10-17T07:44:43.058Z sha 86ef5b5 :: needs real behavior proof before merge. :: [P2] Include restored media in the fresh-seed delivery bound
  • reviewed 2026-10-17T08:27:53.677Z sha 86091fe :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-17T09:24:57.977Z sha 8fc2f46 :: needs real behavior proof before merge. :: [P1] Preserve the active refresh exchange outside the history byte cap
  • reviewed 2026-10-17T10:11:00.882Z sha c9ab460 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-17T17:15:51.647Z sha 7083100 :: needs maintainer review before merge. :: none

Reviewed October 17, 2026, 1:23 PM ET / 17:23 UTC (Revision 8).

@obviyus
obviyus marked this pull request as ready for review October 17, 2026 07:23
@obviyus

obviyus commented Oct 17, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@github-actions

github-actions Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 7083100abbdcc77bb9a28ac1afc41e647e299ead
  • Maintainer: @obviyus
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/embedded-agent-runner/transcript-byte-preflight-authority.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 17, 2026
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. clawsweeper:intake:bug Preliminary submission classification; full source review pending. and removed clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 17, 2026
@obviyus

obviyus commented Oct 17, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in 6db8577.

  • Bug: ordinary Codex turns re-ran host summarization (plus a follow-up native compaction) whenever the transcript mirror passed maxActiveTranscriptBytes, delaying replies.
  • Fix: healthy native threads skip host byte compaction; the host bounds history only when seeding a fresh native thread, with at most one summary when the bounded seed would drop uncovered history.
  • Proof: matched before/after E2E across 15 scenarios (ordinary, manual /compact, rotation, media, plugin refresh, harness switching, reset/revocation, forced-cold upgrade from v2026.10.4), three real models, and 5-repeat latency (ordinary median 1714 ms -> 1485 ms). E2E also caught two seed defects fixed before landing.

Thanks @scotthuang for the #158044 diagnosis that led here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: codex gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. security-sensitive-changed size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant