Skip to content

fix: reduce memory spikes when preparing long session histories - #133753

Merged
steipete merged 3 commits into
mainfrom
steipete/practical-bartik-bebeb0
Aug 31, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/practical-bartik-bebeb0

Conversation

@steipete

@steipete steipete commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Closes #133738 — prompt preparation and detached experience review copy storage-only history payloads.

Additional instructions

This is a same-repository maintainer branch and remains editable by maintainers.

What Problem This Solves

Fixes an issue where users continuing long native Codex conversations, or running detached Skill Workshop experience reviews, would incur large memory spikes when the stored transcript contains substantial native replay metadata. Model-only readers acquired those private payloads before selecting context, and prompt preparation could clone them even when no message-consuming hook existed.

The issue and proof use synthetic data only. This change repairs demonstrated allocation boundaries; it does not attribute or claim to resolve every separately reported Gateway OOM.

Why This Change Was Made

The session owner now supplies a detached model-context view that selects the existing branch/reset/compaction window before hydrating payloads. Query-time SQLite projection excludes storage-only native prompt text and tool-result details, and skips invalidated retained-prefix replay checkpoints. It reuses the existing tree, context-window, and occurrence-based tool-pairing algorithms rather than introducing a history cutoff.

Prompt-hook dispatch owns isolated snapshots after actual registration filtering. Registrations within a dispatch retain their existing ordering and shared-event behavior; separate prepare, ordinary, authorized, and rebuild dispatches cannot mutate the caller's history. Codex no longer clones eagerly, and Workshop no longer opens and clones the complete foreground transcript. Retained-tail statistics and append-parent resolution also use narrow navigation facts while preserving exact raw-byte accounting.

Native mirror attestations, fork drift validation, settled-turn replay, exports, and doctor operations retain full-fidelity evidence. No stored conversation bytes, schema, persisted projection, configuration, dependency, heap/timeout limit, or feature-enable setting changes.

Production LOC after main integration and CI repair: +535/-143 (net +392). Tests/support: +876/-12 (net +864). Growth establishes the missing read/projection ownership boundary and equivalent SQL/in-memory field contract; existing selection algorithms are reused and the raw acquire-then-clone paths are removed. The assertion baseline only shrinks.

User Impact

Long-history prompt preparation and detached reviews avoid allocating private native replay text that is not part of their model context. Hook isolation, visible content, reset/compaction retained tails, tool pairing, sender/media/taint facts, and admission fencing remain intact. Ordinary acquisition failures in experience review now receive the existing recorded failure outcome and cleanup.

Full-fidelity native evidence readers, direct legacy file-only reads, BTW captured-leaf reads, and CLI reseed-budget paths keep their different contracts. This PR does not silently migrate them or promise constant memory for arbitrarily large genuine model-visible output.

Evidence

Failing before, passing after

  • Four actual Codex attempt cases cover no hooks, heartbeat-only, ordinary prompt hooks, and authorized-only hooks. The pre-fix canonical SQLite path parsed 2,097,714 private JSON characters per case from a one-MiB fixture; repaired cases observe zero private parse/clone bytes. No-hook and heartbeat-only cases clone no history.
  • Shared hook regressions initially showed immediate nested mutation escaping into caller history. The repaired dispatcher preserves caller and subsequent-dispatch isolation, including retained references.
  • Real detached experience review against a local synthetic HTTP provider initially parsed 2,097,490 private JSON characters. The repaired path observes zero and preserves the foreground stored-data fingerprint.
  • Retained-tail statistics initially parsed 1,048,821 private JSON characters; repaired reads preserve byte/count facts without acquiring that payload.
  • Reset/compaction checkpoint cases initially acquired 1,049,250 obsolete JSON characters; the repaired reader excludes invalidated checkpoints while preserving valid post-boundary replay.
  • Independent parity verification caught an intermediate mismatch for explicitly retained reset messages marked excludeFromContext. The acquisition owner now follows the existing reset-kept contract; all nine user/assistant/paired-result cases across reset, compaction, and ordinary history pass.

The independent pre-integration boundary rerun passed 98 tests, covering selected context, retained tools, opaque/leaf ancestry, admission tampering and post-admission reset/compaction, incognito, absent/stale index state, cursor cleanup, hook isolation, native fingerprints, settled-turn matching, and fork drift rejection. After integrating main, the expanded boundary run passed 107 tests, plus six actual Codex attempt cases. This includes main's sparse retained-tail batching and transcript import/store coverage. All five synthetic HTTP Workshop E2E outcomes also passed before integration: proposal, no-op, interrupted, rejected, and failed. The last retained-reset predicate correction was reverified with focused tests rather than another unrelated full runtime preparation.

node scripts/run-vitest.mjs src/agents/sessions/session-manager-model-context.test.ts src/config/sessions/session-accessor.sqlite-bounded-context.test.ts src/agents/harness/prompt-compaction-hook-helpers.test.ts extensions/codex/src/app-server/session-history.test.ts extensions/codex/src/app-server/settled-turn-context.test.ts extensions/codex/src/app-server/upstream-fork-boundary.test.ts src/config/sessions/session-accessor.sqlite-history-events.test.ts src/config/sessions/session-accessor.sqlite-import.test.ts src/config/sessions/session-accessor.sqlite-transcript-store.test.ts
node scripts/run-vitest.mjs extensions/codex/src/app-server/run-attempt.test.ts -t 'keeps private native history|applies before_prompt_build|rebuilding'
node scripts/run-vitest.mjs src/skills/workshop/experience-review.e2e.test.ts

Focused core/plugin production and affected test types, type-aware lint, formatting, assertion/max-lines/schema guards, and git diff --check passed before integration. Independent architecture checks found zero runtime import cycles and passed the session-accessor, transcript-reader, and SQLite transaction boundaries. These are scoped checks, not a claim that the entire repository suite ran locally.

Integration base: 237f23b4589795a91dc63778c41d27624bb336dc. Main's retained-history batching (#133680), import identity query compilation reuse (#133689), and legacy codec validation optimization (#133641) are preserved. The new append-parent reader now imports identity lookup from the canonical session-accessor.sqlite-read.ts owner. The expected stale import failed the post-rebase core typecheck with TS2459 before that correction; the same typecheck then passed. Post-integration focused lint, formatting, and git diff --check passed.

Independent isolated Codex autoreview of the complete integrated candidate returned scoped-clean with no findings at its P0-only reporting threshold. This is not an all-priority review certificate.

pnpm build passed before integration (22m47s) and again on the corrected integrated candidate (5m14s). Post-integration commands also passed:

node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core.tsbuildinfo
node scripts/run-oxlint.mjs src/config/sessions/session-accessor.sqlite-transcript-parent.ts src/config/sessions/session-accessor.sqlite-reset-window.ts src/config/sessions/session-accessor.sqlite-transcript-store.ts
node_modules/.bin/oxfmt --check src/config/sessions/session-accessor.sqlite-transcript-parent.ts
git diff --check

CI repair

Initial exact-head CI failed only the runtime-topology architecture job and its aggregate gate. The Kysely guard identified raw column references and SQLite JSON exceptions attached to declarations rather than the primitive expressions.

The correction passes schema-checked eb.ref(...) column expressions into the projection owner, which accepts Kysely Expression<string> and retains typed results. It removes raw identifier snippets; the eight JSON primitive templates, interpolations, and value-parameter order are unchanged. Existing narrowly justified SQLite JSON exceptions now attach directly to their expressions. No casts, guard changes, or allowlist/baseline expansion were used. The formerly failing pnpm lint:kysely, full pnpm check:architecture, 113 boundary/native tests, core typecheck, focused lint/formatting, and pnpm build (5m16s) pass after the correction. Fresh isolated review of the correction is also scoped-clean at P0 with no findings.

pnpm lint:kysely
pnpm check:architecture

Final head: 83fd69c4bfbc01eaa07ce6a3b5ee38218f99877e. Exact-head pull-request CI run 33354235862 completed success on attempt 1, including the required openclaw/ci-gate, repaired runtime architecture gate, built artifacts, and SQLite session lifecycle proof. Native prepare and merge completed without rewriting this head; landed as c09f1360bbe49e3f8cf28926c47e4998b6d37bf0. A post-merge rerun on that exact commit passed 38 model-context, transcript-store/import, and retained-tail tests, including the overlapping mainline identity-insert optimization. Issue closure proof and the post-merge command are recorded; the issue is closed as completed.

Synthetic allocation measurement

Fixed 24 small visible user messages; only native metadata grows to 1 MiB per message (24 MiB aggregate). Fresh Node v26.8.1 processes; imports and fixture seeding are outside the timer. No heap limit was raised. Baseline is source 0b392310b92d90bd37b884c4469b0ec799ad2521; these samples precede mechanical main integration.

Measurement Before Repaired
JS heap growth during acquisition 49.92 MiB 0.82 MiB
RSS growth during acquisition 45.56 MiB 3.13 MiB
Acquisition time 23.21 ms 50.84 ms
Visible messages returned 24 24

These are individual synthetic samples, not a production peak/soak guarantee. SQLite still processes stored bytes, so query-time projection spends additional CPU to avoid aggregate JavaScript allocation.

Native contract inspection and limits

Personally inspected the sibling Codex source and then the public source for the pinned @openai/codex 0.151.0 tag, which resolves to 78c290807ce710180111df227df3b7a4fe845452:

Those contracts require exact native evidence; the model-only view does not replace it. No native protocol behavior changed and no live native-provider request is claimed as proof. The real runner/SQLite proof uses synthetic fixtures and a local HTTP provider. No production state was accessed or modified, and no historical crash caller or production stability soak is claimed.

ClawSweeper review disposition

The review and rank-up moves have been read. They contain no concrete code or security finding, but request these maintainer decisions and evidence:

  • Prompt-hook contract: The documented model-context snapshot is the intended contract for this repair. Public hook types describe messages prepared for the run, not full native transcript evidence; the existing tool-result contract puts model-visible output in content, not details. This deliberately narrows incidental storage-field exposure. Third-party prompt hooks reading private upstreamUserText or tool-result details may need adjustment. No installed-plugin or production inventory was inspected, and universal backward compatibility is not claimed. Full-fidelity evidence readers and tool/persistence hook owners are unchanged.
  • Production growth: The final net +392 production lines establish a missing transient read owner that selects navigation, branch/reset/compaction context, and admission before payload hydration. Existing tree/window/pairing algorithms remain canonical. Stripping or wrapping the raw reader afterward preserves the demonstrated allocation failure; globally reducing evidence breaks native fork/replay; arbitrary cutoffs change context semantics. Old eager-clone and full-foreground-acquisition paths are removed rather than kept as parallel fallbacks.
  • Codex contract: Personal sibling-source inspection and the pinned 0.151.0 source checks linked above satisfy this inspection step. These are source-contract checks, not live native-provider proof.
  • Persistent-data heuristic: No schema, index, migration, retention, or write-format change occurs. This is query-time SELECT projection and read-snapshot ownership, with exact stored-byte fingerprint regression proof. A data migration would be inappropriate.

Exact-head CI remains a separate gate and is not inferred from these dispositions. No additional code change is required by the published rank-up moves.

Docs: session management, plugin hooks, and self-learning.

@steipete steipete self-assigned this Aug 31, 2026
@clawsweeper

clawsweeper Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling extensions: codex size: XL maintainer Maintainer-authored PR labels Aug 31, 2026
@steipete
steipete marked this pull request as ready for review August 31, 2026 03:08
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 31, 2026
@clawsweeper

clawsweeper Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 11:18 PM ET / August 31, 2026, 03:18 UTC.

ClawSweeper review

What this changes

The branch projects selected session context from SQLite so Codex prompts, Workshop reviews, and prompt hooks do not hydrate storage-only transcript payloads.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 5 items remain

The PR remains necessary. Its direct SQLite projection is a coherent repair, but the changed prompt-hook payload contract and required Codex runtime contract remain unverified for merge.

Priority: P2
Reviewed head: cfec9a8f759c3738798f010aa87826919ebaad25
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused source and boundary evidence support the repair, while Codex-contract inspection and plugin compatibility acceptance remain outstanding.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
Evidence reviewed 6 items Current main remains without the repair: The recorded current main and review head differ on the new model-context session owner, so current main does not already contain this implementation.
Projection occurs before payload hydration: The new reader selects navigation data and the retained context window before hydrating selected model payloads, and the session manager applies the read fence before creating a detached view.
The old Codex path cloned complete history: The base implementation passed structuredClone(historyState.messages) to prompt hooks; the introduced code passes the selected history instead.
Findings None None.
Security None None.

How this fits together

SQLite transcript events retain complete replay evidence, while prompt preparation and detached reviews need only the selected model-visible context. The new projection reader supplies that reduced view to model-facing consumers.

flowchart LR
  A[SQLite transcript events] --> B[Model context reader]
  B --> C[Context window selection]
  C --> D[Storage field projection]
  D --> E[Codex prompt preparation]
  D --> F[Workshop experience review]
  D --> G[Prompt hooks]
Loading

Decision needed

Question Recommendation
Should storage-only fields be excluded from the public prompt-hook message contract, with SessionManager.openModelContext() as the supported model-context reader? Accept the projected hook contract: Adopt the documented model-context snapshot for prompt hooks and retain full-fidelity reads only for native evidence operations.

Why: This changes data exposed to third-party hook handlers and substantially expands production code; local source cannot prove whether installed plugins depend on the removed fields.

Before merge

  • Resolve merge risk (P1) - Prompt hooks now omit storage-only metadata and tool-result details; external plugin compatibility has not been established.
  • Resolve merge risk (P1) - The bug fix adds 406 net production lines; the projection owner needs explicit acceptance that this is the simplest coherent repair.
  • Resolve merge risk (P1) - The required direct Codex-source inspection could not be performed, leaving the extension contract unverified.
  • Complete next step (P2) - Maintainer review must settle the public hook contract and production-growth rationale; the mandated Codex source check is unavailable in this environment.
Agent review details

Security

None.

PR surface

Source +406, Tests +864, Docs +6, Other -1. Total +1275 across 28 files.

View PR surface stats
Area Files Added Removed Net
Source 17 552 146 +406
Tests 7 873 9 +864
Docs 3 8 2 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 3 -1
Total 28 1435 160 +1275

Review metrics

Metric Value Why it matters
Production versus test delta production +547/-141 (net +406); tests/support +876/-12 (net +864) The new shared projection owner is substantial bug-fix growth; its test expansion is broad, but the production cost needs the stated owner-boundary justification.

Stored data model

Persistent data-model change detected: migration/backfill/repair: config/assertion-safety-baseline.txt, migration/backfill/repair: src/agents/session-transcript-repair.ts, serialized state: src/config/sessions/session-accessor.sqlite-transcript-store.ts, serialized state: src/config/sessions/session-transcript-read-fence.ts, unknown-data-model-change: src/config/sessions/session-accessor.sqlite-transcript-store.ts, vector/embedding metadata: src/shared/model-context-message.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #133738
Summary: This PR is the candidate fix for the model-context allocation issue.

Members:

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

Merge-risk options

Maintainer options:

  1. Confirm the public contract (recommended)
    Obtain maintainer acceptance for projected prompt-hook data and the additive session reader before merging.
  2. Pause for compatibility design
    Hold the PR if installed prompt-hook plugins must retain storage-only transcript fields.

Technical review

Best possible solution:

Confirm the documented prompt-hook contract, inspect the required Codex source, and explicitly accept the projection owner's production growth before exact-head merge gates run.

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

Yes, from source: the replaced eager full-history clone is directly visible and focused regression tests specify the synthetic scenario, though this review did not execute it.

Is this the best way to solve the issue?

Unclear: projection before hydration is the right owner-boundary direction for inspected OpenClaw paths, but plugin compatibility and the Codex integration contract remain unverified.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 62b41feb1d81.

Labels

Label changes:

  • add P2: This addresses bounded model-context memory and CPU overhead without evidence of data loss, security bypass, or a crash loop.
  • add merge-risk: 🚨 compatibility: The PR changes prompt-hook payloads and extends the behavior of the publicly exported SessionManager.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.

Label justifications:

  • P2: This addresses bounded model-context memory and CPU overhead without evidence of data loss, security bypass, or a crash loop.
  • merge-risk: 🚨 compatibility: The PR changes prompt-hook payloads and extends the behavior of the publicly exported SessionManager.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Inspect the required Codex sibling source for the exact extension contract.
  • Confirm prompt-hook compatibility, production-growth rationale, and exact-head checks.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@steipete

Copy link
Copy Markdown
Contributor Author

Landing verification for the long-history allocation repair. Native review/artifact validation and OPENCLAW_TESTBOX=1 scripts/pr prepare-run 133753 passed, preserving the exact CI-tested head 83fd69c4bfbc01eaa07ce6a3b5ee38218f99877e without another rebase or push.

The allocation owner is the model-context reader, not the native evidence store: select the existing branch/reset/compaction/admission window and project storage-only fields before hydration, then clone only when a message-consuming prompt-hook registration exists. Exact stored bytes and native fork/replay evidence remain unchanged. The documented prompt-hook snapshot is an intentional narrowing; third-party hooks depending on incidental private fields may need adjustment. No installed-plugin compatibility claim or production rollout is implied.

The ClawSweeper review and rank-up moves are addressed in the PR body, including personal sibling and pinned Codex source inspection, the compatibility caveat, and why the net +392 production lines are needed for the missing acquisition owner. Tests/support are +876/-12. The corrected four-file SQL change uses schema-checked column references without changing the JSON projection semantics or weakening guards.

The corrected source head 83fd69c4bfbc01eaa07ce6a3b5ee38218f99877e passed CI run 33354235862, attempt 1, including the required openclaw/ci-gate. All 182 jobs succeeded or were intentionally skipped. Local proof passed 113 focused owner/native tests, core types, Kysely/full architecture, focused lint/format, and the full build. Fresh isolated review was scoped-clean at P0 only. Exact commands, earlier failing-before/passing-after synthetic runner proof, native-source citations, and proof limits remain in the PR body's Evidence section.

@steipete
steipete merged commit c09f136 into main Aug 31, 2026
241 of 243 checks passed
@steipete
steipete deleted the steipete/practical-bartik-bebeb0 branch August 31, 2026 03:56
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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 maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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.

[Bug]: Prompt preparation and experience reviews copy storage-only history payloads

1 participant