Skip to content

fix: recreate agent database after explicit close - #132955

Closed
jerrodcodes wants to merge 1 commit into
openclaw:mainfrom
jerrodcodes:fix/agent-db-recreate-after-close
Closed

jerrodcodes wants to merge 1 commit into
openclaw:mainfrom
jerrodcodes:fix/agent-db-recreate-after-close

Conversation

@jerrodcodes

@jerrodcodes jerrodcodes commented Aug 30, 2026 •

Copy link
Copy Markdown

Related: #129185
Related: #131331

What Problem This Solves

Fixes an issue where users reopening an agent database after an explicit close could get an uninitialized replacement database when the original SQLite file had been deleted or recreated during the same process.

Why This Change Was Made

Successful schema validation is now retained only while the pathname still identifies the same filesystem object. An unchanged database keeps the fast read-only reopen path, while a replaced or recreated file falls back to full owner/schema initialization. The identity check uses the repository's canonical filesystem identity helper plus birth time to distinguish rapid inode reuse. This does not change the database schema.

User Impact

Agents can recover correctly when their database is explicitly closed and then replaced or recreated, without regressing prompt reopen behavior for an unchanged WAL database with another writer active.

Evidence

  • Added a regression test that explicitly closes the database, removes the database/WAL/SHM files, reopens it, and verifies the complete canonical schema including session_key_contract.
  • Focused test: src/state/openclaw-agent-db.test.ts — 121 passed, 4 skipped.
  • scripts/check-changed.mjs -- src/state/openclaw-agent-db.ts src/state/openclaw-agent-db.test.ts passed, including formatting, lint, core/test typechecks, import-cycle checks, and database guards.
  • Full pnpm build passed under Node 24.15.0.
  • Exact-head CI passed, including openclaw/ci-gate and check-sqlite-session-lifecycle.
  • git diff --check passed.
  • Direct SQLite lifecycle reproduction is the relevant live proof; no UI or channel surface changes.

Direct runtime proof

Executed against this PR's production database opener under Node 24.15.0 using an isolated temporary OPENCLAW_STATE_DIR. The script opened and explicitly closed an agent database, removed its database/WAL/SHM files, reopened it, and queried the resulting live SQLite schema. It then explicitly closed and reopened the unchanged file while an independent connection held a WAL BEGIN IMMEDIATE writer:

{
  "explicitCloseSucceeded": true,
  "recreatedSchema": {
    "open": true,
    "userVersion": 19,
    "tableCount": 49,
    "sessionKeyContract": {
      "name": "session_key_contract"
    }
  },
  "unchangedWalResult": {
    "open": true,
    "elapsedUnderOneSecond": true,
    "elapsedMs": 13.8
  }
}

Production code grows to retain and compare a bounded filesystem identity. That state is required to distinguish replacement from an unchanged explicit reopen without forcing every reopen through the write-capable schema path.

AI assistance disclosure: OpenClaw-managed Codex was used for review and identified the unchanged-WAL reopen regression, which is covered on current main. The repository's standalone autoreview helper was unavailable because it uses separate CLI authentication; submission was explicitly authorized with that limitation.

@clawsweeper

clawsweeper Bot commented Aug 30, 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.

@jerrodcodes
jerrodcodes marked this pull request as ready for review August 30, 2026 00:49
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. labels Aug 30, 2026
@clawsweeper

clawsweeper Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Close this PR as superseded by #137424, whose merged repair covers explicit-close recreation and remains on current main.

Root-cause cluster
Relationship: superseded
Canonical: #137424
Summary: The merged canonical repair covers retained validation being incorrectly reused for a replacement database, including replacement without registry mutation.

Members:

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

Canonical path: Keep the merged shared-validation lifecycle and connection-based schema checks, and close this redundant branch.

So I’m closing this here and keeping the remaining discussion on #137424.

Review details

Best possible solution:

Keep the merged shared-validation lifecycle and connection-based schema checks, and close this redundant branch.

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

No current-main failure was executed in this read-only review; source and retained tests explicitly cover the reported close/delete/reopen sequence.

Is this the best way to solve the issue?

The merged repair is the better current solution: it handles registry lifecycle transitions and empty replacements at their existing owners, while preserving ordinary reopen performance without this branch's separate identity bookkeeping.

Security review:

Security review cleared: The introduced patch retains ownership checks and adds no dependency, credential, permission, or authorization surface.

AGENTS.md: found and applied where relevant.

What I checked:

  • Introduced change: The pinned introduced diff adds filesystem identity checks and an explicit-close/delete/reopen regression; it changes no schema definition. (src/state/openclaw-agent-db.ts:352, 9327d90357f5)
  • Merged canonical repair: GitHub verifies that fix(state): revalidate recreated agent databases #137424 merged as 72f7155. Its repair revokes validation at registry transitions and initializes empty replacements even without a registry mutation. (src/state/openclaw-agent-db.ts:370, 72f71553f4a5)
  • Current-main owner boundary: The opened connection supplies schema metadata; missing metadata or same-version divergence demotes retained validation before canonical initialization. Registry removal also invalidates shared validation. (src/state/openclaw-agent-db.ts:419, 7a16e5678921)
  • Exact scenario and sibling control: Current main retains the close/remove/reopen test without registry mutation, checks the resulting schema and registration, and separately covers prompt reopening while an independent WAL writer holds BEGIN IMMEDIATE. (src/state/openclaw-agent-db.test.ts:2956, 7a16e5678921)
  • Repair provenance: Current-main blame attributes the explicit-close replacement regression to the merged canonical repair. Some historical blobs are unavailable locally; the GitHub commit endpoint supplied its introduced patch. (src/state/openclaw-agent-db.test.ts:2956, 72f71553f4a5)
  • Released canonical repair: GitHub confirms v2026.9.5 was published and resolves its tag to ec9c1a1; comparison reports the canonical fix as its ancestor with behind_by zero. This establishes inclusion, not the first containing release. (72f71553f4a5)

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

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 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. labels Aug 30, 2026

@Yigtwxx Yigtwxx left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding a platform data point the checks on head 9327d90357f do not have: all 82 successful runs on that commit are Linux, and the identity this PR keys on behaves differently on NTFS.

Probe on Windows 11 (Node 22.23.2, fs.statSync(path, { bigint: true })): write a file, delete it, write it again under the same name, three times in a row.

recreation ino changed birthtimeNs changed
immediate yes no, identical to the ns
after 100 ms yes no, identical to the ns

That is NTFS file-system tunneling: a file recreated under a recently deleted name inherits the old creation time. So on Windows the birthtimeNs half of isSameAgentDatabaseFileIdentity never discriminates; dev + ino does all the work, and it is sufficient because the Windows ino is the 64-bit file reference including the MFT sequence number, which changes on reuse. Net effect: the new test passes here (1/1 green, and 1/1 red with openclaw-agent-db.ts reverted to main: expected {} to deeply equal { …(49) }), so the fix holds on NTFS, just not for the reason the body gives.

The direction that can hurt is the opposite one. Node's Stats documentation states that on filesystems without a birth time the field "may instead hold either the ctime or 1970-01-01T00:00Z". On the ctime variant any write to the database moves birthtimeNs, so isValidatedReopen is false on every explicit reopen of an unchanged file and each one takes registerOpenClawAgentDatabase plus the write-capable schema path, which is exactly the regression the body says the identity check avoids. The epoch variant is harmless (equal on both sides). I cannot tell you which of the filesystems OpenClaw runs on report ctime there, so I would either drop the birth-time term and accept the rapid same-inode window that dev + ino leaves open, or keep it and say in the comment above AgentDatabaseFileIdentity that on ctime-reporting filesystems the fast reopen path is lost rather than corrupted. Either is a one-line decision for the maintainer; the schema-recreation fix itself is right and the branch is still MERGEABLE/CLEAN after the three commits main has since made to this file.

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 22, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed P2 Normal backlog priority with limited blast radius. 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 Oct 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper recorded closeout evidence for this proposed close.

@clawsweeper clawsweeper Bot closed this Oct 16, 2026
@jerrodcodes

Copy link
Copy Markdown
Author

Spent a lot of time on this and it was an actual bug but okay. Thanks for the communication.

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

Labels

proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants