Skip to content

refactor(state): share admitted worker write envelopes - #167552

Merged
steipete merged 2 commits into
mainfrom
dbasync/dslpd1-1
Oct 9, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/dslpd1-1

Conversation

@steipete

@steipete steipete commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Device tokens, restart sentinels, worktree run leases, prepared-pool presence, and diagnostic writes repeat the same worker transaction admission envelope.

User Impact

No user-visible behavior changes. Existing database admission, current-authority checks, physical-store FIFO, rollback, settlement, schemas, and stored data remain unchanged. No migration or operator action is required.

Why This Change Was Made

The shared-state backend already owns the retained writer. Its new writeAdmitted capability preserves pre-BEGIN opening, then delegates the synchronous transaction to that writer with the same transaction and commit grants. Domain kernels, row comparisons, return values, and operation labels stay with their current owners; custom admission protocols retain the existing write path.

Deslop

D1a removes 50 net production lines (67 added, 117 deleted) and 7 net test lines (34 added, 41 deleted), with 0 net support lines (1 added, 1 deleted): 261 changed lines total. It deletes the run-lease envelope module and consolidates six repeated envelopes covering fifteen command registrations. Device-auth tests reuse their existing target fixture and generated database type; all regression names, cases, and assertions remain.

Receipt-producing and custom-protocol callers retain their existing paths. Public SDK contracts are unchanged.

Evidence

Source baseline: 61a5fc58ecce321bc0bb1b224b447f8d446d099e; candidate: 11843b1dd7fd542ce4548c9554dc0e1f9ed038ea.

Focused real-worker proof passed 268 tests across 19 files, plus all four selected foreign-binding context cases. Coverage includes both admission refusals, rollback, physical-store ordering, unknown native settlement, lost replies, and retained-handle close/reopen behavior. No regression scenario or assertion was deleted.

check-changed, production and all test type graphs, core/script lint, Madge (zero cycles), full Knip, the database-worker ratchet, and fresh isolated P2 review passed. Type checks caught two inline fixture contexts missing the new method; both were fixed before the final passing run. Core lint retains two pre-existing max-lines warnings in untouched files.

Test cost: the 19-file focused command with --maxWorkers=1 took 732.96 s including worker preparation. pnpm test src/infra/device-auth-store.test.ts --maxWorkers=1 passed 14 tests in 172.16 s wall / 21.30 s test time; imports and worker-cache verification dominate. The four binding-context cases took 108.93 s wall / 3.63 s test time. CI timing is pending publication.

Three alternating main/candidate SQL pairs completed on the same host with isolated synthetic state, matching harness hashes, and exact revision receipts. The first pair had later-phase duration skew, so two more pairs were added. Raw all-thread medians (including unassigned statements):

Phase Main Candidate Delta Duration ratio
Boot + connect 2585 2585 0 0.558
First turn 2826 2830 +4 (+0.142%) 0.417
Warmed mean / turn 1187.1 1188.9 +1.8 (+0.152%) 0.876
Second session 4029 4034 +5 1.026
Control plane 34 35 +1 1.218
Cron 1286 1287 +1 1.064
Compaction + shutdown 1610 1597 -13 1.116

The strict-turn changes satisfy the campaign's <=0.5% untouched-owner noise exception. Native SQL + normalized stack groups reconstruct the representative median samples exactly: first turn +4, warmed ten-turn window +18. Every positive group belongs to unchanged session maintenance/readers, cron maintenance, ACP metadata, auth snapshot inspection, mention/target discovery, read-only freshness/schema probes, or the unchanged upstream-watch read path. No positive group was unresolved or introduced by the migrated envelopes. For example, warmed session-entry reads contribute +26 statements before offsets, ACP reads +6, and an additional upstream-watch read contributes its existing two admission reads plus its query (+3). First-turn session maintenance contributes +26 before offsets and cron maintenance +8. This is timing/cache variability, not a booked SQL performance improvement.

Boot+connect paired sums are main [2585, 2568, 2608] vs candidate [2727, 2572, 2585] (equal medians). Compaction+shutdown paired sums are [1606, 1667, 1610] vs [1605, 1597, 1589] (lower in every pair); combining these adjacent windows accounts for shutdown timing skew. All reported gate-window duration ratios are below 1.5. The generic request-origin classifier remains indeterminate without a request census; its conservation check passes exactly, and no unassigned statements are omitted from the raw gate above.

Landing verification

The landing review inspected the full diff at 11843b1dd7fd542ce4548c9554dc0e1f9ed038ea and reused the completed P2 review chain, focused worker proof, and three alternating SQL pairs. The migrated paths execute the same admission calls, transaction envelopes, domain SQL, and operation labels. No new OPENCLAW_* names, schema checks, runtime imports, or worker ownership cutovers are introduced.

Released-surface inspection against v2026.10.1-beta.1 and v2026.9.9 confirms that executeSharedStateCommand, WorkerWriteOperationContext, and the removed worktreeRunLeaseOperation are internal: they are not exposed by src/plugin-sdk, api.runtime, or documented plugin subpaths. No released signature changes or compatibility shims are needed. The published-driver planner selects none of the changed paths; existing restart-sentinel and update-result worker coverage passed.

ClawSweeper completed its exact-head review with no findings. CI attempt 1 passed all 15 executed Node jobs and the production/test type checks. Its only root failure was the Madge cycle between src/agents/prepared-model-catalog-fingerprints.ts and src/agents/prepared-model-catalog-worker.ts; the aggregate CI gate failed downstream. Main already failed on the identical cycle. Both cycle files and the scanner/config/dependency inputs are byte-identical between the tested main baseline 3f76fe021990df309bfcd0905030520bb30f81f4 and CI merge b6c4e43392988697b642e9804aeaecdf0dabee4e. Landing uses the explicitly authorized inherited-failure exception, without representing the failed CI gate as green.

The local released SDK comparison (v2026.10.1-beta.1 → 11843b1dd7fd542ce4548c9554dc0e1f9ed038ea) rendered both frozen revisions and produced digest 962d7fc58d6c3b6f5d4b6f07f9182327c42e1ce095c648ac08ffb8e8684e5b4e: zero entrypoints added or removed. Its 1,187 affected exports include changes since the release baseline and conservative declaration-closure changes; this is not a claim of a globally empty release diff. None of this PR's changed internal function/context names appears in an actual SDK export declaration. writeAdmitted occurs only in a whole-module * declaration fallback. WorkerOperations projects each handler's first argument and result, excluding its changed context argument; the migrated handlers preserve those projected contracts. No released signature is broken by this PR.

Reuse the retained shared-state writer for device auth, restart sentinel, run leases, prepared-pool presence and diagnostic commands. Preserve pre-BEGIN admission, synchronous transaction and commit grants, labels, domain checks and settlement. Remove the superseded lease wrapper and reuse existing test fixtures without deleting scenarios.
Keep custom admission explicit in inline test contexts and update the inventory reference after removing the run-lease wrapper. Preserve all scenarios and assertions.
@clawsweeper

clawsweeper Bot commented Oct 9, 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 scripts Repository scripts agents Agent runtime and tooling size: M labels Oct 9, 2026
@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 11843b1dd7fd542ce4548c9554dc0e1f9ed038ea
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/infra/device-auth-store.worker.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 9, 2026
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Consolidates repeated database-worker write permission checks into the existing shared-state writer while preserving domain mutations.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, behavior-preserving simplification with useful recorded worker validation and limited independently inspected runtime evidence.
Proof confidence 🦐 gold shrimp (3/6) This maintainer refactor is outside the external-contributor proof gate. Recorded real-worker validation covers admission refusals and settlement; the body reports Gateway boot, turns, and shutdown at the pinned head, but the inspected images cover unrelated UI behavior. Source confirms unchanged stored-data contracts and no required migration.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes
Reason: The change reduces repeated security-sensitive transaction plumbing within its existing owner. Prior merged area work establishes the direction, and the consolidation preserves current behavior.

Merge readiness

✅ Ready for maintainer review

This PR remains useful: current main retains the duplicated envelopes, and the consolidation preserves existing transaction semantics. No actionable introduced defect was found.

Priority: P3
Reviewed head: 11843b1dd7fd542ce4548c9554dc0e1f9ed038ea

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The reported Gateway SQL campaign lacks an independently inspected runtime trace isolating the migrated write envelopes.
Agent review details

How this fits together

Database workers persist OpenClaw’s shared state away from the Gateway thread. Domain commands obtain current transaction and commit permission, mutate their owned records, and return settled results.

flowchart TD
 A[Domain write command] --> B[Shared database worker]
 B --> C[Open retained database]
 C --> D[Request transaction permission]
 D --> E[Run domain mutation]
 E --> F[Request commit permission]
 F --> G[Commit or roll back]
 G --> H[Return settled result]
Loading

Technical review

Best possible solution:

Keep the common admitted envelope in the retained worker backend, with domain mutations and specialized admission protocols owned by their existing modules.

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

Not applicable: this PR consolidates existing behavior rather than reporting a runtime defect.

Is this the best way to solve the issue?

Yes: the existing worker backend absorbs repeated transaction plumbing without creating a competing owner or changing domain policy.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Preserved write envelope: The shared helper opens before BEGIN, delegates to the retained writer, and requests transaction and commit admission around the synchronous domain mutation. (src/state/openclaw-state.worker.ts:172, 11843b1dd7fd)
  • Existing transaction authority: The unchanged transaction owner validates schema and write authority after BEGIN; the existing admission owner checks live request and database authority before granting permission. (src/state/openclaw-state-db.ts:477, 11843b1dd7fd)
  • Still necessary on current main: The affected production modules are unchanged between the merge base and fetched main. Main still lacks the consolidated envelope; its inventory-script change concerns separate transcript-reader entries. (src/state/openclaw-state.worker.ts:161, b0c330d27df4)
  • Retained-writer provenance: History and the raw parent patch locate the retained write capability in refactor(placement): move lifecycle and grant preparation to workers #166444, whose stated design preserves synchronous transactions, current authority, and accepted-write settlement. (src/state/openclaw-state.worker.ts:162, af18444df4ac)
  • Compatibility and complete cutover: The introduced diff preserves command inputs, results, operation labels, domain SQL, and custom admission paths. No schema, stored format, configuration, or public SDK contract changes; the removed lease wrapper has no remaining runtime references. (src/state/worker-operation-registry.ts:22, 11843b1dd7fd)
  • Validation and review continuity: The complete PR body reports 268 focused worker cases, four foreign-binding cases, and three alternating runtime SQL comparisons at the reviewed head. Token tests retain rotation, ordering, retirement, and read-only assertions. Prior reviews of this same head recorded no findings or published rank-up moves. No target code or tests were executed during this review. (src/infra/device-auth-store.test.ts:267, 11843b1dd7fd)

Likely related people:

  • Peter Steinberger: Raw commit af18444 adds src/state/openclaw-state.worker.ts:161 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: af18444df4ac; files: src/state/openclaw-state.worker.ts)

PR surface

Source -50, Tests -7, Other 0. Total -57 across 17 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 9 67 117 -50
Tests 7 34 41 -7
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 17 102 159 -57

Labels

Label changes:

No label changes.

Label justifications:

  • P3: This is bounded internal maintenance with no intended user-visible behavior change.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-09T01:23:34.209Z sha 11843b1 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-09T01:53:35.312Z sha 11843b1 :: needs maintainer review before merge. :: none

Reviewed October 8, 2026, 10:13 PM ET / October 9, 2026, 02:13 UTC (Revision 3).

@steipete
steipete merged commit 608134e into main Oct 9, 2026
149 of 154 checks passed
@steipete
steipete deleted the dbasync/dslpd1-1 branch October 9, 2026 02:19
@steipete

steipete commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
* refactor(state): share admitted worker write envelopes

Reuse the retained shared-state writer for device auth, restart sentinel, run leases, prepared-pool presence and diagnostic commands. Preserve pre-BEGIN admission, synchronous transaction and commit grants, labels, domain checks and settlement. Remove the superseded lease wrapper and reuse existing test fixtures without deleting scenarios.

* test(state): complete admitted writer test contexts

Keep custom admission explicit in inline test contexts and update the inventory reference after removing the run-lease wrapper. Preserve all scenarios and assertions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts security-sensitive-changed size: M 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