Skip to content

refactor(placement): migrate remaining native read callers - #166445

Merged
steipete merged 17 commits into
mainfrom
dbasync/w6placement-getters
Oct 7, 2026
Merged

steipete merged 17 commits into
mainfrom
dbasync/w6placement-getters

Conversation

@steipete

@steipete steipete commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Placement preparation and media custody

Ordinary placement preparation should use the database worker or facts its caller already owns. The PR migrates the remaining placement policy/getter callers while retaining live final-effect authority. Reply-media preparation now consumes the workspace captured by its existing custody check, including commentary normalization and local-root selection. The superseded async fallback is removed, and the internal helpers require the captured scope. Text-only replies skip unused root preparation. Local roots still derive requester/account policy at consumption; no host SQL, per-call freshness/schema probes, cross-turn cache, or product instrumentation was added.

Current head: 06de6cc0be8ad6b1b1a183fdab1ce3ec77a8005a. APPROVED TO LAND by explicit maintainer decision on 2026-10-07. The warmed ALL increase is 2209.4 → 2216.1 (+6.7/turn, +0.303%), with valid duration ratio 1.02009. MAIN is unchanged at 28 → 28; first-turn ALL improves 5820 → 5807. Keyed placement-getter worker requests are 0 → 0. The complete attribution below places the positive increase in untouched scheduled reader/maintenance owners. This passes the approved TURN NOISE FLOOR: ≤ +0.5% only for fully attributed untouched-owner increases, with valid alternating-pair duration ratios. No PR-caused new request or statement is excused. Earlier strict no-growth verdicts are retained as historical evidence and are superseded by this acceptance decision.

Current integration: merge commit 06de6cc0be8ad6b1b1a183fdab1ce3ec77a8005a incorporates pinned main 05e6660fdbc0f62ff994a41ce77b6b49ad5ea9b0, without rebasing. GitHub found real conflicts after the previous head passed CI. The only manual conflicts were imports in the provisioning-cancellation test and its support module: main’s canonical session persistence/async cleanup remains alongside this PR’s held-preflight helper and cancellation callback type. Main’s added live dispatch authority checks and test routing remain intact. Those inherited checks add no worker command and do not run in the approved ordinary local-turn workload; this integration adds no PR-specific query or getter request. Independent overlap review and fresh P2 autoreview found no actionable defects. Post-integration proof passed production core types, all 27 core test type graphs, Madge with zero cycles, 92 focused tests in four files (516.02s wrapper), and all seven selected dispatch-authority cases (64.68s wrapper; ten unrelated cases filtered). Exact-head CI run 37678692628 passed for 06de6cc0be8ad6b1b1a183fdab1ce3ec77a8005a; the native watcher completed GREEN with no pending checks. The separate provider-scaffold job initially failed with npm ECONNRESET during dependency installation, before build/tests/validation. Its generator, workflow, dependencies and npm configuration are unchanged by this PR; one identified-infrastructure single-job rerun passed (run 37678691379, attempt 2). No code change or admin exception was needed for that failure. ClawSweeper completed review of this exact head at 2026-10-07 20:08 UTC with no findings and no before-merge items, accepting the documented SQL qualification and conflict integration.

Historical integration proof: 6f6f3543f1974 incorporated 94fc0814ef64, passed 183 focused tests, production/all-core-test types and Madge, and passed CI run 37672166808 with 73 successful and 24 skipped jobs. ClawSweeper completed that head at 2026-10-07 19:18 UTC with no findings or before-merge items and recognized the approved SQL qualification. No CI rerun or admin exception was used; no merge or auto-merge request was sent for that head.

The complete cutover passed 95 existing tests in seven files through node scripts/run-vitest.mjs ... --maxWorkers=1 (the repository wrapper for pnpm test): 617.26s wrapper, 154.22s + 306.62s Vitest wall time. Coverage includes workspace/permission changes during I/O, foreign lifecycle changes, cancellation, large-file bounds, commentary custody, dispatch, and agent media ownership. No test cases or assertions were removed; raw fixtures now persist canonical entries and invoke real scope capture. No test-routing changes were needed. Production, gateway-methods and messaging test types, scoped lint and a fresh P2 review with complete helper context passed. Pre-integration CI run 37664991937 completed successfully on its exact 18dcba901dbd8b78f2be7ad554004ce9802bef07 head: 78 successful jobs and 24 workflow-skipped jobs; the native watcher exited GREEN. No failed-job rerun or admin exception was used. ClawSweeper completed exact-head review at 2026-10-07 18:21 UTC with no actionable correctness findings, recording the then-unresolved SQL qualification decision, which the maintainer has now approved. Its earlier cf8 review and CI are historical evidence.

The changed media helpers have no released Plugin SDK, documented subpath, or api.runtime.* reachability at v2026.10.1-beta.1 or v2026.9.8; no compatibility shim is retained. The existing released SDK comparison and original public-signature proof remain below. No schema, durability, retention, configuration, permission or dependency contract changed. Existing synchronous media authority reads remain follow-up debt at src/gateway/server-methods/chat-reply-media.ts:87 and its live effect assertion; this change reuses their prepared workspace rather than adding another read.

Final paired result — accepted under the approved noise floor

Exactly three alternating pairs ran on one fresh 16-vCPU host, comparing baseline f277bdf4bc69f691acd81186ad4ac6a4822d967c with final 18dcba901dbd8b78f2be7ad554004ce9802bef07. Each source was built fresh; index trees and source cleanliness were verified. The unchanged SQL observer and same calibrated lineage preload were used on both sides. Every median duration ratio is valid; no sample was dropped and no extra pair was run.

Warmed ALL means are baseline [2200.1, 2209.4, 2238.5], final [2208.6, 2248.2, 2216.1]. Median duration is 2.4943 → 2.5444 seconds, ratio 1.02009. First-turn duration ratio is 1.05806. First and warmed windows have zero SQL errors.

Phase Baseline ALL median Final ALL median Delta
Boot 3869 3871 +2
Connect 344 349 +5
First turn 5820 5807 -13
Warmed turn 2209.4 2216.1 +6.7
Second session 6883 6971 +88
Control plane 48 52 +4
Cron 1694 1708 +14
Compaction 1028 1086 +58
Shutdown 902 827 -75
Compaction + shutdown, context only 1920 1923 +3

Warmed MAIN is 28 → 28 (delta 0). Keyed placement getter sends and their SQL are zero in all six runs (per-turn delta 0). Row-facts request means have medians 9.9 → 10.0 per turn; backfill request means have medians 1.1 → 1.0. Those independently selected family medians must not be added to explain the total median.

The selected aggregate-median runs, main-2 → fixed-3, instead reconcile exactly: 22,094 → 22,161 statements across ten warmed turns, +67, with zero arithmetic or source-family residual:

Contribution in selected median runs SQL delta over ten turns
Placement getters 0
Session-row facts (99 → 102 requests) -3
Transcript backfill (11 → 16 requests) +35
Other named active requests -38
Earlier open-request post-completion work -12
Trajectory retention preparation +88
Auth-profile read-only snapshot/WAL metadata +12
Shared-state reader operations -15
Total +67

The unbound native operations are resolved by source stacks but lack generic request IDs. This is accounting for measured reader/maintenance contributions; it does not establish scheduling causality or an inherent placement-getter SQL cost. The maintainer explicitly accepted this fully attributed +0.303% increase under the ≤ +0.5% untouched-owner noise floor; the earlier strict zero-growth hold is resolved. No unchanged-source replay or unrelated scheduling change was used to obtain green.

All workload assertions passed. Three shutdown-only BEGIN IMMEDIATE/database is locked attempts remain in the evidence: one candidate audit-prune attempt recovered with an observed successful audit_events DELETE; two baseline best-effort restart-intent-clear attempts left zero restart-intent rows in the complete closed DB/WAL/SHM snapshot. These unchanged owner paths appeared on opposite sides in prior evidence. No successful restart-intent deletion is claimed, and none of these errors is removed from reporting.

Every native-call row has a lineage counterpart across all six runs, with zero unmatched request keys. Final archive SHA-256: 4294ab6102132e3a5f9693ca08803eecbf47a6851e26c92bb710205edbc090db. The measurement lease is completed, native stop succeeded, the claim is absent, and the task-owned transport worktree is removed. Lane, native PR worktree, tooling and recovery evidence are retained because the PR is unmerged.

Original-head diagnostic request lineage

A separate original-head diagnostic compared pinned baseline f277bdf4bc69f691acd81186ad4ac6a4822d967c with e12b2ed038877baedc8165098035a3fae6ebbc1f. Measurement-only preloads correlate worker ID, request ID, monotonic time, sender stack and native SQL. The original SQL observer is unchanged. Every native-call row is conserved: 58,462/58,462 on baseline and 58,492/58,492 on the original head, with no unmatched request keys. No product source hook or request payload logging was used.

The keyed placement getter sends are zero in both warmed workloads. The observed extra envelopes are generic session-reader work downstream of projection and transcript backfill:

Diagnostic request family Baseline total, ten turns Original total, ten turns Per-turn median, baseline → original Active SQL, baseline → original
Keyed placement getters 0 0 0 → 0 0 → 0
Session-row facts 100 106 10 → 11 1138 → 1169 (+31)
Transcript backfill 11 18 1 → 2 87 → 136 (+49)
Other generic session-reader requests 1280 1280 128 → 128 varies by admitted/cache state

The facts/backfill difference is exactly 13 requests and 80 active-request statements over ten diagnostic turns, with zero post-completion SQL in those two families. Sender/receiver evidence identifies session-row-projection-refresh.readRows/refreshBatch/drain and session-row-transcript-backfill.backfillSessionRowTranscriptFields through session-row-projection-backfill.drain; receiver branches are session-transcript.worker.ts:268 and :279. Activity-summary tail reads are excluded from that family classification. The original nine-pair +5.0 gate result remains authoritative; this single diagnostic pair is not a replacement performance gate.

The historical unassigned +38 is numerically accounted for by SQL/call-chain mapping: 111 exact native-chain groups contribute +28, 18 documented business-chain matches contribute +14, and two unmatched activity-summary PRAGMA groups contribute -4. All positive contributions have a matched chain. Eighty-seven groups have multiple possible diagnostic host callers; their historical request IDs cannot be recovered because the old trace did not record them. These are explicitly group-level mappings, not fabricated exact historical lineage. The other +12 statements in the selected ten-turn comparison were already identified as background work.

The diagnostic first/warmed windows had no SQL errors. Each source recorded one retained shutdown BEGIN IMMEDIATE/database is locked attempt (baseline restart-intent cleanup; original audit pruning). Both source trees remained clean, the diagnostic lease is stopped, and its native claim is closed.

The unrun cf8 capsule remains superseded with zero samples. The final fixed-three series above is accepted under the maintainer-approved noise floor. The raw positive counts remain visible; this is explicit acceptance of fully attributed untouched-owner background work, not a claim that SQL did not increase. Fresh integration-head review and green CI remain required.

Previous integration and qualification at e12b2ed, including both failed series

Landing integration

Not ready to land: final-head CI is green and correctness reviews are clean, but the strict inclusive SQL gate fails. Native exact-head review is validated as the historical pre-approval hold; no prepare or merge request has been submitted.

Integrated main f277bdf4bc69f with a merge commit, preserving the merged parent’s cancellation results, orphan retirement, live profile refresh, session authority, and dependency-audit fixes. Production source is 6d8b54ebc2d7ded4bb2c1e46e8bc5b7c63114000; e12b2ed038877baedc8165098035a3fae6ebbc1f adds only test fixtures, test support, and test routing. The remaining production delta moves ordinary placement reads and policy preparation to the existing worker owner while retaining live final-effect guards.

Integration review fixed a real model-selection race: a memory-only session could become locked or replaced during awaited placement preparation and then be overwritten. The existing lock and identity fence now runs immediately before the in-memory write. Both new placement-race cases failed before the fix; afterward both model-selection suites passed all 33 tests (pnpm test src/model-picker/apply-session-model-selection.test.ts src/model-picker/apply-session-model-selection-placement.test.ts --maxWorkers=1, Vitest 98.19s, wrapper 112.60s including compilation; reported test execution 19.921s).

The first integrated CI run exposed stale fixtures and test timing assumptions. The follow-up supplies the combined placement getter in the dispatch fake, sorts the Gateway test inventory, removes SSH transport from a device-only fixture, targets write admission rather than an earlier read, supplies the empty batched publication reader, and waits on actual preflight abort and physical close settlement. The redispatch fixture now proves its exact missing/reclaimed starting state at native preflight; a held reconciliation sweep was never a session-admission mutex. Existing stale-response, cancellation, no-allocation, recovery, and rollback assertions remain. The catalog-close race was established with a controlled closing-resource diagnostic; natural main passed, so no inherited-CI exception is claimed. The model test’s map-spread lint issue is fixed.

P2 production and fixture reviews are scoped-clean. Production typechecking, all 27 post-integration test type graphs, four affected follow-up type graphs, Madge (zero cycles), line-cap and SQLite-worker ratchets passed. Repaired model-selection, planner, and dispatch proof passed 176 tests; idle suspension passed 20, reconciliation events passed one, workspace recovery passed eight, catalog close passed its focused case, and the final cancellation/preflight proof passed 15. The callback receiver annotation emits identical JavaScript to the reviewed fixture. The focused original integration batch passed six routed project groups in 1301.67s, including wrapper/build/import closure, authority, media, and indirect consumers. These are loaded-host correctness timings, not latency benchmarks. Five-sample baseline/candidate attribution is complete for dispatch, planner, CLI ownership, provisioning cancellation, session events, idle suspension, and workspace recovery: baseline passes 5/5 and the original candidate reproduces each affected contract 5/5. Later repetitions use named-contract filters where recorded, following initial full-file proof. Natural catalog-close samples pass on both sides; the controlled diagnostic independently proves the physical-close sequencing race. No inherited-CI exception is claimed. Final-head CI run 37652451642 completed successfully on e12b2ed038877baedc8165098035a3fae6ebbc1f (77 successful jobs, 24 skipped by the workflow); the native watcher returned GREEN.

Released SDK check: the public model-session-runtime.applySessionModelSelection signature is unchanged against both v2026.9.8 and v2026.10.1-beta.1. The official released comparison completed; a separate integration-base comparison isolates this PR: no entrypoint additions/removals, 147 reachable exports across 25 entrypoints tracing to four internal declaration changes, and no public callable break. The parent’s synchronous Gateway placement adapters, deprecation record, and compatibility type test remain intact. No schema, config, retention, durability, or permission contract changes; no new OPENCLAW_* names.

SQL statement gate — blocked

The original three-pair series alternated main/candidate on one host with every thread and all background SQL counted. Warmed-turn medians pass: MAIN 28 → 28; all threads 2204.0 → 2203.7. The strict first-turn median is 5791 → 5802 (+11), so this series fails. First-turn samples are main [5781, 5795, 5791], candidate [5802, 5788, 5837]; median duration ratio is 1.0785, valid under the 1.5 cutoff. No SQL or prepare errors occurred in that series. Its boot +1 and cron +41 are retained; this is not relabeled an invalid or passing comparison.

The separately predeclared diagnostic finished exactly nine alternating pairs on the same frozen sources: baseline f277bdf4bc69f691acd81186ad4ac6a4822d967c, candidate production tree 3ebf023cad3279343df29f2a12372c7292096e06 from 6d8b54ebc2d7ded4bb2c1e46e8bc5b7c63114000. Final head e12b2ed is production-byte-identical. All 18 runs remain included. First-turn ties at 5805 → 5805; warmed-turn rises from 2203.7 → 2208.7 (+5.0), so the strict warmed gate fails. MAIN stays 509 → 509 for first-turn and 28 → 28 for warmed turns. Median duration ratios are 0.9367 and 0.9614 respectively; all phase ratios are below 1.5. Duration skew does not invalidate this series.

Nine-pair phase Main ALL median Candidate ALL median Delta Candidate/main median duration
Boot 3872 3869 -3 1.0776
Connect 346 345 -1 1.0069
First turn 5805 5805 0 0.9367
Warmed turn, per-turn mean 2203.7 2208.7 +5.0 0.9614
Second session 6846 6869 +23 0.9971
Control plane 56 50 -6 0.9910
Cron 1694 1723 +29 0.9797
Compaction 1045 1078 +33 0.8875
Shutdown 886 859 -27 0.6134
Compaction + shutdown, context only 1920 1916 -4 0.7560

Warmed ALL samples are main [2218.0, 2207.3, 2210.5, 2203.3, 2204.4, 2203.7, 2197.6, 2199.8, 2194.3], candidate [2210.5, 2213.4, 2210.9, 2212.3, 2208.7, 2205.2, 2197.3, 2196.2, 2204.0]. First-turn ALL samples are main [5812, 5790, 5823, 5805, 5813, 5795, 5832, 5776, 5779], candidate [5805, 5807, 5825, 5824, 5827, 5800, 5800, 5774, 5783]. Compaction+shutdown per-pair sums are main [1934, 1935, 1909, 1920, 1988, 1922, 1908, 1916, 1916], candidate [1940, 1909, 1908, 1937, 1929, 1909, 1919, 1909, 1916]; these do not waive either strict turn window.

The request-origin diagnostic keeps the original SQL observer byte-identical and applies the same separately hashed temporary request-entry tracing overlay to both sources. It records exactly one catalog request per run, initiated during boot, with no first-turn or auth-refresh request. Auth SQL crossing first-turn boundaries therefore comes from startup discovery racing agent-database creation. No background statements are subtracted, and first/warmed windows are never combined. The original failed series and this diagnostic are separate evidence, not repeated attempts until green.

Warmed attribution reconciles the median-selected difference of +50 statements over ten turns: native stacks identify +12 as background work and leave +38 unassigned across the asynchronous worker boundary. No foreground increase is positively identified, but that does not establish its absence. Every positive contributor has an equivalent in the baseline traces. Nineteen candidate stack groups are absent from the baseline warmed window: fifteen occur elsewhere in baseline; four are schema/user-version refreshes under the unchanged audit/catalog command owners, with corresponding baseline refreshes under other commands. All nineteen contribute zero to the median-selected +50. This attribution does not qualify the strict gate, and second-session/cron increases remain included.

The nine-pair diagnostic contains six unique shutdown-only SQL errors, all failed BEGIN IMMEDIATE attempts with database is locked: two baseline audit-prune attempts settled through the existing writer FIFO retry with an observed successful audit DELETE; two attempts each in candidate runs 1 and 4 came from the unchanged SIGTERM restart-intent best-effort clear path. No successful restart-intent DELETE is claimed. Complete closed synthetic database/WAL/SHM snapshots from both candidate runs contain zero restart-intent rows. First-turn and warmed windows are error-free; no error is excluded from the report. Aggregate and adjacent-window views must not double-count these six errors.

Both temporary instrumentation overlays were restored to their original bytes, and both pinned source trees were verified clean. The remote measurement exited successfully and the owned Testbox lease was stopped and confirmed completed. No further replication was started. Native review artifacts are validated as the historical pre-approval hold; branch, review state and recovery evidence remain available for continuation.

Focused medians pass for Stop/handoff, worker admission, chat metadata, and media preparation. Ordinary Stop ALL 683 → 681; abandonment plus recovery 215 → 189; worker admission 9 → 6 (empty/pending) and 18 → 12 (retry); chat metadata MAIN 3 → 0, ALL 62 → 62; reply media MAIN 5485 → 5479, ALL 5507.2 → 5504.2; commentary media MAIN 6926 → 6914, ALL 7021.4 → 7015.0. All duration ratios are within the declared bound.

The authority flow’s resident-bind +0.4 and resident-Move −0.4 are four existing scheduled WAL-maintenance statements crossing their adjacent phase boundary. The original stacks identify reclaimSqliteWalFreePages → maintainPeriodic → GatewayScheduler.run/wake → Timeout._onTimeout. Each pair’s combined raw total is 758 → 758 (pairs 1, 2, and 3); no new SQL/stack group appears. This uses the explicitly allowed adjacent-background-window rule and does not combine first/warmed turns.

ClawSweeper revision 6 completed on exact head e12b2ed038877baedc8165098035a3fae6ebbc1f at 2026-10-07 16:36 UTC. It found no actionable correctness or security findings and retained blocked before merge for SQL qualification and the then-unfinished attribution. Attribution is now complete; the SQL blocker remains. The fresh production and fixture P2 reviews are scoped-clean. Green CI and those reviews do not waive the explicit statement gate.

Original implementation, historical proof, and overlap context

What Problem This Solves

Ordinary placement lookups and policy preparation still run SQLite on the Gateway thread even after the placement owner gained worker operations. Several recovery paths also fetch placement and pending-result facts separately.

Why This Change Was Made

Use the existing placement actor and batched reader for remaining native preparation callers, including worker-turn recovery, session operations, model selection, publication, and media preparation. Preserve live authority after waits and immediately before effects. The parent’s single aggregate projection query uses its own SQLite snapshot; multi-batch projections retain one transaction so a foreign commit cannot mix generations.

Stop can interrupt Move after abandonment has been durably accepted. Stop now validates that exact intent and source again after acquiring the workspace lock, then finishes it under Stop’s current authority. Completion uses the acknowledged failed generation; transaction and commit grants recheck the caller and session incarnation. Combined reads and acknowledged write facts avoid extra queries, while final native guards remain live.

This is stacked on #166444 and completes its ordinary getter/policy-preparation caller cutover. It retains #166053's per-turn batching and reuses owner facts.

User Impact

No schema, service, persistent cache, configuration, retention, or durability changes. No new OPENCLAW_* names (464 → 464). Production changes: +408/-203, net +205 (611 changed lines across 39 production files; 57 total paths including tests). Released synchronous SDK getters remain available; worker failures do not silently fall back to native persistence.

The new combined placement/Move reader and the abandonment helper’s returned facts remain internal. Public forceDestroyEnvironment keeps its existing result, and the released placement reader does not expose the new combined method.

Final synchronous predicates remain where released SDK or foreign writers can bypass host publications. These include immediate file/media authority (chat-reply-media.ts:87–107, assistant-media-policy.ts:50, control-ui.ts:480), session reset/retirement across stores (session-placement-lifecycle.ts:146, session-reset-service.ts:816), workspace/Git effects, and final node grant consumption. They are documented debt, not a claim of zero Gateway SQL everywhere. The old exported media-roots preparation helper is private after its bundled callers migrate; the final authority resolver remains live.

SDK contract: v2026.9.8 gateway-runtime.ts exposes Gateway context types; shared-types.ts retains the placement reader and optional retirement service, and placement-projector.ts defines the synchronous getters. Removal requires a compatible public SDK migration.

Evidence

Final-source warmed-turn SQL passes: MAIN 31.0 → 31.0; all-thread median 2954.3 → 2913.0 (−41.3). All-thread ranges are 2951.7–2959.1 → 2907.4–2914.8, with zero SQL errors. These are the child’s original predeclared nine-run controls; the later parent optimization changed no child bytes. The parent’s new six-run controls are reported in its own PR, not mixed with these controls.

Pair MAIN main → PR2 All threads main → PR2
1 31.0 → 31.0 2954.3 → 2907.4
2 31.0 → 31.0 2959.1 → 2914.8
3 31.0 → 31.0 2951.7 → 2913.0

Every sample and all background/helper/maintenance SQL remain counted. The fewer-than-500 campaign target remains unmet.

The full initial check-changed passed all 27 type graphs and three export scans, then found two local no-shadow errors. After the aliases were corrected, the final native three-file check passed every selected phase (2,406.288s), including the repeated 27 type graphs, three Knip scans, lint, and all tail guards. Script lint passed separately (132.936s); final Madge has zero cycles (86.451s), ratchet passed (18.258s), and environment count stayed 464 → 464 (12.894s). Comparable T1 is 829 → 829: the released SDK query kernels remain.

All 25 focused comparison rows are non-growing versus pinned main 8f5c33c30d71, with zero SQL errors. The same shared observer counted successful native executions across every thread, including maintenance. The complete proof records all 21 family test and wrapper wall times; examples are authority 83.18s / 83.00s / 83.46s and grants 28.90s / 29.56s / 29.58s for main / PR1 / PR2. These are instrumented proof wall times, not a latency benchmark. The focused candidate was tree 3cc46328; the final two binding aliases and test cleanup do not change any SQL or control flow. The warmed-turn series uses final tree be3cec3d.

All final focused statement counts (main → PR1 → PR2)
Flow MAIN: main → final PR1 → final PR2 All threads: main → final PR1 → final PR2
stop-handoff/actorRead 3 → 0 → 0 3 → 3 → 3
stop-handoff/ordinaryStop 1042 → 1042 → 1022 1173 → 1172 → 1167
stop-handoff/abandonHandoff 140 → 110 → 87 189 → 186 → 178
stop-handoff/handoffRecovery 12 → 0 → 0 43 → 32 → 14
stop-handoff/handoffIncludingRecovery 152 → 110 → 87 232 → 218 → 192
worker-admission/waitEmpty 6 → 6 → 3 9 → 9 → 6
worker-admission/waitPending 6 → 6 → 3 9 → 9 → 6
worker-admission/restartRetry 9 → 9 → 3 21 → 18 → 12
chat-metadata/chatMetadata 3 → 3 → 0 58 → 58 → 58
media-preparation/replyMedia 5485 → 5485 → 5479 5508.4 → 5508.4 → 5505.4
media-preparation/commentaryMedia 6926 → 6926 → 6914 7027.2 → 7027.2 → 7020.4
authority/residentBind 11 → 0 → 0 11.4 → 10.4 → 10.4
authority/fixedBind 28 → 14 → 14 28 → 24 → 24
authority/residentMove 37 → 14 → 14 67.4 → 65.4 → 65.4
authority/fixedMove 58 → 33 → 33 72.8 → 68.8 → 68.8
lifecycle/adopt 3 → 0 → 0 3 → 3 → 3
lifecycle/moveBegin 13 → 0 → 0 13 → 13 → 13
lifecycle/moveError 7 → 0 → 0 7 → 7 → 7
lifecycle/moveReconcile 0 → 0 → 0 14 → 12 → 12
lifecycle/moveComplete 12 → 0 → 0 12 → 10 → 10
lifecycle/preparedBind 11 → 0 → 0 11 → 10 → 10
lifecycle/retire 6 → 0 → 0 6 → 6 → 6
lifecycle/moveFlow 32 → 0 → 0 46 → 42 → 42
grant/nodeLaunch 25 → 6 → 6 25 → 9 → 9
grant/retain 8 → 0 → 0 8 → 3 → 3

The first actor diagnostic recorded 3 → 4.5 all-thread statements per read. Attribution proved all sources performed the same 984 setup agent-maintenance statements, with 15 of PR2’s statements crossing into the actor window. The common harness now observes and joins that initial owner’s real release promise before warm measurement; it neither closes the owner nor cancels work. The replay is 3 → 3 → 3, and all setup SQL and original samples remain preserved. Nothing is subtracted from any count.

The SQL-budget repair passed six authority/lifecycle suites: 127 tests (83 tests in 110.20s and 44 preparation tests in 88.50s). The later test-only split replayed all 44 cases across the two resulting files in 94.015s (pnpm test … --maxWorkers=1). The full P2 review and subsequent repair/test-layout and final alias/fixture delta reviews are scoped-clean.

The first final media run exposed a fixture lifecycle error: case cleanup removed its database without retiring the placement singleton. The new async reader correctly refused the old physical store on later cases. The repair uses the same singleton lifecycle drain as sibling media tests; original failed output is retained. The original 17-case order passes after that two-line fixture repair (65.535s). The earlier run had one pass and 16 failures; no assertion or timeout was weakened. Media ownership’s three cases also passed. Two earlier Stop fixture failures asserted the initial placement after dispatch was already allowed to advance; the assertion now runs before dispatch while the cancellation event checks stay intact. Their focused replay passed both cases in 452.682s. Six import/build/SDK-boundary suites passed 22 tests (completed project groups: 32.44s, 233.19s, and 74.99s), and the test-routing audit confirms the new barrier suite uses the host-owned Gateway project. The original local batch stalled before executing media tests and was stopped with its exact process IDs; the completed import results were retained and the two media suites ran on Hetzner.

Final source: 0bc57a861cc7 / tree be3cec3d, compared with parent 6a51170bf177. The final parent merge is byte-identical to the tested and measured child tree. The parent integration preserves its final capacity check/dispatch registration ordering while moving the preparation reads.

The published 2026.9.8 driver successfully updated to the persistence owner candidate e1319215d937: canonical package/integrity 890.262s, full cell 648.763s (actual update 539.056s). Readiness returned 200, the running candidate identity matched, durable and incognito sessions survived, and service cleanup passed. Package SHA-256: 25f68560ba5fe5a9be580afce506121c22db3ea7ea5132005e6c079d9019af50. The final diff from that package is two local variable aliases and two test cleanup lines; SQL, authorization, APIs, and transport behavior are unchanged. Both artifacts were downloaded and verified; the owned lease is released and its server is confirmed absent.

The official SDK comparison completed in 1,982.162s including isolated checkout, installation, and cleanup. Its JSON is byte-identical to the prior resolved-type audit: 147 reachable exports across 25 entrypoints, four internal declaration changes, no entrypoint additions/removals, and no public callable break. The final aliases and fixture cleanup do not change this surface.

The parent now owns the projection budget and foreign-commit snapshot regressions. Its one-ID and 250-ID budget cases fail on the original kernel; a real second SQLite connection proves snapshot consistency across larger batches. Computer transport refuses when the turn claim is revoked during placement preparation.

Hosted CI is not green yet. The exact-head CI run failed the production dependency audit on GHSA-6qxp-vccf-f47h; fail-fast cancelled the remaining jobs. Main contains the fix c39d9b0692db, but this PR’s stacked base does not yet contain that commit. Main integration is therefore a merge precondition; no dependency override or audit exception was added. The PR-context header failure was corrected and that check now passes. The requested local/leased gates above passed; this work order stops at READY PRs without a hosted rerun or merge.

Overlap: #166102 (sqlopt-schema), sqlregress, the wave-6 entry/auth/binding/discovery/worktree/transcript/profile lanes, #165901, #165921, and #162433 (design draft, not an active owner). Whoever lands second integrates main.

The original implementation handoff was ready for review. Current landing status and gates are recorded above.

@clawsweeper

clawsweeper Bot commented Oct 7, 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 gateway Gateway runtime size: XL labels Oct 7, 2026
@steipete
steipete marked this pull request as ready for review October 7, 2026 04:13
@clawsweeper clawsweeper Bot added 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 7, 2026
@clawsweeper

clawsweeper Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 7, 2026, 4:08 PM ET / 20:08 UTC (Revision 13).

ClawSweeper review

What this changes

Move remaining session-placement preparation reads into database workers and reuse captured workspace facts for chat attachments while preserving live authorization checks.

Merge readiness

✅ Ready for maintainer review

This PR remains useful, and no blocking correctness finding was identified. The latest integration resolves the previous conflict blocker, and the recorded maintainer acceptance covers the SQL qualification.

Priority: P2
Reviewed head: 06de6cc0be8ad6b1b1a183fdab1ce3ec77a8005a

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Strong source-qualified runtime evidence and a coherent owner cutover support readiness without additional review blockers.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Recorded isolated Gateway workloads exercise placement preparation, Stop/recovery, and media custody after the fix, with successful workload assertions and attributed SQL results. Post-integration boundary validation covers cancellation and authority checks; earlier measurements retain their original source identities. No stored-data contract changes require migration.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded isolated Gateway workloads exercise placement preparation, Stop/recovery, and media custody after the fix, with successful workload assertions and attributed SQL results. Post-integration boundary validation covers cancellation and authority checks; earlier measurements retain their original source identities. No stored-data contract changes require migration.
Evidence reviewed 8 items Pinned introduced change: Reviewed the pinned base-to-head production and test hunks. Raw head records confirm the previous reviewed head and pinned main are separate parents; the stale test merge was not used to infer merge behavior.
Still necessary on current main: Fetched main retains the earlier media scope without captured workspace facts and lacks the combined placement/Move reader. The merged parent #166444 explicitly leaves ordinary getter preparation to this PR.
Release comparison: The latest stable release also retains the earlier media scope contract, without this PR's captured workspace return value.
Findings None None.
Security None None.

How this fits together

Session placement determines whether OpenClaw runs a conversation locally or on a worker. Gateway requests prepare placement facts, then recheck current authority before session mutations, worker operations, or attachment access.

flowchart TD
  A[Gateway requests and replies] --> B[Placement preparation]
  B --> C[Database worker]
  C --> D[Captured placement and workspace facts]
  D --> E[Live authority checks]
  E --> F[Session and worker operations]
  E --> G[Attachment preparation]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +180, Tests +372. Total +552 across 69 files.

View PR surface stats
Area Files Added Removed Net
Source 39 408 228 +180
Tests 30 717 345 +372
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 69 1125 573 +552

Review metrics

Metric Value Why it matters
Production versus test growth production +408/-228, net +180; tests/support/routing +717/-345, net +372 Production growth supports the stated worker-read cutover and guarded Stop settlement; test growth includes relocated boundary coverage.
Accepted warmed SQL qualification all threads +0.303%; main thread 28 → 28 The recorded maintainer decision accepts the fully attributed untouched-owner increase within the approved 0.5% noise floor.

Technical review

Best possible solution:

Keep preparation with the existing database workers and custody owner, preserving current authorization at every final effect.

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

Not applicable to this internal refactor; recorded isolated Gateway workloads and focused boundary regressions exercise the changed behavior.

Is this the best way to solve the issue?

Yes. Reusing existing worker operations and captured custody facts avoids competing owners while preserving released synchronous adapters and live effect guards.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded runtime efficiency and ownership improvement with no demonstrated urgent user-facing regression.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Recorded isolated Gateway workloads exercise placement preparation, Stop/recovery, and media custody after the fix, with successful workload assertions and attributed SQL results. Post-integration boundary validation covers cancellation and authority checks; earlier measurements retain their original source identities. No stored-data contract changes require migration.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded isolated Gateway workloads exercise placement preparation, Stop/recovery, and media custody after the fix, with successful workload assertions and attributed SQL results. Post-integration boundary validation covers cancellation and authority checks; earlier measurements retain their original source identities. No stored-data contract changes require migration.

Evidence

What I checked:

  • Pinned introduced change: Reviewed the pinned base-to-head production and test hunks. Raw head records confirm the previous reviewed head and pinned main are separate parents; the stale test merge was not used to infer merge behavior. (06de6cc0be8a)
  • Still necessary on current main: Fetched main retains the earlier media scope without captured workspace facts and lacks the combined placement/Move reader. The merged parent refactor(placement): move lifecycle and grant preparation to workers #166444 explicitly leaves ordinary getter preparation to this PR. (src/gateway/worker-environments/placement-read-store.ts:34, a6051a2e050b)
  • Release comparison: The latest stable release also retains the earlier media scope contract, without this PR's captured workspace return value. (src/gateway/server-methods/chat-reply-media.ts:76, fc23bc864e45)
  • Authority retained through abandonment: Queued abandonment rereads the exact placement and durable intent after acquiring the workspace lock, rechecks caller authority, passes a live assertion into environment destruction, and guards completion. Native boundary cases cover intent, generation, caller, and incarnation changes before effects or completion. (src/gateway/worker-environments/placement-move-abandon.ts:108, 06de6cc0be8a)
  • Media custody and compatibility: Media preparation consumes the custody owner's captured workspace while retaining live rereads and requester policy. The workspace-change case verifies rejection before file-content reads. The public placement reader retains its synchronous contract and does not expose the new combined method; no stored format or schema changes are introduced. (src/gateway/server-methods/chat-reply-media.workspace.test.ts:79, 06de6cc0be8a)
  • Captured proof and accepted SQL tradeoff: The fetched body matches captured SHA-256 5860cf3975d7cc246f906a02009c16653d827814933da0953f851c62b3011392. It records isolated Gateway workload success, three alternating pairs, unchanged warmed main-thread SQL at 28, and a fully attributed all-thread increase of 0.303% accepted under the maintainer-approved 0.5% noise floor. Historical strict failures remain disclosed. (06de6cc0be8a)

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 (12 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-07T15:09:48.638Z sha 6d8b54e :: needs changes before merge. :: none
  • reviewed 2026-10-07T16:36:58.043Z sha e12b2ed :: blocked before merge. :: none
  • reviewed 2026-10-07T17:21:28.054Z sha e12b2ed :: blocked before merge. :: none
  • reviewed 2026-10-07T17:41:25.664Z sha cf8e756 :: blocked before merge. :: none
  • reviewed 2026-10-07T18:21:05.484Z sha 18dcba9 :: blocked before merge. :: none
  • reviewed 2026-10-07T18:50:59.184Z sha 18dcba9 :: blocked before merge. :: none
  • reviewed 2026-10-07T19:18:37.058Z sha 6f6f354 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-07T19:44:41.626Z sha 6f6f354 :: needs changes before merge. :: none

@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Security-sensitive guard cleared

Current revision: 06de6cc0be8ad6b1b1a183fdab1ce3ec77a8005a

This PR no longer changes files in the maintainer security-review tier.

Separate CODEOWNERS requirements still apply to security policy and enforcement files.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts labels Oct 7, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Oct 7, 2026
Merge current main and its placement, session authority, and dependency fixes. Preserve the worker-read caller cutover and accepted Stop abandonment settlement. Recheck memory-only model-selection locks and session identity immediately before adoption after awaited placement preparation. The new race cases fail before this repair; both focused model-selection suites pass 33 tests. P2 autoreview is scoped-clean.
@steipete

steipete commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Integrated main and fixed the memory-only model-selection race at 6d8b54ebc2d7ded4bb2c1e46e8bc5b7c63114000. The new regression failed before the fix; both focused model-selection suites now pass 33 tests. P2 autoreview is scoped-clean. The PR body records current integration evidence and the remaining measurement/CI gates.

@steipete

steipete commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

Remove the async workspace fallback after media consumers switch to the
custody owner's captured facts. Require the captured scope for path
normalization and derive local roots from it without another getter.
Preserve live authority checks and requester policy at each effect.

Migrate helper tests through canonical session persistence and real scope
capture, preserving permission, workspace, cancellation and output checks.
No released SDK surface, schema, retention or durability contract changes.

Validation: all 95 focused tests passed in 617.26 seconds; production and
affected test types, scoped lint, and a fresh P2 review passed.
The earlier cf8 head has green CI; final-head SQL qualification is pending.
@steipete

steipete commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Oct 7, 2026
Merge main 94fc081 without rebasing.
Resolve the Gateway worker test inventory conflict by preserving both
call-device-auth and chat-auth-readiness entries in sorted order.
Retain main's reader cleanup and guard refactors together with the async
placement preparation, media custody facts, and live final-effect checks.

The maintainer approved the prior +0.303% warmed SQL increase under the
fully attributed untouched-owner noise floor. Integration adds no PR
query or worker request; its resolved production overlaps preserve guard
order and semantics, so the approved measurement evidence is retained.

Validation: production types and all 27 core test type graphs passed;
madge found zero cycles; 183 focused tests passed in 642.75 seconds;
fresh P2 review is scoped-clean. New exact-head CI is required before merge.
@steipete

steipete commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Oct 7, 2026
@steipete

steipete commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete merged commit 83a9540 into main Oct 7, 2026
169 of 172 checks passed
@steipete
steipete deleted the dbasync/w6placement-getters branch October 7, 2026 20:25
@steipete

steipete commented Oct 7, 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 8, 2026
…166445)

* refactor(placement): run lifecycle and grant preparation in workers

* test(placement): retain lifecycle boundaries in worker fixtures

* refactor(placement): prepare native caller reads in workers

* test(placement): align startup and recovery owner lifetimes

* perf(placement): reuse Stop grants and acknowledged state

* test(placement): settle media owners between fixtures

* perf(placement): avoid single-query projection transactions

* test(placement): fix async caller integration fixtures

Match combined placement reads and validate device fixtures with one transport. Wait for native preflight cancellation and exact resource-close settlement while preserving stale-response, no-allocation, and recovery assertions. Reuse the existing runtime fixture to keep the test file within its line budget, and restore sorted worker-test routing.

P2 autoreview is scoped-clean. The final callback receiver annotation emits identical JavaScript to the reviewed fixture. Focused boundary, dispatch, model-selection, planner, type, and lint checks passed; remaining repeated attribution and SQL diagnostics are recorded in the PR landing evidence.

* perf(placement): reuse reply media custody facts

Reuse the workspace already resolved by the media custody authority check
for normalization and local roots. Commentary shares the same snapshot
across both phases; text-only replies skip unused root preparation.
Keep live authority rereads before effects and preserve foreign-commit
visibility without adding host SQL, freshness probes, or schema checks.

Validation: 78 focused media and dispatch tests passed in 557.58 seconds;
production and affected test types, scoped lint, and P2 review passed.
The inclusive SQL gate remains pending a fresh alternating comparison.

* refactor(placement): require prepared media workspace facts

Remove the async workspace fallback after media consumers switch to the
custody owner's captured facts. Require the captured scope for path
normalization and derive local roots from it without another getter.
Preserve live authority checks and requester policy at each effect.

Migrate helper tests through canonical session persistence and real scope
capture, preserving permission, workspace, cancellation and output checks.
No released SDK surface, schema, retention or durability contract changes.

Validation: all 95 focused tests passed in 617.26 seconds; production and
affected test types, scoped lint, and a fresh P2 review passed.
The earlier cf8 head has green CI; final-head SQL qualification is pending.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: XL 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