Skip to content

fix(doctor): bound legacy session store read with size cap and stat-failure fix - #110772

Merged
steipete merged 9 commits into
openclaw:mainfrom
cxbAsDev:fix/bound-doctor-sqlite-read
Jul 21, 2026
Merged

steipete merged 9 commits into
openclaw:mainfrom
cxbAsDev:fix/bound-doctor-sqlite-read

Conversation

@cxbAsDev

@cxbAsDev cxbAsDev commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

The readLegacySessionRecords function in src/commands/doctor-session-sqlite.ts reads legacy JSON session store files during openclaw doctor with a path-based fs.readFileSync(path). A malicious or accidental FIFO substitution at that path could block the CLI indefinitely, and a file swapped between any path-based size check and the read could cause unbounded memory consumption.

Why This Change Was Made

Doctor migration runs during openclaw doctor, regularly invoked by users. The fix opens the file first with a pinned descriptor, validates the descriptor as a regular file, and reads no more than the validated byte count. This eliminates both the FIFO-blocking availability risk and the Time-of-Check-Time-of-Use (TOCTOU) race where a different file could be consumed.

What Changed

Replaced the path-based read with a descriptor-bound, nonblocking, byte-capped read in readLegacySessionRecords:

  1. fs.openSync(path, O_RDONLY | O_NONBLOCK) (POSIX) / "r" (Windows) — Opens the file first without blocking on FIFOs.
  2. fs.fstatSync(fd) — Stats the descriptor (not the path) to confirm it is a regular file and to learn its size.
  3. Bounded descriptor read loop — Reads at most storeStat.size bytes from the same fd, so same-inode growth after fstat cannot be consumed.
  4. fs.closeSync(fd) — Closes the descriptor via try/finally, guaranteeing cleanup.

All error paths (ENOENT, EACCES, non-regular file) produce equivalent store_unreadable issues as before. The parent-directory validation for missing stores is preserved. No new hard size cap is introduced, so existing valid legacy stores of any size continue to migrate.

User Impact

Before After
Path-based read → could block on a substituted FIFO → O_NONBLOCK open returns immediately; FIFOs are rejected by fstat
File swapped between check and read → could read unbounded data → fd pins the inode; bounded read closes same-inode growth path
Normal migration with valid files → works → works (unchanged); no new hard size cap

Evidence

All doctor-session-sqlite tests pass (2 skipped, platform-specific):

 ✓ |doctor-session-sqlite| src/commands/doctor-session-sqlite.test.ts (68 tests) 2671ms
 Test Files  1 passed (1)
      Tests  68 passed (68)

Real Behavior Proof

Valid legacy store migration

Ran the production openclaw doctor --session-sqlite inspect command against a real legacy session store file using the branch build. Path redacted to <tmp>.

$ openclaw doctor --session-sqlite inspect --session-sqlite-store <tmp>/valid-sessions.json --non-interactive --json
{
  "targets": [{
    "storePath": "<tmp>/valid-sessions.json",
    "issues": [],
    "legacyEntries": 1,
    "sqliteEntries": 0
  }],
  "totals": {
    "issues": 0,
    "legacyEntries": 1,
    "targets": 1
  }
}

The valid 93-byte store is read successfully and reports one legacy entry.

FIFO rejection without blocking

A focused runtime script using the same O_NONBLOCK descriptor-acquisition strategy confirms that a substituted FIFO is rejected promptly:

const openFlags =
  process.platform === "win32"
    ? "r"
    : fs.constants.O_RDONLY | fs.constants.O_NONBLOCK;
const fd = fs.openSync(fifoPath, openFlags);
const storeStat = fs.fstatSync(fd);
if (!storeStat.isFile()) {
  throw new Error(`not a regular file: ${fifoPath}`);
}

Output:

FIFO rejected in 1ms: not a regular file: /tmp/openclaw-proof-110772-XXXXXX/fifo
Regular file read bytes: 31

The FIFO path is rejected in milliseconds because O_NONBLOCK prevents fs.openSync() from blocking for a writer; the descriptor-bound fstat() sees a FIFO and throws.

Descriptor-growth boundary proof

The bounded read loop consumes at most the byte count validated by fstatSync. A runtime script exercises this by opening a valid store, growing it after fstatSync, and confirming only the original validated bytes are read:

const fd = fs.openSync(tmp, "r");
const storeStat = fs.fstatSync(fd);
// Grow the same inode after descriptor validation.
const appendFd = fs.openSync(tmp, "a");
fs.writeSync(appendFd, Buffer.alloc(10 * 1024 * 1024, "x"));
fs.closeSync(appendFd);
// Read at most storeStat.size bytes from the pinned fd.
const buf = Buffer.alloc(storeStat.size);
let totalBytes = 0;
while (totalBytes < storeStat.size) {
  const bytesRead = fs.readSync(fd, buf, totalBytes, storeStat.size - totalBytes, totalBytes);
  if (bytesRead === 0) {
    break;
  }
  totalBytes += bytesRead;
}
const parsed = JSON.parse(buf.subarray(0, totalBytes).toString("utf-8"));

Output:

validated size: 31
size after growth: 10485791
bytes read: 31
parsed keys: [ 'session1' ]

Even though the file grew by 10 MiB on the same inode, the reader stops at the fstat-validated size and the JSON object still parses correctly.

@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations size: XS 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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 18, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 19, 2026, 7:00 AM ET / 11:00 UTC.

Summary
The PR changes legacy session-store migration to open a nonblocking file descriptor, validate and bound reads through that descriptor, and add unreadable-store regression coverage.

PR surface: Source +52, Tests +35. Total +87 across 2 files.

Reproducibility: Source-reproducible: the pre-change path-based reader permits the FIFO and read-after-check scenarios described in the PR, and the PR supplies after-fix terminal evidence. I did not independently execute a FIFO reproduction in this read-only review.

Review metrics: none identified.

Stored data model
Persistent data-model change detected: migration/backfill/repair: src/commands/doctor-session-sqlite.test.ts, migration/backfill/repair: src/commands/doctor-session-sqlite.ts, serialized state: src/commands/doctor-session-sqlite.ts, unknown-data-model-change: src/commands/doctor-session-sqlite.ts. Confirm migration or upgrade compatibility proof before merge.

Merge readiness
Overall: 🦞 diamond lobster
Proof: 🦞 diamond lobster
Patch quality: 🦞 diamond lobster
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Next step before merge

  • [P2] No discrete automated repair remains; route the exact current head through ordinary maintainer review and normal merge checks.

Security
Cleared: The patch adds no dependency, secret, permission, workflow, or supply-chain surface and hardens handling of hostile or accidental special file paths.

Review details

Best possible solution:

Merge the focused descriptor-bound reader after ordinary maintainer review, retaining uncapped migration compatibility and the targeted unreadable-store behavior.

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

Source-reproducible: the pre-change path-based reader permits the FIFO and read-after-check scenarios described in the PR, and the PR supplies after-fix terminal evidence. I did not independently execute a FIFO reproduction in this read-only review.

Is this the best way to solve the issue?

Yes. Binding open, validation, and bounded reads to one descriptor is the narrowest maintainable fix for both special-file blocking and the size-validation race while preserving valid legacy stores.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 104691f82231.

Label changes

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR provides redacted after-fix terminal evidence for the production doctor command, FIFO rejection, and the descriptor-growth boundary; no contributor follow-up proof is needed.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove merge-risk: 🚨 availability: Current PR review selected no merge-risk labels.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: A legacy session-store path that can indefinitely block openclaw doctor is an urgent availability defect in a recovery and migration workflow.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR provides redacted after-fix terminal evidence for the production doctor command, FIFO rejection, and the descriptor-growth boundary; no contributor follow-up proof is needed.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR provides redacted after-fix terminal evidence for the production doctor command, FIFO rejection, and the descriptor-growth boundary; no contributor follow-up proof is needed.
Evidence reviewed

PR surface:

Source +52, Tests +35. Total +87 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 79 27 +52
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 2 114 27 +87

What I checked:

  • Descriptor-bound migration read: The proposed reader opens the store before inspecting it, validates the pinned descriptor as a regular file, and bounds reads to the descriptor's fstat size; this addresses path swapping and post-stat file growth without restoring the removed hard size cap. (src/commands/doctor-session-sqlite.ts:347, 489314af8281)
  • Regression coverage: The patch adds coverage for a stat failure caused by a non-directory parent and for a non-regular store path, both expected to surface as store_unreadable rather than aborting doctor inspection. (src/commands/doctor-session-sqlite.test.ts:120, 489314af8281)
  • After-fix behavior proof: The PR body includes redacted production CLI output for a valid legacy store plus terminal output showing prompt FIFO rejection and a descriptor-growth read limited to the initially validated byte count. (489314af8281)
  • Review-cycle continuity: The latest head follows the earlier review findings by removing the incompatible fixed size cap and adding POSIX O_NONBLOCK before descriptor validation; no prior blocker remains evidenced at this head. (src/commands/doctor-session-sqlite.ts:347, 489314af8281)

Likely related people:

  • penggaolai: Authored the latest commits removing the hard cap and adding the O_NONBLOCK descriptor acquisition used by the current PR head. (role: recent contributor to the exact doctor migration path; confidence: low; commits: a374469d080d, 489314af8281; files: src/commands/doctor-session-sqlite.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.
Review history (22 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-19T08:30:11.450Z sha 2aeac850bf245fa3ae8872a276275429bd293480 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-19T09:08:40.858Z sha 4e070022a52ae5b058ed3d6624f633c7fd337639 :: needs real behavior proof before merge. :: [P1] Preserve migration for valid stores above the new cap
  • reviewed 2026-07-19T09:26:44.578Z sha 4e070022a52ae5b058ed3d6624f633c7fd337639 :: found issues before merge. :: [P1] Preserve migration for valid stores above the new cap
  • reviewed 2026-07-19T09:44:29.766Z sha 9ca1d8de071c3c4257a064580e01ea69f4d8e148 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-19T10:09:40.206Z sha 88d3cc3a5b557460262c5d6a151c665f9f2c91d4 :: needs changes before merge. :: [P1] Avoid blocking before rejecting special files
  • reviewed 2026-07-19T10:22:39.939Z sha 5124cea0a6d2ba71a55458b15bb85708ae8074bb :: needs changes before merge. :: [P1] Reject FIFOs before a blocking open
  • reviewed 2026-07-19T10:38:07.353Z sha fee2d71e0c50607a309e32bba449d6ecac9d3d26 :: needs changes before merge. :: [P1] Reject FIFOs before opening the store path
  • reviewed 2026-07-19T10:55:45.180Z sha 489314af82813f2cad9d0a41c164393fd59ffa6f :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 19, 2026
@cxbAsDev

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 19, 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:

@cxbAsDev cxbAsDev changed the title fix(doctor): bound legacy session store read with size cap fix(doctor): bound legacy session store read with size cap and stat-failure fix Jul 19, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 19, 2026
@cxbAsDev

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Updated PR with descriptor-bound read fixes (TOCTOU eliminated) and test evidence. Please re-review.

@clawsweeper

clawsweeper Bot commented Jul 19, 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:

@cxbAsDev

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

All P1 findings addressed: descriptor-bound reads eliminate TOCTOU, tests pass, PR body updated with evidence. Please re-review.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jul 19, 2026
@cxbAsDev
cxbAsDev force-pushed the fix/bound-doctor-sqlite-read branch from fdae8c9 to c4a73c4 Compare July 19, 2026 05:48
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 19, 2026
@cxbAsDev

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Rebased onto latest main and force-pushed. The previous checks-node-compact-small-7 failure was unrelated to this PR's doctor-session-sqlite changes (it was the acp-cli-exit.process.test.ts test failing on a stale merge base). Current CI run is now green.

@clawsweeper

clawsweeper Bot commented Jul 19, 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:

@cxbAsDev
cxbAsDev force-pushed the fix/bound-doctor-sqlite-read branch from c4a73c4 to ec67364 Compare July 19, 2026 06:10
@cxbAsDev

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Force-pushed to latest main again. All required checks are green on head ec67364f; no failures. Please re-evaluate for ready-for-maintainer-look.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jul 19, 2026
@cxbAsDev
cxbAsDev force-pushed the fix/bound-doctor-sqlite-read branch from 5124cea to fee2d71 Compare July 19, 2026 10:35
@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. labels Jul 19, 2026
@cxbAsDev
cxbAsDev force-pushed the fix/bound-doctor-sqlite-read branch from fee2d71 to 489314a Compare July 19, 2026 10:52
@cxbAsDev

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Added O_NONBLOCK to the legacy session store open path so a substituted FIFO cannot block the CLI; the descriptor-bound fstat rejects non-regular files. PR body now includes a FIFO rejection proof in addition to the descriptor-growth boundary proof.

@clawsweeper

clawsweeper Bot commented Jul 19, 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 rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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. labels Jul 19, 2026
@steipete steipete self-assigned this Jul 21, 2026
cxbAsDev and others added 9 commits July 20, 2026 19:46
statSync with throwIfNoEntry: false returns undefined for paths whose
parent is a regular file (ENOTDIR) rather than throwing. When a store
appears missing but its parent directory is not a directory, report
store_unreadable instead of silently treating it as an absent store.
Replace statSync-then-readFileSync with openSync/fstatSync/readFileSync on the
same file descriptor to eliminate the TOCTOU race where a file can change
between size validation and read.
… store migration

Replace readFileSync(fd, 'utf-8') — which reads to EOF — with a
descriptor-bound loop that reads at most the byte count validated by
fstatSync. This prevents same-inode growth after fstat from bypassing
the 50 MiB per-store cap and causing OOM.
@steipete
steipete force-pushed the fix/bound-doctor-sqlite-read branch from 489314a to cbb7055 Compare July 21, 2026 02:47
@steipete
steipete merged commit 831499e into openclaw:main Jul 21, 2026
119 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 Jul 21, 2026
…ailure fix (openclaw#110772)

* fix(doctor): bound legacy session store read with size cap

* fix(doctor): handle ENOTDIR in legacy store stat preflight

statSync with throwIfNoEntry: false returns undefined for paths whose
parent is a regular file (ENOTDIR) rather than throwing. When a store
appears missing but its parent directory is not a directory, report
store_unreadable instead of silently treating it as an absent store.

* fix(doctor): use descriptor-bound read for legacy session store files

Replace statSync-then-readFileSync with openSync/fstatSync/readFileSync on the
same file descriptor to eliminate the TOCTOU race where a file can change
between size validation and read.

* fix(doctor): bound descriptor read to validated byte count in session store migration

Replace readFileSync(fd, 'utf-8') — which reads to EOF — with a
descriptor-bound loop that reads at most the byte count validated by
fstatSync. This prevents same-inode growth after fstat from bypassing
the 50 MiB per-store cap and causing OOM.

* style(doctor): add braces for curly lint rule

* fix(doctor): remove hard 50 MiB cap to preserve legacy migration compatibility

* fix(doctor): open legacy session store with O_NONBLOCK to prevent FIFO blocking

* refactor(doctor): reuse bounded descriptor reader

* fix(doctor): report descriptor stat failures

---------

Co-authored-by: OpenClaw Agent <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
@cxbAsDev
cxbAsDev deleted the fix/bound-doctor-sqlite-read branch September 3, 2026 15:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. 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.

3 participants