Repository navigation
Conversation
…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.
|
🦞👀 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. What this changesAdds Example: Run
Review scores
ProductKind: Feature · Worth it: Needs a maintainer decision · Fix scope: Partial 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 Decision needed
Before merge
FindingsNone. Agent review detailsHow this fits togetherThe 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
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +85, Tests +176, Docs +34. Total +295 across 8 files. Added test files: 1. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed October 22, 2026, 4:34 AM ET / 08:34 UTC (Revision 2). |
|
This pull request has been automatically marked as stale due to inactivity. |
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]>
|
This pull request has been automatically marked as stale after 7 days without qualifying human activity. |
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]>
|
Closing due to inactivity. |
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.jsonformat covers the approval workflow today, but also repairs config and other state.User Impact
Operators can run
openclaw database init --jsonto initialize absent, empty, or recognized native-bootstrap state and get its path, schema version, andcreated/foundstatus. 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 approvestill 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
databasealready 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:The verb follows
openclaw storage init: create when absent, verify when present. Two simultaneous initializers may both returncreated; 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/cliclient,operator.read, loopback token authentication, andautoApproveLocal: false.The initializer scenario inserts one approval row directly after
init, becausedevices approveneeds 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
All three Gateway logs show
startup.maintenance.pairingcompleting:The initializer created 101 tables, with only the
primaryrow inschema_meta. A second run returnedfoundand preserved database and config bytes. Also run through the built CLI: zero-byte initialization;--profilepath 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:
doctor --fix --non-interactivedatabase init --jsondoctor --fix --non-interactivedatabase init --jsondoctor --fix --non-interactivedatabase init --jsonDoctor'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-migrationsorstartup-migrationsrows; 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:
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.pnpm test <file> --maxWorkers=1wall timesrc/state/openclaw-state-db-init.test.tsThe 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 buildexited 0; the Gateway runs used that build. It printed an existing startup-JavaScript size advisory.pnpm check:docs, lint on the changed files, andgit diff --checkpassed.pnpm checkpassed guards and typechecks, then stopped at tenmax-lineserrors in untouched files; those same ten reproduce onb2d00be5without this change.pnpm check:changedpassed formatting, guards, and typechecks, then failed the unused-export scan onClientVoiceToolEffectinsrc/talk/client-voice-session-store.ts, also reproduced onb2d00be5. These broader checks have not been rerun for this final revision.