Repository navigation
perf(gateway): prepare sharing and custody authority through session workers - #165600
Conversation
…workers Carry fresh row and sharing facts through existing session readers and writer grants while retaining live source custody before dispatch and commit. Fence synchronous SDK mutations, retain physical owners through cleanup, and join accepted persistence without replaying unknown outcomes.
|
🦞👀 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: blocked before merge. Reviewed October 5, 2026, 11:14 AM ET / 15:14 UTC (Revision 3). ClawSweeper reviewWhat this changesThe PR moves repeated session-sharing and accepted-input authority reads into existing workers while retaining live authorization before dispatch and transcript writes. Merge readiness⛔ Blocked before merge - 2 items remain This remains useful follow-on work beyond the merged admission repair. No actionable introduced defect was found, but the declared latest-repair and update qualification is not yet complete. Priority: P2 Review scores
Verification
How this fits togetherGateway chat admission accepts user input and binds it to a session and caller. Session workers prepare current storage and membership facts, which the Gateway checks before dispatching agents or committing transcripts. flowchart TD
A[User chat input] --> B[Gateway admission]
B --> C[Session read workers]
C --> D[Current session and membership facts]
D --> E[Live caller and custody checks]
E --> F[Agent dispatch]
E --> G[Transcript writer]
G --> H[Committed input and settlement]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +626, Tests +560, Docs +11. Total +1197 across 44 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Preserve the existing worker and custody owners, released synchronous callbacks, and current authorization semantics while qualifying the candidate through the published updater. Do we have a high-confidence way to reproduce the issue? Not applicable to this performance refactor; the body provides repeated real-runtime SQL measurements, and no new failing path was established during this read-only review. Is this the best way to solve the issue? Yes: carrying fresh facts through existing readers and writer grants preserves one authority owner and avoids a competing cache or scheduler. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 1cd64928a366. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
History |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Keep restart-dedupe eligibility with its existing owner and revalidate full authority at the claim. Mark Gateway dispatch ownership only after its guarded callback enters, so asynchronous custody refusal still settles queued input and releases admission.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
Incognito pending-input staging used file-backed custody facts that cannot represent its process-local database identity. Keep this route under its existing native source and permission guards through staging, dispatch, transcript persistence, and accepted settlement. Durable worker custody is unchanged. This fixes the valid chat.send rejection introduced by #165600. Strengthen the existing native custody test with real Gateway authorization: metadata and transcript writes succeed, caller revocation prevents the next effect, and accepted transcript data and cleanup survive that revocation. The regression fails on current main with SESSION_MUTATION_AUTHORIZATION_CHANGED. Validation: 26 focused custody/sharing/freshness tests passed in 257.53s wall (2.974s for the native Incognito case); isolated pre-fix regression failed in 103.43s wall. Codex review is clean through P2. No schema, permission, retention, or update migration changes are required. The full changed-file gate passed in 982.08s, including core production and all 27 core-test type graphs, typed lint, storage ratchets, and import checks. Linux end-to-end replay did not execute: Testbox allocation timed out, AWS refused capacity, and the Hetzner source-witness check refused the textual diff before tests despite matching base and candidate file hashes. The unrelated Doctor 60-second failure remains unresolved; no deadline or retry policy was changed.
…workers (openclaw#165600) * perf(gateway): prepare sharing and custody authority through session workers Carry fresh row and sharing facts through existing session readers and writer grants while retaining live source custody before dispatch and commit. Fence synchronous SDK mutations, retain physical owners through cleanup, and join accepted persistence without replaying unknown outcomes. * chore(sessions): document worker fact assertion invariants * test(gateway): retain profile source in authorization fixtures * fix(gateway): keep custody errors on leaf state contracts * test(gateway): clean up custody settlement checks * fix(sessions): preserve custody across nested reads and foreign rewrites * fix(sessions): preserve custody preparation and undispatched cleanup Keep restart-dedupe eligibility with its existing owner and revalidate full authority at the claim. Mark Gateway dispatch ownership only after its guarded callback enters, so asynchronous custody refusal still settles queued input and releases admission.
Incognito pending-input staging used file-backed custody facts that cannot represent its process-local database identity. Keep this route under its existing native source and permission guards through staging, dispatch, transcript persistence, and accepted settlement. Durable worker custody is unchanged. This fixes the valid chat.send rejection introduced by openclaw#165600. Strengthen the existing native custody test with real Gateway authorization: metadata and transcript writes succeed, caller revocation prevents the next effect, and accepted transcript data and cleanup survive that revocation. The regression fails on current main with SESSION_MUTATION_AUTHORIZATION_CHANGED. Validation: 26 focused custody/sharing/freshness tests passed in 257.53s wall (2.974s for the native Incognito case); isolated pre-fix regression failed in 103.43s wall. Codex review is clean through P2. No schema, permission, retention, or update migration changes are required. The full changed-file gate passed in 982.08s, including core production and all 27 core-test type graphs, typed lint, storage ratchets, and import checks. Linux end-to-end replay did not execute: Testbox allocation timed out, AWS refused capacity, and the Hetzner source-witness check refused the textual diff before tests despite matching base and candidate file hashes. The unrelated Doctor 60-second failure remains unresolved; no deadline or retry policy was changed.
What Problem This Solves
The #156941 adoption in #164682 moved the first sharing lookup to workers but left repeated custody assertions issuing 55 main-thread SQLite statements per warmed chat turn. Accepted input must still detect sharing or custody changes between admission and dispatch.
Why This Change Was Made
Prepare exact session rows and membership through the existing session readers, then carry transaction-local facts through pending-input, transcript-turn, and SessionManager writer grants. Each synchronous consumer retains its captured physical source and writer FIFO, fences intervening synchronous SDK writes with the native mutation witness, and validates the original caller immediately before dispatch or commit. Collected input validates every source against the same final row/membership snapshot.
Bundled dispatch, retries, followups, ACP initiation, steering persistence, and dedupe preparation consume these facts. Accepted persistence remains joined through cleanup, including unknown outcomes. Pre-ACK steering settlement joins the backing owner and does not start new source-workspace preparation after acceptance.
User Impact
The moved sharing/custody reads leave the Gateway thread while preserving live authority. No new service, cache, schema, permission, retention, durability, configuration, or environment variable is introduced. No update migration is needed. Incognito continues through its existing process-held owner.
Three retained synchronous paths bound the zero-SQL claim:
src/auto-reply/reply/dispatch-acp.ts:309→src/sessions/user-turn-transcript-runtime-context.ts:36. It is reachable through thev2026.9.8agent-harness SDK (QuestionInputAuthority/AgentQuestionDispatcher). Its replacement needs a versioned awaited question contract and bundled-caller cutover; removal belongs to the next SDK major.src/config/sessions/session-accessor.entry.ts:460retains indexed absence queries atsrc/config/sessions/session-accessor.sqlite-exact-read.ts:286. Non-selected physical sources are other-owner reads; alternate keys on the selected source can be same-owner legacy reads. Ordinary unambiguous targets skip these probes. This is follow-up debt, separate from the moved sharing/custody operations.src/agents/sessions/session-manager-message-admission.ts:34–37. This is pre-existing indexed OTHER-owner SQL: destination facts cannot authorize disclosure of source content. The same-store path consumes transaction-local worker facts.Evidence
Original measured candidate:
5c4b624a15f4fe455ae1e8cc2db3b117f4d11061; original pinned base:689bda012dae1fd39862098df4e3393590be89c5.Current candidate:
2eb044b52310b9cbaed56a9ecbb718f15c0606d8, including main4f83b608af8b4b3a8f6a2685eb788baf45dbc69fthrough merge commit490558b8eeccb72a709e3ced5fe078fb308fa860. Conflict resolution retained main's native-mutation fence and typed transcript-conflict error alongside the custody cutover.490558b8validation passed 158 tests across 14 files (1,080.78 s), then 224 tests with one existing skip across 11 files (917.92 s), each usingpnpm test <files> --maxWorkers=1. Coverage includes live sharing revocation after acceptance and before dispatch, profile binding, steering, withdrawal, ordered readers, foreign rewrite, recovered input, dispatch, shutdown, indirect callers, and worker/wrapper import closures. Core production and all 27 core/test type graphs passed; madge and runtime import checks found zero cycles. The worker ratchet passed and no newOPENCLAW_*names were added. The native routing audit found the affected real-custody tests already in host-owned projects.CI on
490558b8exposed two PR-caused regressions, repaired in2eb044b5: ordinary compaction handoff was incorrectly checked as restart-dedupe input before eligibility; asynchronous custody rejection was incorrectly marked as dispatched, skipping pending-input cleanup. The repairs retain lifetime checks during preparation and full authority at claim, and transfer cleanup ownership only after actual dispatch handoff. No assertions or test deadlines were weakened. Clean-main comparison runs pass both affected flows. Fresh full-diff Codex P2 review, core types, and scoped lint pass. The repaired head passed 80 tests across six files with--maxWorkers=1in 955.67 s, including the full compaction and resumed-session suites. Compaction attribution used five Node 24 runs on each side: the pre-fix PR failed the same three cases every time, while main passed all seven cases every time. Resumed-session attribution also reproduced five PR failures against five passing main controls; the first run preserved the full original order, followed by four selections of the primary failing case. All reproduction processes are closed. CI run 37329881341 completed successfully on exact head2eb044b52310b9cbaed56a9ecbb718f15c0606d8; its 28 Node test steps used 5,394 aggregate CI seconds across parallel jobs. No CI failure exception is needed.Fresh SDK report for the integrated tree: 179 reachable exports, 17 reachable declaration differences, zero direct export declaration/signature changes, and zero added/removed entrypoints, digest
8a559fd9. Inspection against releasedv2026.9.8confirms existing synchronous receipt, recorder, and question contracts remain unchanged; additions are optional. The three-file CI repair changes only function bodies and leaves those declarations unchanged.The prior three Knip findings below belong to the original base. On clean main
4f83b608, the production Knip command instead reportsBranchSummaryResult(src/agents/runtime/index.ts),renderRootHelpText(src/cli/program/root-help.ts),stripEnvelopeFromMessage(src/gateway/chat-sanitize.ts), andresolvePolicyPluginActivationState(src/plugins/config-policy.ts); the integrated candidate reports the same four findings. All four files are untouched by this PR. Baseline reproduction took 206.03 s. Every remaining check after that inherited failure passed separately.Published-driver update cell passed on Blacksmith Testbox
tbx_01m469pqg7fh5jmvf2njbsea7g(workflow). The canonical packer built exact commit2eb044b52310b9cbaed56a9ecbb718f15c0606d8/ tree795f1e2c8160c42e96e30ae7e01183c7cc3f0e2d; package integrity passed, SHA-256d3b8a0fd0321fc53c466843f0a008e5290b3bf7ee93174c278f6374bce036f90. The nativepublished-driver-update-docker.shcell ran published2026.9.8against that candidate and finished withreadyz=200, verified running build/version, and passing durable/incognito state assertions. The update took 215.355 s; the full remote build/package/cell command exited 0 in 19m3s. Fixture service shutdown passed. The earlier integration-candidate lease was stopped while queued before any build or cell started.ClawSweeper completed its trusted review of
2eb044b5at 2026-10-05T15:14:48Z with no actionable code or security findings. Its only remaining qualification requests are satisfied by the completed repair controls and published-driver proof above.Current candidate surface: production +776 / -150 / net +626 across 33 files; tests/support +652 / -92 across ten files; docs +11 in one file. Total 44 files. No new tests or weaker assertions were added for the landing repairs.
The performance measurements below retain their original candidate identity.
Matched sqlmeasure4 runs on pinned base → final head, three repetitions each, Node 24.21.0 / SQLite 3.53.4, unchanged six-file harness with native-call calibration and source-map attribution:
openclaw-agent-db-readonly.ts:116session-accessor.sqlite-entry-read.ts:101session-accessor.sqlite-participant-projection.ts:56These sites retain SQL for unrelated callers; the table classifies the sharing/custody stack. The exact median-run MAIN delta reconciles as −55.0 sharing +2.0 existing verbose schema/user probes −0.3 sandbox +0.9 scheduled GitHub OAuth maintenance = −52.4/turn. All remaining owner cohorts are unchanged; no unattributed remainder.
Independent medians need not sum. The tradeoff is more worker SQL while removing synchronous custody reads from the Gateway thread. These are execution counts, not latency claims. Testbox queued without a runner for about 15 minutes and was stopped; remote admission then reached its shared fleet limit, so the final pair ran in an isolated local checkout with synthetic state. No budget bypass or active cloud lease remains.
Every run completed all 13 turns, native child work, cron (
finished/ok), compaction and clean shutdown. Audit-prune lock retries occurred before [2,0,1] and after [1,1,4], with matching stacks and successful same-worker DELETE/COMMIT settlement. After run 3 also had two boot operator-approval lock retries that settled through the same owner. All database paths stayed inside the fixtures. Baseline run walls: 276.1/267.8/305.1 s; final: 160.3/237.3/151.5 s. Fresh final runtime build: 542.6 s.All focused commands use
pnpm test <files> --maxWorkers=1. Wall times include worker preparation on the loaded local host; they are not CI runtime claims.Core/test types, scoped lint, line-cap and assertion-safety ratchets passed. Database-worker ratchet passed against the pinned base (34.66 s); final madge reported 0 cycles (141.26 s). No environment names were added (464 before and after). Indirect caller tests were audited for worker routing; they already belong to host-owned projects, so no routing exception was needed.
node scripts/check-changed.mjs --staged --base 689bda012dae1fd39862098df4e3393590be89c5 --timedran for 1,888.07 s and failed at inherited Knip findings:GoogleMeetJoinResult(extensions/google-meet/src/transports/types.ts),resolveGatewayWorkboardWorkspaceAccess(extensions/workboard/src/gateway-helpers.ts) andMeetingRuntimeOwner(src/meeting-bot/runtime-facade-types.ts). The exact production Knip command reproduced all three on clean base689bdain 389.59 s. All preceding guards and core plus 27 test type graphs passed; every remaining native check after Knip was run and passed. Subsequent corrections passed affected types, lint and ratchets. The inherited findings are left visible and untouched.Plugin SDK diff against the pinned base: 179 exports affected transitively (
reachable), 17 unique reachable declaration diffs, zero direct export declaration/signature changes and zero entrypoints added or removed. The changes add optional async/lifetime/authority fields; released synchronous receipt, recorder and question contracts remain intact. Reviewed digest:f1d50ae1. The command and native temporary-worktree cleanup completed successfully in 985.9 s.The real transcript boundary failed before the cutover with 264 caller-thread SQL observations, then passed with zero after it. These observations include preparation and execution and are separate from the statement-count benchmark. The workspace steering regression also failed on the earlier candidate with an erroneous source terminal result and passed after the settlement repair. Existing browser ACL/lifecycle expectations remain intact; restoring access cannot revive refused input.
Codex P2 review is clean for the full change and the final corrections, including final test bytes. Madge initially found a cycle through a state-database facade; importing the existing leaf contract corrected it. Review and regression work also repaired ordered-read reentry and foreign-store metadata authorization: negative controls fail on the preceding implementation, while current-source tests pass. The final committed tree matches the reviewed and tested tree.
Original measured candidate production: +791 / −145 / net +646, 936 changed lines across 33 files. Tests/support: +652 / −92 across ten files; documentation: +11 in one file. Total: 44 files. No changelog edit (release-owned).
Related overlapping work: #165028 (shared source seam), #165205, #165193 (incorporated through the pinned main base), and #162433. This branch uses the existing owners and does not alter another PR branch. Concurrent session, channel, and incognito cutovers may require focused reconciliation by the later lander.