Repository navigation
perf(sqlite): fast schema gates, background integrity verification, and downgrade protection - #110271
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e60e31b85c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| agentId: target.agentId, | ||
| pathname: sqlitePath, | ||
| }); | ||
| requireQuarantineCleared(); |
There was a problem hiding this comment.
Clear quarantine only after compact validation succeeds
When doctor --fix calls this path for an agent DB that is already at the current schema, migrateOpenClawAgentDatabaseForMaintenance() is a no-op, but this line still clears the persisted quarantine before compactDoctorSqliteFile() runs its full integrity check. If the later compact/validation fails because the original corruption is still present outside schema_meta, the row and in-process latch have already been removed, so subsequent opens can proceed via the cheap schema_meta check. Clear the quarantine only after the full repair/compact validation has succeeded.
Useful? React with 👍 / 👎.
|
Codex review: needs real behavior proof before merge. Reviewed July 18, 2026, 12:27 AM ET / 04:27 UTC. Summary PR surface: Source +1224, Tests +864, Docs +120, Config +6, Generated +19, Other +111. Total +2344 across 46 files. Reproducibility: no. high-confidence live reproduction is provided in the reviewed material. The source and supplied tests model schema incompatibility and corruption paths, but there is no inspectable real gateway/update/restart transcript for this head. Review metrics: 1 noteworthy metric.
Stored data model Root-cause cluster Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge readiness Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch. Rank-up moves:
Proof guidance:
Risk before merge
Maintainer options:
Next step before merge
Maintainer decision needed
Security Review findings
Review detailsBest possible solution: Preserve fail-closed protection across restart when verification persistence fails—either retain full open validation for that path or introduce an approved durable quarantine design—then provide redacted live proof of updater refusal-before-stop, gateway startup refusal, and repaired-database recovery. Do we have a high-confidence way to reproduce the issue? No high-confidence live reproduction is provided in the reviewed material. The source and supplied tests model schema incompatibility and corruption paths, but there is no inspectable real gateway/update/restart transcript for this head. Is this the best way to solve the issue? No. The cheap-gate and delayed-verifier direction is reasonable, but reducing full open-time validation is not safe until a failed quarantine write has a restart-safe fail-closed behavior. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 2a2e97b96057. Label changesLabel justifications:
Evidence reviewedPR surface: Source +1224, Tests +864, Docs +120, Config +6, Generated +19, Other +111. Total +2344 across 46 files. View PR surface stats
What I checked:
Likely related people:
What the crustacean ranks mean
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics. How this review workflow works
Review history (2 earlier review cycles)
|
…ne terminal open failures
…y integrity in the background
e60e31b to
1cd3595
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1cd35959ac
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } catch { | ||
| // Accepted tradeoff: a locked/unavailable state DB must not block agent | ||
| // opens, or every transient state hiccup takes all agents down. The | ||
| // in-process latch still covers this process; a missed cross-process | ||
| // quarantine is re-detected by the next daily verifier pass. |
There was a problem hiding this comment.
Fail closed on quarantined state DB before agent opens
When the state DB itself has a durable quarantine row after a restart, readOpenClawDatabaseVerification() throws SqliteIntegrityError; this blanket catch treats it like a transient lock and proceeds to open/migrate the agent DB without enforcing any persisted agent quarantine rows. The later registry write will still fail on the quarantined state DB, but by then ensureAgentSchema() may already have updated schema_meta/indexes in a database the verifier marked bad, so deterministic state quarantine should fail closed here while only transient lock/unavailable errors are skipped.
Useful? React with 👍 / 👎.
| ? checkTargetDatabaseSchemas( | ||
| packageTargetSchemaVersions, | ||
| preManagedServiceStop?.serviceEnv ?? process.env, |
There was a problem hiding this comment.
Check managed service state dir before stopping
When a managed gateway service uses its own OPENCLAW_STATE_DIR, the earlier package preflight checks process.env, and this service-env check runs only after stopManagedServiceBeforeMutableUpdate() has already stopped the service. In that setup an incompatible target is still able to interrupt the healthy gateway before being refused; inspect the service env and run this schema preflight before issuing the stop, then keep this post-stop recheck only for TOCTOU.
Useful? React with 👍 / 👎.
|
Merged via squash.
|
…nd downgrade protection (#110271) * perf(sqlite): gate schema version before integrity scans and quarantine terminal open failures * feat(gateway): refuse incompatible database schemas at boot and verify integrity in the background * feat(update): refuse installing builds that cannot open the current databases * docs: add database schema reference with version history and downgrade guidance * test(update): tolerate optional runner options in git-mutation mocks * refactor(update): split npm package-target metadata out of update-check * chore: model verifier internals for knip and regenerate docs map * chore(i18n): resync stale iOS localization catalog * chore: allowlist read-only preflight and verifier raw SQLite access
…nd downgrade protection (openclaw#110271) * perf(sqlite): gate schema version before integrity scans and quarantine terminal open failures * feat(gateway): refuse incompatible database schemas at boot and verify integrity in the background * feat(update): refuse installing builds that cannot open the current databases * docs: add database schema reference with version history and downgrade guidance * test(update): tolerate optional runner options in git-mutation mocks * refactor(update): split npm package-target metadata out of update-check * chore: model verifier internals for knip and regenerate docs map * chore(i18n): resync stale iOS localization catalog * chore: allowlist read-only preflight and verifier raw SQLite access
What Problem This Solves
A user running a schema-11 agent DB (main/dev build) had the updater stop their healthy gateway and install v2026.7.2-beta.2, which supports schema 9. Every subsequent health/connect/message retry then ran a full synchronous
quick_check+integrity_check+foreign_key_checkover the 21 GB database on the gateway main thread (30-45s, 100% CPU), only to fail with "schema 11 > 9" - and nothing latched the failure, so the scan repeated forever. Three separate gaps stacked: the updater has no DB-schema preflight, the expensive integrity scan ran before the cheap version gate (#105179 ordering), and terminal open failures were retried from scratch.Discussion context: Discord report by Dave Morin, sanity-checked against
main; the integrity-on-open series (#104938, #105179, #105222, #106065, #108663) is a defensive response to the still-open corruption incident #101290 (brokenschema_metaindex).Why This Change Was Made
Downgrades must be refused instantly and cheaply at every layer, upgrades must stay proven and communicated, and full-file integrity scanning belongs off the hot path while keeping the detection #101290 still needs:
user_version+ schema owner before any scan. A newer-schema DB refuses in microseconds with an error naming the build that owns the DB (schema_meta.app_versionis now stamped, previously alwaysnull) and linking the new docs page.integrity_check('schema_meta')- the observed CLI startup preflight can corrupt the live state DB while a gateway is running — health-check commands caused "database disk image is malformed" (2026.6.6, macOS); vanilla SQLite control does NOT reproduce #101290/fix(sqlite): reject corrupt agent state before startup mutation #105179 corruption class - plus the redundantquick_checkpass is gone everywhere (integrity_checkis a strict superset per sqlite.org/pragma.html). The full scan still runs where slow is correct: before a pending migration (now with a user-visible log line), in doctor/backup/compact, and in a new gateway background verifier.integrity_check+foreign_key_checkper DB, results persisted to a new additivedatabase_verificationstable in the state DB. On proven corruption it quarantines the DB: closes any live handle and latches the path so later opens fail fast until doctor repairs it.package.jsonnow publishesopenclaw.schemaVersions;openclaw updatefetches the target's declared support (npm registry / gitshow <rev>:package.json) and refuses before stopping any service when an on-disk DB is newer than the target supports. Dry-run reports it; targets without metadata skip the check.database_verificationstable is additive derived cache (same fold pattern as 0c17cd4), so older builds still open the state DB.https://docs.openclaw.ai/reference/database-schemas- layout, versioning contract, per-version history mapped to release tags, integrity-check matrix, and an explicitly unsupported manual downgrade recipe with a worked 11->9 example.User Impact
Evidence
node scripts/run-vitest.mjs src/infra/sqlite-integrity.test.ts src/infra/sqlite-user-version.test.ts src/state/openclaw-agent-db.test.ts src/state/openclaw-state-db.test.ts src/state/openclaw-database-maintenance.test.ts src/state/openclaw-database-preflight.test.ts src/state/openclaw-database-verify.test.ts src/commands/doctor-session-sqlite.test.ts src/commands/doctor-state-sqlite-compact.test.ts src/commands/doctor.test.ts src/infra/update-check.test.ts src/infra/update-runner.test.ts src/cli/update-cli.test.ts src/infra/tsdown-config.test.ts test/release-check.test.ts src/gateway/server-startup.test.tsSqliteSchemaVersionError(no scan), latch fail-fast + clear-on-repair, quarantine closes a live handle, boot preflight fixtures, updater refusal before service stop (package + git modes, dry-run, missing-metadata skip), package.json/constants drift guard, worker bundle packaging guard.node scripts/generate-kysely-types.mjs --verifyclean;git diff --checkclean; oxfmt clean on all changed files; docs MDX/link checks green (738 files, 6061 links).node scripts/check-changed.mjs(local fallback; Blacksmith backend timed out): all lanes green except the pre-existing maincheck:test-typesorphans noted below; corepnpm tsgoclean, import cycles 0.check:test-typesis broken on currentorigin/mainby two orphaned test files (src/shared/deferred-event-buffer.test.ts,src/tools/protocol.test.ts) whose prod modules were deleted by the deadcode refactors; unrelated to this PR and repaired separately on main.