Skip to content

refactor(sessions): record creation, compaction and spawn signals through workers - #164367

Merged
steipete merged 9 commits into
mainfrom
dbasync/sessignals2
Oct 3, 2026
Merged

steipete merged 9 commits into
mainfrom
dbasync/sessignals2

Conversation

@steipete

@steipete steipete commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Session creation, compaction, and child-spawn signals still executed SQLite on the Gateway thread. Periodic pruning and cold custom-store discovery also retained synchronous access.

Why This Change Was Made

Await the existing sessionState.record and sessionState.prune worker operations at every native producer. Creation notices and watcher cursors prepare their physical stores through the existing asynchronous store owner, retaining live checks at worker admission. Embedded compaction settles through its existing event chain; max-lines compaction settles signaling before replying.

Pruning coordination lives in a small sibling module to respect the line cap. Explicit sweeps join an in-flight periodic prune before enforcing their own cutoff. Ambient-watch invalidation stays active through settlement. The compiled-wrapper inventory includes the extracted module.

The native recorder remains only for the explicitly excluded adopted/native-binding paths in session-catalog-gateway-copy.ts and session-catalog-continue.ts. Their periodic pruning uses the same worker. Seed-cursor and pruning kernel sites are reclassified by operation, without marking the mixed event kernel worker-only.

User Impact

Creation/compaction dedupe, child seed cursors, notice ordering, and the 30-day/50,000-row limits are unchanged. Signal failures remain best effort; a lost acknowledgement after COMMIT never replays creation or compaction. No schema, configuration, durability, retention, or update change; zero new OPENCLAW_* names.

Production: 18 files, +259 / -108 / net +151 (367 changed lines). The complete diff has 37 files including tests, routing, inventory, and documentation.

Related: #164288 (merged dependency). Caller overlap with #164284 is limited to the signal await; pending-input ownership is preserved. #162433 remains the standing umbrella-draft exception. Adjacent profile/workspace authority work is not restructured.

Evidence

  • Current pinned-main inventory: T1 1,241 → 1,233, against b94391aa2c5a6e248ea60848cee6394759187f94. Seven kernel sites now execute only in workers; the native prune transaction is removed. The initial lane measurement was 1,245 → 1,237, also -8.
  • Calibrated boundary tests prove zero caller-thread SQL for creation, compaction, spawn, and periodic pruning, including cold custom stores. The cold-store regression initially exposed 73 caller-thread SQL calls.
  • Real entry-point coverage: sessions.create followed by public read, chat-send creation, both RPC compaction branches, embedded subscription compaction, native subagent spawn, and ACP spawn. Coverage includes dedupe, exact seed cursors, original-store retention across yields, revocation at transaction/commit, retention bounds, unknown commit acknowledgements, and error-class identity.
  • 241 focused tests passed: the main two batches covered 229 tests— 64 boundary/RPC/import tests in 113.42 s and 165 remaining regression tests in 194.59 s. All commands used pnpm test <files> --maxWorkers=1. The final lint-only adjustments passed 24 focused tests in 42.49 s. The remaining 12 heartbeat/hook tests passed in 70.90 s after completing their async callers. After main integration, the 24 creation/chat tests passed in 76.74 s. Times include local setup/compilation; CI seconds are pending.
  • Explicit shared-import checks passed: test/scripts/runtime-process-build-graph.test.ts, src/state/openclaw-state.worker.imports.test.ts, and src/auto-reply/reply/get-reply.imports.test.ts. Embedded persistence tests use the existing database-worker fork lane because the broker intentionally refuses admission from a Vitest worker thread; no new configuration or worker pin was added.
  • node scripts/check-changed.mjs passed on the final main-relative diff, including all core/core-test types, full core/script lint, dead exports, storage/import/auth guards, and ratchets. Madge reports 0 cycles. SDK exports/surface checks passed. Fresh Codex autoreview through P2 is scoped-clean against the pinned main base; the final test-only completion also passed P2 review.

Merge preconditions and remaining risk

  • Formal Plugin SDK comparison against v2026.9.8 completed on Blacksmith Testbox, exit 0, for 36384f81fc20931dc2489c6037c7a1a0fdfdd181. Report SHA-256: 50ded0495ed11d54fed16e4711245bb4d710d6180f28dccb3ecb1588627b0858; API-diff digest: 0ee1df54. The report includes intervening main changes since the release. The changed signal functions and handleCompactionEnd have no callable released SDK/runtime export; whole-module declaration snapshots in the report are conservative closure detail, not public function exports. The released afterEntryMutation callback already permits and awaits Promise<void> | void. No compatibility adapter is required for this cutover. Subsequent landing repairs affect only tests, routing, and the wrapper inventory.
  • The combined dependency review identified an inherited P2 on main: prepareWatchedSessionsPromptAsync reads title rows from the default agent database rather than configured session.store (src/agents/watched-sessions-prompt.ts:139). This lane does not modify that reader; its own main-relative review is clean.

The earlier local SDK comparison failed in managed process cleanup; the completed Testbox comparison above replaces that missing proof.

Landing validation and CI repair

Initial CI found two PR-caused harness defects. The extracted prune module required session-state-events.ambient-read.ts in the compiled-wrapper inventory; adding that dependency passes all 17 eager-import tests (101.73 s locally), and the baseline passed the file five times. The native-slash creation test needed the existing database-worker fork lane because worker threads cannot own the SQLite broker. The original PR failed that exact attribution assertion in 5/5 runs; the merge base passed 5/5; the routing repair passes all 10 tests (141.61 s including cold compilation). Assertions and production behavior are unchanged. The PR-context failure was the body heading format and is now green.

A real Gateway shutdown regression now holds an accepted creation signal across the close prelude, proves new creation requests are refused, then verifies that the accepted signal is persisted exactly once before the database closes. pnpm test src/gateway/server-close.session-signals.test.ts --maxWorkers=1 passed (199.67 s cold total; 32.46 s test execution). The same test passed in 12.131 s in CI on the repaired head. Its real request-entry, shutdown, and worker composition cannot be proven by the existing mocked worker-control tests. Scoped types, lint, and formatting pass; fresh Codex P2 autoreview of the landing repairs is scoped-clean.

The inherited watched-title reader is byte-identical at the merge base and reviewed head (src/agents/watched-sessions-prompt.ts, blob a1b3261822efb4843b9e1fcf64b46d8dc43eeae9). No production change was needed for shutdown settlement or either CI repair.

Landing repairs: 3c9ca36bc727538a4ee98077406514ca962b7cae. The full changed-file check completed successfully for all four repair files, including every core test type graph, full core/script lint, storage/source ratchets, and all three dead-export scans. The production and SDK source bytes are unchanged from the completed SDK report.

Move live-turn, compaction, and bundled harness watched-session preparation to the existing shared-state and exact-entry readers. Capture store identity and current disclosure authority across waits, preserving deterministic prompt bytes.

Keep the released synchronous SDK helper as deprecated third-party compatibility and require a live host assertion for its async replacement. Record the approved additive SDK surface and compiled-wrapper dependency.
Resolve adjacent worker-access documentation additions by retaining both. Production changes merged without conflicts; the integrated ambient cutover received a clean independent P2 review.
Model the actual worker context and read-context capture so pruning settlement tests reach the worker. The incomplete fixture reproduced four CI failures in five candidate runs; five base runs passed. All 11 repaired tests and the targeted typecheck pass, with a clean independent P2 review.
Main's SQLite cleanup introduced import-time query-cache factories. Keep those helpers real while retaining the fixture's forbidden SQL calls. The missing-export failure reproduced five times on main and five times on the exact CI merge; all 28 tests in the repaired CI group and the targeted typecheck pass, with a clean P2 review.
…ough workers

Await best-effort signal settlement through the existing shared-state worker. Prepare custom watcher and creation-notice stores asynchronously, preserve ambient prune invalidation, and join explicit sweeps before applying their cutoff. Keep adopted/native-binding recording on its existing native path. Schema, retention, durability and configuration are unchanged.
Preserve the reviewed session-signal cutover while integrating the landed ambient dependency and current session caller changes.
@clawsweeper

clawsweeper Bot commented Oct 3, 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 docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: L labels Oct 3, 2026
@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 Oct 3, 2026
@steipete

steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 3, 2026, 12:03 PM ET / 16:03 UTC (Revision 4).

ClawSweeper review

What this changes

Move session creation, compaction, child-spawn signals, and periodic history pruning into existing database workers, with callers awaiting settlement.

Merge readiness

✅ Ready for maintainer review

The PR remains useful: current main still records these signals synchronously. Both prior harness findings are resolved, and this review found no blocking introduced defect.

Priority: P2
Reviewed head: 3c9ca36bc727538a4ee98077406514ca962b7cae

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused worker cutover with meaningful production-boundary coverage and resolved prior findings.
Proof confidence 🐚 platinum hermit (4/6) ✨ media proof bonus Sufficient (linked_artifact): Inspected production-boundary harnesses exercise creation/read, lost real-worker commit acknowledgements, custom-store discovery, replacement rollback, and accepted-work shutdown settlement; the exact-head shutdown shard succeeded. The captured body records after-fix results, although raw CI logs were proxy-blocked. No stored-data contract changes require migration.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (linked_artifact): Inspected production-boundary harnesses exercise creation/read, lost real-worker commit acknowledgements, custom-store discovery, replacement rollback, and accepted-work shutdown settlement; the exact-head shutdown shard succeeded. The captured body records after-fix results, although raw CI logs were proxy-blocked. No stored-data contract changes require migration.
Evidence reviewed 9 items Pinned change ownership: Reviewed the introduced merge-base-to-head delta, rather than endpoint drift. The checkout is the original PR head; the supplied test merge is stale and was not used to claim removal of current-main behavior.
Still necessary on main: Fetched main retains the synchronous creation recorder calling recordSessionStateEvent. The related merged worker-read and pending-input PRs do not implement this signal-producer cutover.
Worker admission and settlement: The recorder captures its shared-state context, prepares watcher stores asynchronously, and checks current store and session admission at transaction and commit. Unknown signal outcomes remain best effort without replaying the originating action. Embedded compaction returns its recording promise to the existing serialized subscription chain.
Findings None None.
Security None None.

How this fits together

Session lifecycle actions produce durable signals and notices consumed by session history and agent prompts. This change moves their SQLite work off the Gateway thread while preserving ordering and store ownership.

flowchart TD
  A[Session lifecycle actions] --> B[Capture store ownership]
  B --> C[Prepare watcher stores]
  C --> D[Check current admission]
  D --> E[Database worker]
  E --> F[Durable signals and cursors]
  F --> G[Publish notices]
  G --> H[Bounded history pruning]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +151, Tests +387, Docs +10, Other +12. Total +560 across 37 files.

View PR surface stats
Area Files Added Removed Net
Source 18 259 108 +151
Tests 16 452 65 +387
Docs 1 13 3 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 2 13 1 +12
Total 37 737 177 +560

Review metrics

None.

Technical review

Best possible solution:

Keep signal persistence and pruning under the existing worker owner while preserving dedupe, notice ordering, live admission checks, and shutdown settlement.

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

Not applicable as a refactor; current-main source establishes the synchronous producer path, and the inspected boundary regressions target the worker cutover.

Is this the best way to solve the issue?

Yes. Reusing existing worker operations and migrating their callers preserves one persistence owner and avoids new schema or configuration surface.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded runtime improvement removing synchronous signal work from the Gateway thread without an evidenced urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (linked_artifact): Inspected production-boundary harnesses exercise creation/read, lost real-worker commit acknowledgements, custom-store discovery, replacement rollback, and accepted-work shutdown settlement; the exact-head shutdown shard succeeded. The captured body records after-fix results, although raw CI logs were proxy-blocked. No stored-data contract changes require migration.
  • proof: sufficient: Contributor real behavior proof is sufficient. Inspected production-boundary harnesses exercise creation/read, lost real-worker commit acknowledgements, custom-store discovery, replacement rollback, and accepted-work shutdown settlement; the exact-head shutdown shard succeeded. The captured body records after-fix results, although raw CI logs were proxy-blocked. No stored-data contract changes require migration.

Evidence

What I checked:

  • Pinned change ownership: Reviewed the introduced merge-base-to-head delta, rather than endpoint drift. The checkout is the original PR head; the supplied test merge is stale and was not used to claim removal of current-main behavior. (3c9ca36bc727)
  • Still necessary on main: Fetched main retains the synchronous creation recorder calling recordSessionStateEvent. The related merged worker-read and pending-input PRs do not implement this signal-producer cutover. (src/sessions/session-created.ts:18, 01d4351e8f93)
  • Worker admission and settlement: The recorder captures its shared-state context, prepares watcher stores asynchronously, and checks current store and session admission at transaction and commit. Unknown signal outcomes remain best effort without replaying the originating action. Embedded compaction returns its recording promise to the existing serialized subscription chain. (src/sessions/session-state-events.ts:436, 3c9ca36bc727)
  • Real creation boundary and lost acknowledgement: The creation regression invokes sessions.create for an explicit non-main session, loses the acknowledgement after the real worker commit, verifies one durable event and one notice, then successfully invokes sessions.describe. This satisfies the scoped public creation/read composition requirement. (src/gateway/server.sessions.create-notices.test.ts:19, 3c9ca36bc727)
  • Shutdown boundary proof: The inspected regression starts an isolated Gateway, holds an accepted signal through shutdown admission closure, refuses a new request, then verifies exactly one persisted creation event after database closure. GitHub confirms job 111235893999 succeeded on the exact reviewed head: https://github.com/openclaw/openclaw/actions/runs/37134354348/job/111235893999. The captured body reports 12.131 seconds of CI test execution. (src/gateway/server-close.session-signals.test.ts:16, 3c9ca36bc727)
  • Store replacement rejection: Real-worker boundary coverage includes creation, compaction, spawn, periodic retention, cold custom stores, and rollback when a spawn watcher store changes at transaction or commit admission; rejected writes leave both the event version and cursor unchanged. (src/sessions/session-state-events.worker-boundary.test.ts:428, 3c9ca36bc727)

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 (3 earlier review cycles)
  • reviewed 2026-10-03T15:20:20.440Z sha 36384f8 :: needs changes before merge. :: none
  • reviewed 2026-10-03T15:28:09.610Z sha 36384f8 :: blocked before merge. :: [P2] [P2] Include the pruning module's ambient-read dependency | [P2] [P2] Route the native-slash regression through the worker fork lane
  • reviewed 2026-10-03T15:50:26.488Z sha 3c9ca36 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. 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. 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 Oct 3, 2026
Include the prune coordinator's ambient-read dependency in the compiled
wrapper inventory and route the native-slash signal test through the existing
host-broker fork lane without changing its behavioral assertions.

Prove that accepted session creation signals settle across the Gateway close
prelude while new requests are refused, before shared-state workers close.

Focused boundary tests, changed-file checks, and P2 autoreview passed.
@steipete

steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. labels Oct 3, 2026
@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 status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 3, 2026
@steipete
steipete merged commit 43ff5f1 into main Oct 3, 2026
173 of 174 checks passed
@steipete
steipete deleted the dbasync/sessignals2 branch October 3, 2026 16:05
@steipete

steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 4, 2026
…ough workers (openclaw#164367)

* refactor(agents): prepare watched-session prompts from worker reads

Move live-turn, compaction, and bundled harness watched-session preparation to the existing shared-state and exact-entry readers. Capture store identity and current disclosure authority across waits, preserving deterministic prompt bytes.

Keep the released synchronous SDK helper as deprecated third-party compatibility and require a live host assertion for its async replacement. Record the approved additive SDK surface and compiled-wrapper dependency.

* test(sessions): align worker control fixture with admissions

Model the actual worker context and read-context capture so pruning settlement tests reach the worker. The incomplete fixture reproduced four CI failures in five candidate runs; five base runs passed. All 11 repaired tests and the targeted typecheck pass, with a clean independent P2 review.

* test(sessions): preserve query factories in worker fixture

Main's SQLite cleanup introduced import-time query-cache factories. Keep those helpers real while retaining the fixture's forbidden SQL calls. The missing-export failure reproduced five times on main and five times on the exact CI merge; all 28 tests in the repaired CI group and the targeted typecheck pass, with a clean P2 review.

* refactor(sessions): record creation, compaction and spawn signals through workers

Await best-effort signal settlement through the existing shared-state worker. Prepare custom watcher and creation-notice stores asynchronously, preserve ambient prune invalidation, and join explicit sweeps before applying their cutoff. Keep adopted/native-binding recording on its existing native path. Schema, retention, durability and configuration are unchanged.

* test(sessions): await remaining signal caller fixtures

* fix(sessions): complete signal worker wrapper and test coverage

Include the prune coordinator's ambient-read dependency in the compiled
wrapper inventory and route the native-slash signal test through the existing
host-broker fork lane without changing its behavioral assertions.

Prove that accepted session creation signals settle across the Gateway close
prelude while new requests are refused, before shared-state workers close.

Focused boundary tests, changed-file checks, and P2 autoreview passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts 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