Skip to content

fix: preserve session caches when database workers exit - #173239

Merged
steipete merged 4 commits into
mainfrom
dbasync/admitrev
Oct 15, 2026
Merged

steipete merged 4 commits into
mainfrom
dbasync/admitrev

Conversation

@steipete

@steipete steipete commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Session turns reread actor, auth, and session facts when an admitted database worker exits, even though releasing its handle changes no data. Worker exit advanced both the database-wide and unscoped write revisions, invalidating every cache using those receipts.

User Impact

Live session caches survive an idle reader's exit. Real writes, quarantine, schema changes, final-handle retirement, and physical-file replacement retain their existing invalidation and admission behavior. No schema, configuration, SDK, or stored-data changes.

Why This Change Was Made

The shared admission owner releases the departing worker's reference without manufacturing a write receipt. The existing per-worker reference metadata also records the number of native writes awaiting receipt publication. The native write owner increments that count once per connection and clears it after publishing scoped and database-wide receipts. Before handle retirement, the receipt owner invalidates only databases with an interrupted native write. The broker already joins worker exit before settling the caller. This covers COMMIT-before-receipt crashes, including writes without a domain grant, without adding SQL, worker requests, or admission handshakes. Final-handle retirement remains intact; this does not restore the reverted final-close retention change from #172676.

Removed check and accepted edge: worker exit no longer assumes an unobserved write merely because a handle was open. Idle and fully settled workers may exit without invalidating data facts. A crash during a native write still invalidates that database, even if SQLite ultimately rolled it back; losing a committed write's receipt is not accepted.

Evidence

The real-worker regression fails on the base in both ordinary and retained-worker modes: termination increments the write token from 1 to 2 despite no write. It also verifies that a real worker commit invalidates receipts and that quarantine revokes scoped receipts and admission facts.

Two isolated Codex review rounds completed. Review identified a real COMMIT-before-receipt window. The final repair (af7bbee21910) tracks native writes directly and deletes the interim grant-specific tracker; generic shared-state writes need no separate domain grant. The ungranted credential write cited in review independently fails closed on unknown settlement, but the missing physical write receipt still needed repair. The native and schema-maintenance crash regressions intercept the actual COMMIT, terminate the worker before its observer returns, require receipt invalidation before caller rejection, and read back the durable row. The final four owner test files passed: 89 tests, with 3 existing skips, including both native-COMMIT crash cases. The test wrapper completed successfully, including generated-output verification. All three P1 review threads are addressed and resolved; the requested two-round review limit was retained.
Changed-file formatting and type-aware lint pass. The initial 46 focused lifecycle/receipt tests passed. Prior-head CI passed type, lint, source-contract, Madge, PostgreSQL conformance, and database ratchet jobs. Its durability test timed out at a queued chat.send; focused base and candidate replays both timed out earlier at sessions.create under heavy host load, so the original CI failure remains unclassified rather than being called inherited. Final-head CI completed: types, lint, source contracts, architecture/Madge, database ratchets, PostgreSQL conformance, and security checks pass. The sole failing CI test, serializes concurrent ownership claims for one unowned database, is inherited. Single stock-test replays passed on both base and candidate because the fixture signals an earlier integrity transaction. A focused baseline reproduction at 7cd0f47de8b used the same ensureOpenClawAgentDatabaseSchema entrypoint, pausing both processes at the actual schema BEGIN after their ownership/emptiness reads. Releasing them produced two successful claims (expected one), final owner worker-b, and both owners in the registry. Only scheduling was instrumented; production code and SQL were unchanged. The schema-owner source is byte-identical on base and candidate. This is routed to the agent-database owner; this PR changes no agent-owner code. Landing uses the authorized inherited-failure exception, not a claim that CI is green.

The exact final-head Knip export scan completed on native Blacksmith Testbox, pinned to af7bbee21910. Its production findings (prepareWorkerGitHubBindingGrant, DropdownMenuController, scrollState) and full-tree findings (DropdownMenuController, openDropdownSubmenu) all match the same rule and files in main's dependency job. None is in a changed file. The script scan passes with zero entries. The lease is stopped. No update cell applies: this changes handle and write-receipt bookkeeping, not the schema, migration implementation, update, Doctor, plugin loading, or service lifecycle.

Measured SQL and request counts

Three alternating base/candidate pairs, ten warmed turns each, using the copied shared harness and exact-pin builds: base 7cd0f47de8b, candidate af7bbee21910, Node 24.21.0. Values are median [min–max] across the three per-run means. Causal counts follow turn attribution; raw counts include background work in the warm execution windows (requests use dispatch windows).

Warmed metric Base Candidate
All-thread causal SQL statements/turn 81.4 [81.4–89.8] 81.4 [81.4–81.4]
Causal requests/turn 27.3 [27.3–28.8] 27.3 [27.3–27.3]
Causal MAIN statements/turn 0 [0–0] 0 [0–0]
All-thread raw warm-window SQL/turn 86.6 [84.6–96.6] 86.6 [85.5–86.7]
Raw warm-window requests/turn 28.2 [28.1–29.9] 28.1 [28–28.5]
Raw warm-window MAIN statements/turn 1.3 [0–1.3] 0.4 [0.4–1.3]
Shared admission owner T1 calls 0 0

The ordinary warm median does not regress. The first baseline had four exit-triggered agent-database invalidations during warmed turns (89.8 SQL / 28.8 requests per turn); the other two baselines had none during warmed turns. No candidate run emitted a release-triggered revision increment. The saving is conditional on an exit, not a universal reduction on every turn. First-turn raw statement medians are 1050 → 1050 and request medians 158 → 154. Whole measured workload medians are 3719 → 3667 SQL and 768 → 758 requests. Whole-workload MAIN is exactly 467 on every run: the same 13 background plugin-lifecycle lease reads shift between first-turn and warm windows. Zero causal MAIN is not a claim of zero background MAIN.

Forced worker exit

A separately labeled pair starts one extra real read-only admitted worker after the first turn, then terminates it after warm turn five. Its real exit event calls releaseWorker; the actor writer remains alive. Both sides remove the departing reference (1 → −1, then absent), preserve all 12 sibling references, and retain admission. Base revisions advance 93 → 94 and 5 → 6; candidate revisions remain 93 → 93 and 5 → 5. The reader has no pending write; pending-write settlement and native COMMIT-before-receipt crashes are separately exercised through the production tracker tests.

Following warm turn (turn 6) Base Candidate
SQL statements / requests / MAIN 98 / 33 / 0 80 / 27 / 0
Actor hydration SELECTs 1 0
Auth-store SELECTs 1 0
Context-selection SELECTs 7 0
Exact-entry SELECTs 6 4
Other SELECTs 11 8
Watermark SELECTs 1 1
BEGIN / COMMIT statements 15 / 15 13 / 13

The next turn avoids 18 statements and 6 requests: 14 SELECTs plus two BEGIN/COMMIT pairs, with INSERT/UPDATE counts unchanged. Neighboring turns are 80 SQL / 27 requests on both pins. Across all ten diagnostic warm turns, causal means are 83.2 → 81.4 SQL and 27.9 → 27.3 requests; raw warm means are 84.7 → 83.9 SQL and 28.3 → 28.1 requests. The generic operation deltas are execute: −6 SQL / −2 requests, and task: −12 SQL / −4 requests across the ten turns. Read-family participating-request counts overlap and are not summed. Receipt instrumentation reports zero errors.

Measurement limitations: two candidate attempts failed before the first turn from the inherited fresh-store catalog-before-schema race fixed separately by #173196 (55d9dab98ad4); both are excluded. Pair 3 was repeated on both pins with a bounded wait for the existing initial-schema receipt, issuing no SQL or RPC; the forced pair uses the same wait. One initial readiness-helper path mismatch also failed before any measured turn and is excluded. Earlier matching pairs remain valid. Every included run completed all 13 top-level turns, the spawned child, compaction, and clean shutdown. Cron is unmeasured because the fixture lacks a stored inference account. The forced probe is an exit diagnostic, not a startup benchmark; its full-workload totals are 3705 → 3707 SQL and 767 → 763 requests. No latency claim on the loaded host.

LOC: production +51/−29 (net +22); tests/fixtures +127/−65; docs +10/−4; total +188/−98 across 9 files. The obsolete synthetic test asserting exit-time invalidation is deleted; the real-worker lifecycle test owns the regression.

Release worker handle custody without advancing data write revisions. Real native settlement and quarantine retain their invalidation paths; final-handle retirement and physical-file readmission stay intact.
@clawsweeper

clawsweeper Bot commented Oct 15, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T18:41:24.198500Z af7bbee New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: S labels Oct 15, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1abf08ee10

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 15, 2026
@clawsweeper

clawsweeper Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR releases exiting workers’ database references without invalidating surviving session and auth caches.

Example: A worker finishes updating proof.value to 43, then exits while a sibling keeps the database open.

  • Before: Worker exit advances the write revision again and invalidates the sibling’s settled cache.
  • After: Worker exit preserves the settled receipt and cached value 43.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Useful, narrowly scoped optimization with a blocking interrupted-writer invalidation defect and no final-effect proof for that authority-sensitive case.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) Security review found an item that needs attention.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Idle database worker exits force otherwise warmed session and auth caches to reread unchanged facts.
Reason: The maintainer-authored direction has clear performance value, provided writer-crash invalidation remains correct.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep this PR open: preserving idle-reader caches is useful, but removing all exit-time invalidation also preserves stale receipts after an interrupted writer commits.

Priority: P2
Reviewed head: 1abf08ee10a7574f03db36e6547c31f3f6e72f71

Before merge

  • Add real behavior proof - Authority-chain proof required: show an allowed placement grant dispatch and rejection before transport I/O when a placement or parent-approval mutation commits but its worker exits before receipt settlement; supplied coverage exercises only a settled write followed by idle termination, and the body lists live measurements as pending. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Preserve shared invalidation for interrupted writer exits (P1) - If a worker commits a native write and stops before finishSqliteDatabaseWrite publishes its revisions, this cleanup now leaves both write revisions unchanged. With a live sibling, retireUnreferenced does not retire the admission, so pre-write cache receipts remain valid despite changed data. Operation-level outcome-unknown handling does not advance these shared revisions. This also affects createPlacementStandingGrantRuntime.consume(), whose final guard depends on receipt equality. Preserve invalidation for potentially unsettled writers while exempting proven idle readers or settled handles.
  • Resolve security concern: Receipt-backed authority can survive lost write settlement - Placement grant validation saves a database receipt, and node dispatch later consumes it without rereading the durable parent; operation-domain uncertainty is not connected to that retained receipt.

Findings

  • [P1] Preserve shared invalidation for interrupted writer exits — src/infra/sqlite-database-admission-record.ts:223-224
  • [high] Receipt-backed authority can survive lost write settlement — src/gateway/operator-approval-placement-grants.ts:253

Tests

  • Missing end-to-end proof: The added real-worker test covers settled writes followed by idle termination, but does not show rejection at transport dispatch after a committed mutation loses receipt settlement.
Agent review details

How this fits together

The shared SQLite admission registry receives worker reference changes and native write settlements, then publishes revisions used by session caches and authorization consumers.

flowchart TD
  A[Database worker] --> B[Native SQLite operation]
  B --> C[Write settlement]
  C --> D[Shared admission revisions]
  A --> E[Worker exit cleanup]
  E --> D
  D --> F[Session and auth caches]
  D --> G[Placement grant dispatch guard]
Loading

Technical review

Best possible solution:

Preserve idle-reader receipts while retaining shared invalidation for writers whose native changes may have committed without settlement.

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

Current-main source invalidates receipts whenever a departing worker retains an open reference, including an idle reader; the PR reports a failing real-worker regression, but this review executed no target code.

Is this the best way to solve the issue?

The shared admission owner is the right repair boundary, but unconditional preservation also removes recovery for unpublished committed writes.

Full review comments:

  • [P1] Preserve shared invalidation for interrupted writer exits — src/infra/sqlite-database-admission-record.ts:223-224
    If a worker commits a native write and stops before finishSqliteDatabaseWrite publishes its revisions, this cleanup now leaves both write revisions unchanged. With a live sibling, retireUnreferenced does not retire the admission, so pre-write cache receipts remain valid despite changed data. Operation-level outcome-unknown handling does not advance these shared revisions. This also affects createPlacementStandingGrantRuntime.consume(), whose final guard depends on receipt equality. Preserve invalidation for potentially unsettled writers while exempting proven idle readers or settled handles.
    Confidence: 0.94

Overall correctness: patch is incorrect
Overall confidence: 0.93

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Worker-exit write receipt invalidation changes intended behavior with a stated reason (19eddcf: Retire closed database metadata while invalidating receipts after potentially interrupted worker writes; later simplifications preserved that open-handle recovery.)
  • Final-handle admission retirement keeps the original intent (9f8c71e: Restore physical-file replacement detection and Doctor source preservation after the earlier retention optimization.)

Testing

Proof path: in-process harness.

Security

Needs attention: The removed crash invalidation protects receipts consumed by the final placement-grant authorization guard.

Evidence

Security concerns:

  • [high] Receipt-backed authority can survive lost write settlement — src/gateway/operator-approval-placement-grants.ts:253
    Placement grant validation saves a database receipt, and node dispatch later consumes it without rereading the durable parent; operation-domain uncertainty is not connected to that retained receipt.
    Confidence: 0.9

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 19eddcf adds src/infra/sqlite-database-admission-record.ts:191 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 19eddcf75194; files: src/infra/sqlite-database-admission-record.ts)

PR surface

Source -7, Tests -25, Docs +2. Total -30 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 2 9 -7
Tests 1 39 64 -25
Docs 1 6 4 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 47 77 -30

Labels

Label changes:

  • add P2: The intended improvement reduces unnecessary session reads; the blocking defect requires an interrupted writer.
  • add merge-risk: 🚨 session-state: An interrupted committed write can leave surviving caches holding unchanged receipts for stale session data.
  • add merge-risk: 🚨 security-boundary: The same receipts guard placement authorization immediately before node transport dispatch.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P2: The intended improvement reduces unnecessary session reads; the blocking defect requires an interrupted writer.
  • merge-risk: 🚨 session-state: An interrupted committed write can leave surviving caches holding unchanged receipts for stale session data.
  • merge-risk: 🚨 security-boundary: The same receipts guard placement authorization immediately before node transport dispatch.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 15, 2026, 11:48 AM ET / 15:48 UTC.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1c7ba1d435

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: aa4a984251

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@steipete
steipete merged commit e60c548 into main Oct 15, 2026
143 of 147 checks passed
@steipete
steipete deleted the dbasync/admitrev branch October 15, 2026 19:12
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
)

Keep handle retirement separate from data-write revisions so idle worker exits preserve actor, auth, and session facts. Track unsettled native writes in the existing worker reference cell and publish invalidation before retiring a worker that may have committed without a receipt. Real writes, quarantine, and final-handle retirement retain their invalidation semantics.

Validated with 89 owner tests (3 existing skips), native COMMIT crash regressions, final-head type/lint/source-contract/Madge/database-ratchet/PostgreSQL/security gates, and a Knip scan with only exact inherited findings. The unrelated concurrent agent-ownership claim failure is reproduced on the baseline and routed to its owner; landing uses the authorized inherited-failure exception.

Warmed SQL/request measurements and a forced idle-worker-exit diagnostic are recorded in the PR.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M 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.

1 participant