Skip to content

fix(doctor): bound session snapshot store reads with size cap - #110835

Closed
nocodet888-arch wants to merge 3 commits into
openclaw:mainfrom
nocodet888-arch:fix/doctor-snapshot-store-bound
Closed

nocodet888-arch wants to merge 3 commits into
openclaw:mainfrom
nocodet888-arch:fix/doctor-snapshot-store-bound

Conversation

@nocodet888-arch

@nocodet888-arch nocodet888-arch commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Doctor session-snapshot scan/repair loaded session store JSON with unbounded
fs.readFileSync at two call sites. A corrupted or hostile multi-GB
sessions.json under the user state directory could OOM openclaw doctor
before JSON parse or repair logic ran.

Earlier revisions checked size via pathname statSync then opened the path
again, and repair hydration could still allocate after a store grew while
queued.

Why This Change Was Made

  1. readSnapshotStoreRaw pins one FD (openSync/fstatSync), enforces the
    16 MiB cap while reading via readFileDescriptorBoundedSync, and closes in
    finally.
  2. Repair passes maxBytes: MAX_SNAPSHOT_STORE_BYTES into updateSessionStore
    so writer hydration cannot allocate above the bound after queued growth.
  3. Oversized stores fail closed with operator-visible Session snapshots notes
    and structured kind: "store-too-large" / would-skip-oversized-session-store.

User Impact

Before: An oversized session store could force an unbounded sync string
alloc during doctor snapshot health, or bypass a pathname-stat race / grow
while repair waited.

After: Stores above 16 MiB are rejected on a pinned descriptor (and at the
writer load boundary). Doctor reports the skip; normal stores continue.

Evidence

  • Changed: src/commands/doctor-session-snapshots.ts,
    src/config/sessions/store-load.ts, src/config/sessions/store.ts
  • Production path: noteSessionSnapshotHealth →
    loadSessionStoreForSnapshotScan / repair updateSessionStore({ maxBytes })
    → descriptor-bounded read
  • Head: ec2d1617bce

Real behavior proof

Behavior or issue addressed

A ~17 MiB session store is not fully buffered. Isolated
openclaw doctor --non-interactive --yes prints a Session snapshots note that
the store was skipped as oversized. Descriptor-bound + writer maxBytes close
the concurrent-growth gaps called out in review.

Canonical reachability path

openclaw doctor → session snapshot health →
readSnapshotStoreRaw (pinned FD + bounded read) /
updateSessionStore(..., { maxBytes }) → skip + warn on overflow

Shared helper / provider constraint check

Uses readFileDescriptorBoundedSync; same 16 MiB campaign cap; no new
config/env keys.

Real environment tested

Local trusted source checkout at PR head; Node 22.23.1; isolated
OPENCLAW_STATE_DIR with a planted 17 MiB sessions.json; CLI via
node scripts/run-node.mjs doctor --non-interactive --yes.

Exact steps or command run after this patch

node scripts/run-vitest.mjs src/commands/doctor-session-snapshots.test.ts \
  -t "oversized session stores" --reporter=verbose

Evidence after fix

Redacted CLI previously captured:

◇  Session snapshots ───────────────────────────────────────────────────────────╮
│  - Skipped oversized session store                                            │
│    .../sessions.json: file too large (17825792 bytes, max 16777216).          │
├───────────────────────────────────────────────────────────────────────────────╯

Fix classification

bugfix — resource bound / OOM hardening (descriptor + writer load)

AI Assistance

AI-assisted implementation and proof.

@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations size: S labels Jul 18, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jul 18, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 7, 2026, 8:50 PM ET / September 8, 2026, 00:50 UTC.

ClawSweeper review

What this changes

Limits Doctor’s session-snapshot JSON reads to 16 MiB, including repair hydration, and reports oversized stores instead of loading them.

Merge readiness

⛔ Blocked before merge - 7 items remain

This remains useful: current main and the latest release retain the unbounded snapshot read, and the merged SQLite fix explicitly excluded it. Both previous guard-placement findings are addressed, but overflow reporting still has a defect.

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

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful hardening with real CLI evidence, but overflow reporting and upgrade validation remain unresolved.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The captured isolated Doctor CLI trace demonstrates the production snapshot owner rejecting a 17 MiB file and printing the intended warning. Preserve that proof; concurrent growth and queued repair remain separate regression-validation gaps.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The captured isolated Doctor CLI trace demonstrates the production snapshot owner rejecting a 17 MiB file and printing the intended warning. Preserve that proof; concurrent growth and queued repair remain separate regression-validation gaps.
Evidence reviewed 10 items Introduced changes and previous findings: The complete host-provided merge-base-to-head patch adds descriptor-bounded reads and passes maxBytes into writer hydration before the mutator. These address the two retained previous findings. Unrelated UI endpoint drift is excluded.
Overflow exception contract: The shared reader throws RangeError with 'File exceeds … bytes' after crossing its byte budget. Doctor’s isOversizedStoreError recognizes only messages containing 'file too large', so growth-triggered overflow is silently discarded by structured detection.
Writer boundary: Capped loads bypass object-cache reads, pin a descriptor, enforce the limit, and propagate RangeError before normalization or mutation. The ordinary uncapped load path remains available.
Findings 1 actionable finding [P2] Normalize bounded-reader overflow into an oversized-store issue
Security None None.

How this fits together

Doctor inspects cached skill paths in legacy session files and optionally repairs outdated paths through a serialized writer. Its results become console notes and structured health findings.

flowchart TD
 A[Doctor command] --> B[Legacy session files]
 B --> C[Descriptor read with byte limit]
 C -->|Within limit| D[Inspect cached skill paths]
 C -->|Over limit| E[Skipped-store warning]
 D --> F[Serialized repair writer]
 F --> G[Backup and repaired file]
Loading

Decision needed

Question Recommendation
Should snapshot inspection and repair intentionally skip every legacy store above 16 MiB, including valid upgrade data? Approve a snapshot-only cutoff: Accept the limit after demonstrating that large valid stores remain intact and can complete the supported migration workflow.

Why: The limit prevents unbounded reads but introduces an operator-visible cutoff absent from the existing migration contract.

Before merge

  • Normalize bounded-reader overflow into an oversized-store issue (P2) - When a file grows past 16 MiB after fstatSync, this newly added call throws RangeError('File exceeds … bytes'). isOversizedStoreError only recognizes file too large, so detectSessionSnapshotHealthIssues silently continues and omits the warning and dry-run effect for the rejected store. Normalize the helper’s overflow into the same typed result as the initial size check, and cover growth during reading.
  • Resolve merge risk (P1) - Valid legacy stores above 16 MiB will lose snapshot inspection and repair until operators take additional action; preservation-safe upgrade behavior is not demonstrated.
  • Resolve merge risk (P1) - GitHub context reports merge conflicts, and current main uses a different legacy-store owner; the resolved implementation has not been reviewed.
  • Resolve merge risk (P1) - Concurrent-growth rejection and queued writer hydration lack the regression coverage requested in the previous review.
  • Complete next step (P2) - Resolve conflicts onto the current Doctor-only legacy owner, fix overflow reporting, validate the revised read and writer boundaries, and obtain agreement on the 16 MiB cutoff.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.

Findings

  • [P2] Normalize bounded-reader overflow into an oversized-store issue — src/commands/doctor-session-snapshots.ts:371-372
Agent review details

Security

None.

PR surface

Source +129, Tests +52. Total +181 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 3 143 14 +129
Tests 1 52 0 +52
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 195 14 +181

Review metrics

Metric Value Why it matters
Snapshot read policy 1 new hard cutoff: 16 MiB; 0 new config keys The threshold changes which existing stores Doctor can inspect and repair.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/commands/doctor-session-snapshots.ts, serialized state: src/config/sessions/store-load.ts, unknown-data-model-change: src/commands/doctor-session-snapshots.ts, unknown-data-model-change: src/config/sessions/store-load.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Prove preservation across the cutoff (recommended)
    Keep the cap scoped to snapshot work and verify normal repair, oversized-file preservation, and large-store migration through the current owner.
  2. Pause for incremental processing
    Defer the hard cutoff if maintainers require snapshot repair for valid large stores.

Technical review

Best possible solution:

Keep bounded reads in the current Doctor-only legacy owner, report every overflow consistently, and preserve a supported migration path for valid large stores.

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

Yes, from source: current main reads the complete legacy JSON file before parsing, and the revised branch drops structured overflow warnings when growth triggers the helper’s RangeError. Neither path was executed during this review.

Is this the best way to solve the issue?

Acceptable mitigation, but not yet the best finished fix: reuse the bounded reader in the current legacy owner and normalize its overflow result; a global heap increase would leave the unbounded read intact.

Full review comments:

  • [P2] Normalize bounded-reader overflow into an oversized-store issue — src/commands/doctor-session-snapshots.ts:371-372
    When a file grows past 16 MiB after fstatSync, this newly added call throws RangeError('File exceeds … bytes'). isOversizedStoreError only recognizes file too large, so detectSessionSnapshotHealthIssues silently continues and omits the warning and dry-run effect for the rejected store. Normalize the helper’s overflow into the same typed result as the initial size check, and cover growth during reading.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is bounded resource hardening for legacy Doctor snapshot processing.
  • merge-risk: 🚨 compatibility: Previously accepted valid stores above 16 MiB will be skipped and require operator recovery or migration.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The captured isolated Doctor CLI trace demonstrates the production snapshot owner rejecting a 17 MiB file and printing the intended warning. Preserve that proof; concurrent growth and queued repair remain separate regression-validation gaps.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured isolated Doctor CLI trace demonstrates the production snapshot owner rejecting a 17 MiB file and printing the intended warning. Preserve that proof; concurrent growth and queued repair remain separate regression-validation gaps.

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)
  • Dallin Romney: 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.

  • Normalize overflow reporting and add growth-during-read regression coverage.
  • Exercise capped writer hydration, normal repair, and oversized-store preservation through the current legacy owner.
  • Demonstrate the supported migration path for valid stores above 16 MiB.

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 (11 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-31T08:03:36.520Z sha efba8c7 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-04T12:35:45.883Z sha efba8c7 :: needs changes before merge. :: [P2] Read the capped store from a stable descriptor
  • reviewed 2026-08-13T01:03:07.341Z sha efba8c7 :: found issues before merge. :: [P2] Read the capped store from a stable descriptor
  • reviewed August 16, 2026, 8:31 AM ET / 12:31 UTC sha unknown :: needs changes before merge. :: [P2] Read the capped store from a pinned descriptor
  • reviewed 2026-08-23T02:09:44.490Z sha efba8c7 :: needs changes before merge. :: [P2] Read the capped store through a pinned descriptor | [P2] Apply the cap before entering the legacy writer
  • reviewed August 29, 2026, 12:16 AM ET / 04:16 UTC sha unknown :: needs changes before merge. :: [P1] Rebase onto the current legacy store owner | [P2] Bound the writer's read before its mutator
  • reviewed 2026-08-29T04:16:26.156Z sha efba8c7 :: blocked before merge. :: [P1] Rebase onto the current legacy store owner | [P2] Bound the writer's read before its mutator
  • reviewed 2026-09-05T12:41:40.599Z sha efba8c7 :: blocked before merge. :: [P2] Enforce the size limit while reading a pinned descriptor | [P2] Apply the repair bound before the writer loads the store

@nocodet888-arch

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Oversized stores now emit an operator-visible Session snapshots warning (and structured store-too-large issues). PR body refreshed with redacted isolated openclaw doctor --non-interactive --yes CLI proof against a ~17 MiB sessions.json.

@clawsweeper

clawsweeper Bot commented Jul 18, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. 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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. 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 Jul 18, 2026
@clawsweeper clawsweeper Bot added 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. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed 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. labels Aug 4, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Aug 23, 2026
@clawsweeper clawsweeper Bot removed the rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. label Sep 6, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Sep 6, 2026
@steipete steipete self-assigned this Sep 7, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Sep 7, 2026
Pin one FD for snapshot store reads, enforce the 16 MiB cap while reading,
and plumb maxBytes through updateSessionStore hydration so repair cannot
allocate after a store grows while queued.
@nocodet888-arch

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Pushed ec2d1617bce: descriptor-pinned bounded snapshot reads + maxBytes on updateSessionStore writer hydration. Addresses the concurrent-growth / writer-load review findings. Body updated.

@clawsweeper

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

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Sep 8, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Sep 8, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

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

Labels

commands Command implementations merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M stale Marked as stale due to inactivity status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants