Skip to content

fix(memory-core): restore MEMORY.md when the in-place fallback write fails midway - #126486

Merged
obviyus merged 3 commits into
openclaw:mainfrom
yetval:fix/memory-inplace-write-restore
Aug 27, 2026
Merged

obviyus merged 3 commits into
openclaw:mainfrom
yetval:fix/memory-inplace-write-restore

Conversation

@yetval

@yetval yetval commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When Memory Core cannot replace MEMORY.md atomically because the directory blocks temporary files or rename, it falls back to updating the existing writable file in place. If that write fails partway with EFBIG, ENOSPC, or another write error, the old file is left partially overwritten.

This is user-data corruption. The recall store does not mark the promotion as complete, but the lost MEMORY.md bytes are not recoverable downstream.

Root cause

writeExistingMemoryInPlace verifies the current file against expectedContent, opens it with r+, and calls writeFile. The old implementation closed the file after a partial write error without restoring the verified preimage.

Only the append-only promotion path enables this ACL-compatible fallback. Consolidation uses atomic replacement and does not write in place.

Fix

The in-place writer now restores the verified preimage before it returns the original write error. The restore uses positional writes and advances by bytesWritten until every byte is back. It then truncates to the original byte length and synchronizes the file.

The offset loop is required because a restore write can make partial progress without throwing. A zero-progress write stops with an explicit recovery error instead of looping forever.

Proof

Real kernel EFBIG proof used the production writeMemoryContent entry point, a real read-only directory, a writable existing MEMORY.md, and ulimit -f 2.

  • Current main 2a76736fcb77440e98b2569a63d27a46f5683482: EFBIG; 55-byte preimage became a 1,024-byte partial file; afterEqualsOriginal=false.
  • Final head c3f3e8008ab5491b79a6ff24bebfaa9b4d8d5af8: EFBIG; file stayed 55 bytes; afterEqualsOriginal=true.
  • The same two recovery tests fail against current-main writer code for the corrupted-content assertion.
  • The short-write test fails against the first one-shot restore commit with a spliced file, then passes with the full offset loop.
  • node scripts/run-vitest.mjs extensions/memory-core/src/short-term-promotion-memory-write.test.ts extensions/memory-core/src/short-term-promotion.test.ts: 2 files passed, 93 tests passed.
  • node_modules/.bin/oxfmt --check ...: passed.
  • node_modules/.bin/oxlint ...: passed.

The existing short-term-promotion.test.ts integration covers the successful append-only ACL fallback through the full promotion owner. Telegram cannot observe this filesystem failure, so the required default direct-message probe is collateral only; the kernel EFBIG run is authoritative.

Scope

  • Production: +25 lines for failure-only preimage recovery.
  • Tests: +114 lines for partial failure and short restore writes.
  • Normal successful writes keep the same path and cost.
  • No config, schema, protocol, or migration changes.

Telegram collateral

The generic default direct-message probe passed on the final head. The dedicated QA user sent Please answer with OPENCLAW_E2E_BASIC only.; the TDLib timeline recorded the user message, two typing events, and the bot reply OPENCLAW_E2E_BASIC. The gateway log recorded readiness and clean shutdown. The mock-provider log recorded one POST /v1/responses request.

This filesystem durability bug is not Telegram-observable. The real kernel EFBIG writer proof above is authoritative.

@clawsweeper

clawsweeper Bot commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@yetval
yetval marked this pull request as ready for review August 20, 2026 00:05
@clawsweeper clawsweeper Bot added 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 20, 2026
@clawsweeper

clawsweeper Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 23, 2026, 12:04 AM ET / 04:04 UTC.

ClawSweeper review

What this changes

The PR restores the verified original MEMORY.md content when the permission-triggered in-place promotion fallback fails partway through writing.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep open: current main still lacks recovery when the in-place MEMORY.md fallback partially writes and then fails. This is a focused owner-boundary repair with strong terminal proof; rebase/current-main validation is the remaining merge precaution.

Priority: P1
Reviewed head: 4377cd7cc5c69cf185dbceb27119fdf8fb722fd3

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A small, owner-local durability repair with focused regression coverage and convincing after-fix terminal evidence.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR body provides before/after terminal evidence from the production writer using a real read-only directory and kernel EFBIG, showing byte-for-byte recovery after the fix.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body provides before/after terminal evidence from the production writer using a real read-only directory and kernel EFBIG, showing byte-for-byte recovery after the fix.
Evidence reviewed 6 items Current-main gap: Current main writes and truncates the existing file in the fallback, then closes it without a recovery catch; a partial write error therefore propagates with the altered file left in place.
Owner-boundary repair: The branch restores the expected preimage in an offset loop, truncates to its original byte length, syncs, and only then rethrows the original write error.
Caller and sibling scope: Only the append-only promotion path enables the in-place fallback; consolidation calls the same writer without it, so the recovery belongs in the shared write owner rather than a downstream caller.
Findings None None.
Security None None.

Live Verification

Command: pnpm openclaw memory promote --help

Result: PASS (completed)

pnpm openclaw memory promote --help
runner@runnervm76f27:/tmp/clawsweeper-live-proof-126486-yhaRbm/target$ pnpm openclaw memory promote --help
$ node scripts/run-node.mjs memory promote --help
pnpm openclaw memory promote --help
[openclaw] Building TypeScript (dist is stale: missing_build_stamp - build stamp missing).
[openclaw] Building bundled plugin assets.
[canvas] build: node scripts/bundle-a2ui.mjs
[log] ‹DIR›/a2ui.bundle.js  chunk │ size: 399.96 kB
[log] ‹DIR›/a2ui-v0.9.bundle.js  chunk │ size: 615.66 kB
[log]
[success] rolldown v1.2.0 Finished in 108.77 ms
[diffs] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts curated
[diffs-language-pack] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts full
[discord] build: node --import tsx ../../scripts/build-discord-activity-sdk.mts
[tsdown-build] invocation 1/2 finished in 0.7s
node_modules/web-tree-sitter/web-tree-sitter.js (2343:30) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2343:31 ]
      │
 2343 │           ASM_CONSTS[start] = eval(func);
      │                               ──┬─
      │                                 ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

node_modules/web-tree-sitter/web-tree-sitter.js (2366:32) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2366:33 ]
      │
 2366 │           moduleExports[name] = eval(func);
      │                                 ──┬─
      │                                   ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

node_modules/playwright-core/lib/coreBundle.js (65821:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65821:29 ]
       │
 65821 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/playwright-core/lib/coreBundle.js (65828:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65828:29 ]
       │
 65828 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

[tsdown-build] invocation 2/2 finished in 14.7s
[plugin-control-plane-loads] verified 36 built modules with native require and checked doctor closures
runtime-postbuild: 10 phases completed in 4440ms (slowest: built plugin control-plane loads 3690ms)
│
◇

OpenClaw 2026.8.1 (4377cd7) — All your chats, one OpenClaw.

Usage: openclaw memory promote [options]

Rank short-term recalls and optionally append top entries to MEMORY.md

Options:
  --agent ‹id›              Agent id (default: default agent)
  --apply                   Append selected candidates to MEMORY.md (default: false)
  -h, --help                Display help for command
  --include-promoted        Include alr
… output truncated …

Assertions:

  • PASS expect_output: --apply

How this fits together

Memory Core promotes recalled short-term entries into an agent’s MEMORY.md through manual promotion and scheduled dreaming. It prefers an atomic replacement, then uses an existing-file fallback only when directory permissions block replacement; successful writes are then recorded as promoted.

flowchart LR
A[Promotion candidates] --> B[Promotion apply flow]
B --> C[Atomic MEMORY.md replacement]
C -->|Directory permission failure| D[Existing-file fallback]
D -->|Write succeeds| E[Mark entries promoted]
D -->|Write fails| F[Restore verified original bytes]
F --> G[Surface write failure]
E --> H[Updated long-term memory]
Loading

Before merge

  • Resolve merge risk (P1) - The branch is behind current main. GitHub reports it cleanly mergeable and the current-main comparison isolates the behavioral change to recovery, but focused Memory Core validation should be refreshed after integration before merge.
  • Complete next step (P2) - No automatable repair remains; the existing branch is the coherent fix and needs normal current-main merge validation.
Agent review details

Security

None.

PR surface

Source +25, Tests +127. Total +152 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 25 0 +25
Tests 1 127 0 +127
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 152 0 +152

Review metrics

Metric Value Why it matters
Production versus regression coverage production +25, tests +127 The production growth is confined to preimage recovery at the only in-place writer and is covered for partial failure, short restoration writes, and successful fallback writes.

Stored data model

Persistent data-model change detected: serialized state: extensions/memory-core/src/short-term-promotion-memory-write.test.ts, unknown-data-model-change: extensions/memory-core/src/short-term-promotion-memory-write.test.ts, vector/embedding metadata: extensions/memory-core/src/short-term-promotion-memory-write.test.ts, vector/embedding metadata: extensions/memory-core/src/short-term-promotion-memory-write.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: canonical
Canonical: #126486
Summary: This PR is the canonical remaining durability fix for the permission-triggered in-place fallback; the related atomic-write work covers a distinct primary path.

Members:

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

Merge-risk options

Maintainer options:

  1. Refresh Memory Core validation on current main (recommended)
    Rebase or merge-queue the branch and rerun the focused fallback-recovery suite before landing the persisted-memory write change.

Technical review

Best possible solution:

Keep the existing ACL-compatible fallback and land this preimage recovery at its sole write owner after current-main validation.

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

Yes—source-reproducible: current main has a direct r+ write with no recovery catch, and the PR supplies before/after terminal evidence for a permission-triggered EFBIG path.

Is this the best way to solve the issue?

Yes. The writer is the only layer holding the verified preimage; removing the shipped fallback would require a separate compatibility decision, while downstream recovery cannot restore lost bytes.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 91fb03223afd.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P1: A failed promotion can otherwise destroy persisted long-term memory on the affected fallback path.
  • merge-risk: 🚨 session-state: The patch changes failure recovery for the persisted MEMORY.md write path.
  • 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 body provides before/after terminal evidence from the production writer using a real read-only directory and kernel EFBIG, showing byte-for-byte recovery after the fix.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides before/after terminal evidence from the production writer using a real read-only directory and kernel EFBIG, showing byte-for-byte recovery after the fix.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Introduced the current-main split write owner and append caller that contain the existing in-place fallback. (role: recent Memory Core owner; confidence: high; commits: 6ea8a7111cbe, 28630a9a6501; files: extensions/memory-core/src/short-term-promotion-memory-write.ts, extensions/memory-core/src/short-term-promotion-apply.ts)
  • yetval: Authored the current recovery branch and the earlier merged MEMORY.md atomic-write repair. (role: durability contributor; confidence: medium; commits: 4377cd7cc5c6, 0317d7e62801; files: extensions/memory-core/src/short-term-promotion-memory-write.ts, extensions/memory-core/src/short-term-promotion.ts)

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 (4 earlier review cycles)
  • reviewed 2026-08-20T00:11:32.220Z sha 641b4db1d5a8c528ac5f26f00a3c72f13db59e93 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-20T00:27:39.759Z sha 641b4db1d5a8c528ac5f26f00a3c72f13db59e93 :: needs changes before merge. :: [P1] Complete partial restoration writes before truncating
  • reviewed 2026-08-20T01:35:28.988Z sha 4377cd7cc5c69cf185dbceb27119fdf8fb722fd3 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-21T22:52:14.420Z sha 4377cd7cc5c69cf185dbceb27119fdf8fb722fd3 :: needs maintainer review before merge. :: none

@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: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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 20, 2026
@yetval

yetval commented Aug 20, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Addressed the P1 finding: the restore now advances an explicit offset by each bytesWritten result until the full preimage is written, fails on zero progress, and only then truncates and syncs. Added a focused regression that makes the first restore write report short bytesWritten and asserts the file equals the original preimage; it fails against the single-write restore with the exact spliced-content corruption the review predicted. Proof regenerated on pristine main c5fd625 and head 4377cd7cc5c; PR body updated.

@clawsweeper

clawsweeper Bot commented Aug 20, 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:

@clawsweeper clawsweeper Bot added 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. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. 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. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Aug 20, 2026
yetval and others added 3 commits August 27, 2026 10:01
…fails midway

The append-only promotion fallback writes the new content directly into the
existing MEMORY.md when directory ACLs block atomic replacement. A mid-write
failure such as EFBIG or ENOSPC left the file partially overwritten and the
original entries destroyed. The fallback now rewrites the verified original
content and truncates back to its length before rethrowing, so a failed
in-place write leaves MEMORY.md exactly as it was.
FileHandle.write can report fewer bytes than requested without throwing.
Advance an explicit offset by each bytesWritten result until the whole
preimage is restored, and fail the restore on zero progress, so a short
restore write can never splice failed-promotion bytes into MEMORY.md.
Use the real file handle without type laundering, skip the POSIX-only permission harness on Windows, and rely on the existing append-path integration for successful fallback coverage.

Co-authored-by: Ayaan Zaidi <[email protected]>
@obviyus
obviyus force-pushed the fix/memory-inplace-write-restore branch from 4377cd7 to c3f3e80 Compare August 27, 2026 08:07
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Aug 27, 2026
@obviyus
obviyus merged commit ff45aaf into openclaw:main Aug 27, 2026
113 of 115 checks passed
@obviyus

obviyus commented Aug 27, 2026

Copy link
Copy Markdown
Collaborator

Thanks @yetval!

Bug: When MEMORY.md could only be updated in place, a partial disk-limit failure could overwrite the user’s saved memory.
Fix: Memory Core now restores the verified original bytes in a complete offset loop before it truncates, syncs, and returns the original write error.
Example: Before, a real EFBIG error changed a 55-byte file into a 1,024-byte partial file. After, the same EFBIG error left all 55 original bytes unchanged.
Proof: The production writer reproduced the kernel EFBIG failure on current main and preserved the full preimage on the final head; 93 focused tests and exact-head CI passed.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 28, 2026
…claw#126486)

Preserve the verified MEMORY.md preimage when the ACL-compatible in-place promotion fallback fails after a partial write. Complete short restore writes before truncating and syncing, then return the original write error.

Co-authored-by: Yuval Dinodia <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: memory-core Extension: memory-core merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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. triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants