Skip to content

feat(cli): create the shared state database before the first Gateway start - #167546

Closed
xyrolle wants to merge 1 commit into
openclaw:mainfrom
xyrolle:feat/database-init
Closed

xyrolle wants to merge 1 commit into
openclaw:mainfrom
xyrolle:feat/database-init

Conversation

@xyrolle

@xyrolle xyrolle commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Related: #167545

Draft proposal awaiting the design answer in the linked issue. It adds a public CLI contract on the state database and should not merge before that answer. I am happy to rework it toward the preferred interface.

What Problem This Solves

A container image that provisions the operator's own devices before first start has no command that only creates the shared state database. Doctor against the retired devices/paired.json format covers the approval workflow today, but also repairs config and other state.

User Impact

Operators can run openclaw database init --json to initialize absent, empty, or recognized native-bootstrap state and get its path, schema version, and created/found status. Repeating the command preserves current database contents. Older, newer, or incompatible mature state is refused with repair/version guidance and exit status 1.

The command only creates storage. It does not make direct approval-row writes a supported interface; devices approve still needs a pending request. Doctor remains the supported offline import route. The design question is whether storage initialization alone is useful enough to add, or whether a supported offline approval command is preferable.

Leave the database path absent for a new installation. A file that already exists, even empty or partly initialized, follows the Gateway's existing-state policy and lacks the Doctor-owned deletion-history table. State selection uses the process environment and --profile; the database command does not load dotenv files.

Why This Change Was Made

database already owns the schema and write-ownership commands, so the subcommand lives there and loads the state module only in its action. It goes through the opener the Gateway uses, with one new internal flag: when the file already holds mature state, the opener validates it and returns before the writable setup and schema convergence an ordinary open performs. Fresh state takes the existing bootstrap path, so the result is the database an ordinary open would have created. The command closes its own handle and does not record migration completion, change config or workspaces, issue credentials, or start a Gateway or plugin runtime.

I did not build it on withOpenClawStateStartupMigrationCheckpointDatabase, which also creates a fresh database: on older state that path can add its checkpoint tables or indexes before the caller sees anything, and this command has to refuse older state untouched. With schema version 19 and the lease-owner index removed:

[checkpoint-connection] bytes identical: false; idx_state_leases_owner present after: 1; user_version: 19
[init] bytes identical: true; idx_state_leases_owner present after: 0; user_version: 19

The verb follows openclaw storage init: create when absent, verify when present. Two simultaneous initializers may both return created; schema changes remain serialized by the existing maintenance owner.

No schema or version bump, dependency, SDK export, Gateway startup change, or changelog edit. The main risk is the new public operator contract on database admission, which awaits the linked design decision. Updates retain the existing Doctor migration path; this command refuses mature state that needs migration.

Evidence

A real Gateway built from this change accepted the synthetic approved device on its first connection after either Doctor or initialization plus a direct test insert. All scenarios used the same signed cli/cli client, operator.read, loopback token authentication, and autoApproveLocal: false.

The initializer scenario inserts one approval row directly after init, because devices approve needs a pending request. That insert is test setup, not something this PR proposes to support. Today's behaviour on main uses the same build with unchanged Gateway and pairing code, a legacy file, and no Doctor or initializer. It differs in two inputs, so it does not isolate the command.

First connections and shutdowns, verbatim
{"scenario":"doctor","firstConnection":{"accepted":true,"protocol":4,"scopes":["operator.read"],"attempts":1}}
{"scenario":"doctor","gatewayExit":0}
{"scenario":"init","firstConnection":{"accepted":true,"protocol":4,"scopes":["operator.read"],"attempts":1}}
{"scenario":"init","gatewayExit":0}
{"scenario":"todays-behaviour-on-main","firstConnection":{"accepted":false,"name":"GatewayClientRequestError","code":"NOT_PAIRED","message":"device pairing required (requestId: ef385870-402e-444f-9705-f22f5ca98d7a)","attempts":1}}
{"scenario":"todays-behaviour-on-main","gatewayExit":0}

All three Gateway logs show startup.maintenance.pairing completing:

2026-10-09T03:54:01.706+03:00 [gateway] startup trace: startup.maintenance.pairing 8.5ms total=7101.1ms eventLoopMax=0.0ms
2026-10-09T03:54:09.115+03:00 [gateway] startup trace: startup.maintenance.pairing 9.4ms total=5778.4ms eventLoopMax=0.0ms
2026-10-09T03:54:14.884+03:00 [gateway] startup trace: startup.maintenance.pairing 5.5ms total=4953.9ms eventLoopMax=0.0ms

The initializer created 101 tables, with only the primary row in schema_meta. A second run returned found and preserved database and config bytes. Also run through the built CLI: zero-byte initialization; --profile path selection; older, newer, incompatible, and externally owned database refusal with exit 1 and byte-identical preserved databases.

The supported alternative was measured on the same fresh directory, reset to the same inputs before each command:

Command Run Wall User CPU System CPU Total CPU
doctor --fix --non-interactive 1 6.58 s 4.88 s 1.38 s 6.26 s
database init --json 1 0.63 s 0.67 s 0.13 s 0.80 s
doctor --fix --non-interactive 2 5.85 s 4.93 s 1.50 s 6.43 s
database init --json 2 0.58 s 0.68 s 0.13 s 0.81 s
doctor --fix --non-interactive 3 4.70 s 4.29 s 1.16 s 5.45 s
database init --json 3 0.60 s 0.68 s 0.13 s 0.81 s

Doctor's five-to-seven-second cost is modest. It imported the approval, archived the retired file, changed config, created backups and a recovery capture, and left rows in nine tables plus temporary lease activity. The initializer took about 0.6 seconds, created only the database file, and left config and the legacy file unchanged. It does not import or approve the device. Neither route left state-migrations or startup-migrations rows; Doctor additionally wrote its shared-auth migration ledger. The official container entrypoint already runs Doctor, which weakens the case for another command solely for this workflow.

Bundled plugins were disabled. Doctor exited 0, but this structured-health warning limits the health-check evidence:

│  doctor:structured-health-repairs run failed: Unable to resolve bundled  │
│  plugin public surface memory-core/doctor-health-api.js                  │

Focused tests exercise real database admission, native-bootstrap row preservation, ordinary-opener equivalence, and refusal without changing existing bytes. They cannot pass on b2d00be5, where the new function does not exist.

Test file Tests Sum of case durations pnpm test <file> --maxWorkers=1 wall time
src/state/openclaw-state-db-init.test.ts 8 0.373 s 8.40 s

The file uses one template for five mature-state cases, reducing full schema creations to four including native-bootstrap coverage. The 0.373-second sum is below the under-five-second target. Byte-preservation assertions use byte equality instead of deep object comparison. About 3.8 seconds of wall time was compiled-worker preparation and cache validation. No Gateway boots, timers, polling, or worker configuration were added. CI seconds are pending.

The unchanged startup-preflight availability suite also passed: 5 tests, 9.260 seconds summed case time, 28.85 seconds wall time.

  • pnpm build exited 0; the Gateway runs used that build. It printed an existing startup-JavaScript size advisory.
  • pnpm check:docs, lint on the changed files, and git diff --check passed.
  • Broader checks are not green. The last pnpm check passed guards and typechecks, then stopped at ten max-lines errors in untouched files; those same ten reproduce on b2d00be5 without this change.
  • The last pnpm check:changed passed formatting, guards, and typechecks, then failed the unused-export scan on ClientVoiceToolEffect in src/talk/client-voice-session-store.ts, also reproduced on b2d00be5. These broader checks have not been rerun for this final revision.
  • Independent review of the final revision and CI are pending before this draft is ready to merge.

…start

Add `openclaw database init [--json]`: create an absent, empty, or recognized native-bootstrap shared state database through the canonical opener and report its path, schema version, and whether it was created or found. Mature state that is older, newer, or incompatible is refused unchanged. The command records no migration completion, changes no config or workspace, and starts no Gateway or plugin runtime.
@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 docs Improvements or additions to documentation cli CLI command changes size: M labels Oct 9, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 9, 2026
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

Adds openclaw database init [--json] to create fresh shared state or validate existing state without migrating it.

Example: Run openclaw database init --json with OPENCLAW_STATE_DIR=/tmp/provisioning and no existing database.

  • Before: There is no storage-only database initialization command.
  • After: The command creates /tmp/provisioning/state/openclaw.sqlite and reports its path, schema version, and created status; another invocation reports found.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused patch has supplied entry-point evidence and no definite introduced finding, but its partial provisioning scope and unresolved product direction prevent adoption.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The contributor records built-CLI fresh initialization, repeat-run byte preservation, profile selection, unchanged refusal cases, and a subsequent real Gateway connection using synthetic approval setup; inspected node-update screenshots belong to linked historical work and add no initializer coverage.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Needs a maintainer decision · Fix scope: Partial
User problem: Container operators want to provision their own devices before first start without relying on retired-file import and Doctor's broader repairs.
Reason: Storage creation does not supply supported offline device approval, and neither the paired discussion nor recorded maintainer decisions approve this additional public contract.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep this PR open pending the paired provisioning design decision; the focused implementation has no definite introduced defect, but storage initialization alone only partially addresses the requested workflow.

Priority: P3
Reviewed head: bfda273e8f60c26d686f081f12b64e1daed28f4c
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should pre-start device provisioning retain Doctor's import route, gain a supported offline approval operation, or independently expose storage initialization?
  • Recommendation: Document Doctor as the supported interface: Keep the working import route and clarify its supported provisioning contract before adding another command.
  • Why: Doctor already enables the reported workflow, while the proposed initializer leaves approved-device provisioning unsupported without direct database writes and explicitly awaits an owner decision.

Before merge

  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

None.

Agent review details

How this fits together

The database CLI resolves the operator's state location and delegates admission, schema bootstrap, ownership checks, and handle cleanup to the existing shared-state database owners.

flowchart TD
  A[Operator CLI] --> B[Database command]
  B --> C[Shared state admission]
  C --> D[Fresh schema bootstrap]
  C --> E[Existing schema validation]
  D --> F[Close handle and report result]
  E --> F
Loading

Technical review

Best possible solution:

Choose a supported pre-start provisioning interface through the existing pairing and storage owners before adopting a separate storage-only CLI contract.

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

This is a feature proposal rather than a demonstrated startup defect; source and supplied traces corroborate the existing Doctor route and the absence of a storage-only CLI command.

Is this the best way to solve the issue?

The implementation narrowly reuses existing admission and bootstrap owners, but its value depends on whether storage initialization has an independent supported use beyond offline device provisioning.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Canonical fresh and native bootstrap keeps the original intent (a5d67c6: Initialize recognized fresh/native state canonically before checkpoint DDL to avoid partially initialized databases being treated as legacy.)
  • Existing-state admission without automatic repair keeps the original intent (3c4c111: Managed replacement runtimes consume compatible existing state without taking over schema or historical repair ownership.)
  • Database CLI lazy loading and passive startup keeps the original intent (9c27ac1: Load database operation runtimes only after the selected action while retaining path, error, and ownership semantics.)
  • Historical row repair keeps the original intent (d314668: Doctor owns historical repairs while runtime admission preserves existing rows and enforces compatibility.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

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

PR surface

Source +85, Tests +176, Docs +34. Total +295 across 8 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 4 88 3 +85
Tests 1 176 0 +176
Docs 3 45 11 +34
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 309 14 +295

Review metrics

Metric Value Why it matters
Public CLI surface 1 new subcommand with a --json output flag Creates an operator-facing storage admission contract without adding a persisted setting or schema version.

Root-cause cluster

Relationship: partial_overlap
Canonical: #167545
Summary: The paired issue owns the provisioning interface decision; this proposal implements only its storage-initialization option.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • remove status: ⏳ waiting on author: Current PR status no longer selects a status label.

Label justifications:

  • P3: This is a nonblocking provisioning improvement with a working Doctor alternative.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Record the chosen provisioning interface in the paired design discussion.

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 execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-09T01:14:47.706Z sha bfda273 :: blocked before merge. :: none

Reviewed October 22, 2026, 4:34 AM ET / 08:34 UTC (Revision 2).

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 22, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Oct 23, 2026
steipete added a commit that referenced this pull request Oct 25, 2026
An explicit cron run reads its authorized job definition and private scratch separately inside a SQLite read transaction. Read both in one dialect-layer LEFT JOIN so they share a statement snapshot, removing three SQL statements per SQLite run without another worker request.

The job reader keeps its all-column authorization relation, ordered narrow projection, exact returned-ID check, existing decoder/config revision and legacy creation fallback. Missing scratch still reports revision 0; deletion keeps its revision tombstone. The standalone maintenance reader remains. No schema, cache, write, receipt, claim-before-effect, delivery authority, FIFO or 64-receipt retention change.

PostgreSQL retains the shared reader's outer read-only transaction and rollback: its exact-job read is 4→3 SQL, not 4→1. SQLite exact-job is 4→1, heartbeat 3→1; PostgreSQL heartbeat remains 3→3. Accepted noncontract edges: an absent/malformed job can now require scratch SELECT privilege, and malformed job plus unsafe numeric scratch can reject the numeric data first. These do not remove the existing caller/source/cancellation checks.

The production delta is +3 lines: one joined query replaces the transaction and duplicate read while sharing NULL handling with heartbeat. Existing test files cover read-after-write, tombstones, missing jobs/monitors and both database engines. No new suite or runner is added.

Acceptance was registered before measurement: the committed `scripts/bench-cron-run.mts` drives signed WebSocket `cron.run` against an isolated synthetic Gateway/provider, once cold and twice warm. Each run must produce one start, one finish, one Responses request and exact-run history verification. Compare execution, history verification and settlement separately and together, plus shutdown and the entire invocation. The scratch owner must fall from 4→1 SQL with 1 request and 0 MAIN throughout; no cost may be deferred outside the run. Keep cold/warm separate and report median/p95/range. Three same-platform alternating pairs when calm, or one pair plus source attribution under campaign load. Counts and profiles make no latency/CPU-speed claim; timing claims require the timing lock, load below 24 and ≥5 alternating samples per arm. A 20% user-facing regression stops acceptance. Delivery mode none does not claim an external-send proof.

The same-platform explicit comparison (baseline 814e732, candidate 93a6c4) gives:

| SQL / requests / MAIN | Baseline | Candidate |
| --- | --- | --- |
| Cold execution + verification + settlement | 257 / 80 / 0 | 254 / 78 / 0 |
| Warm 1 | 247 / 64 / 0 | 235 / 60 / 0 |
| Warm 2 | 252 / 61 / 0 | 245 / 65 / 0 |
| Warm median | 249.5 / 62.5 / 0 | 240 / 62.5 / 0 |
| Warm descriptive p95 | 252 / 64 / 0 | 245 / 65 / 0 |
| Warm range | 247–252 / 61–64 / 0 | 235–245 / 60–65 / 0 |
| Shutdown | 22 / 6 / 5 | 40 / 10 / 5 |
| Whole invocation | 1383 / 356 / 58 | 1369 / 352 / 58 |

Each of the three runs completed one start, finish, Responses request and exact history verification. The scratch owner is exactly 4/1/0 → 1/1/0 in every run, all in its execution phase, with no extra or deferred scratch requests. All execution/verification/settlement phases are SQL-error-free and runtime MAIN remains zero. The count comparison is diagnostic, not an error-free full invocation: the frozen analyzer rejects two failed shutdown `state_leases` DELETEs (`database is locked`). Shutdown exceeds the 20% stop threshold; it was stopped and explicitly accepted by the coordinator as inherited after an independent main shutdown-lock reproduction. The separate SHUTDOWNLOCK lane owns that repair. The scratch join changes no lease code or writes. No latency or CPU-speed claim is made.

The frozen 3.1.5 standard workload is a different scheduled `cron.add` flow: three valid baselines gave 06.cron 231/62/0, 235/65/0, 233/63/0 (median 233/63/0), versus ordinary warm 45/12/0. The descriptive excess is 188 SQL/51 requests, not causal subtraction. One extra standard setup aborted before any Gateway; it supplies no performance evidence. The existing scratch source is identical across that baseline and the explicit baseline. Full current-standard delta is deferred to the next census.

Validation: count regression red on baseline (2 SELECTs and BEGIN/COMMIT), all 17 scratch-store tests green on the candidate; two isolated Codex P0–P2 reviews scoped-clean. The existing two-engine conformance test passed on actual SQLite and PostgreSQL 17, with catalog/trigger parity and cleanup verified. Test cost: scratch cases totaled 6.528 s (125.95 s file duration, mostly transform); the two engine cases totaled 1.846 s (260.62 s file duration, mostly transform). The candidate build and official source-freshness check passed at measured runtime head 93a6c4d; the three-sample invocation completed with the shutdown limitation above. Exact-head CI run 40176443806 completed successfully: 39 successful jobs, 26 skipped, no failures, including all three actual PostgreSQL shards, production/test types, lint, source contracts, Madge, and worker/T1/dialect ratchets. The earlier run passed types, lint and source contracts but found a worker-inventory omission: the new direct query was conservatively labeled T1. Head a187ecf corrects only inventory metadata and regenerates its snapshot: the worker snapshot and its private heartbeat helper are W, while the native Doctor reader stays T3. No runtime or SQL change is involved. The generated snapshot also catches up existing main classifications; targeted script lint and formatting pass. The two production reviews remain valid; this tooling-only correction adds no production review round. PG review approved the semantics at 68c24c4, and the coordinator explicitly carried REVIEW-OK to 93a6c4d because only benchmark TypeScript annotations changed. Candidate counts and the inherited-shutdown disposition are recorded; the corrected head’s CI and all three PG shards passed. The test-only import relocation avoids another open PR's adjacent import change; production bytes remain identical to both isolated reviews and database proof. The benchmark annotations fix CI TS7022 without changing emitted behavior.

Final-head overlap at a187ecf: complete shared-index base-versus-candidate merge-tree comparison covers 21 peers (#183410, #183285, #181057, #180871, #180286, #180139, #169241, #168956, #168615, #167546, #167471, #165039, #161997, #157922, #157693, #156613, #141004, #137788, #136476, #129388, #121204). No new source conflict paths, regions or messages. Six peers (#181057, #180871, #180139, #169241, #129388, #121204) have added or changed conflicts confined to the fully generated worker inventory. The coordinator explicitly accepted this class because main's snapshot was stale and generated outputs must be regenerated, not hand-edited. The same exact-head disposition carries PG REVIEW-OK because runtime bytes are unchanged. Exact-head CI and all three PostgreSQL shards passed.

PG checklist: (1) read-only; existing writer transaction/advisory-lock, DML/conflict and cross-store commit ordering unchanged. (2) At most one joined row via the existing composite primary keys, original job fields plus four scratch fields, unchanged 256 KiB scratch write bound. (3) No cache/generation or invalidation change; one statement snapshot, existing outer PG read transaction retained. (4) No schema/admission/identity/retry/probe change. (5) Same worker owner, one request, no MAIN expansion; target 4→1 SQL in all three real Gateway runs, with the inherited shutdown failure disclosed above. (6) Actual PostgreSQL 17 and SQLite owner conformance passed; all three final-head PostgreSQL CI shards and the other selected static checks passed.

Knip was run separately because ordinary PR CI excludes it. The canonical candidate export scan failed with 26 script, 20 production and 16 full-tree findings; none is in a changed file. All 62 occurrences (52 unique file/symbol pairs), scanner/config/compiler inputs and package inputs are unchanged from merge-base dada70f. The only removed imports, runSqliteReadSnapshotSync and loadCronRows, both retain multiple real production consumers. Current-main diagnostic sections reported 14 script and 7 production findings; main has already repaired 40 candidate occurrences in unrelated changes. Its separate full-tree scan was intentionally stopped after the coordinator accepted the source-attributed inherited findings; it is not a passing full-main scan. No ignored exports, baselines or unrelated code were changed. The failed candidate scan is explicitly accepted as inherited; all branch changes and selected CI static checks pass.

Pre-merge shared-index refresh retains 17 open peers from that audit. Only #180871 moved (f140f16); its fresh base-versus-candidate comparison still adds conflicts solely in the generated worker inventory, within the coordinator-accepted class. No new source conflicts.

Co-authored-by: Peter Steinberger <[email protected]>
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale after 7 days without qualifying human activity.
Without new human activity, Barnacle may close it as not planned 7 days after this message was posted. This is administrative inactivity cleanup, not a claim that the problem is fixed.
A human update restarts the inactivity clock; a new PR head also restarts it. A maintainer can add no-stale for a durable hold, or bad-barnacle to suppress Barnacle. Remove the hold when work can resume.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 26, 2026
An explicit cron run reads its authorized job definition and private scratch separately inside a SQLite read transaction. Read both in one dialect-layer LEFT JOIN so they share a statement snapshot, removing three SQL statements per SQLite run without another worker request.

The job reader keeps its all-column authorization relation, ordered narrow projection, exact returned-ID check, existing decoder/config revision and legacy creation fallback. Missing scratch still reports revision 0; deletion keeps its revision tombstone. The standalone maintenance reader remains. No schema, cache, write, receipt, claim-before-effect, delivery authority, FIFO or 64-receipt retention change.

PostgreSQL retains the shared reader's outer read-only transaction and rollback: its exact-job read is 4→3 SQL, not 4→1. SQLite exact-job is 4→1, heartbeat 3→1; PostgreSQL heartbeat remains 3→3. Accepted noncontract edges: an absent/malformed job can now require scratch SELECT privilege, and malformed job plus unsafe numeric scratch can reject the numeric data first. These do not remove the existing caller/source/cancellation checks.

The production delta is +3 lines: one joined query replaces the transaction and duplicate read while sharing NULL handling with heartbeat. Existing test files cover read-after-write, tombstones, missing jobs/monitors and both database engines. No new suite or runner is added.

Acceptance was registered before measurement: the committed `scripts/bench-cron-run.mts` drives signed WebSocket `cron.run` against an isolated synthetic Gateway/provider, once cold and twice warm. Each run must produce one start, one finish, one Responses request and exact-run history verification. Compare execution, history verification and settlement separately and together, plus shutdown and the entire invocation. The scratch owner must fall from 4→1 SQL with 1 request and 0 MAIN throughout; no cost may be deferred outside the run. Keep cold/warm separate and report median/p95/range. Three same-platform alternating pairs when calm, or one pair plus source attribution under campaign load. Counts and profiles make no latency/CPU-speed claim; timing claims require the timing lock, load below 24 and ≥5 alternating samples per arm. A 20% user-facing regression stops acceptance. Delivery mode none does not claim an external-send proof.

The same-platform explicit comparison (baseline 814e732, candidate 93a6c4) gives:

| SQL / requests / MAIN | Baseline | Candidate |
| --- | --- | --- |
| Cold execution + verification + settlement | 257 / 80 / 0 | 254 / 78 / 0 |
| Warm 1 | 247 / 64 / 0 | 235 / 60 / 0 |
| Warm 2 | 252 / 61 / 0 | 245 / 65 / 0 |
| Warm median | 249.5 / 62.5 / 0 | 240 / 62.5 / 0 |
| Warm descriptive p95 | 252 / 64 / 0 | 245 / 65 / 0 |
| Warm range | 247–252 / 61–64 / 0 | 235–245 / 60–65 / 0 |
| Shutdown | 22 / 6 / 5 | 40 / 10 / 5 |
| Whole invocation | 1383 / 356 / 58 | 1369 / 352 / 58 |

Each of the three runs completed one start, finish, Responses request and exact history verification. The scratch owner is exactly 4/1/0 → 1/1/0 in every run, all in its execution phase, with no extra or deferred scratch requests. All execution/verification/settlement phases are SQL-error-free and runtime MAIN remains zero. The count comparison is diagnostic, not an error-free full invocation: the frozen analyzer rejects two failed shutdown `state_leases` DELETEs (`database is locked`). Shutdown exceeds the 20% stop threshold; it was stopped and explicitly accepted by the coordinator as inherited after an independent main shutdown-lock reproduction. The separate SHUTDOWNLOCK lane owns that repair. The scratch join changes no lease code or writes. No latency or CPU-speed claim is made.

The frozen 3.1.5 standard workload is a different scheduled `cron.add` flow: three valid baselines gave 06.cron 231/62/0, 235/65/0, 233/63/0 (median 233/63/0), versus ordinary warm 45/12/0. The descriptive excess is 188 SQL/51 requests, not causal subtraction. One extra standard setup aborted before any Gateway; it supplies no performance evidence. The existing scratch source is identical across that baseline and the explicit baseline. Full current-standard delta is deferred to the next census.

Validation: count regression red on baseline (2 SELECTs and BEGIN/COMMIT), all 17 scratch-store tests green on the candidate; two isolated Codex P0–P2 reviews scoped-clean. The existing two-engine conformance test passed on actual SQLite and PostgreSQL 17, with catalog/trigger parity and cleanup verified. Test cost: scratch cases totaled 6.528 s (125.95 s file duration, mostly transform); the two engine cases totaled 1.846 s (260.62 s file duration, mostly transform). The candidate build and official source-freshness check passed at measured runtime head 93a6c4d; the three-sample invocation completed with the shutdown limitation above. Exact-head CI run 40176443806 completed successfully: 39 successful jobs, 26 skipped, no failures, including all three actual PostgreSQL shards, production/test types, lint, source contracts, Madge, and worker/T1/dialect ratchets. The earlier run passed types, lint and source contracts but found a worker-inventory omission: the new direct query was conservatively labeled T1. Head a187ecf corrects only inventory metadata and regenerates its snapshot: the worker snapshot and its private heartbeat helper are W, while the native Doctor reader stays T3. No runtime or SQL change is involved. The generated snapshot also catches up existing main classifications; targeted script lint and formatting pass. The two production reviews remain valid; this tooling-only correction adds no production review round. PG review approved the semantics at 68c24c4, and the coordinator explicitly carried REVIEW-OK to 93a6c4d because only benchmark TypeScript annotations changed. Candidate counts and the inherited-shutdown disposition are recorded; the corrected head’s CI and all three PG shards passed. The test-only import relocation avoids another open PR's adjacent import change; production bytes remain identical to both isolated reviews and database proof. The benchmark annotations fix CI TS7022 without changing emitted behavior.

Final-head overlap at a187ecf: complete shared-index base-versus-candidate merge-tree comparison covers 21 peers (openclaw#183410, openclaw#183285, openclaw#181057, openclaw#180871, openclaw#180286, openclaw#180139, openclaw#169241, openclaw#168956, openclaw#168615, openclaw#167546, openclaw#167471, openclaw#165039, openclaw#161997, openclaw#157922, openclaw#157693, openclaw#156613, openclaw#141004, openclaw#137788, openclaw#136476, openclaw#129388, openclaw#121204). No new source conflict paths, regions or messages. Six peers (openclaw#181057, openclaw#180871, openclaw#180139, openclaw#169241, openclaw#129388, openclaw#121204) have added or changed conflicts confined to the fully generated worker inventory. The coordinator explicitly accepted this class because main's snapshot was stale and generated outputs must be regenerated, not hand-edited. The same exact-head disposition carries PG REVIEW-OK because runtime bytes are unchanged. Exact-head CI and all three PostgreSQL shards passed.

PG checklist: (1) read-only; existing writer transaction/advisory-lock, DML/conflict and cross-store commit ordering unchanged. (2) At most one joined row via the existing composite primary keys, original job fields plus four scratch fields, unchanged 256 KiB scratch write bound. (3) No cache/generation or invalidation change; one statement snapshot, existing outer PG read transaction retained. (4) No schema/admission/identity/retry/probe change. (5) Same worker owner, one request, no MAIN expansion; target 4→1 SQL in all three real Gateway runs, with the inherited shutdown failure disclosed above. (6) Actual PostgreSQL 17 and SQLite owner conformance passed; all three final-head PostgreSQL CI shards and the other selected static checks passed.

Knip was run separately because ordinary PR CI excludes it. The canonical candidate export scan failed with 26 script, 20 production and 16 full-tree findings; none is in a changed file. All 62 occurrences (52 unique file/symbol pairs), scanner/config/compiler inputs and package inputs are unchanged from merge-base 71bc695. The only removed imports, runSqliteReadSnapshotSync and loadCronRows, both retain multiple real production consumers. Current-main diagnostic sections reported 14 script and 7 production findings; main has already repaired 40 candidate occurrences in unrelated changes. Its separate full-tree scan was intentionally stopped after the coordinator accepted the source-attributed inherited findings; it is not a passing full-main scan. No ignored exports, baselines or unrelated code were changed. The failed candidate scan is explicitly accepted as inherited; all branch changes and selected CI static checks pass.

Pre-merge shared-index refresh retains 17 open peers from that audit. Only openclaw#180871 moved (f140f16); its fresh base-versus-candidate comparison still adds conflicts solely in the generated worker inventory, within the coordinator-accepted class. No new source conflicts.

Co-authored-by: Peter Steinberger <[email protected]>
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

@openclaw-barnacle openclaw-barnacle Bot closed this Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes docs Improvements or additions to documentation P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M stale Marked as stale due to inactivity

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant