Skip to content

refactor(sessions): move status and typed creation reads into workers - #169608

Merged
steipete merged 19 commits into
mainfrom
dbasync/t1cut-s1
Oct 12, 2026
Merged

steipete merged 19 commits into
mainfrom
dbasync/t1cut-s1

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Status/model-directive presentation and typed session creation still reached synchronous transcript/native paths. Session mutations also repeated reads already covered by their loaded state or successful write receipts.

User Impact

No intended visible behavior change. Status retains fresh usage/model facts, and typed native deletion participants retain transaction and post-commit settlement. No schema, permission, retention, plugin-loading, service-lifecycle, or update contract changes.

Why This Change Was Made

Prepare status facts through the existing history worker and render them without database access. Reuse the existing native-binding worker transaction for typed creation participants. Remove duplicate rewrite/compaction reads, fold ACP provenance retention into the node upsert, and use DELETE RETURNING for stale primary-conversation demotion.

This is the first focused PR in the owner/API cutover. Conservative T1 callsites in the 17 assigned files fall 46 → 43 against original inventory metadata (44 → 43 when applying today's ACP Doctor-only classification to both revisions). Mixed native/worker kernels are still reported honestly; remaining ordinary currentness, leaf/completion and Memory-corpus callers are being cut over separately. Deprecated SDK/native, incognito, offline repair and actual effect guards are not relabeled worker-only here.

Removed checks and accepted edges

  • Rewrite preparation's duplicate version/parent read and copied-event rereads: use loaded facts until the transaction's single generation/sequence/mutation-time comparison; reject an actual stale rewrite there.
  • Compaction's next-sequence lookup, appended-row scan and final version reread: trust the append receipt; another read is not an integrity check.
  • Reply initialization's intermediate pathname recapture: trust admitted source identity until the final effect guard; a replaced path can still produce a snapshot of the admitted source, and the commit checks its target.
  • Ordinary goal callback presence no longer forces native SQL: worker grants cover host callbacks; explicit native/cross-store authority retains its effect boundary.

Statements and requests

Shared harness on one Hetzner host, alternating M,C,M,C,M,C. Immutable base c0e0bbaf21e7e4fd559cae660a4be92bfcbdbfee; measured implementation 6ccf82c4af4cfc680807d8d7b732b4df34166543. Later changes split tests, remove a test for a deliberately deleted intermediate check, and extract unchanged provenance preparation. The shared harness is unchanged; a task-local census observer counts logical sends, excluding continuation/reply frames.

Per warmed turn, median [min–max] Base Candidate
All-thread statements 329.4 [329.1–329.6] 329.8 [328.2–339.4]
Logical requests 100.8 [100.8–100.9] 100.9 [100.4–102.2]
MAIN statements 0 [0–0] 0 [0–0]
Whole-workload statements 9,583 [9,570–9,604] 9,614 [9,601–9,617]
Whole-workload requests 1,904 [1,901–1,910] 1,912 [1,906–1,912]

Warmed duration ratio 1.012. Warm delta is +0.12% statements/+0.10% requests. Added warm executions are existing session-row/transcript-watermark and background Memory admission/index work; no new ordinary-turn command was introduced. The first-turn median shifted +56 statements as background work moved from connection into the turn. Per RAW TURN INCREASE, an extra M,C pair measured 9,636 → 9,605 statements and 1,910 → 1,906 requests over startup→shutdown, establishing redistribution rather than a workload increase. That pair's first turn was 1,114 → 1,136 statements and 225 → 214 requests.

Per-operation deltas: fully loaded ACP identity changes remove one provenance SELECT and UPDATE; partial legacy snapshots retain one SELECT. Conversation demotion removes one SELECT. Rewrite removes its preliminary version read and per-source event rereads; its host preparation drops one maintenance request. Compaction removes the next-sequence read, appended-row scan and final version read. Harness request medians remain 6→6 session.entries.replace, 15→15 each rewrite prepare/commit, and 4→4 maintenance reads; the particular rewrite/compaction helpers are not all exercised by this workload, so no warmed saving is claimed for them. Status moves reads to the worker and adds one cold session-entry-read request across the workload (18→19).

Evidence

  • Two Codex autoreview rounds completed. First-round suspected missing row usage was declined after tracing production callers: resident rows receive prepared facts, private TUI skips usage fallback, and chat-history's fallback has no stored entry. CI subsequently exposed a direct-render fallback fixture, now migrated to async terminal preparation. Second round: no P0/P1 findings.
  • Focused owner suites passed on the measured implementation; final focused run also passed before the v6 process change. Current-head static/test proof is delegated to PR CI. Initial proof exposed two stale pure-render tests (now prepared asynchronously), one intermediate identity-check test (deleted; commit boundary retained), and line-cap growth (resolved by coherent test split/provenance extraction).
  • Madge, dialect and T1 ratchets passed on the measured implementation. Knip had 65 findings on both immutable base and candidate (no new findings).
  • Regression coverage includes fresh status after in-process append, ACP provenance retention, rewrite/compaction mutation boundaries, typed participant settlement and zero caller-thread SQL.
  • No SDK surface change and no published-driver update cell required.

Earlier CI exposed fixture/type/lint issues that are fixed. The isolated CLI sessions --json completed successfully with an empty session list. Workshop learning has the identical missing-announcement failure on main run 38205338506/job 114669571918. Incognito and label-lookup fixtures now persist their configuration through the owner, retaining their behavior assertions.

Final PR delta against integrated main: production +363/−262 across 26 files, tests +1085/−662 across 17 files, docs +31/−24 across 2 files. No warmed-query reduction is claimed; this moves cold reads off MAIN and removes redundant mutation reads.

Final integration and CI attribution

The latest integration includes main a27b46c127eb4. Its only conflict was the deletion-proof helper: main independently landed the equivalent terminal-abort handling, and main's version is retained. No production SQL changed in this resolution. CI on 1ecfd72f89120 passed production/test types, all lint stripes, source contracts, architecture and database ratchets, plus the built-artifact lifecycle proof.

The actor stale-version failure traced to main 670306081a73d (#169651): prepared appends intentionally stopped reading/retrying snapshots, while an old fixture still injected a stale expectation and expected replay. The integrated main already corrects the fixture to expect one refusal. A focused base/head diagnostic stalled before test cases and was canceled; it is not reported as passing or reproduced-inherited evidence. The separate Bun rewind diagnostic also stalled in worker compilation before assertions; no result is claimed. The data-version suite passed its behavior assertions and failed during native retirement cleanup. Those cleanup files are unchanged by this PR. The type-suppression inventory failure identifies an unchanged main-tooling Bun annotation. Workshop's missing learning announcement is independently reproduced in main CI as recorded above. Final integration includes main 2fc20b367b69d; exact-head PR CI is run 38226567508 at 72514211565e1. The inventory resolution preserves both ACP Doctor-only metadata and main’s config-health worker classification. It regenerates the inventory without changing runtime SQL. Final static results are recorded below as they complete.

Source attribution for the Bun rewind count assertion: 9c54108 → 1ecfd72 leaves the fork handler, message-cut operation, upstream reader, and its connection/revision cache unchanged. Durable fork omits native deletion capture and sends no nativeBindings, so the new typed replacement participant does not run there. Its two pre-existing upstream callbacks can each execute a SELECT when connection/read-revision reuse is unavailable. No PR-added callback or invalidation was found; this is source attribution, not a claim of reproduced inherited failure.

Fresh main-tier CI at 2e631903584bd (run 38223693899) passed types, lint, source contracts, architecture/Madge, and ratchets. Knip found the unused export retainLegacyAcpMigrationSourcesJson; 992add916eb8b makes that same-module helper private. Three other UI/cron findings are removed by main f0a14bf986e60, included in the subsequent main integration. The remaining manual jobs were canceled after the required static evidence was collected; their tests are not claimed as passing. A current-main Knip baseline (run 38224696307) records unrelated unused gateway-prewarm.mjs and renderPublicSessionCardSvg.

Final stack live check (v6)

One additional baseline/candidate live pair exercises the complete three-PR stack: baseline 9c54108f9f20a, candidate 22bf8aa966027. This supplements, rather than replaces, the valid PR-local alternating proof above. Per warmed turn (total divided by ten): statements 306.7 → 381.9, requests 84.0 → 106.7, MAIN 0 → 0.2. Whole workload: statements 9,283 → 10,211, requests 1,668 → 2,016, MAIN 1,984 → 1,982. Candidate warmed elapsed time was 114.3s versus 18.8s baseline, so the raw pair is severely duration-skewed.

The transcript hydration, anchor, row-facts, patch preparation/commit, activity-summary and actor operations retain their statement/request counts; row backfill falls 100/20 → 95/19. Twelve additional periodic Memory refresh cycles account for twelve each of entry, corpus, tombstone and transcript requests. The two warmed MAIN statements are untouched scheduled GitHub OAuth maintenance, not this lane. Lifecycle has one extra 13-statement generation-tracker setup batch with unchanged request count. Five ordered-cache misses, one entry-admission read and exact-entry request differences remain incompletely attributed; this pair is not claimed as a clean no-increase proof.

All 13 turns, cron, compaction, child terminal and shutdown completed. mentions.dismiss returned retryable UNAVAILABLE, so the outer all-RPC assertion failed (40/41 RPCs passed); no SQL execution failed in that phase and the generic owner catch hides the underlying exception. The run is qualified live evidence, not a fully passing end-to-end run.

Exact-head Knip (72514211565e1, run 38226745674, job 114736339119) reports only unused gateway-prewarm.mjs and renderPublicSessionCardSvg in src/gateway/control-ui-public-session-card-render.ts. The same rules/files fail on current main run 38224696307; both are untouched by this PR. This is an inherited static exception, not a waived new finding.

The main-tier core-test-types-4 failure is also exactly inherited: session-entry-patch.authority.test.ts:41:22,56:12 reports TS2532 on both candidate job 114736339016 and main run 38224696307/job 114729780171 at b82b033920ee7. The fixture’s optional return and affected contracts are unchanged. The incognito “vanished non-default agent” mismatch is the same failure as main run 38209130771, job 114679390704: expected the not-found error, received Unknown agent id "work".

Landing evidence at 72514211565e1

Exact PR run 38226567508: every production/test type lane and all basic/type-aware lint stripes passed; source contracts passed; architecture reports zero runtime and Madge cycles; fast database-worker/T1 and dialect ratchets passed. Main-tier run 38226745674 collected the broader static scans: the only static failures are the exact main-matching Knip and TS2532 findings above. Its remaining broad jobs were canceled after static evidence was complete, so their tests are not claimed as passing.

Remaining test failures are disposed under the authorized inherited-failure route. Besides the exact main incognito failure, the detached-context variants pin an admission reread intentionally removed on main by 5aa61b5216632 (#169523); their older passing main run predates that change. The fork upstream-read count has an unchanged two-callback call chain and no new lane guard/invalidation. Raw-edited listing/projection fixtures and their complete read paths match integrated main; main a9b40cf325e8d (#169340) removed repeat canonical validation for admitted stores. The asynchronous resident preview failure is outside this lane's active path: resident materialization sets skipTranscriptUsageFallback: true, already supplies prepared terminal facts, and the title/preview worker, projector, test and transcript-only append path are unchanged. No standalone current-main execution is claimed for these source-attributed cases. Owner follow-ups should retire the two obsolete detached-check variants and investigate the remaining cache/count/fixture assertions; no retry, guard, timeout, baseline increase or weakened assertion was added here.

Landing uses the coordinator-authorized head-pinned REST squash because native provisioning requires the off-limits canonical checkout. No schema/update/Doctor/plugin-loading/service-lifecycle change is made, so the published-driver update cell is not applicable.

Final CI run 38226567508 is terminal. Its last completed failure is the same raw-cursor generation_mismatch assertion as main run 38205338506/job 114669571918; the test is unchanged by this PR. No new failure class appeared after merge. The verified squash commit is f61bbd1668c5a67cabc38aedd1f920d6e439f99d, authored by Peter Steinberger.

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

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: XL labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR moves status reads and typed session-creation work into existing workers and removes redundant mutation reads.

Example: Status is requested after transcript usage increases from 1,000 to 2,000 tokens.

  • Before: The status renderer reads the transcript synchronously and displays 2.0k/32k.
  • After: The history worker prepares usage before the renderer displays the same 2.0k/32k.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation is coherent with no verified introduced defect; behavior confidence rests mainly on reported workload measurements and worker-backed integration coverage.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored internal refactor is outside the ordinary contributor proof gate; workload measurements support worker execution, while the empty-list CLI smoke does not exercise typed participant settlement.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
User problem: Synchronous cold session reads and redundant mutation reads can delay other Gateway work.
Reason: The maintainer-directed change follows the established worker migration and retains public contracts and existing creation-publication ownership.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR open: it advances the approved session-worker migration without a verified introduced defect, but GitHub reports a conflict and several CI failures remain unattributed.

Priority: P2
Reviewed head: 1ecfd72f89120ce1607a872ae8315ed28b163371

Before merge

  • Complete next step - Resolve GitHub's reported merge conflict and classify the actor, fork query-count, cleanup, and suppression-inventory failures against matching base evidence; repair only failures caused by this PR.

Findings

None.

Tests

  • Missing end-to-end proof: Public sessions.create with typed native participants followed by a read or turn is not demonstrated, and baseline-failing regression runs are not supplied.
Agent review details

How this fits together

Session operations send reads to the history worker and mutations to the agent executor, which return prepared facts and committed publications for status rendering and native participant settlement.

flowchart TD
  A[Session operations] --> B[History worker]
  A --> C[Agent executor]
  B --> D[Agent SQLite]
  C --> D
  C --> E[Native binding settlement]
  E --> F[Shared SQLite]
  B --> G[Status presentation]
  C --> G
Loading

Technical review

Best possible solution:

Complete the existing worker cutover while preserving status output, final transaction checks, and native settlement ordering.

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

Fetched-main source confirms synchronous status reads and the native-participant creation exclusion; no target code or tests were executed during this read-only review.

Is this the best way to solve the issue?

Reusing the existing readers, executor, and settlement owner is appropriate, and the removed reads retain transaction-local validation or committed receipts.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Status and fallback preparation keeps the original intent (b7f616e: Move session storage work off the Gateway thread while keeping fallback selection policy with the host.)
  • Creation and typed native participants changes intended behavior with a stated reason (f19b09b: Share creation orchestration while preserving native cleanup, alias adoption, and worker publication.)
  • Rewrite validation changes intended behavior with a stated reason (b0ae5b6: Publish complete replacement branches atomically and refuse stale loaded snapshots.)
  • Compaction receipts keeps the original intent (3648942: Commit compaction boundaries and accounting under existing writer authority, then adopt committed version facts.)
  • ACP migration provenance keeps the original intent (dac3cb6: Retain exact migration-source identity without allowing lifecycle replacements to inherit a previous generation's provenance.)
  • Goal worker selection changes intended behavior with a stated reason (f753f73: Move Goal management into the executor while preserving authority and native SDK guard compatibility; explicitly native and cross-store sources still select the native adapter.)
  • Reply initialization changes intended behavior with a stated reason (077f28f: Prepare reply snapshots through session readers while retaining authoritative writer validation.)
  • Conversation demotion keeps the original intent (a2ec3f6: Separate external conversation addresses from local session context and preserve durable associations.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit dc6018d adds src/status/session-fallback-model.ts:32 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: dc6018d2071d; files: src/status/session-fallback-model.ts)
  • Josh Avant: Raw commit 0b85966 adds src/config/sessions/session-accessor.sqlite-conversation.ts:55 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 0b8596607208; files: src/config/sessions/session-accessor.sqlite-conversation.ts)

PR surface

Source +85, Tests +429, Docs +8, Other +16. Total +538 across 46 files. Added test files: 3.

View PR surface stats
Area Files Added Removed Net
Source 24 347 262 +85
Tests 18 1096 667 +429
Docs 2 29 21 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 2 16 0 +16
Total 46 1488 950 +538

Review metrics

Metric Value Why it matters
Production versus test LOC Production +347/−262; tests and support +1,096/−667. Production growth connects existing settlement and prepared-fact owners; test growth includes relocated coverage plus freshness, mutation, rollback, and settlement cases.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is an internal session-performance improvement with no intended visible behavior change.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Record public sessions.create with typed native participants, followed by a read or turn showing settlement and publication.

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.

History

Review history (7 earlier review cycles)
  • reviewed 2026-10-12T04:39:30.463Z sha efa2b7f :: needs changes before merge. :: none
  • reviewed 2026-10-12T04:51:10.967Z sha bd20a0b :: needs changes before merge. :: [P2] Include the native-settlement closure in the PR wrapper inventory
  • reviewed 2026-10-12T05:31:23.690Z sha f3b5d51 :: needs changes before merge. :: [P2] Include the native-settlement closure in the PR wrapper inventory
  • reviewed 2026-10-12T06:05:31.296Z sha ca56d83 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-12T06:40:35.088Z sha 89d8968 :: needs changes before merge. :: none
  • reviewed 2026-10-12T07:12:59.029Z sha 70c03a9 :: needs changes before merge. :: none
  • reviewed 2026-10-12T07:58:44.095Z sha 6ef6657 :: needs changes before merge. :: none

Reviewed October 12, 2026, 4:24 AM ET / 08:24 UTC (Revision 8).

@clawsweeper clawsweeper Bot added merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 12, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Oct 12, 2026
@clawsweeper clawsweeper Bot removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 12, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 12, 2026
@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 12, 2026
@steipete
steipete merged commit f61bbd1 into main Oct 12, 2026
249 of 339 checks passed
@steipete
steipete deleted the dbasync/t1cut-s1 branch October 12, 2026 09:08
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…openclaw#169608)

Prepare status and model facts through the history worker and route typed creation participants through the existing writer transaction. Remove redundant rewrite and compaction reads, fold ACP provenance retention into upsert, and use DELETE RETURNING for conversation demotion.

Retain named SDK/native, incognito, offline repair, and effect-boundary contracts. SQL measurement and inherited CI evidence are recorded in the PR.
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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant