Skip to content

fix(logbook): drain accepted work before closing SQLite - #138754

Merged
steipete merged 1 commit into
mainfrom
codex/sqlite-goal-logbook-drain
Sep 5, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/sqlite-goal-logbook-drain

Conversation

@steipete

@steipete steipete commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Related: #127526, #127608.

What Problem This Solves

Fixes an issue where stopping or replacing Logbook could lose an accepted capture, analysis result, or generated standup because SQLite closed while the operation awaited a runtime response. Recording an analysis failure could also replace the original error with a closed-database error. Registry retirement could leave the service's database and timers alive when ordinary service shutdown was skipped.

Why This Change Was Made

The service now owns admitted database-using operations through their final writes and error recording. Stop prevents new work and clears timers immediately, then waits for accepted work before closing the connection once. Capture, analysis, and standup retain their admitted store; analysis finishes its current batch without starting another after shutdown begins. Day questions remain independent because they finish all database reads before awaiting the answer.

Ordinary service stop and whole-plugin restart/disable cleanup share that drain. Retirement revokes the published service and prevents a retired registration from opening a database later. Session/run cleanup does not dispose the global store. Existing host shutdown deadlines, model/capture deadlines, write queries, schemas, retention, and configuration are unchanged.

User Impact

Accepted activity and standup results can finish saving during shutdown, and actual model failures retain their original error. Shutdown may wait for already accepted work under the existing host deadline; no new timeout or cancellation policy is introduced.

Evidence

  • Seven held-operation regressions failed on the original implementation. The final complete Logbook suite passes 75 tests in seven files, including retirement before service startup.
  • The required changed-file gate passes production/test types, lint, formatting, dead-export scans, database/storage guards, and import cycles. Fresh independent Codex review found no actionable P0–P2 findings.
  • Native SQLite probes cover capture held at node discovery or invocation, successful and rejected analysis, a pending second batch, standup persistence, independent day questions, fresh reopen/integrity, and exactly-once close. Successful and rejected standup hooks also request stop synchronously to exercise reentrant shutdown.
  • An actual plugin-registration/registry-retirement probe holds a synthetic standup response. Before the fix, retirement completes with four database descriptors open. Afterward it waits for the accepted result, saves it, and releases all four descriptors. Retired-before-start registration remains unopened. These probes use synthetic runtime boundaries and real SQLite; they do not call a real model or capture personal screens.
  • Independent proof on commit db1f25125721 passed all five phases on the first attempt: the held-operation matrix, actual registry retirement, reentrant shutdown, nine fresh-process table-hash/integrity checks, and real Gateway status/days/timeline payloads before and after restart. The exact-head runtime build passed. All synthetic state and processes were removed; the complete synthetic trace is posted below.

Production delta is +49 lines, including a net-neutral move of the existing status type. The added code supplies the previously missing service-operation lifetime owner and retirement binding; placing a drain only in the database store would miss the asynchronous work between queries. Tests add 276 lines net. The old immediate-close path and duplicate stop ownership are removed.

The related reports also propose forwarding cancellation through structured media extraction. This PR repairs database lifetime by draining accepted work and preserves current cancellation contracts; it does not claim that separate interruption work is implemented or automatically close those broader reports.

@clawsweeper

clawsweeper Bot commented Sep 5, 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 plugin: logbook Logbook automatic work journal plugin size: L maintainer Maintainer-authored PR labels Sep 5, 2026
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Native Logbook proof passed on commit db1f25125721150fa923f8ca045b990da10d4971, tree 4483a37d99ea88dea111176c1472c63ed9531d1b, clean before and after. Node 24.20.0 / SQLite 3.53.4 / macOS arm64. The exact-head qaRuntime build passed in 32.77 seconds; all five runtime phases passed on the first attempt in 77.15 seconds.

Real owner or flow Observed result
Capture held at node discovery / invocation Stop remains pending with SQLite open. Each accepted capture persists one frame before exactly one close; new database work is refused.
Analysis completion during stop The accepted batch records its observation/card and finishes as done. The next batch stays pending; no later analysis starts.
Analysis failure during stop The accepted batch records the original synthetic error, the next batch stays pending, and SQLite closes once. No secondary closed-database error replaces the cause.
Standup completion during stop The answer commits before close and is readable in a fresh process.
Ask completion after stop SQLite closes before the held answer returns because all database reads already finished; the answer still succeeds without reopening the store.
Actual registered Gateway handler + registry retirement Held standup keeps retirement pending with 4 native SQLite descriptors. After release, the handler succeeds, the standup persists and 0 descriptors remain, while the old registry object is still retained.
Retired-before-start registry The real service launcher reports the expected retired-runtime refusal and opens 0 descriptors.
Reentrant stop, success and failure A completion hook requests shutdown; SQLite stays open through settlement. Success persists its standup; failure retains its original error. Both finish closed.
Fresh-process readback Nine independent Node processes read matching complete table hashes and pass integrity/foreign-key checks after the owning service closes.
Actual CLI/Gateway reads and restart 64 synthetic cards over two days retain exact status, day lists, timelines, statistics and raw bytes across restart. Capture stays disabled across its scheduled interval; frames and batches remain zero.

The source-bound external probes execute the real owners:

node --import ./scripts/tsx.mjs "$PROOF/native.mjs" "$CHECKOUT"
node --import ./scripts/tsx.mjs "$PROOF/registry.mjs" "$CHECKOUT" candidate
node --import ./scripts/tsx.mjs "$PROOF/reentrant.mjs" "$CHECKOUT"

The built CLI queries the normal isolated Gateway, then repeats after shutdown/restart:

openclaw gateway call logbook.status --json
openclaw gateway call logbook.days --json
openclaw gateway call logbook.timeline --params '{"day":"2026-09-04"}' --json

Full Gateway payload SHA-256 before and after restart: 1b833355758a329768b48fc2411227ddc9d17513e52a92ad34d0dcd2cf2ccc75.
Runtime log SHA-256: 2a2d01e470594859c4f50fe1c75cf7e094fac318f5d5f0aa280927aca9fdb348.

All synthetic state is removed, the local port is closed, and no owned processes remain. Source and proof-script hashes are retained in the completion receipt. The expected injected analysis failure and retired-service refusal are recorded, not suppressed.

This is orderly drain, not immediate cancellation or interruption of accepted node/model work. Provider and node boundaries use deterministic synthetic responses; no personal screen capture, external model call or channel delivery occurs. The live Gateway uses capture-disabled reads. No PostgreSQL, other-platform, Workboard or subsequent Logbook query-change coverage is claimed.

@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 Sep 5, 2026
@clawsweeper

clawsweeper Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 4, 2026, 9:55 PM ET / September 5, 2026, 01:55 UTC.

ClawSweeper review

What this changes

Logbook now stops accepting database work, drains accepted captures, analysis, and standups, and shares that shutdown with plugin retirement before closing SQLite.

Merge readiness

✅ Ready for maintainer review

Keep open as a necessary, focused lifecycle repair: current main still closes SQLite before asynchronous work settles. No blocking correctness findings were identified.

Priority: P1
Reviewed head: db1f25125721150fa923f8ca045b990da10d4971

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-boundary repair with strong exact-head native evidence, useful regression coverage, and no blocking findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The exact-head native evidence exercises LogbookService and actual registry retirement against real SQLite, showing delayed close, persisted accepted results, original-error retention, and descriptor release. Synthetic runtime responses isolate the lifetime invariant; separate Gateway restart/readback evidence supplements it without claiming live-provider coverage.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The exact-head native evidence exercises LogbookService and actual registry retirement against real SQLite, showing delayed close, persisted accepted results, original-error retention, and descriptor release. Synthetic runtime responses isolate the lifetime invariant; separate Gateway restart/readback evidence supplements it without claiming live-provider coverage.
Evidence reviewed 12 items Pinned introduction and merge-result scope: The checkout matches the original PR head. Its raw parent is the pinned merge base. The verified test merge has the supplied base followed by the exact head, and its result changes only the seven Logbook files; unrelated endpoint drift is not attributed to this PR.
Current main still contains the defect: Current main's stop method closes and clears the store synchronously without joining asynchronous operations. Its Logbook subtree matches the PR merge base, so the proposed repair is not already present.
Operation ownership covers final writes: Operations are registered before runtime callbacks execute. Stop blocks new admission and joins the registered promises before closing the captured connection. Capture, analysis, and standup retain that connection; analysis stops before another batch, while ask performs all database reads before awaiting its answer.
Findings None None.
Security None None.

How this fits together

Logbook turns screen captures and model responses into a local activity journal. Its background service and Gateway methods share a SQLite store whose connection must remain open until accepted work finishes saving.

flowchart TD
  A[Capture and analysis timers] --> C[Logbook service]
  B[Gateway journal requests] --> C
  C --> D[Accepted asynchronous work]
  E[Shutdown or plugin retirement] --> F[Reject new work and drain]
  D --> G[Save results or original errors]
  G --> H[Close SQLite once]
  F --> H
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +49, Tests +276. Total +325 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 3 208 159 +49
Tests 4 294 18 +276
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 502 177 +325

Review metrics

Metric Value Why it matters
Production versus test growth Production +49 lines net; tests +276 lines net; status-type relocation net 0 Production growth supplies the missing asynchronous lifetime owner and retirement binding without adding configuration, schema, or public API surface.

Technical review

Best possible solution:

Keep the lifetime owner in LogbookService: a store-only close guard cannot protect asynchronous gaps between queries, so the focused operation tracking and shared retirement drain are justified.

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

Yes: hold a capture or model response, stop the service, then release it; current main closes SQLite before the continuation writes. This is source-proven and supported by supplied before/after probes, not independently executed during this review.

Is this the best way to solve the issue?

Yes, for orderly database shutdown: the patch uses the existing asynchronous service and lifecycle contracts and covers each database-using operation without changing storage formats. Provider interruption remains separate work rather than a prerequisite for this repair.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P1: Current main can discard accepted journal results and replace analysis failures with closed-database errors during shutdown or replacement.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The exact-head native evidence exercises LogbookService and actual registry retirement against real SQLite, showing delayed close, persisted accepted results, original-error retention, and descriptor release. Synthetic runtime responses isolate the lifetime invariant; separate Gateway restart/readback evidence supplements it without claiming live-provider coverage.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The exact-head native evidence exercises LogbookService and actual registry retirement against real SQLite, showing delayed close, persisted accepted results, original-error retention, and descriptor release. Synthetic runtime responses isolate the lifetime invariant; separate Gateway restart/readback evidence supplements it without claiming live-provider coverage.

Label justifications:

  • P1: Current main can discard accepted journal results and replace analysis failures with closed-database errors during shutdown or replacement.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The exact-head native evidence exercises LogbookService and actual registry retirement against real SQLite, showing delayed close, persisted accepted results, original-error retention, and descriptor release. Synthetic runtime responses isolate the lifetime invariant; separate Gateway restart/readback evidence supplements it without claiming live-provider coverage.
  • proof: sufficient: Contributor real behavior proof is sufficient. The exact-head native evidence exercises LogbookService and actual registry retirement against real SQLite, showing delayed close, persisted accepted results, original-error retention, and descriptor release. Synthetic runtime responses isolate the lifetime invariant; separate Gateway restart/readback evidence supplements it without claiming live-provider coverage.

Evidence

What I checked:

  • Pinned introduction and merge-result scope: The checkout matches the original PR head. Its raw parent is the pinned merge base. The verified test merge has the supplied base followed by the exact head, and its result changes only the seven Logbook files; unrelated endpoint drift is not attributed to this PR. (270e210b08b5)
  • Current main still contains the defect: Current main's stop method closes and clears the store synchronously without joining asynchronous operations. Its Logbook subtree matches the PR merge base, so the proposed repair is not already present. (extensions/logbook/src/service.ts:146, e2b49d25399d)
  • Operation ownership covers final writes: Operations are registered before runtime callbacks execute. Stop blocks new admission and joins the registered promises before closing the captured connection. Capture, analysis, and standup retain that connection; analysis stops before another batch, while ask performs all database reads before awaiting its answer. (extensions/logbook/src/service.ts:129, db1f25125721)
  • Retirement and ordinary stop share cleanup: The plugin clears its published service before draining, joins repeated stop requests, handles whole-plugin restart/disable through the existing lifecycle API, excludes session/run cleanup, and refuses startup after registration retirement. (extensions/logbook/index.ts:75, db1f25125721)
  • Existing host contracts support the repair: The service API already permits asynchronous stop. The host preserves one cleanup promise across callers and applies its existing replacement deadline; Gateway replacement awaits strict stop before starting successors. Replacement failure schedules recovery rather than treating timed-out cleanup as successful replacement. (src/plugins/services.ts:238, db1f25125721)
  • Storage and sibling-boundary inspection: The store closes its maintenance owner and native SQLite connection synchronously; it cannot account for model or node awaits between queries. Workboard independently uses operation-owned draining, but its private nested-operation runtime is not a reusable Logbook API. No schema, query, retention, configuration, or permission changes are introduced. (extensions/logbook/src/store.ts:261, db1f25125721)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vincent Koc: 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.

@steipete
steipete merged commit 4eb20a9 into main Sep 5, 2026
106 checks passed
@steipete
steipete deleted the codex/sqlite-goal-logbook-drain branch September 5, 2026 02:37
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 5, 2026
vincentkoc added a commit to LiuwqGit/openclaw that referenced this pull request Sep 5, 2026
* refs/remotes/origin/main: (602 commits)
  fix(plugins): trace trust refusals and repair legacy provenance (openclaw#138746)
  perf(sqlite): reuse compiled plugin state point reads (openclaw#138758)
  refactor: type chat prefetch dependencies and clean loading tests (openclaw#138793)
  ci: reduce Doctor test startup and core lint jobs (openclaw#138796)
  feat(update): retain run history and share outcome reports (openclaw#138690)
  chore(deps): update @openclaw/fs-safe to 0.8.1 (openclaw#138500)
  fix: preserve global board ownership from pinning to notifications (openclaw#138675)
  fix(gateway): deliver session catalog updates from slow hosts (openclaw#138674)
  perf(sessions): index pending conversation replies (openclaw#127182)
  perf(auth): reuse ordered provider alias entries (openclaw#138805)
  docs(diagnostics): clarify whole-process CPU metrics (openclaw#138804)
  perf(memory): narrow source reads and stream embedding cache rows (openclaw#138766)
  fix: allow older source on newer Testbox checkouts (openclaw#138782)
  fix(agents): preserve recovered task progress and lifecycle ownership (openclaw#138785)
  perf(codex): reduce rollout tail scan CPU (openclaw#138784)
  perf(gateway): stop projecting history deltas at the byte budget (openclaw#138655)
  fix(build): bound native declaration inputs to checkout (openclaw#138742)
  fix(cli): preserve foreground Gateway argument handling (openclaw#138765)
  fix(ui): align task toolbar with side-panel tabs (openclaw#138769)
  fix(logbook): drain accepted work before closing SQLite (openclaw#138754)
  ...

# Conflicts:
#	src/agents/embedded-agent-runner/compact.queued.ts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR P1 High-priority user-facing bug, regression, or broken workflow. plugin: logbook Logbook automatic work journal plugin proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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