Skip to content

fix: stop transcript storms during context overflow recovery - #147202

Merged
VACInc merged 3 commits into
openclaw:mainfrom
VACInc:fix/bounded-overflow-transcript-recovery
Sep 13, 2026
Merged

VACInc merged 3 commits into
openclaw:mainfrom
VACInc:fix/bounded-overflow-transcript-recovery

Conversation

@VACInc

@VACInc VACInc commented Sep 13, 2026 •

Copy link
Copy Markdown
Member

Summary

High Level TLDR

Fixes transcript storms and long Gateway stalls when context-overflow recovery trims tool results in a session with retained history.

What Problem This Solves

A small recovery edit could copy almost the entire session archive, including historical reset markers, into fresh transcript entries. In the observed incident, recovery copied about 1.67 million entries and held a synchronous database write for 924 seconds.

User Impact

Long-running conversations can recover from context overflow without duplicating archived turns or reset markers. Existing history remains readable. This prevents new amplification; it does not delete previously duplicated records or change retention, schemas, configuration, or permissions.

Why This Change Was Made

Root Cause

Recovery opened an unbounded SessionManager, unlike normal attempts. The truncation planner then consumed the raw branch instead of the canonical model-context window. Its earliest historical replacement made the existing atomic branch rewrite copy the entire remaining suffix.

Recovery now shares the normal attempt hydration limits using the resolved model budget, and truncation selects entries through the existing model-context iterator. This preserves the established reset-retention and compaction rules and retains the existing atomic publication and writer-authority checks.

Verification

Real behavior proof

The regression uses a synthetic context engine with real SQLite storage, run admission, writer claims, overflow recovery, compaction publication, truncation, and independent reopen reads. It covers successful compaction, failed-compaction fallback, a compacted context that needs no truncation, and a 200k-token resolved model budget with 1.2 MB of current tool output.

On the original production code, all four added regression cases fail: archived reset counts double, and archive-only oversized output causes unnecessary transcript copies. The larger-budget case separately fails on the initial PR revision because recovery omits the eligible tool output and surfaces overflow. With the fix, original row digests remain unchanged, reset counts stay constant, current tool output shrinks when needed, and recovery returns retry. The default fixture output fits normal attempt hydration while still exceeding the truncation threshold.

node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run.compaction-runtime.test.ts src/agents/embedded-agent-runner/run.overflow-context-recovery.test.ts src/agents/embedded-agent-runner/run/overflow-context-recovery.test.ts src/agents/embedded-agent-runner/run.timeout-context-recovery.test.ts
node scripts/run-vitest.mjs src/agents/embedded-agent-runner/tool-result-truncation.test.ts src/agents/embedded-agent-runner/transcript-rewrite.test.ts src/agents/embedded-agent-runner/run/attempt-session-boundary.test.ts

Evidence

  • After the review correction, 93 recovery tests passed, including all four added regressions. The existing truncation, atomic rewrite, and attempt-boundary suites also passed (133 tests). The Workboard cleanup regression passed.
  • The initial full check-changed pass covered core/test typechecks, lint, dead exports, and repository guards. After the review correction, core typechecking, the affected agent test type graph, and type-aware lint for all changed production/test files passed again. git diff --check passed.
  • Independent autoreview found no actionable P0–P2 defects; a separate readiness pass found no additional required change.
  • Benchmark: Linux x64, Node 24.19.0, one Vitest worker, real SQLite fixture with 64 archived tool turns/reset boundaries and one current tool result. One warmup and five fresh-state measured samples per version; only recovery is timed.
Recovery measurement Original Fixed
Median duration 176.36 ms 29.82 ms
Appended transcript entries 262 4
Copied historical resets 64 0

Full benchmark process peak RSS was 2,345 MiB before and 2,361 MiB after, including test compilation/setup; no peak-memory reduction is claimed. The measured recovery improvement is approximately 83% on this fixture, not a production latency projection.

Repeatable benchmark probe

Save this temporary test beside run.compaction-runtime.test-support.ts, then run it with OPENCLAW_VITEST_MAX_WORKERS=1 node scripts/run-vitest.mjs <test-path>. Compare the PR production files with their base versions while keeping this fixture unchanged. Remove the temporary test afterward.

import { it, expect } from "vitest";
import { withRecoveryFixture } from "./run.compaction-runtime.test-support.js";

it("measures archived-history overflow recovery", async () => {
  for (let sample = 0; sample < 6; sample += 1) {
    await withRecoveryFixture({ historicalTurns: 64 }, async (fixture) => {
      const before = await fixture.snapshot();
      const started = performance.now();
      expect(await fixture.recover("overflow", true)).toEqual({ action: "retry" });
      const elapsedMs = performance.now() - started;
      const after = await fixture.snapshot();
      console.log({
        sample, warmup: sample === 0, elapsedMs,
        addedEvents: after.eventDigests.length - before.eventDigests.length,
        addedResets: after.resetCount - before.resetCount,
      });
    });
  }
}, 120_000);

Incident-scale synthetic archive

A separate real-SQLite probe seeded 1,700,007 transcript entries through replaceTranscriptEvents, ran actual overflow recovery, then independently reopened storage and compared every original row digest. Recovery took 3,869.54 ms, appended 4 entries, and copied 0 historical resets. All existing row digests matched. This was one cold sample; the small repeated benchmark above supplies the before/after comparison. Seeding and full-archive verification are excluded from recovery timing.

Repeatable large-archive probe

Save this temporary test beside the recovery fixture and run it with one worker using the same Vitest command as above. It uses synthetic text and isolated test storage; remove the probe afterward.

import { expect, it } from "vitest";
import { loadTranscriptEvents } from "../../config/sessions/session-accessor.sqlite-read.js";
import { replaceTranscriptEvents } from "../../config/sessions/session-accessor.sqlite-transcript-write.js";
import { withRecoveryFixture } from "./run.compaction-runtime.test-support.js";

it("recovers with 1.7 million archived entries", async () => {
  await withRecoveryFixture({}, async (fixture) => {
    const target = fixture.openWriter().getSessionTarget()!;
    const original = await loadTranscriptEvents(target);
    const current = original.slice(1);
    const entries: unknown[] = [original[0]];
    let parentId: string | null = null;
    const seedStarted = performance.now();
    for (let index = 0; index < 1_700_000; index += 1) {
      const id = `archived-${index}`;
      entries.push({
        type: "message", id, parentId, timestamp: "2026-01-01T00:00:00.000Z",
        message: { role: "user", content: "Archived fixture request", timestamp: 1 },
      });
      parentId = id;
    }
    entries.push({ type: "reset", id: "archive-reset", parentId, timestamp: "2026-01-01T00:00:00.000Z", reason: "new" });
    parentId = "archive-reset";
    for (const event of current) {
      const entry = event as { id: string; parentId: string | null };
      entries.push({ ...entry, parentId });
      parentId = entry.id;
    }
    await replaceTranscriptEvents(target, entries);
    entries.length = 0;
    const before = await fixture.snapshot();
    console.log(JSON.stringify({ phase: "seeded", events: before.eventDigests.length, elapsedMs: performance.now() - seedStarted }));
    const recoveryStarted = performance.now();
    expect(await fixture.recover("overflow", true)).toEqual({ action: "retry" });
    const elapsedMs = performance.now() - recoveryStarted;
    const after = await fixture.snapshot();
    expect(after.eventDigests.slice(0, before.eventDigests.length)).toEqual(before.eventDigests);
    expect(after.resetCount).toBe(before.resetCount);
    expect(after.toolResultChars).toBeLessThan(before.toolResultChars);
    console.log(JSON.stringify({ phase: "recovered", elapsedMs, addedEvents: after.eventDigests.length - before.eventDigests.length, copiedResets: after.resetCount - before.resetCount, maxRSSKiB: process.resourceUsage().maxRSS }));
  });
}, 1_200_000);

CI repair

The first hosted run passed the core lint stripe but failed extension lint on an unawaited async Workboard test cleanup introduced by #147191 in the merge base. A separate one-line test-only repair awaits harness.close(). The affected concurrency test and type-aware plugin lint pass locally. No Workboard production behavior changes.

What was not tested

No production Gateway restart or live provider/channel replay was performed. The private incident archive was not copied into a test environment; the 1.7-million-entry synthetic archive matches its order of magnitude, not its exact payloads or disk/cache state. The fix uses the existing supported storage and update paths; no migration or operator action is required after installation.

@clawsweeper

clawsweeper Bot commented Sep 13, 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 size: S maintainer Maintainer-authored PR labels Sep 13, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 13, 2026
@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 13, 2026, 1:40 PM ET / 17:40 UTC (Revision 2).

ClawSweeper review

What this changes

Bounds overflow recovery to the model’s current context, prevents archived tool results from triggering transcript copies, and adds regression coverage plus an asynchronous test-cleanup fix.

Merge readiness

✅ Ready for maintainer review

The prior budget finding is addressed, and no new blocking defect was found. Current main still contains the archive-wide recovery path, so this protected PR remains useful.

Priority: P1
Reviewed head: 1367c224ba4bb35ebbf7147acec47d42feafc2c1

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with strong storage-boundary evidence and the prior finding resolved.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied Linux/Node SQLite probes exercise the actual recovery and transcript-publication owners with synthetic engine outcomes, then independently reopen storage to verify retry, reduced current output, and preserved history. They cover the resolved-budget correction and incident-scale archives; they do not claim live-provider or production-latency equivalence.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied Linux/Node SQLite probes exercise the actual recovery and transcript-publication owners with synthetic engine outcomes, then independently reopen storage to verify retry, reduced current output, and preserved history. They cover the resolved-budget correction and incident-scale archives; they do not claim live-provider or production-latency equivalence.
Evidence reviewed 9 items Introduced recovery changes verified: The merge-base-to-head diff introduces bounded recovery hydration and canonical context selection; it does not include the unrelated UI and TUI endpoint drift.
Prior finding resolved: All three recovery-session calls now receive contextTokenBudget. Attempt dispatch and attempt recovery both obtain that value from runtime.contextTokenBudget. The added 200,000-token regression uses 1.2 MB of current tool output and verifies successful truncation and retry.
Canonical context and storage ownership: The imported iterator belongs to this repository’s agent-core package and is also consumed by model-context construction. It applies existing compaction, reset-retention, and exclusion rules. SessionManager.prepareTranscriptRewrite retains bounded ancestry and delegates durable publication to the existing storage owner; the patch does not change schemas or writer authority. No Codex dependency contract is implicated.
Findings None None.
Security None None.

How this fits together

OpenClaw’s embedded agent retries context-overflow failures by compacting conversation history and trimming tool output. Recovery reads the SQLite transcript and publishes changes through the existing atomic rewrite owner before retrying inference.

flowchart TD
  A[Context overflow] --> B[Compaction recovery]
  C[Resolved model budget] --> D[Bounded transcript reader]
  B --> D
  D --> E[Current context selection]
  E --> F[Tool output truncation]
  F --> G[Atomic transcript publication]
  G --> H[Retry inference]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +13, Tests +86, Docs +2, Other 0. Total +101 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 5 26 13 +13
Tests 3 94 8 +86
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 10 123 22 +101

Review metrics

Metric Value Why it matters
Archive amplification 262 → 4 appended entries; 64 → 0 copied resets The supplied repeated SQLite benchmark directly measures the unwanted transcript amplification.
Incident-scale preservation 1,700,007 existing entries; 4 appended; all original digests preserved The supplied cold synthetic probe exercises recovery at the reported incident’s order of magnitude.

Technical review

Best possible solution:

Use one bounded model-context view for attempts and recovery while preserving archived transcript bytes and existing atomic publication safeguards.

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

Yes: current main selects historical tool results from the raw branch, allowing the suffix rewrite to copy archived turns and resets; the supplied SQLite regressions exercise that mechanism. This review did not execute them.

Is this the best way to solve the issue?

Yes: reusing the canonical context iterator and the attempt’s existing hydration limits repairs the selection boundary without adding a second rewrite mechanism or changing retention.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The supplied Linux/Node SQLite probes exercise the actual recovery and transcript-publication owners with synthetic engine outcomes, then independently reopen storage to verify retry, reduced current output, and preserved history. They cover the resolved-budget correction and incident-scale archives; they do not claim live-provider or production-latency equivalence.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The supplied Linux/Node SQLite probes exercise the actual recovery and transcript-publication owners with synthetic engine outcomes, then independently reopen storage to verify retry, reduced current output, and preserved history. They cover the resolved-budget correction and incident-scale archives; they do not claim live-provider or production-latency equivalence.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: The reported overflow-recovery incident held a synchronous database write for 924 seconds, stalling an active Gateway workflow.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The supplied Linux/Node SQLite probes exercise the actual recovery and transcript-publication owners with synthetic engine outcomes, then independently reopen storage to verify retry, reduced current output, and preserved history. They cover the resolved-budget correction and incident-scale archives; they do not claim live-provider or production-latency equivalence.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied Linux/Node SQLite probes exercise the actual recovery and transcript-publication owners with synthetic engine outcomes, then independently reopen storage to verify retry, reduced current output, and preserved history. They cover the resolved-budget correction and incident-scale archives; they do not claim live-provider or production-latency equivalence.

Evidence

What I checked:

Likely related people:

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

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-13T17:13:36.939Z sha bfec2cedba28a567c5e7511bdf8a931fd8697a83 :: blocked before merge. :: [P2] [P2] Pass the resolved attempt budget into recovery hydration

@VACInc
VACInc force-pushed the fix/bounded-overflow-transcript-recovery branch from bfec2ce to 1367c22 Compare September 13, 2026 17:33
@VACInc

VACInc commented Sep 13, 2026

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

Updated head: 1367c224ba4bb35ebbf7147acec47d42feafc2c1.

Addressed the effective-budget finding: every recovery reader now receives the resolved model budget. A 200k-token / 1.2 MB tool-result regression fails on the initial PR and passes after the correction. All 93 recovery tests, core and affected test typechecks, changed-file lint, and fresh independent review pass.

Added the requested scale evidence and repeatable probe to the PR body: real SQLite with 1,700,007 synthetic entries recovered in 3,869.54 ms, appended 4 entries, copied 0 resets, and preserved every original row digest. This is one cold synthetic sample; the separate repeated before/after benchmark is 176.36 ms versus 29.82 ms median. No production latency equivalence is claimed.

A separate test-only commit awaits Workboard cleanup introduced by #147191, which caused the first CI run's sole failure. The affected test and plugin lint pass locally. No merge or autofix requested.

@clawsweeper

clawsweeper Bot commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 13, 2026
@VACInc VACInc self-assigned this Sep 13, 2026
@VACInc
VACInc merged commit 06c345f into openclaw:main Sep 13, 2026
218 of 220 checks passed
@VACInc

VACInc commented Sep 13, 2026

Copy link
Copy Markdown
Member Author

Merged via squash.

@VACInc
VACInc deleted the fix/bounded-overflow-transcript-recovery branch September 13, 2026 17:51
vincentkoc added a commit that referenced this pull request Sep 13, 2026
* commit '201f11afefdb19a9c75e9d3542bf7425c80df7a7': (141 commits)
  fix: keep catalog discovery scoped and execution lazy (#147159)
  fix: serialize reclamation worker shutdown with foreground writes (#147178)
  test(sessions): cover abrupt committed transcript recovery (#143984)
  fix: stop transcript storms during context overflow recovery (#147202)
  fix: reduce CPU overhead for small history and usage reads (#147205)
  fix: resume tasks after tools finish and the model times out (#147203)
  refactor(scripts): share SQLite reliability message waits (#146900)
  feat(exec): configure approval reviewer thinking and fastMode (#147192)
  test: remove redundant Bonjour module headers (#146981)
  refactor: share streaming media tail boundary update (#146989)
  refactor(tui): classify resume candidates once (#146983)
  improve: skip unused toast dismissal work (#147196)
  fix(linux): recover saved remote connections without replacing active sessions (#146047)
  fix: doctor stays silent when Windows state dir is under OneDrive (#123720)
  feat: announce successful Daybreak retries (#147146)
  feat(code-mode): reuse results across code cells (#147154)
  refactor(test): reuse CLI plugin fixture writer (#147186)
  test: skip unused compiler setup in routing fixtures (#147194)
  test: reuse LINE webhook runtime fixture (#146710)
  fix(code-mode): check automation and process result types (#147143)
  ...
vincentkoc added a commit that referenced this pull request Sep 13, 2026
* commit '2d87daf04b78992382299d552f15ac84a86a23ed': (1815 commits)
  fix(ui): distinguish tool activity with semantic icons (#147207)
  fix(linux): recover completed Quick Chat replies without resending (#146048)
  feat(desktop): unify Tauri title bar and window controls (#147097)
  refactor(test): share plugin fixture server shims (#147225)
  perf(gateway): defer worker workspace execution imports (#143496)
  fix(gateway): post-ack webhook work fails with "Async work scope is closed" (#144801)
  refactor(scripts): centralize upgrade survivor version floors (#146975)
  fix(ci): check publication registries before FRV fanout (#147184)
  fix(qa): align system-agent delegation with channel contracts (#145905)
  improve: reduce repeated chat message identity work (#147210)
  fix(channels): remove stale pre-tool previews from Slack and Telegram (#147106)
  fix: keep catalog discovery scoped and execution lazy (#147159)
  fix: serialize reclamation worker shutdown with foreground writes (#147178)
  test(sessions): cover abrupt committed transcript recovery (#143984)
  fix: stop transcript storms during context overflow recovery (#147202)
  fix: reduce CPU overhead for small history and usage reads (#147205)
  fix: resume tasks after tools finish and the model times out (#147203)
  refactor(scripts): share SQLite reliability message waits (#146900)
  feat(exec): configure approval reviewer thinking and fastMode (#147192)
  test: remove redundant Bonjour module headers (#146981)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
…w#147202)

* fix: stop transcript storms during context overflow recovery

* test: await Workboard cleanup after attachment race

* fix: use resolved model budgets during overflow recovery

---------

Co-authored-by: VACInc <[email protected]>
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 maintainer Maintainer-authored PR P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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