Skip to content

refactor: retain shared database handles until their last worker closes - #147246

Merged
steipete merged 2 commits into
mainfrom
codex/shared-state-native-borrows
Sep 13, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/shared-state-native-borrows

Conversation

@steipete

@steipete steipete commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Shared-state workers need to release their own reference without closing a native database handle another worker still uses.

User Impact

This is internal database lifecycle cleanup that prepares existing shared-state workers for further SQLite worker migration. It requires no configuration or data migration.

Why This Change Was Made

The existing shared-state cache now owns native-handle references. Workers retain the exact published handle, release their own reference on close, and leave final disposal to the cache. Failed final cleanup remains retryable through either the cache or the original worker, and an old released reference cannot close a replacement handle. The current read-only status-summary path keeps its existing lazy behavior.

Evidence

  • Nine synthetic Node SQLite cases pass for the reviewed runtime implementation, including the full status call with 513 tasks and shared actor close/reopen.
  • Two cleanup-retry cases pass on the unchanged cache/borrow source. A preserved pre-fix control fails canonical retry after the same JavaScript callback failure.
  • Core types, actor lint, formatting, and independent review pass after current-main composition. All 18 selected test type graphs passed on the preserved checkpoint before that one-file composition. Canonical dependency/export checks and a fresh full review also pass.

A full local build was not run. This does not claim Bun physical-release proof; the broker’s existing VM-exit requirement remains in force.

@clawsweeper

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

@openclaw-barnacle openclaw-barnacle Bot added size: M maintainer Maintainer-authored PR labels Sep 13, 2026
@steipete
steipete marked this pull request as ready for review September 13, 2026 17:54
@clawsweeper clawsweeper Bot added 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 Sep 13, 2026
@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 13, 2026, 2:24 PM ET / 18:24 UTC (Revision 2).

ClawSweeper review

What this changes

Shared-state workers retain individual references to their SQLite connection, allowing the cache to retire it after the final worker releases it and retry failed cleanup.

Merge readiness

✅ Ready for maintainer review

The change remains useful: current main still closes shared handles by path when a worker closes. No blocking defect was established in the pinned patch, and this maintainer-authored PR is protected from automatic closure.

Priority: P2
Reviewed head: 77e2fd578a41769191c0b311917ce1aa1894cadd

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused ownership change with relevant regression coverage and no established blocking defect.
Proof confidence 🌊 off-meta tidepool Not applicable: The maintainer-authored PR is exempt from external-contributor proof. Its reported Node SQLite scenarios match shared-worker lifetime and cleanup retry; they do not claim Bun physical release, and no new authority-proof requirement was established.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The maintainer-authored PR is exempt from external-contributor proof. Its reported Node SQLite scenarios match shared-worker lifetime and cleanup retry; they do not claim Bun physical release, and no new authority-proof requirement was established.
Evidence reviewed 8 items Current main still needs the lifecycle change: The fetched main revision still calls closeOpenClawStateDatabaseByPath and clears the open-failure latch from each worker's close method. It does not implement per-worker native references.
Reference ownership and retirement: Workers retain the canonical connection and reject execution after close. The reference owner releases each reference once, retires only after the last release, and transfers failed cleanup to the existing cache.
Meaningful regression coverage: The added worker test checks that a surviving worker can update rows after its sibling closes and that those rows survive final close and reopen. Cleanup tests cover retry through both the original reference and canonical cache without closing a replacement connection. Tests were inspected, not executed.
Findings None None.
Security None None.

How this fits together

OpenClaw’s shared-state worker executes task, flow, and preference operations against a cached SQLite connection. The database cache coordinates connection ownership, worker drainage, and final cleanup.

flowchart TD
  A[Task and preference operations] --> B[Shared-state workers]
  B --> C[Retained database references]
  C --> D[Canonical database cache]
  B --> E[Worker closes]
  E --> F{Last reference released?}
  F -->|No| D
  F -->|Yes| G[Coordinated cleanup and retry]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +164, Tests +95. Total +259 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 3 200 36 +164
Tests 2 96 1 +95
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 296 37 +259

Review metrics

None.

Technical review

Best possible solution:

Keep native connection retirement in the canonical cache, with workers releasing only their own references and failed disposal remaining retryable.

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

Not applicable as a reported production incident; the shared-worker close/reopen scenario is concrete in the regression test, but this read-only review did not execute it.

Is this the best way to solve the issue?

Yes. Extending the existing cache’s lifetime ownership is a focused approach, and the worker and retry paths preserve one canonical native owner.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded internal database lifecycle improvement without evidence of an urgent user-facing outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The maintainer-authored PR is exempt from external-contributor proof. Its reported Node SQLite scenarios match shared-worker lifetime and cleanup retry; they do not claim Bun physical release, and no new authority-proof requirement was established.

Evidence

What I checked:

  • Current main still needs the lifecycle change: The fetched main revision still calls closeOpenClawStateDatabaseByPath and clears the open-failure latch from each worker's close method. It does not implement per-worker native references. (src/state/openclaw-state.worker.ts, c72435e19089)
  • Reference ownership and retirement: Workers retain the canonical connection and reject execution after close. The reference owner releases each reference once, retires only after the last release, and transfers failed cleanup to the existing cache. (src/state/openclaw-state-db-borrow.ts:20, 77e2fd578a41)
  • Meaningful regression coverage: The added worker test checks that a surviving worker can update rows after its sibling closes and that those rows survive final close and reopen. Cleanup tests cover retry through both the original reference and canonical cache without closing a replacement connection. Tests were inspected, not executed. (src/state/openclaw-state.worker.summary.test.ts:154, 77e2fd578a41)
  • Review continuity: The previous completed review recorded no findings. GitHub's exact-head commit response confirms that the subsequent commit only removes an unused re-export from openclaw-state-db.ts. Local tree entries also confirm the cache blob is unchanged from the earlier reviewed head. (src/state/openclaw-state-db.ts:733, 77e2fd578a41)
  • Existing storage contract: The storage guidance assigns connection acquisition and lifecycle to the existing owners and distinguishes internal lifecycle changes from persistent-contract changes. This patch adds no schema, durable representation, configuration option, or plugin API. Public docs: docs/reference/database-schemas/storage-changes.md. (docs/reference/database-schemas/storage-changes.md:309, 77e2fd578a41)
  • Recent area history: Current-main history includes shared database admission, Windows shutdown cleanup, and WAL health work by Peter Steinberger. GitHub maps the shared admission commit to steipete; this supports routing beyond authorship of the proposed branch, without establishing original introduction. (src/state/openclaw-state-db-cache.ts, 7b87a492ab5d)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (1 earlier review cycle)
  • reviewed 2026-09-13T18:04:36.016Z sha f56fd6e :: needs maintainer review before merge. :: none

@steipete
steipete merged commit 8132c7c into main Sep 13, 2026
186 of 187 checks passed
@steipete
steipete deleted the codex/shared-state-native-borrows branch September 13, 2026 18:57
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Sep 13, 2026
* commit 'cf45ff4d6a9c13164463db860285a02c1c4f2e8c':
  test(macos): observe readiness cancellation and deadline ownership (#145056)
  fix(ci): route QA Profile Evidence to its run-status owner test (#147293)
  fix(install): preserve runtime links when Node validation fails (#147221)
  test(auto-reply): reuse memory session fixtures (#147262)
  fix: hide subagent sessions from Activity (#147253)
  ci: record resources for slow runtime test commands (#147254)
  fix(update): recognize FreeBSD boot identities in triage leases (#147243)
  refactor(active-memory): share closing tag line scan (#147031)
  fix: resume Settings autosave after Reload Config (#147136)
  fix(cli): keep conversation context after cancellation (#147139)
  fix(channels): make system-agent approval cards actionable (#147152)
  refactor: retain shared database handles until their last worker closes (#147246)
  refactor(slack): share workspace-qualified target resolution (#147024)
  refactor(msteams): remove duplicate quoted-table test (#147270)
vincentkoc added a commit that referenced this pull request Sep 13, 2026
* commit 'ac59d5e09eb468dc23cf95e447608b57e71b52af': (176 commits)
  improve(gateway): avoid redundant startup preflight work (#147285)
  test(macos): observe readiness cancellation and deadline ownership (#145056)
  fix(ci): route QA Profile Evidence to its run-status owner test (#147293)
  fix(install): preserve runtime links when Node validation fails (#147221)
  test(auto-reply): reuse memory session fixtures (#147262)
  fix: hide subagent sessions from Activity (#147253)
  ci: record resources for slow runtime test commands (#147254)
  fix(update): recognize FreeBSD boot identities in triage leases (#147243)
  refactor(active-memory): share closing tag line scan (#147031)
  fix: resume Settings autosave after Reload Config (#147136)
  fix(cli): keep conversation context after cancellation (#147139)
  fix(channels): make system-agent approval cards actionable (#147152)
  refactor: retain shared database handles until their last worker closes (#147246)
  refactor(slack): share workspace-qualified target resolution (#147024)
  refactor(msteams): remove duplicate quoted-table test (#147270)
  fix(qa): bind coverage IDs to producer assertions (#144000)
  fix(linux): explain FreeBSD desktop setup prerequisites (#147211)
  fix(memory): split embedding batches rejected for an input array item cap (#139541)
  test: isolate timing metadata persistence from inherited settings (#147112)
  refactor(status): retire test-only helper publication (#147071)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
…es (openclaw#147246)

* refactor: retain shared database handles until their last worker closes

* refactor: remove unused shared database borrow reexport
steipete added a commit that referenced this pull request Sep 18, 2026
…#146547)

Related: #144592
Related: #147375
Related: #147246
Dependency: #151816

## What Problem This Solves

Stored transcript detail and note lookups return promises but still execute SQLite on the Gateway event loop.

## User Impact

Transcript identity, descriptor, note, summary, and utterance lookups execute in the shared SQLite worker. Existing selectors, content, ordering, limits, and error responses are preserved. No schema migration or configuration change is required.

Chronological list queries and streaming/export snapshots retain their current owners. Capture appends are a separate stacked change in #151760.

## Why This Change Was Made

Eleven typed commands call the existing read kernels through the canonical shared-state worker. Compound enumeration, matching, and library reads keep one deferred snapshot. First-use schema creation finishes before those reads, canonical close drains accepted work, and existing-only task inspection stays non-creating. Meeting fixtures stop producers before asynchronous database cleanup, and canonical test routing keeps worker consumers in their owning processes.

The composition preserves Doctor's device-token dispatch alongside all eleven transcript commands, shared transaction-settlement checks, plugin-reload ownership, and current test-routing changes. Chronological reads preserve their parent-timezone date function; exports preserve their snapshot lifetime.

Qualified dependency history from #151816 is incorporated through normal merge ancestry. It pins the deprecated message facade at its published exports, aligns three global surface limits with the resulting smaller counts, and carries the canonical catalog-materialization prerequisite with its strict 18-read assertion. The per-entry SDK compatibility limit remains unchanged. This does not claim that dependency PR #151816 has merged.

## Evidence

The current catalog carry passed a fresh normal production build in 319.083 seconds and all five real transcript/Doctor SQLite worker controls in 21.595 seconds. Fresh independent P2 review found no actionable issues. These checks cover the changed Gateway and shared-worker import closures. All 58 non-doc meeting feature files, including the combined Doctor/transcript dispatcher, remain byte-identical to `6b3c5acb8634`; storage docs only gain the qualified upstream task paragraph.

The SDK owner's strict catalog control and 25 archived-list/backfill controls are reused for matching owner inputs. The strict assertion retains three binding-authority checks and zero plugin-state worker operations while accounting for 18 SQLite reads after canonical materialization changes. The shared worker composition is separately covered by the five fresh controls above.

Retained compiled child CLI/Gateway proof belongs to the earlier captured-main `6c6dc44250d` composition: the test body passed in 21.539 seconds under its unchanged 180-second bound, with 404.282 seconds for the supported wrapper and private-QA build. It checks canonical SQLite state, delegated missing-session cleanup while the isolated Gateway stays alive, transcript list/show/path commands, and exported bytes. This compiled scenario was not rerun on the latest catalog carry.

The preceding combined 62-file gate passed in 966.651 seconds, including production/test types, SDK/storage boundaries, formatting, lint, and three unused-export scans with zero findings. Six SDK facade tests and independent P2 review passed. The subsequent exact three SDK ratchet decreases passed all ten existing reporter tests, the canonical surface check, the changed-script gate, and fresh P2 review. Earlier reload and routing controls remain attributed to their qualified inputs.

CI at `6b3c5acb8634` completed with 140 successful jobs, 14 skipped, and one substantive failure plus its aggregate gate: the shared catalog benchmark expected 20 reads but the CI main composition performed 18. That matched the SDK owner's independently reproduced prerequisite issue. This carry includes its qualified canonical prerequisite and strict assertion correction; strict equality, authority-count, and zero-I/O checks remain intact, with unchanged deadlines. The new head requires its own hosted CI before landing.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 19, 2026
…openclaw#146547)

Related: openclaw#144592
Related: openclaw#147375
Related: openclaw#147246
Dependency: openclaw#151816

## What Problem This Solves

Stored transcript detail and note lookups return promises but still execute SQLite on the Gateway event loop.

## User Impact

Transcript identity, descriptor, note, summary, and utterance lookups execute in the shared SQLite worker. Existing selectors, content, ordering, limits, and error responses are preserved. No schema migration or configuration change is required.

Chronological list queries and streaming/export snapshots retain their current owners. Capture appends are a separate stacked change in openclaw#151760.

## Why This Change Was Made

Eleven typed commands call the existing read kernels through the canonical shared-state worker. Compound enumeration, matching, and library reads keep one deferred snapshot. First-use schema creation finishes before those reads, canonical close drains accepted work, and existing-only task inspection stays non-creating. Meeting fixtures stop producers before asynchronous database cleanup, and canonical test routing keeps worker consumers in their owning processes.

The composition preserves Doctor's device-token dispatch alongside all eleven transcript commands, shared transaction-settlement checks, plugin-reload ownership, and current test-routing changes. Chronological reads preserve their parent-timezone date function; exports preserve their snapshot lifetime.

Qualified dependency history from openclaw#151816 is incorporated through normal merge ancestry. It pins the deprecated message facade at its published exports, aligns three global surface limits with the resulting smaller counts, and carries the canonical catalog-materialization prerequisite with its strict 18-read assertion. The per-entry SDK compatibility limit remains unchanged. This does not claim that dependency PR openclaw#151816 has merged.

## Evidence

The current catalog carry passed a fresh normal production build in 319.083 seconds and all five real transcript/Doctor SQLite worker controls in 21.595 seconds. Fresh independent P2 review found no actionable issues. These checks cover the changed Gateway and shared-worker import closures. All 58 non-doc meeting feature files, including the combined Doctor/transcript dispatcher, remain byte-identical to `6b3c5acb8634`; storage docs only gain the qualified upstream task paragraph.

The SDK owner's strict catalog control and 25 archived-list/backfill controls are reused for matching owner inputs. The strict assertion retains three binding-authority checks and zero plugin-state worker operations while accounting for 18 SQLite reads after canonical materialization changes. The shared worker composition is separately covered by the five fresh controls above.

Retained compiled child CLI/Gateway proof belongs to the earlier captured-main `a16c8616eac` composition: the test body passed in 21.539 seconds under its unchanged 180-second bound, with 404.282 seconds for the supported wrapper and private-QA build. It checks canonical SQLite state, delegated missing-session cleanup while the isolated Gateway stays alive, transcript list/show/path commands, and exported bytes. This compiled scenario was not rerun on the latest catalog carry.

The preceding combined 62-file gate passed in 966.651 seconds, including production/test types, SDK/storage boundaries, formatting, lint, and three unused-export scans with zero findings. Six SDK facade tests and independent P2 review passed. The subsequent exact three SDK ratchet decreases passed all ten existing reporter tests, the canonical surface check, the changed-script gate, and fresh P2 review. Earlier reload and routing controls remain attributed to their qualified inputs.

CI at `6b3c5acb8634` completed with 140 successful jobs, 14 skipped, and one substantive failure plus its aggregate gate: the shared catalog benchmark expected 20 reads but the CI main composition performed 18. That matched the SDK owner's independently reproduced prerequisite issue. This carry includes its qualified canonical prerequisite and strict assertion correction; strict equality, authority-count, and zero-I/O checks remain intact, with unchanged deadlines. The new head requires its own hosted CI before landing.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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.

1 participant