Skip to content

fix(doctor): repair stale session files whose header crosses a read chunk boundary - #154034

Merged
steipete merged 1 commit into
openclaw:mainfrom
xydt-juyaohui:fix/session-header-boundary-decode
Sep 20, 2026
Merged

steipete merged 1 commit into
openclaw:mainfrom
xydt-juyaohui:fix/session-header-boundary-decode

Conversation

@xydt-juyaohui

@xydt-juyaohui xydt-juyaohui commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: openclaw doctor --fix silently skips repairing a session transcript path that went stale when that session's header line is longer than one 8192-byte read chunk and a multibyte character straddles the boundary.

User Impact

Affected sessions are now repaired as intended instead of being skipped, so users keep working conversation history after a Doctor migration instead of being left on a transcript path that no longer exists. No configuration change or manual action is required.

Why This Change Was Made

resolveStaleLegacySessionFile() validates a candidate transcript by reading its first line — the session header — before adopting it. It read one fixed 8192-byte window and decoded it with Buffer.toString("utf8"). When the complete JSON header extends beyond that window, the truncated JSON fails to parse and the surrounding catch returns undefined, silently skipping the repair. A split multibyte character is also decoded as U+FFFD, but U+FFFD alone does not make a JSON string invalid.

The fixed window is the actual defect: the reader must reach the end of the header while preserving UTF-8 character boundaries. The fix scans the header in chunks with a StringDecoder (Node's incremental UTF-8 decoder, which carries a partial sequence into the next chunk) and stops at the first newline, keeping a character budget so an unterminated file still cannot be read without bound. The scan moved to src/infra/first-line-read.ts so the new behavior lives in a coherent sibling module rather than growing an over-cap file.

Only the header scan changed. The existing guards (legacy file must be gone, no collision rename, sessionId must be a string) and the byte-exact state comparison are untouched.

Evidence

Real Doctor flow, before and after (primary proof)

Driven through the production entry point migrateLegacySessions() — the same function openclaw doctor --fix calls — against two identical fixtures that differ only in the header shape. The fixture is a session whose store entry points at a legacy transcript path that no longer exists, while the live copy sits in the target directory. A repaired session makes Doctor report the Repaired migrated session transcript paths change.

  • baseline = short header (42 bytes)
  • boundary-split = same JSON padded so a 3-byte character 中 starts at offset 8191 and is split by the 8192-byte chunk boundary (8197 bytes)

Before the fix, only the baseline is repaired; the boundary-split header silently loses the repair:

[baseline-short-header]  changes = ["Merged sessions store → …", "Repaired migrated session transcript paths"]
[baseline-short-header]  repaired_reported = true
[boundary-split-header]  changes = ["Merged sessions store → …"]
[boundary-split-header]  repaired_reported = false
RESULT baseline_reports_repair = true
RESULT boundary_reports_repair = false
RESULT VERDICT = FAIL: a header shape loses the repair (bug still present)

After the fix, both header shapes are repaired:

[baseline-short-header]  changes = ["Merged sessions store → …", "Repaired migrated session transcript paths"]
[baseline-short-header]  repaired_reported = true
[boundary-split-header]  changes = ["Merged sessions store → …", "Repaired migrated session transcript paths"]
[boundary-split-header]  repaired_reported = true
RESULT baseline_reports_repair = true
RESULT boundary_reports_repair = true
RESULT VERDICT = PASS: Doctor detects and reports the stale-transcript repair for BOTH headers

Decode-level isolation

Scanning the same bytes directly shows the mechanism, with the old and new reads compared side by side:

=== header first line, chunk boundary splits a 3-byte CJK char ===
OLD (toString window) parses  = undefined                 <- mangled, header unusable
NEW (StringDecoder)   parses  = { type: 'session', id: 'sess-boundary-1', ... }
OLD has U+FFFD               = true
NEW has U+FFFD               = false
resolveStaleLegacySessionFile = …\sessions\sess-boundary-1.jsonl
RESULT VERDICT = PASS: boundary-split header now decodes correctly (pre-fix it was mangled)

Regression test

src/infra/state-migrations.legacy-session-store.test.ts — "repairs a stale session file whose header straddles the read chunk boundary". This is a real pre-fix-fails / post-fix-passes gate, not a test that mirrors the implementation:

Revision node scripts/run-vitest.mjs src/infra/state-migrations.legacy-session-store.test.ts
pre-fix (source reverted to merge-base) 1 failed | 7 passed (8) — the new test fails
post-fix 8 passed (8)
FAIL |infra| src/infra/state-migrations.legacy-session-store.test.ts > repairs a stale session file whose header straddles the read chunk boundary
AssertionError: expected undefined to be '...\sessions\sess-boundary-1.jsonl'

Local gates

  • oxlint -c .oxlintrc.json <changed files> -> Found 0 warnings and 0 errors. (includes the max-lines rule the line-cap ratchet enforces)
  • oxfmt --check <changed files> -> All matched files use the correct format.
  • tsc --noEmit -p tsconfig.json -> no errors reported for either changed file

Earlier CI

All shards covering this change are green: check-lint + check-lint-core-1..5, check-test-types and check-test-types-core-1, checks-windows-node-test-1..2, checks-fast-core, and 42/43 checks-node-compact-large-* plus all 43 checks-node-compact-small-*.

Three checks remain red and none of them touch this diff:

Gaps

The Doctor proof runs the real migrateLegacySessions() entry point against a synthetic state directory on Windows; it does not exercise a published-updater upgrade against an installed release. The store normalizes sessionFile out of the persisted entry shape, so the observable outcome is Doctor's repair decision and its reported change, which is what the proof asserts.

Maintainer landing review

The scoped Codex autoreview is clean, and the ClawSweeper review of head 48c2cc9a31188275eceaca773c46875c0a7dc732 found no introduced correctness defect. The exact-head CI gate is green according to the campaign's REST check-runs verification, superseding the earlier CI notes above; native preparation independently verifies hosted evidence.

Disposition of ClawSweeper's September 20, 21:16 UTC rank-up moves:

  • Published-updater-to-candidate proof: skipped for this explicitly authorized landing. The existing Windows migration-owner before/after proof and regression are retained; a published-driver upgrade and canonical history readback remain unrun and are not claimed here.
  • Changed-test wall time and CI duration: skipped for this landing, which is instructed to reuse existing proof without rerunning. No measured per-file duration was supplied, so none is claimed.

Follow-up: header parse failures still skip silently; recording an explicit Doctor non-outcome is a named follow-up outside this patch.

@clawsweeper

clawsweeper Bot commented Sep 20, 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.

@xydt-juyaohui
xydt-juyaohui force-pushed the fix/session-header-boundary-decode branch from f1acab5 to 0d477e3 Compare September 20, 2026 20:17
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 20, 2026
@clawsweeper

clawsweeper Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed September 20, 2026, 5:47 PM ET / 21:47 UTC (Revision 3).

ClawSweeper review

What this changes

Doctor reads legacy session headers across UTF-8 chunks so long headers no longer prevent stale transcript-path repair, with a regression test.

Merge readiness

⛔ Blocked before merge - 2 items remain

This remains a useful, focused fix absent from current main and the latest release. No introduced correctness defect was found, but the required upgrade evidence remains incomplete; the PR-body assertion that checks were waived is not corroborated by maintainer discussion.

Priority: P2
Reviewed head: 48c2cc9a31188275eceaca773c46875c0a7dc732

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation is focused and has meaningful before/after evidence, but required upgrade coverage remains incomplete.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: Needs stronger real behavior proof before merge: the Windows migrateLegacySessions trace proves the corrected repair decision using real files, but explicitly omits the policy-required published-updater × candidate run and canonical history readback. Provide redacted terminal output, logs, or a linked transcript; terminal screenshots or video also count. Remove secrets and private details. Updating the PR body should trigger re-review; otherwise ask a maintainer to comment @clawsweeper re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: Needs stronger real behavior proof before merge: the Windows migrateLegacySessions trace proves the corrected repair decision using real files, but explicitly omits the policy-required published-updater × candidate run and canonical history readback. Provide redacted terminal output, logs, or a linked transcript; terminal screenshots or video also count. Remove secrets and private details. Updating the PR body should trigger re-review; otherwise ask a maintainer to comment @clawsweeper re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 8 items Pinned introduction and merge composition: The merge-base-to-head patch changes the header reader, its migration caller, and one regression test. The verified test merge records the pinned base followed by the exact PR head and retains that same scope.
Current main still has the defect: The fetched main implementation reads only 8192 bytes before JSON parsing. A valid header extending beyond that window is truncated and rejected by the existing catch.
Latest-release check: The supplied latest release, v2026.9.5, also contains the fixed 8192-byte window; this requested repair is not already shipped there.
Findings None None.
Security None None.

How this fits together

Doctor inspects legacy session records and transcript files before migrating conversation state. Header validation determines whether an existing transcript can replace a missing legacy path.

flowchart TD
  A[Legacy session record] --> B[Doctor migration]
  C[Candidate transcript] --> D[Bounded UTF-8 header reader]
  D --> E[Validate session identity]
  B --> E
  E --> F[Repair eligible transcript path]
  F --> G[Normalize and persist session state]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: Needs stronger real behavior proof before merge: the Windows migrateLegacySessions trace proves the corrected repair decision using real files, but explicitly omits the policy-required published-updater × candidate run and canonical history readback. Provide redacted terminal output, logs, or a linked transcript; terminal screenshots or video also count. Remove secrets and private details. Updating the PR body should trigger re-review; otherwise ask a maintainer to comment @clawsweeper re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Complete next step (P2) - Record measured changed-test wall time and available CI duration, or link a verified maintainer exception to that requirement.
Agent review details

Security

None.

PR surface

Source +26, Tests +35. Total +61 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 2 42 16 +26
Tests 1 35 0 +35
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 77 16 +61

Review metrics

None.

Technical review

Best possible solution:

Keep the bounded reader in the existing migration owner and demonstrate that the affected conversation remains readable after a published-updater upgrade.

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

Yes: current main truncates valid JSON headers exceeding 8192 bytes, and the contributed fixture places a multibyte character at that boundary. Source establishes the failure mechanism; this review did not execute it.

Is this the best way to solve the issue?

Yes for the parsing defect: incremental UTF-8 decoding with a bounded scan preserves the existing identity and collision checks. Full migration recovery still needs the required upgrade evidence.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This repairs a bounded legacy-session migration failure triggered by unusually long transcript headers.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: Needs stronger real behavior proof before merge: the Windows migrateLegacySessions trace proves the corrected repair decision using real files, but explicitly omits the policy-required published-updater × candidate run and canonical history readback. Provide redacted terminal output, logs, or a linked transcript; terminal screenshots or video also count. Remove secrets and private details. Updating the PR body should trigger re-review; otherwise ask a maintainer to comment @clawsweeper re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Pinned introduction and merge composition: The merge-base-to-head patch changes the header reader, its migration caller, and one regression test. The verified test merge records the pinned base followed by the exact PR head and retains that same scope. (src/infra/first-line-read.ts:15, 48c2cc9a3118)
  • Current main still has the defect: The fetched main implementation reads only 8192 bytes before JSON parsing. A valid header extending beyond that window is truncated and rejected by the existing catch. (src/infra/state-migrations.session-store.ts:455, af00d16e3573)
  • Latest-release check: The supplied latest release, v2026.9.5, also contains the fixed 8192-byte window; this requested repair is not already shipped there. (src/infra/state-migrations.session-store.ts:455, ec9c1a13db89)
  • Production-path proof and its limits: The captured PR body, sourceRevision f98d78a78ada14f1717646fc1b42cf120e6d4ac39effc927a85846d04305bace, supplies Windows before/after output from migrateLegacySessions using real fixture files. Both short and boundary-split headers report repair after the fix. It expressly leaves published-updater execution and canonical history readback unrun. The changed regression is reported to fail before the fix and pass afterward. (src/infra/state-migrations.legacy-session-store.test.ts:242, 48c2cc9a3118)
  • Repair reporting is narrower than history recovery: The migration sets the repaired-path flag before normalizing and saving the store. Canonical entry projection removes the retired sessionFile field, so the reported repair decision alone does not establish that conversation history remains available after the complete migration. (src/infra/state-migrations.legacy-sessions.ts:258, 48c2cc9a3118)
  • Applicable policy and prior-request disposition: The fully read root policy requires published-driver × candidate proof for Doctor changes and measured cost for changed tests. Both previous rank-up requests are explicitly acknowledged but skipped in the captured body. Live reads found no non-bot discussion comments or reviews corroborating an exception; no proof override label was supplied. (AGENTS.md, 48c2cc9a3118)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Jason (Json): 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.

  • Add published-updater-to-candidate evidence showing the affected conversation remains readable after migration.
  • Record the changed test file's measured wall time and available CI duration, or supply a verified maintainer exception.

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 (2 earlier review cycles)
  • reviewed 2026-09-20T20:29:01.042Z sha 0d477e34d8d7e017f8deb0a1469139f698835373 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-20T21:16:18.030Z sha 48c2cc9 :: needs real behavior proof before merge. :: none

A fixed 8192-byte read window could end inside a multibyte character, and
toString("utf8") then replaced the split character with U+FFFD. The header
stopped parsing, so the stale sessionFile repair silently did nothing and the
session kept pointing at a path that no longer exists. Scan the header in
chunks with a StringDecoder and stop at the first newline instead.
@xydt-juyaohui
xydt-juyaohui force-pushed the fix/session-header-boundary-decode branch from 0d477e3 to 48c2cc9 Compare September 20, 2026 21:06
@steipete
steipete merged commit ddcd17b into openclaw:main Sep 20, 2026
235 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 21, 2026
…nclaw#154034)

Doctor could skip stale transcript-path repair when a valid session header extended past its fixed 8192-byte read window. Read the complete first line with bounded incremental UTF-8 decoding so long headers and split multibyte characters preserve the existing session identity and collision safeguards.

Release-note context: restore Doctor's repair of stale session transcript paths for headers that cross a read chunk boundary. No configuration change or operator action is required. Thanks to @xydt-juyaohui for the fix.

Evidence: the existing regression fails before the fix and passes afterward (8 tests passed), and the reported Windows migration-owner flow repairs both short and boundary-split headers. The approved head has green hosted CI and a scoped-clean Codex review. Published-updater-to-candidate proof and per-file timing measurements remain unrun in this landing lane.

Follow-up: header parse failures still skip silently; record an explicit Doctor non-outcome in follow-up work.

Co-authored-by: 琚耀辉0668001366 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants