Repository navigation
refactor(conversations): move binding and delivery authority to workers - #166259
Conversation
|
🦞👀 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. |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Codex review: blocked before merge. Reviewed October 7, 2026, 2:52 PM ET / 18:52 UTC (Revision 23). ClawSweeper reviewWhat this changesMoves conversation registration, binding mutations, and delivery authority into existing database workers, batches routing reads, and preserves released synchronous plugin contracts. Warning SQLite table change This PR modifies persisted SQLite tables in Merge readiness⛔ Blocked before merge - 3 items remain Current main does not cover the central worker cutover, so this PR remains useful. The previous size-limit finding is resolved, and no new blocking correctness defect was found; repaired-head performance qualification remains incomplete. Priority: P2 Review scores
Verification
How this fits togetherConversation routing connects discovered channel addresses to agent sessions. Database workers supply current bindings and delivery receipts, while the Gateway checks live routing authority before handing messages to channel adapters. flowchart TD
A[Discovered channel addresses] --> B[Conversation registration worker]
B --> C[Conversation and session records]
D[Current bindings and configuration] --> E[Live routing authority]
C --> E
E --> F[Platform send handoff]
F --> G[Delivery receipts and recovery]
Before merge
Agent review detailsSecurityNone. PR surfacePR surface statistics unavailable: the file list is incomplete. Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep the existing worker and admission owners, preserving live revocation checks and released selectors while eliminating the measured singleton overhead. Do we have a high-confidence way to reproduce the issue? Not applicable to this refactor as a bug reproduction. The body records a deterministic pre-repair SQL regression and a failing negative-control test, but current-head workload qualification is pending. Is this the best way to solve the issue? Yes: extending the existing worker and admission owners is the maintainable direction, and the inspected repair retains freshness and final-effect checks rather than bypassing them. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 94fc0814ef64. 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
HistoryReview history (22 earlier review cycles; latest 8 shown)
|
Merge current main into the conversation binding worker cutover without rebasing. Preserve the binding singleton cleanup, live adapter authority, both worker-test inventories, and main's interrupted recovery fixture semantics. Keep released synchronous binding selectors source-compatible with a focused type assertion, and correct stale migration guidance identified during review.
Merge main with the MCP SDK advisory fix and current session/worktree owners. Retain both worker test-routing inventories and the conversation binding cutover. Fresh P2 review is scoped-clean; affected type, behavior, and all-thread SQL comparisons are being refreshed for this integrated source.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
5 upstream commits, including openclaw#166690 (consolidate embedded runner execution paths) and openclaw#166259 (move binding and delivery authority to workers). Four conflicts, all in the embedded runner, plus two semantic breaks: - compact-reasons.ts: upstream turned the reason if-chain into a COMPACTION_TEXT_REASONS table. The feature's "unknown_model" rule is now a table row in its original position, and the table is typed with the feature's CompactionReasonCode (upstream has no such union). - run/attempt-tool-prepare.ts: upstream rewrote the tool-construction IIFE as an if-block. The feature's whole delta in that hunk (skillsSnapshot, disableContinuationTools, continueWorkOpts, requestCompactionOpts, drainsContinuationDelegateQueue) is re-applied at the same anchor. - run/run-attempt-dispatch.ts: both imports kept. - run/payloads.ts: upstream now builds an array of parsed reply directives. The feature's multi-hop split moves into that array: when the raw answer holds an earlier continuation signal and more than one non-empty hop, each hop is parsed into its own directive item (whitespace preserved as before). Otherwise the result is upstream's single canonical directive, the same result as the old single-text path. - session-delivery-queue-storage.ts (semantic): openclaw#166259 removed the synchronous getDeliveryQueueEntryStatus. The feature's ackSessionDelivery idempotency check now reads the receipt through upstream's inspectDeliveryQueueReceipt with the same stateDir. - delivery-queue-test-support.ts (semantic): loadDeliveryQueueEntry now lives in upstream's delivery-queue-sqlite.test-support.ts. Checks, all on the canonical runner: - Typecheck: core, plus test shards agents-embedded-runner, agents-embedded, agents-other, infra, messaging-auto-reply, gateway-methods, gateway-server, gateway-other, commands and extensions-test, all clean. - Tests: payloads*, compact-reasons*, attempt-tool-prepare*, run-attempt-dispatch*, session-delivery-queue* and the embedded-runner continuation suites, 31 files, all green. - Ratchets: assertion-safety and database-worker both OK. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Jhynq2GVpzuVQQieebEubg
…cated Merging upstream 030003c combined two imports of messageToolOutcome in delivery-dispatch.double-announce.test.ts: ours from the feature's double-announce.test-support module, and upstream's from delivery-dispatch.test-fixtures (openclaw#166259). The file failed to parse ("Identifier `messageToolOutcome` has already been declared"), which surfaced as Mode-B 37676831899's line-cap ratchet failure. The two helpers are byte-identical, so the feature's copy is removed and upstream's fixture is used. The feature's delivery-outbound.runtime passthrough mock (which wrapped the real sendDurableMessageBatchCore, with no assertion on it) is dropped. The file passes 84/84 without it, and the change keeps the file within its line-cap baseline. 84/84 under scripts/run-vitest.mjs; services-cron test typecheck shard clean; oxlint and conflict-marker checks clean. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Jhynq2GVpzuVQQieebEubg
…rs (openclaw#166259) * refactor(conversations): move binding and delivery authority to workers * fix(conversations): settle cancelled preparation and route worker tests Keep awaited origin binding preparation inside chat admission cleanup so an abort before persistence retires the admitted run. Reuse the Kysely owner for JSON tuple expansion and assign database consumers to their host-owned test projects without duplicating coverage. The repaired Goal and attachment cases pass, along with binding, registry, query, close-order, and tooling checks. Retain the first-call MCP request timeout for separate investigation from the corrected missing-broker failure. * fix(conversations): release borrowers when writer admission refuses Clone request inputs before capturing database ownership and release the borrowed executor around the complete writer admission. Preserve outcome-unknown handling after dispatch and release before awaiting transport settlement. Four real queue/input refusal regressions failed before the fix. The complete registry suite, focused types and lint, line-cap checks, Madge, and P2 review pass. * perf(state): reuse admitted content versions and join startup recovery * test(worktrees): await allocation readiness without polling * perf(conversations): reuse freshly admitted binding rows * refactor(state): consolidate admitted cache lookup
What Problem This Solves
Conversation discovery, binding mutations, and delivery recovery execute SQLite work on the Gateway thread and repeat reads for every discovered address.
User Impact
Moves this work to the existing database workers and batches address registration and binding inspection while preserving routing, delivery receipts, live revocation checks and released SDK signatures. No new service, schema, configuration, environment name, retention policy, or user action is introduced.
Why This Change Was Made
The agent executor owns conversation rows; the shared-state worker owns current bindings and delivery recovery. Registration batches return the listing in the same request. Mutations compare expected ownership against transaction-local rows, and listings refresh every requested session after expiry-pruning waits. Main's canonical shared-worker
writeoperation owns binding mutations; the duplicate transaction context was removed during integration with #166444.The final conversation check surrounds the concrete platform-method handoff. Revocation before initiation prevents the send; the database transaction and FIFO release before transport settlement. Accepted work is joined, and an uncertain native settlement never authorizes replay. Slack supplies an optional batch route preparer while retaining its scalar resolver for older supported hosts.
Released synchronous selectors remain compatible with v2026.9.8 and v2026.10.1-beta.1, including
getConversationSession, binding service/manager selectors, and synchronous authority guards. Deprecation recordconversation-binding-sync-mutationsretains its next-Plugin-SDK-major removal gate; type assertions cover these contracts. Registration already returned a Promise and is not reachable through released SDK exports, documented subpaths, orapi.runtime.*.Short, indexed reads of other owners' binding state remain inside routing grants to preserve immediate revocation checks. Follow-up debt:
src/gateway/conversation-route-ownership.ts:284,326,346, viasrc/infra/outbound/session-binding-service.ts:399. Same-owner conversation facts come from the worker transaction. The compiled-wrapper inventory and import closures are checked.Evidence and Current Readiness
Published candidate:
69d5f7a5ad7aa9bf2f2873896a20c65c4ac2570e, treef7b603fc87d72e2a4ef9bdb32177b72f95175adb. Main3856df48f5c953b26d17938b6888dfa2f3fa826dwas integrated through merge commitsfbd403d26c970and2f53a69c274f5, resolving real conflicts with #166621 and #166659. The final repair retains all four live authority checks and reuses serialized binding rows only after the existing read owner freshly confirms the same schema, foreign-commit and local-mutation revision. Expiry and returned objects are evaluated afresh; write transactions, pinned snapshots and authorizer-controlled reads bypass the bounded cohort. The read callback now consumes the admission's existing scope, adding no extra freshness probe.The final correction
69d5f7a5ad7amoves the cached-map lookup into the existing admission owner and usestoReversed()in the regression test. It resolves the normal lint diagnostics without changing row reuse or authority semantics. Five-file local lint passes (27.39 s), 52 focused tests across four files pass (188.74 s), core types (29.29 s) and core-test types (424.93 s) pass, and a fresh P0–P2 review is scoped-clean. Earlier import-closure and zero-cycle proof remains applicable; no imports changed in this correction.Merged through native
scripts/pras699a3c58bf28512d6b46a48f6f13447457a10172at 2026-10-07 19:08:30 UTC. Exact-head CI 37669251529, required gates, SQL qualification, local SDK diff and completed ClawSweeper review all passed admission. No admin exception or security waiver was used. The reviewed head was69d5f7a5ad7aa9bf2f2873896a20c65c4ac2570e; the landed commit is verified on main. Historical failed counts and checks below remain explicitly attributed to their source heads.Qualified final-head all-thread SQL comparison (
69d5f7a5/3856df48)One unchanged alternating main/candidate comparison completed all six full workloads and focused probes on isolated Linux through native Crabbox (
run_4113ce0bc6a9f33b0e22b953e76a0b79). All 19 harness/probe hashes are unchanged. The earlier6ddlint attempt executed zero measurements. Functional assertions pass and all phase duration ratios satisfy the 1.5 limit; first-turn, warmed-total and combined compaction/shutdown ratios are 0.9942, 1.0010 and 1.0012. The lease stopped and all owned remote processes, worktrees, proof/payload files and archive links were removed after verified download.Compaction's standalone +38 median is existing background work moving across the adjacent shutdown boundary. Memory publication remains exactly 53 statements per workload: main compaction/shutdown splits are 0+53, 0+53 and 53+0; candidate splits are 53+0, 0+53 and 13+40. Plugin compare-and-apply remains exactly 56 statements per combined window. Both sources retain one memory attach, 117 create statements and 28 drop statements there. Content-marker reads decrease from 19 to 12. Every pair's combined count is equal or lower, so the median gate passes without a rerun or changed window.
All 38 positive combined full-stack variants have baseline native-site witnesses. Ten require the explicitly inspected
cacheAdmission.refresh→readmethod mapping; both call the same byte-identical freshness primitive, and the new helper carries its existing scope through the reader instead of issuing another probe or worker request. Twenty-seven complete caller chains differ, so this is not a claim of identical full stacks. No new shutdown operation or per-item settlement loop was introduced.Raw failures remain separate: main 0 / 0 / 0, candidate 1 / 0 / 1, all shutdown-only
BEGIN IMMEDIATElock refusals. Repetition 1 is the coordinator-classified synchronous restart-intent SIGTERM path (see #166528 citation below); repetition 3 is the existing audit-prune retry path. Those restart/audit modules and the native freshness primitive are byte-identical to the baseline. Every functional workload and graceful close completed; no failed attempt is counted as successful SQL or used as an inherited-CI exception.The exact-head local SDK report passed in 273.86 seconds including cleanup and is byte-identical to the
6ddreport: digest81e882f7dc4aa3713539ae66298013ba7d936bacd835abd37b75cd25b25f489e, 195 affected exports, unchanged named declaration deltas, and no entrypoint changes. ClawSweeper completed this exact head at 2026-10-07 18:52:43 UTC, run37669430627, with no actionable correctness or security finding; its prior size finding is resolved and its requested SQL/SDK qualification is supplied here. Inspected code introduces zero configuration options, defaults, schema versions, persisted formats or retention changes; the automatic config/schema path warning does not identify an actual compatibility change.The repair passes 180 focused tests across 14 files, covering binding queries/mutations, live route authority, Slack, shared read admission and snapshots, runtime build graph and import closures. The initial grouped run took 419.94 seconds; one accidental three-read assertion in a separate single-read fixture was corrected and the complete six-test file passed in 17.80 seconds. The new regression itself passed in 261 ms and independently failed on the published pre-fix code (three domain selections versus one; 74.91-second cold negative-control run). It proves three fresh probes still occur while row selection is reused, plus foreign/local changes, expiry and returned-object isolation. No production failure, assertion weakening, sleep or timeout change was involved.
Core types (19.01 s), core-test types (326.38 s), zero-cycle Madge (28.07 s), formatting and diff checks pass. Independent P0–P2 review of the repair is scoped-clean with full revision/read-owner context; the unchanged preceding PR delta retains its clean full review. The preceding integration passed 285 tests across 30 files and its extension/root-test type lanes. Its eight-file lint passed on isolated Linux in 55.21 seconds after a local declaration prerequisite timed out at its normal 300-second budget. The changed files now receive their own normal-budget Linux lint gate with the new measurement.
CI 37666853036 on
6ddf09c7failedcheck-lint-core-2for the test's copied-array.reverse(). Its cache-owner file-size warning was also a hard error in the focused lint gate. Both are PR-caused and corrected by69d5f7a5; the failed job log was retained once, and no old job was rerun. The isolated6ddf09c7attempt stopped at lint before any workload or probe; its resources were cleaned up. The new source receives one SQL-only comparison after passing lint locally.Pre-fix CI 37661862312 and its required gate passed on
2f53a69c, with no failed or cancelled checks. This is prior-head evidence, not current-head CI; no admin exception is requested.The local SDK report for
6ddf09c7passed in 275.57 seconds including cleanup, digest81e882f7dc4aa3713539ae66298013ba7d936bacd835abd37b75cd25b25f489e. It has 195 affected exports (193 reachable plus two equivalent aliases); the one additional reachable export,agentCommandFromIngress, has an identical declaration and a changed dependency-closure hash. All named declaration deltas match2f53a69c; no entrypoint changes or new SDK incompatibility were found. The final correction report is complete and identical, as recorded above.The pre-fix local SDK diff passed in 1,161.75 seconds including cleanup, digest
a3fe4eba188b005ae11b6bd294193d14030d1ef6cf93022823477d45be70cd01: the same 194 affected exports (192 reachable and two equivalent aliases), no entrypoint additions/removals or newly affected exports. Its sole changed declaration delta moves optionalwithDirectAdapterHandoffinto sharedOutboundChannelContextwith the same signature. The repair changes no released function signature; its exact-head report is complete, as recorded above.ClawSweeper's durable review completed the pre-fix
2f53a69cat 2026-10-07 17:56 UTC, run37662062194, with no actionable correctness or security findings. The final-head review is complete, as recorded above. The automatic SQLite-table/config compatibility warning is a path-classification false positive: there is no DDL, version, persisted-table, stored-format, configuration or default change. The detailed review also confirms unchanged formats.Pre-fix integrated SQL comparison (
2f53a69c/3856df48)One unchanged alternating main/candidate comparison completed all six full workloads and paired focused probes on isolated Linux. All 19 harness/probe hashes are unchanged. Functional assertions pass, every phase's candidate/main median duration ratio is at most 1.5, and the owned remote lease and scratch were stopped and removed. Successful statement totals include all threads and processes; failed attempts remain separate.
Shutdown's standalone deltas are −2 / +106 / +6. Their exact attributed components are lease/integrity close −2 / −14 / −2, memory sync/publication 0 / +80 / 0, shared-state/schema admission 0 / +32 / 0, restart-intent admission 0 / +10 / 0, and audit writer 0 / −2 / +8. The +6 median is the existing audit retry's +8 offset by close's −2. All 24 positive combined full-stack variants map to native SQL sites present in baseline across all threads; the
clean_closeupdate moves between main and worker threads while retaining exactly one statement per workload. All 18 direct shutdown, memory, audit, lease and admission owner modules are byte-identical. The combined window decreases in every pair and by median; no new shutdown work is introduced.That pre-fix candidate repetition 2 records two failed synchronous SIGTERM restart-intent attempts, matching the coordinator's inherited classification and #166528 baseline citation below. Repetition 3 also records one audit-prune lock refusal through the unchanged existing retry path. Failed attempts are retained separately; every workload and graceful close completed. No failing attempt is counted as successful SQL or used as an inherited CI exception.
The singleton regression is deterministic authority-inspection overhead, not timing noise. Candidate uses four live binding inspections: initial registration selection, transaction admission, commit admission and final list filtering. Each costs one
PRAGMA data_versionplus one batched selection, giving eight host statements plus five worker statements. Main uses two inspections plus one host registration insert: generic absent-row lookup costs seven host plus five worker statements; bound/Slack exact-hit lookup costs five host plus five worker statements. No empty-batch or additional worker-request cost was found. A scalar shortcut does not help because the scalar inspector already delegates to the batch owner. Removing only the redundant transaction-stage domain inspection would leave 11 total statements, still above bound/Slack main's 10. Initial filtering, pre-commit revocation and post-await response filtering protect distinct observable contracts; no guard was removed. The new repair reuses freshly qualified row bytes instead of removing authority checks; its measurement is pending.Last qualified all-thread SQL comparison (
e7b564ca/af18444d)One unchanged alternating main/candidate comparison ran six full workloads and paired probes on isolated Linux. All functional assertions and focused receipts pass. Statement totals include Gateway main, workers and helper processes; prepares and failed attempts remain separately reported.
Every warmed-turn position has a lower median. The first warm pair's +15 remains in the record: two extra retention aggregates add 41 helper statements while worker statements decrease 26. It does not fail the median gate. Second-session's +1 median is below the 2% allowance: maintenance plan snapshots vary from [14,8,8] to [8,13,13], and age snapshots from [24,14,15] to [14,24,23]. These are existing maintenance operations, including their transaction/freshness/publication work. Cron's positive third pair similarly has two extra current-projection transactions and one additional plan/age snapshot; its phase median decreases.
Shutdown's standalone +64 median is timing-dependent placement of existing work. Main performs all 53 memory-publication statements during compaction; candidate performs [2,0,53] there and [51,53,0] during shutdown, exactly 53 total per workload. The three-statement plugin compare-and-apply tail also moves from compaction into shutdown. Both owners already join their accepted work at close.
All nine positive complete-stack variants resolve to native SQL sites present in baseline's combined window: lease-path selection, transaction BEGIN, capture retirement BEGIN/ROLLBACK and busy-timeout handling. Seven full caller chains differ because lease verification uses an alternate existing release branch and direct/service-assisted transaction or timeout branches trade places between idle close and restart-intent consumption. This is not a claim that all full stacks are identical. The source-bound comparison finds no new SQL site, shutdown owner operation, or per-item settlement loop; all affected owner modules are unchanged. The complete combined window decreases in every pair and at its median.
Known shutdown diagnostic and campaign follow-up
Candidate repetition 3 has two failed
BEGIN IMMEDIATEattempts throughclearGatewayRestartIntentSync→consumeGatewayRestartIntentPayloadSync→onSigterm(database is locked); all graceful closes complete. The coordinator classified this as the pre-existing synchronous restart-intent write at SIGTERM using PR #166528's main measurements, which recorded shutdown-only lock refusals [2, 0, 2]. Keep the synchronous restart-intent/active-writer contention as a campaign follow-up; it is not changed by this PR. The unchanged counting contract reports failed attempts separately from successful statements. No non-shutdown or focused execution failure occurred.Integration and Retained Failure History
Overlap was integrated with merge commits, preserving both owners: session authority #165370, native creation #165819, schema admission #166253, Board reads #166403, integrity retention #166412, worktree ownership #166236 and placement lifecycle #166444. Incidental cleanup overlap #166427/#166439/#166560/#166566/#166621/#166659 is preserved. The latter integration retains main row normalization, transaction helper, consolidated native read capability and shared outbound context. The native account adapter keeps its specialized worker mutation boundary because the public adapter factory does not carry the private expected-row predicate through its scalar unbind callbacks; no public helper signature was expanded. The row encoder removed by main stays removed; the malformed/legacy-row fixture now writes its intentional physical rows independently, with unchanged assertions. The adjacent preflight lane #166252 remains coordinated through main. Source-map and MCP SDK advisory fixes came from main, including #166217; this PR does not patch dependencies.
The previous
565c6ad6CI run failed the unchanged one-second branch-graph timing assertion at 1153.279 ms. Five exact merge and five exact base whole-file runs pass 17 tests each on Node 24.19.0. Its cause remains unresolved, and passing controls do not prove a repair or qualify an inherited-CI exception. No old CI rerun was requested; required conflict integration produced later green CI; the current head has its own passing run linked above.Earlier independently reproduced main defects were repaired and integrated: terminal font fixture types (
1d10375ee563, published via1b395594318b), Gateway teardown admission ordering (4ed39a25f674), and requester sharing authority (f6e6805b99b7, published through96ccec4a1385). Their original failures, negative controls, focused proof and reviews are retained in the landing evidence. Requester failure reproduced in all five base and five merge runs before repair; 121 positive scoped tests pass after it.Earlier PR fixes include Goal/admission cleanup and routing (
c8a16c077e0c), borrower release and input cloning (dc08d2168718), admitted content-version memo and parallel startup (718b382179e0), and capacity readiness proof (9a3da8b04a965). Live-authority, foreign-commit, rollback, pinned-snapshot and unknown-settlement safeguards remain. Historical per-sample/standalone-phase failures remain recorded; the current disposition uses the coordinator's clarified median and adjacent-window rule, not erased counts or selected reruns.