Skip to content

fix(db): use structural recovery schema check - #1487

Merged
khaira777 merged 4 commits into
mainfrom
fm/flocafe-fix-recovery-schema-check
Nov 7, 2026
Merged

khaira777 merged 4 commits into
mainfrom
fm/flocafe-fix-recovery-schema-check

Conversation

@khaira777

@khaira777 khaira777 commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Fixes #1483 (https://github.com/FreeOpenSourcePOS/FloCafe/issues/1483): In main/db.ts:1804-1831, 1882-1914, checkHealthyDatabaseFile / isHealthyDatabaseFile compares raw sqlite_master.sql table definitions (normalizedSchemaDefinitions) against a freshly built reference instead of structural table definitions (getSchemaDefinitions at main/db.ts:4896-4914). Databases created on older versions and upgraded since (or healed by applySafeFixes) have different raw CREATE TABLE text and fail checkHealthyDatabaseFile during interrupted replacement journal recovery (recoverInterruptedDatabaseReplacement). Update getRecoverySchemaReference / checkHealthyDatabaseFile to use structural table definitions (getSchemaDefinitions), reuse getRecoverySchemaReference(currentVersion) in validateDirectBackup, and add regression tests covering upgraded databases.

What Changed

  • Updated getRecoverySchemaReference and checkHealthyDatabaseFile in main/db.ts to validate schema definitions via getSchemaDefinitions rather than raw sqlite_master.sql text, and extended describeTableStructure to record per-column/constraint collations and ON CONFLICT resolution policies.
  • Reused getRecoverySchemaReference(currentVersion) inside validateDirectBackup so same-version direct backup validation shares the cached recovery schema reference, and updated docs/architecture/data-and-migrations.md to reflect the structural check and shared cache.
  • Added regression coverage in tests/schema-health.test.ts and tests/schema-reference-cache.test.ts for upgraded and applySafeFixes-healed databases during isHealthyDatabaseFile and interrupted replacement recovery, ON CONFLICT and collation drift detection, and cached reference reuse during direct restores.

Risk Assessment

✅ Low: The change cleanly switches recovery schema validation to structural table definitions, reuses the cached recovery schema reference during direct backup validation, preserves per-column collation and conflict-policy checks, and adds thorough behavioral regression tests.

Testing

Ran the targeted schema health (npm run test:schema-health, including tests/schema-health.test.ts and tests/schema-reference-cache.test.ts) and backup/restore (npm run test:backup) test suites, compiled the backend (npm run build), and drove all three scenarios live against the real Electron/Express backend and SQLite engine in an isolated userData directory (saving the full verification report to ~/.no-mistakes/evidence/01M6SMRZ2K8F6BCHM5TSVSNXAF/live-recovery-schema-validation.json); no UI surface was changed so no screenshot artifact was needed, and all scenarios and tests passed.

  • Live validation: ✅ go - 3 of 3 scenarios driven live against the product
Scenario Result Live Evidence
Store database upgraded from v98 to v124 and healed via POST /api/db-tools/apply-safe-fixes (with raw CREATE TABLE SQL differing from a fresh install) passes isHealthyDatabaseFile and recovers cleanly… ✅ pass live ~/.no-mistakes/evidence/01M6SMRZ2K8F6BCHM5TSVSNXAF/live-recovery-schema-validation.json
Owner restores an upgraded same-version backup via POST /api/db/restore and validateDirectBackup reuses the cached recovery schema reference without opening a redundant in-memory reference database ✅ pass live ~/.no-mistakes/evidence/01M6SMRZ2K8F6BCHM5TSVSNXAF/live-recovery-schema-validation.json
Adversarial database snapshots with moved column collations (COLLATE NOCASE moved off payment_methods.name) or modified column/table UNIQUE ON CONFLICT policies are rejected by isHealthyDatabaseFile a… ✅ pass live ~/.no-mistakes/evidence/01M6SMRZ2K8F6BCHM5TSVSNXAF/live-recovery-schema-validation.json
Evidence: Live recovery schema validation report

{ "scenarios": { "scenario1_upgraded_journal_recovery": { "healthDriftFindingsBeforeFix": ["missing_column:products.cb_percent"], "applySafeFixesResponse": { "applied": ["missing_column:products.cb_percent"], "skipped": [], "errors": [] }, "healthCheckFindingsAfterFix": 0, "rawCreateTableSqlDiffersFromFreshInstall": true, "preparedPhaseRecovery": { "apiHealth": { "status": "ok", "db": "ok", "service": "Flo Local API" }, "recoveredCategory": { "id": "cat-upgraded-live", "name": "Upgraded Store Category" }, "journalRemoved": true }, "committedPhaseRecovery": { "apiHealth": { "status": "ok", "db": "ok", "service": "Flo Local API" }, "recoveredCategory": { "id": "cat-upgraded-live", "name": "Upgraded Store Category" }, "journalRemoved": true } }, "scenario2_direct_backup_restore_and_cache": { "coldRestoreHttp": { "status": 200, "body": { "success": true, "mode": "direct", "backupVersion": 124, "currentVersion": 124, "tablesRestored": 69, "cleanupPending": false } }, "coldRestoreSchemaBuildDelta": 1, "coldRestoreMemoryDbDelta": 1, "warmRestoreHttp": { "status": 200, "body": { "success": true, "mode": "direct", "backupVersion": 124, "currentVersion": 124, "tablesRestored": 69, "cleanupPending": false } }, "warmRestoreSchemaBuildDelta": 0, "warmRestoreMemoryDbDelta": 0, "transientCategoryRemovedByRestore": true }, "scenario3_adversarial_collation_and_conflict_guards": { "collationMovedOffPaymentMethodsName": { "isHealthyDatabaseFile": false, "startupJournalRecoveryRejectedWithError": "Interrupted database replacement recovery snapshot could not be validated" }, "columnUniqueOnConflictReplace": { "isHealthyDatabaseFile": false, "startupJournalRecoveryRejectedWithError": "Interrupted database replacement recovery snapshot could not be validated" }, "tableUniqueOnConflictReplace": { "isHealthyDatabaseFile": false, "startupJournalRecoveryRejectedWithError": "Interrupted database replacement recovery snapshot could not be validated" } } } }

{
  "scenarios": {
    "scenario1_upgraded_journal_recovery": {
      "healthDriftFindingsBeforeFix": [
        "missing_column:products.cb_percent"
      ],
      "applySafeFixesResponse": {
        "applied": [
          "missing_column:products.cb_percent"
        ],
        "skipped": [],
        "errors": []
      },
      "healthCheckFindingsAfterFix": 0,
      "rawCreateTableSqlDiffersFromFreshInstall": true,
      "preparedPhaseRecovery": {
        "apiHealth": {
          "status": "ok",
          "db": "ok",
          "service": "Flo Local API",
          "version": "2.4.7",
          "timestamp": "2026-11-07T00:07:54.119Z"
        },
        "recoveredCategory": {
          "id": "cat-upgraded-live",
          "name": "Upgraded Store Category"
        },
        "journalRemoved": true
      },
      "committedPhaseRecovery": {
        "apiHealth": {
          "status": "ok",
          "db": "ok",
          "service": "Flo Local API",
          "version": "2.4.7",
          "timestamp": "2026-11-07T00:07:54.185Z"
        },
        "recoveredCategory": {
          "id": "cat-upgraded-live",
          "name": "Upgraded Store Category"
        },
        "journalRemoved": true
      }
    },
    "scenario2_direct_backup_restore_and_cache": {
      "coldRestoreHttp": {
        "status": 200,
        "body": {
          "success": true,
          "mode": "direct",
          "backupVersion": 124,
          "currentVersion": 124,
          "tablesRestored": 69,
          "cleanupPending": false
        }
      },
      "coldRestoreSchemaBuildDelta": 1,
      "coldRestoreMemoryDbDelta": 1,
      "warmRestoreHttp": {
        "status": 200,
        "body": {
          "success": true,
          "mode": "direct",
          "backupVersion": 124,
          "currentVersion": 124,
          "tablesRestored": 69,
          "cleanupPending": false
        }
      },
      "warmRestoreSchemaBuildDelta": 0,
      "warmRestoreMemoryDbDelta": 0,
      "transientCategoryRemovedByRestore": true
    },
    "scenario3_adversarial_collation_and_conflict_guards": {
      "collationMovedOffPaymentMethodsName": {
        "isHealthyDatabaseFile": false,
        "startupJournalRecoveryRejectedWithError": "Interrupted database replacement recovery snapshot could not be validated"
      },
      "columnUniqueOnConflictReplace": {
        "isHealthyDatabaseFile": false,
        "startupJournalRecoveryRejectedWithError": "Interrupted database replacement recovery snapshot could not be validated"
      },
      "tableUniqueOnConflictReplace": {
        "isHealthyDatabaseFile": false,
        "startupJournalRecoveryRejectedWithError": "Interrupted database replacement recovery snapshot could not be validated"
      }
    }
  }
}

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 3 of 3 scenarios driven live against the product
Scenario Result Live Evidence
Store database upgraded from v98 to v124 and healed via POST /api/db-tools/apply-safe-fixes (with raw CREATE TABLE SQL differing from a fresh install) passes isHealthyDatabaseFile and recovers cleanly… ✅ pass live ~/.no-mistakes/evidence/01M6SMRZ2K8F6BCHM5TSVSNXAF/live-recovery-schema-validation.json
Owner restores an upgraded same-version backup via POST /api/db/restore and validateDirectBackup reuses the cached recovery schema reference without opening a redundant in-memory reference database ✅ pass live ~/.no-mistakes/evidence/01M6SMRZ2K8F6BCHM5TSVSNXAF/live-recovery-schema-validation.json
Adversarial database snapshots with moved column collations (COLLATE NOCASE moved off payment_methods.name) or modified column/table UNIQUE ON CONFLICT policies are rejected by isHealthyDatabaseFile a… ✅ pass live ~/.no-mistakes/evidence/01M6SMRZ2K8F6BCHM5TSVSNXAF/live-recovery-schema-validation.json
  • npm run test:schema-health
  • npm run test:backup
  • npm run build
  • Live Electron + Express backend E2E verification driving /api/db-tools/health-check, /api/db-tools/apply-safe-fixes, /api/health, /api/db/restore, initDatabase(), and isHealthyDatabaseFile() across upgraded, healed, and adversarially tampered SQLite databases
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Use getSchemaDefinitions in getRecoverySchemaReference and checkHealthyDatabaseFile so upgraded databases and applySafeFixes-healed databases pass health checks during interrupted replacement journal recovery, and reuse getRecoverySchemaReference(currentVersion) in validateDirectBackup. Fixes #1483.
@coderabbitai

coderabbitai Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Use structural schema checks for database recovery

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Compare table structure instead of raw CREATE TABLE text so upgraded and healed databases pass
 recovery checks.
• Share the cached schema reference with direct backup validation, avoiding redundant schema builds.
• Cover interrupted replacement recovery and reference caching with regression tests.
Diagram

graph TD
  M["Migration pipeline"] --> R["Cached schema reference"] --> H["Recovery health check"]
  C[("Candidate database")] --> S["Structural schema inspection"] --> H
  B[("Backup file")] --> V["Direct backup validation"]
  R --> V
  B --> S
Loading
High-Level Assessment

Reuse the existing structural schema comparison and cached ideal-schema reference. Canonicalizing raw CREATE TABLE text separately would duplicate schema logic and remain sensitive to equivalent migration-generated SQL.

Files changed (4) +180 / -32

Bug fix (1) +6 / -28
db.tsShare structural schema reference across recovery and restores +6/-28

Share structural schema reference across recovery and restores

• Replaces raw CREATE TABLE comparison in recovery health checks with getSchemaDefinitions, allowing structurally equivalent upgraded tables. Direct backup validation now reuses the cached recovery reference instead of building another ideal database.

main/db.ts

Tests (2) +170 / -1
schema-health.test.tsCover upgraded and healed database recovery +126/-0

Cover upgraded and healed database recovery

• Creates an upgraded database with differing raw table SQL, heals a column through applySafeFixes, and verifies its health check passes. Tests recovery from both prepared and committed replacement journals.

tests/schema-health.test.ts

schema-reference-cache.test.tsVerify direct restores reuse the schema reference +44/-1

Verify direct restores reuse the schema reference

• Counts in-memory database opens to confirm warm direct restores build no new ideal schema. Verifies a cold restore builds the reference once and a subsequent health check reuses it.

tests/schema-reference-cache.test.ts

Documentation (1) +4 / -3
data-and-migrations.mdDocument structural recovery schema checks +4/-3

Document structural recovery schema checks

• Clarifies that recovery compares structural table definitions and normalized non-table definitions against an ideal schema reference shared with direct restores.

docs/architecture/data-and-migrations.md

@qodo-code-review

qodo-code-review Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Payment names can become ambiguous ✓ Resolved

Resolving commit: 0dad33f

Resolution reason
The structural descriptor now records collations per owning column (e.g. "name:NOCASE" vs
"created_at:NOCASE") via splitCreateTableDefinitions and per-clause parsing, replacing the flat
sorted list of collation names. It also tracks ON CONFLICT policies on unique/PK/NOT NULL/CHECK
constraints. A test moves NOCASE from payment_methods.name to created_at and expects
isHealthyDatabaseFile to reject it. This addresses the column-ownership gap via a different
implementation than the suggested fix (which only asked for column association and a test), and the
test covers the suggested moved-collation scenario.
Description
getSchemaDefinitions records table collations as a sorted list without recording which column owns
each one. A database with COLLATE NOCASE moved from payment_methods.name to another text column
now passes recovery health checks, allowing names that differ only by case even though payment
resolution looks them up case-insensitively.

2. Duplicate names can erase payment methods ✓ Resolved

Resolving commit: 0dad33f

Resolution reason
Includes UNIQUE/PRIMARY KEY ON CONFLICT policies in the structural descriptor (uniqueConstraints
policy suffix and conflictPolicies list) and adds regression tests asserting that a database with ON
CONFLICT REPLACE on payment_methods.name is rejected as unhealthy.
Description
describeTableStructure records that a unique constraint exists but omits its ON CONFLICT policy.
A database whose payment_methods.name constraint uses ON CONFLICT REPLACE now passes recovery
health checks, and inserting an existing name replaces its existing row instead of returning the
duplicate-name error expected by the payment-method route.

Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #10
  🌐 PR #34
✅ Compliance rules (platform): 5 rules
✅ Cross-repo context — repo relationships
Review mode: Auto: ⚖️ Balanced: Touches database recovery and restore validation; high-risk, but logic change is small.

Grey Divider

Tip of the day
💡 Did you know, you can hide the parts of a finding you never read, like the evidence or the agent prompt

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread main/db.ts Resolved
Comment thread main/db.ts Resolved
@khaira777 khaira777 changed the title fix: use structural table definitions in recovery schema checks fix(db): use structural recovery schema check Nov 6, 2026
@khaira777 khaira777 changed the title fix(db): use structural recovery schema check fix(main): use structural table definitions in recovery schema checks Nov 7, 2026
@khaira777 khaira777 changed the title fix(main): use structural table definitions in recovery schema checks fix(db): use structural recovery schema check Nov 7, 2026
@khaira777
khaira777 merged commit 7d50fca into main Nov 7, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/flocafe-fix-recovery-schema-check branch November 7, 2026 03:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(db): use structural table definitions in checkHealthyDatabaseFile

1 participant