Skip to content

feat(startup): newer-database recovery flow - #1405

Merged
khaira777 merged 17 commits into
mainfrom
fm/flocafe-1341-newer-db-recovery
Oct 29, 2026
Merged

khaira777 merged 17 commits into
mainfrom
fm/flocafe-1341-newer-db-recovery

Conversation

@khaira777

@khaira777 khaira777 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1341

Behavior

When an older FloCafe app build opens a database created or migrated by a newer app version (PRAGMA user_version > LATEST_SCHEMA_VERSION), startup intercepts SchemaVersionMismatchError before the generic error box and presents a dedicated recovery dialog. Users can download the latest version, open the backups directory, restore a compatible backup after explicit confirmation, or safely exit without touching any files.

Design Decision

FloCafe uses forward-only migrations and never attempts lossy or speculative reverse migrations. Safe recovery from an older binary opening a newer database provides guided upgrade paths or restores a validated pre-upgrade backup while preserving the newer database and all active sidecars in a timestamped recovery archive with atomic replacement journal protection.

Migration Implications

None. This change introduces no database schema migrations, table alters, or persistent state changes.

Tests Run

  • npm run test:newer-db-recovery: verifies non-mutating preflight checks, header vs WAL inspection, compatible backup discovery, cancellation safety, journaled replacement, sidecar preservation, and simulated ENOSPC/IO storage error resilience.
  • npm run test:backup: verifies backup creation, integrity inspection, and direct restore workflows.
  • npm run test:shutdown-lifecycle: verifies clean shutdown and quiescent connection draining.
  • npm run docs:check: markdown lint, link validation, and doc policies.
  • npm run lint and npm run build: typecheck and Oxlint checks.

Remaining Limitations

Restoring requires an intact compatible backup; if no compatible backup is available, the user must update FloCafe to a version supporting the database schema.

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ No issues found.

⚠️ **Test** - 1 warning
  • ⚠️ The Test agent did not finish within its invocation budget. Reported: agent run tests timed out after 30m0s: agent last produced output 483ms ago (686 observed); agent reported: antigravity parse events: context deadline exceeded. This is a budget or provider-slowness cut, not a code failure. Re-running the same request costs another full budget, so no further attempt is made automatically. If this repository's targeted tests or evidence gathering routinely approach the default 30m0s, raise test_agent_timeout in global config. Respond with fix to spend another budget: a repair turn runs only for selected findings other than this budget cut, then validation re-runs. Or abort and retry after raising the budget.

  • ⚠️ The Test agent did not finish within its invocation budget. Reported: agent run tests timed out after 30m0s: agent last produced output 524ms ago (151 observed); agent reported: antigravity parse events: context deadline exceeded. This is a budget or provider-slowness cut, not a code failure. Re-running the same request costs another full budget, so no further attempt is made automatically. If this repository's targeted tests or evidence gathering routinely approach the default 30m0s, raise test_agent_timeout in global config. Respond with fix to spend another budget: a repair turn runs only for selected findings other than this budget cut, then validation re-runs. Or abort and retry after raising the budget.

✅ **Document** - passed

✅ No issues found.

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

✅ No issues found.

@coderabbitai

coderabbitai Bot commented Oct 29, 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

Comment @coderabbitai help to get the list of available commands.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Add safe recovery for newer databases during startup

✨ Enhancement 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Offer update, backup inspection, confirmed restore, or safe exit when an older app detects a newer
 database.
• Validate backups by SQLite content and preserve the newer database and sidecars during journaled
 replacement.
• Test rollback, interrupted recovery, credential reset, and startup behavior with isolated
 fixtures.
Diagram

graph TD
  A["Startup"] --> B{"Newer schema?"} -->|"yes"| C["Recovery options"] -->|"restore"| D["Validate backups"] --> E{"Confirm restore?"} -->|"yes"| F["Journaled replacement"] -->|"success"| G["Normal startup"]
  B -->|"no"| G
  C -->|"update or exit"| H["Safe exit"]
  E -->|"cancel"| C
  F -->|"failure"| C
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Update-only recovery
  • ➕ Avoids database replacement in an older build.
  • ➖ Cannot restore service from a compatible backup when updating is unavailable.
2. Reuse the normal restore entry point unchanged
  • ➕ Would reduce new replacement code.
  • ➖ Does not accommodate startup's newer-schema guard or guarantee preservation of the newer database and active sidecars.

Recommendation: Keep the dedicated recovery flow while reusing the existing maintenance lock and replacement journal. It provides offline recovery without reverse migrations and makes preservation and rollback explicit; update-only recovery is safer but less useful.

Files changed (8) +4505 / -415

Enhancement (3) +2141 / -341
db.tsImplement preflight and journaled downgrade restore +1524/-194

Implement preflight and journaled downgrade restore

• Adds non-mutating schema inspection, content-based backup discovery, and sidecar-aware preservation, replacement, and rollback. Validated backups can migrate forward; successful replacement repairs sequences and clears stale authentication, pairing, and Drive state.

main/db.ts

downgrade-recovery.tsAdd interactive newer-database recovery flow +400/-0

Add interactive newer-database recovery flow

• Presents update, folder, restore, and exit actions with backup metadata and an explicit warning before replacement. Keeps recovery options available after validation or restore failures.

main/downgrade-recovery.ts

index.tsRoute schema mismatches through recovery +217/-147

Route schema mismatches through recovery

• Intercepts the typed schema mismatch, closes database access, and invokes recovery instead of the generic error dialog. Successful restoration repeats normal initialization; update and exit choices run cleanup and exit safely.

main/index.ts

Documentation (2) +78 / -21
data-and-migrations.mdDocument downgrade recovery and database safety rules +69/-17

Document downgrade recovery and database safety rules

• Describes non-mutating schema preflight, backup validation and selection, confirmation, sidecar preservation, and replacement-journal recovery. Updates backup metadata and health-check documentation.

docs/architecture/data-and-migrations.md

runtime-and-lifecycle.mdDocument the startup recovery branch +9/-4

Document the startup recovery branch

• Explains how a schema mismatch enters recovery before generic startup failure handling and how successful restoration resumes initialization.

docs/architecture/runtime-and-lifecycle.md

Other (3) +2286 / -53
package.jsonRegister the newer-database recovery test suite +2/-1

Register the newer-database recovery test suite

• Adds a dedicated test command and includes it in the main test sequence.

package.json

newer-db-downgrade-recovery.test.tsExercise downgrade recovery with isolated SQLite fixtures +1931/-0

Exercise downgrade recovery with isolated SQLite fixtures

• Tests WAL preflight, backup classification, confirmation, restoration, credential reset, and migration from older schemas. Fault-injection and child-process cases cover rollback, journal replay, staging failures, shutdown, and startup resumption.

tests/newer-db-downgrade-recovery.test.ts

startup-failure-child.cjsExtend startup harness for newer-database outcomes +353/-52

Extend startup harness for newer-database outcomes

• Adds mocked recovery dialogs and database operations for exit, update, restore, and shutdown modes. Verifies cleanup ordering, startup after restoration, and avoidance of generic startup-error handling.

tests/startup-failure-child.cjs

@qodo-code-review

qodo-code-review Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Restores can leave a journal behind ✓ Resolved
Description
restoreCompatibleBackupForDowngrade inventories, archives, and records only the active database
and its -wal and -shm sidecars, while removeDatabaseFiles() leaves flo.db-journal in place
during replacement and rollback. If the newer database has a hot rollback journal, its preserved
copy lacks a file needed for recovery, and the leftover journal can be encountered when SQLite opens
the restored backup; interrupted-replacement recovery has the same cleanup gap.
Code

main/db.ts[R3652-3655]

+      const presentSidecars: ReplacementJournalSidecar[] = [];
+      for (const suffix of ['-wal', '-shm'] as const) {
+        const sidecarPath = `${dbPath}${suffix}`;
+        if (!pathEntryExists(sidecarPath)) continue;
Relevance

●●● Strong

Accepted recovery precedents prioritize complete artifact cleanup and preserving all replacement
evidence.

PR-#791

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The restore implementation enumerates only -wal and -shm sidecars for archiving and rollback,
then uses removeDatabaseFiles() for replacement, rollback, and interrupted recovery; that helper
removes the same sidecars but not -journal. Snapshot validation explicitly recognizes -journal
as a sidecar that cannot be ignored, confirming that the omitted file matters to this flow.

Preserve data files during downgrade handling
main/db.ts[3652-3661]
main/db.ts[3696-3714]
main/db.ts[3753-3763]
main/db.ts[3895-3907]
main/db.ts[3696-3718]
main/db.ts[2533-2542]
main/db.ts[3753-3766]
main/db.ts[1682-1685]
main/db.ts[3895-3904]
main/db.ts[1043-1050]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The downgrade restore path does not account for `flo.db-journal`: a newer database may be archived without a journal needed for recovery, while the old journal remains beside the replacement database.

## Fix Focus Areas
- main/db.ts[1682-1685]
- main/db.ts[3652-3661]
- main/db.ts[3696-3714]
- main/db.ts[3753-3764]
- main/db.ts[3895-3907]

## Recommended Fix
Before destructive replacement, either safely support `-journal` throughout archive creation, replacement journaling, active-file removal, rollback restoration, and interrupted-recovery cleanup, or reject an active `-journal` with an actionable error. Ensure an old journal cannot remain beside a replacement database, and add tests for normal restore, rollback, and interrupted recovery with a rollback journal present.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Temp staging can overwrite files ✓ Resolved
Description
Database health and schema probes use copyFileSync without COPYFILE_EXCL when copying snapshots
into temporary directories. A staging-path collision or pre-existing destination can therefore
replace a temporary snapshot instead of failing safely, affecting recovery verification and schema
preflight.
Code

main/db.ts[R1195-1198]

+      tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'flo-db-health-probe-'));
+      tempDbPath = path.join(tempDir, 'probe.db');
+      fs.copyFileSync(filePath, tempDbPath);
+      for (const suffix of presentSidecars) {
Relevance

●●● Strong

Prior accepted recovery staging feedback favors exclusive, app-owned temporary snapshot writes.

PR-#217

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The added staging paths are under os.tmpdir(), but the snapshot and sidecar copies use plain
copyFileSync without exclusive-write flags or explicit restrictive permissions. The same pattern
appears in recovery verification, health probing, and schema preflight staging.

Rule 4229622: Restore/staging of DB snapshots must use an app-owned OS temp directory (not the backup source directory)
main/db.ts[1088-1093]
main/db.ts[1195-1200]
main/db.ts[1871-1875]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Temporary database snapshots are copied into app-owned temporary directories with `copyFileSync` but without exclusive creation or explicit restrictive permissions.

## Fix Focus Areas
- main/db.ts[1088-1092]
- main/db.ts[1195-1199]
- main/db.ts[1871-1875]

## Recommended Fix
Stage each database and sidecar file using exclusive creation with restrictive permissions, such as opening the destination with `wx` and mode `0o600`, or using an equivalent exclusive-copy implementation before opening the staged database.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

3. Low temp disk space blocks normal startup after a crash ✓ Resolved
Description
inspectDatabaseVersionNonMutating copies the whole live flo.db and any -wal/-shm/-journal
files into os.tmpdir() whenever those files exist. If the copy fails and the header version is
supported, it throws "Could not stage active database for schema preflight". After any crash or
forced kill (common on POS machines), a supported-version install with a large database and a small
or full temp volume now hits the generic Initialization Error and exits. Before this change it
opened in place. The committed and prepared journal checks, which now call
checkHealthyDatabaseFile(..., true), also need this temp copy, so they fail the same way.
Code

main/db.ts[R1877-1884]

+    } catch (stageError) {
+      if (headerVersion > maxSupported) {
+        return { schemaVersion: headerVersion, appVersion: null };
+      }
+      throw new Error(
+        `Could not stage active database for schema preflight: ${stageError instanceof Error ? stageError.message : 'unknown error'}`,
+        { cause: stageError },
+      );
Relevance

●● Moderate

Startup failure risk is plausible, but no close precedent addresses temp-space exhaustion during
schema preflight.

PR-#217

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
initializeDatabase always runs the preflight before opening the database. When sidecar files are
present the preflight copies everything to temp, and it rethrows a copy failure whenever
headerVersion <= maxSupported, which covers every user who never downgraded. initialize() treats
this as a generic failure: it shows the Initialization Error dialog and calls app.exit(1). Each
startup after a crash also copies the full database and WAL synchronously before the app opens.

main/db.ts[1843-1885]
main/db.ts[1947-1955]
main/db.ts[1190-1209]
main/db.ts[1646-1653]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The startup schema preflight copies the full live database and its sidecar files into os.tmpdir() whenever sidecars exist. If that copy fails for a supported-version database, it throws, so a normal install cannot start after a crash. The journal health checks also force full temp copies, with throwOnStagingError=true.

## Fix Focus Areas
- main/db.ts[1843-1885]
- main/db.ts[1646-1653]
- main/db.ts[1700-1711]

## Recommended Fix
When the header version is <= maxSupported and the copy fails, do not throw. Return the header version, or null, and let the normal open path continue: `runMigrations` already raises SchemaVersionMismatchError after the WAL is replayed. Optionally, decode page 1 from the WAL file directly instead of copying the whole database. For the journal health checks, fall back to the earlier read-only in-place probe when the temp copy fails, instead of aborting startup.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

4. Backup list freezes the app while scanning ✓ Resolved
Description
discoverDowngradeBackups runs synchronously on the Electron main process. For every .db file in
backups/ it calls materializeRestoreSource, which reads the whole file into memory with
fs.readFileSync and writes it to temp, and then runs a full PRAGMA integrity_check, a
foreign-key check and inventory-ledger validation. With many large daily or pre-upgrade backups, the
recovery dialog stops responding with no progress shown after the user clicks Restore Compatible
Backup, and the OS may offer to kill the app.
Code

main/db.ts[R3515-3521]

+    let staged: { snapshotPath: string; cleanup: () => void } | undefined;
+    try {
+      staged = materializeRestoreSource(fullPath, liveDbPath);
+      const inspection = inspectBackupSnapshotForDowngrade(
+        staged.snapshotPath,
+        maxSupportedSchemaVersion,
+      );
Relevance

●● Moderate

Synchronous large-backup validation may freeze Electron, but async redesign is subjective without
matching precedent.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The discovery loop checks every candidate one after another. materializeRestoreSource buffers the
whole file in memory before writing a temp copy, and inspectBackupSnapshotForDowngrade runs the
full integrity and foreign-key checks. All of this runs inside runDowngradeRecoveryFlow on the
main process, with no async yield and no progress UI.

main/db.ts[3485-3567]
main/db.ts[5451-5463]
main/downgrade-recovery.ts[290-293]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Backup discovery fully loads and validates every backup synchronously on the main process, which freezes the recovery dialog.

## Fix Focus Areas
- main/db.ts[3485-3567]
- main/downgrade-recovery.ts[290-319]

## Recommended Fix
First read only the SQLite header (`readSqliteHeaderInfo`) to sort candidates and drop newer or non-SQLite files cheaply. Then run the full content validation only on the top N compatible candidates, or lazily when one is selected (the restore already re-validates under the lock). Alternatively, run discovery in a worker thread and show a progress message.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #39
  🌐 PR #1
⚠️ Tickets: not configured — No jira, linear integration is connected for the linked tickets
✅ Compliance rules (platform): 5 rules
✅ Cross-repo context — repo relationships
  ⚠️ Failed to retrieve: FreeOpenSourcePOS/RevFlo — Could not prepare repository FreeOpenSourcePOS/RevFlo. Please retry; if the problem persists, contact support.
  ⚠️ Failed to retrieve: FreeOpenSourcePOS/FloAdmin — Could not prepare repository FreeOpenSourcePOS/FloAdmin. Please retry; if the problem persists, contact support.
  ⚠️ Failed to retrieve: FreeOpenSourcePOS/docs.flopos.com — Could not prepare repository FreeOpenSourcePOS/docs.flopos.com. Please retry; if the problem persists, contact support.
Review mode: Auto: 🧠 Deep: Recovery logic spans startup, database, filesystem safety, migration, and credentials.

Grey Divider

Tip of the day
💡 Did you know, you can add REVIEW.md to your repo root and Qodo follows it on every PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread main/db.ts Resolved
Comment thread main/db.ts Resolved
Comment thread main/db.ts Resolved
Comment thread main/db.ts Resolved
@khaira777 khaira777 changed the title feat(main): add newer-database downgrade recovery flow feat(startup): newer-DB downgrade recovery flow Oct 29, 2026
@khaira777
khaira777 force-pushed the fm/flocafe-1341-newer-db-recovery branch from d45788f to aa3c9db Compare October 29, 2026 20:04
@khaira777 khaira777 changed the title feat(startup): newer-DB downgrade recovery flow feat(main): add downgrade recovery flow for newer database versions Oct 29, 2026
@khaira777 khaira777 changed the title feat(main): add downgrade recovery flow for newer database versions feat(startup): newer-DB downgrade recovery flow Oct 29, 2026
@khaira777
khaira777 force-pushed the fm/flocafe-1341-newer-db-recovery branch from aa3c9db to 858dae1 Compare October 29, 2026 20:48
@khaira777 khaira777 changed the title feat(startup): newer-DB downgrade recovery flow feat(main): newer-database downgrade recovery flow Oct 29, 2026
@khaira777 khaira777 changed the title feat(main): newer-database downgrade recovery flow feat(startup): newer-database downgrade recovery Oct 29, 2026
@khaira777 khaira777 changed the title feat(startup): newer-database downgrade recovery feat(main): newer-database downgrade recovery flow Oct 29, 2026
@khaira777 khaira777 changed the title feat(main): newer-database downgrade recovery flow feat(startup): newer-database recovery flow Oct 29, 2026
Intercept SchemaVersionMismatchError during startup before generic error handling and present a dedicated newer-database recovery flow offering Get Latest Version, Open Backups Folder, Restore Compatible Backup, and Exit.

Inspect candidate backups by SQLite content rather than filename, require explicit data-absence confirmation before restore, preserve the newer database and any -wal/-shm sidecars in backups/, and coordinate replacement through the atomic database replacement journal before continuing normal startup initialization.

Fixes #1341
… and async scan

- Refuse active flo.db-journal rollback journals before archiving, writing a replacement journal, or mutating active files, and clear stale -journal sidecars during replacement and interrupted recovery.
- Fall back to private .flo-db-stage-* staging on the database volume when os.tmpdir() snapshot staging fails, failing closed only when neither volume can stage and cleaning stranded stage directories at startup.
- Inspect canonical _flo_meta.schema_version alongside PRAGMA user_version in non-mutating preflight, replacement health checks, and runMigrations.
- Prefilter non-SQLite and header-newer backup candidates via readSqliteHeaderInfo and yield between candidates in discoverDowngradeBackupsAsync.
@khaira777
khaira777 force-pushed the fm/flocafe-1341-newer-db-recovery branch from 19909c6 to 0e7ccc8 Compare October 29, 2026 22:56
@khaira777 khaira777 changed the title feat(startup): newer-database recovery flow feat(main): newer database downgrade recovery flow Oct 29, 2026
@khaira777 khaira777 changed the title feat(main): newer database downgrade recovery flow feat(startup): newer-database recovery flow Oct 29, 2026
@khaira777
khaira777 merged commit 64cf399 into main Oct 29, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/flocafe-1341-newer-db-recovery branch October 29, 2026 23:06
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.

design(startup): older app opening a newer database (downgrade flow)

1 participant