Repository navigation
refactor(storage): reduce duplicate reads around final authority guards - #167571
Conversation
Combine Workshop session permission and transcript-anchor validation, reuse GC preparation, and evaluate each final owner predicate once. Preserve synchronous foreign-commit checks and route guarded sandbox commands through the existing native launch boundary. Prepare ClickClack descriptive reads in workers while retaining live visibility checks, and document the remaining guards and their SDK retirement contract. Schemas, durability, retention, permissions, and update behavior are unchanged.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
|
Codex review: needs maintainer review before merge. What this changesThis PR reduces repeated database reads for background learning, sandbox commands, checkout cleanup, and ClickClack discussions while preserving current permission checks. Review scores
ProductKind: Performance · Worth it: Yes Merge readiness✅ Ready for maintainer review This PR contains useful, owner-directed work that remains distinct from current main. The earlier sandbox recreation finding is resolved, and no additional actionable code defect was identified. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherOpenClaw workers prepare session and runtime facts from SQLite databases. Learning, sandbox execution, checkout cleanup, and discussion operations consume those facts and check current authority before performing effects. flowchart TD
A[Session and runtime databases] --> B[Worker preparation]
B --> C[Learning and runtime operations]
A --> D[Current authority checks]
C --> D
D --> E{Authority still valid?}
E -->|Yes| F[File, command, checkout, or channel effect]
E -->|No| G[Refuse stale operation]
Technical reviewBest possible solution: Keep preparation with existing workers and retain live effect-boundary checks until the documented versioned SDK cutover can replace them safely. Do we have a high-confidence way to reproduce the issue? Not applicable to a behavioral bug report: this is an internal optimization supported by recorded calibrated SQL measurements and inspected owner-boundary regressions. Is this the best way to solve the issue? Yes: consolidating preparation within existing owners while retaining fresh final checks avoids introducing a competing authority cache or storage path. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against f8e594e461ef. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +162, Tests +602, Docs +38. Total +802 across 34 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (7 earlier review cycles)
Reviewed October 9, 2026, 3:36 AM ET / 07:36 UTC (Revision 8). |
Carry the registry creation timestamp and workspace through Docker and Podman setup completion. This preserves the admitted generation without another database read and avoids cleaning up a successfully recreated container. The worker still rejects genuine reservation replacements.
Preserve main projection-snapshot anchor reads and the consolidated final-authority query. Conflict resolution retains both query paths without additional SQL; focused Workshop, append metadata, and anchor worker tests pass.
Keep main deletion of the redundant session-patch suite and move the native-replacement read regression into the existing session-list suite. Prepare compiled workers at collection; both session-read tests pass.
Async binding-index hydration reads stored binding metadata before checking capacity. Populate both boundary fixtures with typed bindings so they exercise capacity and reclamation rather than malformed data; preserve all existing assertions.
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
…ds (openclaw#167571) * perf(storage): consolidate final authority guards Combine Workshop session permission and transcript-anchor validation, reuse GC preparation, and evaluate each final owner predicate once. Preserve synchronous foreign-commit checks and route guarded sandbox commands through the existing native launch boundary. Prepare ClickClack descriptive reads in workers while retaining live visibility checks, and document the remaining guards and their SDK retirement contract. Schemas, durability, retention, permissions, and update behavior are unchanged. * fix(storage): retain authority across prepared reads * fix(sandbox): retain registry generation when recreating containers Carry the registry creation timestamp and workspace through Docker and Podman setup completion. This preserves the admitted generation without another database read and avoids cleaning up a successfully recreated container. The worker still rejects genuine reservation replacements. * test(clickclack): seed complete bindings for capacity checks Async binding-index hydration reads stored binding metadata before checking capacity. Populate both boundary fixtures with typed bindings so they exercise capacity and reclamation rather than malformed data; preserve all existing assertions.
Related: #166703
What Problem This Solves
Final permission and lifecycle checks must observe native and foreign-process writes immediately before privileged effects; earlier worker migrations left duplicate preparation reads around those checks.
User Impact
The affected operations retain live permission and lifecycle checks while avoiding duplicate preparation reads. No schema migration, configuration, durability, retention, permission change, or operator action is required.
Why This Change Was Made
Workshop joins source permissions, lifecycle revision, and the accepted transcript anchor into one current statement. Sandbox completion checks its captured generation inside the existing worker transaction, and guarded remote-shell commands check authority at native launch. Worktree GC reuses its prepared census and makes one live owner-state decision at final admission. ClickClack hydrates indexes in its existing session queues, prepares descriptive facts asynchronously, and preserves fresh binding/revocation checks for visibility and mutations.
Released synchronous SDK signatures remain available. The new async session reader is optional. Short cross-owner authority reads remain live until native/foreign writers can publish complete revocation facts; their retirement path is the next Plugin SDK major, documented in
worker-access.md.Evidence
Reviewed head:
65baafdd29e6a4ef15972d866ea8571e9f4286dc. Fresh P2 reviews were scoped-clean. ClawSweeper review completed on this exact head at 2026-10-09T07:36:24.272Z with zero code findings. The original sandbox recreation finding is fixed.SQL disposition: five valid remote alternating pairs replace the invalid earlier local comparison. Changed-path first/warmed SQL and requests are identical in every sample. Warmed median +0.126% is entirely unchanged-owner variance within the explicit 0.5% allowance. Raw first-turn +44 and combined startup +13 remain visible below: these are attributed unchanged startup/maintenance work, not a literal numerical pass. Under the latest landing instruction to fix PR-caused increases and otherwise land, this qualifies; no consolidated guard adds warmed statements. Later conflict integrations preserve the final guard SQL, so no redundant full series was run.
Published-driver update passed on AWS Linux/x64: released
2026.9.9updated to the exact reviewed commit, all command exit records are zero,/readyzreturned 200, the running build is65baafdd29e6a4ef15972d866ea8571e9f4286dc, and durable/incognito post-update checks passed. The recorded run42a8d8aa-c6be-4567-b849-55b84d935003finished with statussucceeded. The full canonical cell took 482.884 s, including 387.480 s for the update command, with its original 1125 s budget unchanged. Package build/integrity passed in 463.8 s; tarball SHA-2566ba28d08dc7708e8aa727b102521933aeabd412a55207a8c18ec0a218ff4f839.The earlier local Linux/arm64 Docker cell remains a failed observation: exit 124 after 1095.99 s while activation was beginning, despite successful candidate admission, Doctor, canary startup and previous-Gateway verification. It was CPU/I/O active, not OOM-killed. This remote pass does not claim to fix that local timing limitation. Recovery first encountered a lossy host upload, then a dependency-install quota in
/tmp; the final build used the same source/lockfile under the advertised/workfilesystem, without raising quotas or weakening timeouts. The original local package SHA-256 was4b895c7aac03d31c1f7308a896e8066910ae1c3dda8775dd84b8d94386367de7; it was not used by the final rebuilt AWS cell. A non-fatal startup gzip warning (365.2 KiB versus 364.7 KiB) is retained, not suppressed.Landed through the native admin route as
83ce1401d658f4c723063a9900ba5af9bcbb5adb. Native receipt verification and the landing-parent audit matched parent94c0f0d589ab60ffd91d51fb1a433231961e2562; independent security and current authority passed admission. The CI exception below retains failed and cancelled coverage honestly. Final main also contained incidental helper extraction #167646 in ClickClackservice-open.ts; the inspected, conflict-free composition preserves those helpers and this PR's worker preparation and live guards.Repairs and integration
ClawSweeper identified an actual Docker/Podman recreation bug: registry updates preserve the original timestamp/workspace, but completion reconstructed those immutable fields and rejected the successful recreation. Commit
d24cfbb0712d6154398fd84fe2f2359e2d436e60carries the captured fields forward without changing the strict worker predicate or adding SQL. Both engine regressions failed withSandbox runtime generation changedbefore the fix; Docker recreation and registry suites then passed 41 tests in 810.26 s wall, including 315.6 s worker compilation. The real-registry boundary is necessary because mocks hid this contract.Merge commits
4c09f2c2d248b08846d787264b0fb7f351398e73,fb69da5c0fc628d8c83237eee9ebbb31c2e128ea, and3f93a03c5425b14e76e0853638580189bdcc17e9resolve actual main conflicts and the already-fixed dependency audit. They preserve append metadata reuse from #167291 and projection-anchor optimization from #167238. Overlapping cleanup #167563 removed a session-patch suite; its deletion stays intact, and the async-read/native-replacement regression now lives in the session-list suite with compiled-worker preload. No rebase was used.CI also exposed malformed ClickClack capacity fixtures containing empty objects. Commit
65baafdd29e6a4ef15972d866ea8571e9f4286dcsupplies valid typed bindings without changing production code or assertions. Both focused cases and all 35 contract tests pass: 213.14 s command wall, 0.306 s actual tests (earlier CI cases 0.245 s).Correctness, compatibility, and check coverage
Regression coverage exercises foreign permission changes, lifecycle resets, replacement, deletion, transcript rewrites, allowed appends, sandbox reservation replacement/revocation, broker launch admission, worktree activity/placement changes, ClickClack cold-index visibility, FIFO hydration, cross-runtime revocation, accepted-work settlement, and native replacement through the async reader.
Original owner/sibling proof passed 74 tests in 256.12 s and 182 in 641.38 s; final lane ClickClack proof passed 72 tests in 401.93 s wall. Landing integration proof passed 27 Workshop/transcript tests in 669.94 s, then 30 in 1022.33 s after projection integration (including worker builds). The moved async-read suite passed 2 tests in 177.90 s. All focused commands used one worker. Seconds-long costs here include actual SQLite worker/admission contracts and shared compilation; test assertions were not weakened.
Core production/test and extension production/test typechecks passed, with affected lanes repeated after integrations. Runtime-process build graph, PR wrapper closure, get-reply imports, and transcript-reconcile imports passed. Original Knip, check-changed, and source ratchets passed. These results are reused only for unchanged inputs.
Two later local failures are independently inherited from main: Madge's
prepared-model-catalog-fingerprints.ts↔prepared-model-catalog-worker.tscycle, and the history-reader chainsession-entry-read.worker.ts→session-accessor.sqlite-entry-list.read.ts→session-accessor.sqlite-exact-read.tsintroduced by #167520. Reported inputs match the integrated baseline and inspected mainab5fd51b5e826fdcf3344e4838963ca656be649d. Exact-head CI lint passed:check-lint, both core shards, all three extension shards, andcheck-additional-extension-package-boundary. Local and Linux/arm64 supplemental lint preparation hit the same 300 s SDK-declaration tooling limit; these are not claimed as passing lint runs. The earlier remote focused core lint also passed on the measured repaired candidate. No redundant retry is needed because current CI supplies the actual lint proof.Released SDK audit against
v2026.10.1-beta.1andv2026.9.9: synchronousapi.runtime.agent.session.getSessionEntryand remote-shell helper/callback shapes are unchanged;getSessionEntryAsyncis optional. Released transcript admission/version validators retain their compatibility record and type test. Anchor, GC policy and ClickClack store changes are internal. Local SDK API diff passed in 426.62 s, digestd20dba0b: no entrypoints/direct exported symbols added or removed; 131 reachable-surface changes were reviewed for optional additions and internal helper/type cleanup.Retained cross-owner final-guard debt:
src/agents/worktrees/owner-protection.ts:56reads current session authority before shared-state GC mutation; placement checks remain at:96and:103. These short checks remain counted, with complete revocation publication/next SDK major as the retirement path. No zero-host-SQL assertion is imposed on them. The diff adds zero newOPENCLAW_*names.CI exception
CI run 37886053166, attempt 1 tested this head via merge
da4895c9db565760cb277bc7f206f8dab4c06c6f, with ordered parents maina134038ad7fbf939038ada4dde61c0fa7eb02e33and the reviewed head. Its tree matches the derived merge exactly. Two remaining roots qualify under the explicitly authorized untouched/unrelated exception:reply-tool-authority.worker.test.ts:157, before route binding, foreign update, or any changed guard.server.sessions.effort-scopes.test.ts:24fails its model fixture setup withUnknown provider "openai", before effort mutation or changed owners.All 24 causal source inputs matched the tested baseline and main inspected at 2026-10-09 05:14 UTC. Recent main CI was green: no matching failed main run or local reproduction is claimed. Source and call-path inspection independently exclude this PR. After that inspection, main commit
a73ef559b23a6325f0ea39cc90dac22eaf50a916repaired the reply-authority fixture by observing both cold and prepared worker lanes. The target main already contains that repair; under the explicitly authorized untouched/unrelated admin route, no source-changing CI retry or branch refresh is needed to carry it into the final merge. The effort-scopes failure remains independently unrelated. The aggregate CI gate failed and 29 sibling jobs were cancelled by the successful fail-fast monitor; those cancellations are incomplete coverage, never passing proof. Complete native evidence binds each root, all 108 terminal jobs, checkout/source/log hashes, and cancellation provenance. Security-fast, dependency review, and security-sensitive review are green; native admission will revalidate current security and authority. No rerun was used to obtain green.Additional owner observation
Three alternating remote Sandbox pairs include actual worker SQL. First creation decreases 52→31 all-thread statements; warmed creation 50→29. MAIN creation statements decrease 35→14, with requests unchanged at 2→2. First/warmed final guards remain 8→8 / 7→7, guarded transport 7→7, and foreign-revocation checks 7→7. All observed phases have zero SQL failures and duration ratios below 1.5. This shows removed work around creation while preserving live final authority.
Workshop/GC and ClickClack have completed correctness and MAIN-only observations, but their separate all-thread owner probes remain an explicit limitation. Vitest clears
NODE_OPTIONS, so earlier samples did not observe child-worker SQL. Corrected instrumentation passes both MAIN/child calibration (each 8 native calls, 2 prepares, 7 successful statements, zero failures), but two baseline owner attempts hit the unchanged 120 s no-output watchdog and exited 143 (165 s and 289.75 s wall). The first produced no workload evidence; the second emitted a partialok:falsereceipt during shutdown covering Workshop and idle/retired GC with actual worker SQL. It is not a completed baseline sample, and no paired candidate or ClickClack sample ran. The second attempt used the supported native worker prebuild, which succeeded in 111.9 s. No timeout, test assertion, or production code was weakened. Further optional observation stopped after the repeated tooling failure; no complete Workshop/GC or ClickClack all-thread totals are claimed. The separate required five-pair full Gateway measurement is independently calibrated and complete.Statement and request proof
The previous local comparison was invalid because two warmed positions exceeded the 1.5 duration-ratio bound. It is superseded by the complete remote report below, not counted as passing evidence.
Five alternating pairs on Blacksmith Testbox
tbx_01m4fezcpspq9jsvbaha6zcgfw. Baseb0c330d27df4a528f65185cc3e509284d1b218d9, candidated24cfbb0712d6154398fd84fe2f2359e2d436e60.All ten full workloads passed: 13 top-level turns, child completion, control RPCs, cron, compaction and graceful shutdown. All 20 MAIN/worker calibrations passed 8 native calls, 2 prepares, 7 successful statements, 0 failures. No sample was discarded.
Maximum phase duration ratio: 1.017; no window exceeds 1.5. Full all-thread/MAIN/request phase table, including all 10 warmed positions:
Raw first-turn arithmetic is not green: 2666→2710 (+44,+1.650%). Startup combined median is 5333→5346 (+13,+0.244%). The warmed median is 1115.1→1116.5 (+1.4,+0.126%); every delta SQL/request group is in unchanged owners. Foreground first-turn after separately identifying maintenance/catalog work is 2562→2557. These numbers remain visible for applying the coordinator’s latest PR-attributable-work rule; they are not silently normalized to a pass.
The changed-path totals above are direct/correlated observed stacks, with raw worker IDs, request keys and nanosecond timestamps retained. All first/warmed median delta groups have an empty changed-path intersection. Original three-pair and final five-pair archives are retained.
First-turn statement delta by request group (median-supplying runs, preserving the exact +44 total):
task-worker:workers.placementProjection: +3.task-worker:sessionRows.sharedFacts: -1.sqlite-broker:cron.planStartup: +7.unattributed: +13.sqlite-broker:pluginState.entries: +2.readonly-process:pluginCatalog.read: -26.task-worker:agentDatabaseDeletion.snapshot: +9.sqlite-broker:deliveryQueue.mediaRetentionSnapshot: +9.sqlite-broker:pluginState.sweep: +6.task-worker:generatedHtmlProvenance.list: +2.sqlite-broker:deliveryQueue.pruneTombstones: +7.sqlite-broker:managedImages.entries: +3.task-worker:session-store-projection: +3.sqlite-broker:bootstrap.prune: +4.sqlite-broker:open: +1.sqlite-broker:cron.loadMutable: +3.task-worker:channelIngress.failedHealth: -1.Warmed statement delta by request group:
task-worker:session-exact-entries: -0.5/turn.task-worker:session-row-facts: +1.4/turn.task-worker:sessionRows.sharedFacts: +0.3/turn.task-worker:exec-approvals.read: -0.1/turn.readonly-process:auth-profile-rows: +0.3/turn.The +13 native first-turn group is startup/plugin lifecycle lease acquire/release work; its raw stack reaches
runGatewayPostReadyStartupMaintenance. Delivery media snapshot/tombstone cleanup and managed-image/provenance cleanup reachserver-maintenance.ts; cron startup/load and health snapshot work also occur in the baseline. Catalog differences are the same 26-statement existing read-only admission batch appearing twice or three times; retain this as timing/admission variance, not a guard saving. Full SQL strings and caller stacks are inevidence-5pairs/attribution-median-groups.json.gz.Observed native SQL failure records: 8; details in sql-final-report.json.
Native lock diagnostics are retained rather than treated as successful statements: 7 connect-phase
BEGIN IMMEDIATErefusals at unchangedreleaseOpenClawStateLeaseBestEffort/ plugin-startup maintenance (2 baseline, 5 candidate), plus 1 candidate second-session attempt in the unchanged audit writer. All workload outcomes completed; no fix of these pre-existing concurrency paths is claimed.Size and remaining boundary
Static T1 owner-file sites decrease 784→783 against the original lane base; these are not dynamic statement counts. Production +469/−307 (net +162), tests +692/−90 (net +602), docs +40/−2 (net +38). Growth supplies worker preparation, composable authority queries and meaningful revocation regressions, with no new storage/schema owner. Rare ClickClack cold admission can add worker requests; this is not represented as a universal all-thread reduction. Negative unbound visibility retains a current binding point read, and title backfill retains native authority checks after its worker scan.