Skip to content

fix(import): restore large gzip backups within available storage - #1032

Open
devnoname120 wants to merge 3 commits into
OpenStrap:mainfrom
devnoname120:fix/large-gzip-restore-1031
Open

devnoname120 wants to merge 3 commits into
OpenStrap:mainfrom
devnoname120:fix/large-gzip-restore-1031

Conversation

@devnoname120

@devnoname120 devnoname120 commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Fixes #1031.

inflateGzip rejects every stream once its output exceeds 2 GiB, before the database merge can begin. That fixed storage-safety guard also rejects the roughly 5.5 GB backup reported in the issue, even when the device has enough free space. The error does not establish that the backup is corrupt.

Change

  • Budget gzip extraction against the destination volume's available storage using the existing iOS/Android openstrap/storage bridge. freeDiskBytes now accepts an optional path; database compaction keeps its existing default.
  • Limit output to max(0, min(freeBytes ~/ 2, freeBytes - 512 MiB)). This leaves at least half the initial available space for the subsequent merge/journal and at least 512 MiB of headroom. It is a conservative extraction budget, not a guarantee that the later merge will fit.
  • Keep the 2 GiB fallback when capacity cannot be queried, with an explanation and an uncompressed-import workaround rather than claiming the format is unsupported.
  • Report low storage and mid-write ENOSPC as storage failures. Partial output is removed and the source is preserved.
  • Preserve storage failures through backup detection and NOOP resolution, and report them per file without retrying as CSV or discarding successful files from the same selection.

The backpressured streaming pipeline and CRC32/ISIZE checks are unchanged. In particular, gzip ISIZE remains checked modulo 2^32, so valid output above 4 GiB is accepted. No dependency, database schema, or analytics-version changes. The separate ZIP extraction limits are intentionally unchanged.

Why storage serialization is part of this fix

This addresses the concurrent-budget review finding, not an unrelated storage refactor. The extraction limit is calculated from a free-space snapshot. Two gzip restores, or a restore and VACUUM, could otherwise budget the same space and spend the headroom that this fix leaves for the merge and journal.

lib/data/storage_operation.dart provides a shared main-isolate queue instead of estimating and tracking reservations. LocalDb.importFromDbFile, NoopImporter.importFile, and WhoopImporter.importFiles hold it through extraction, consumption/merge, and temporary-file cleanup; releasing it immediately after inflation would expose the merge's headroom again. Own-backup inspection uses it too because detecting a renamed gzip can require extraction.

LocalDb.exportCopy, vacuumAndCheckpoint, vacuumIfBloated, and DerivationEngine.compactStorage participate because their database rewrites can compete for the same space. Manual compaction queries capacity inside the queue and takes the storage gate before the derive latch. Automatic VACUUM, which already holds the derive latch, defers with the existing -1 retry sentinel rather than deadlocking with an import waiting to derive.

This coordinates these operations within the main isolate; it is not an OS-level reservation against external writers. Runtime ENOSPC handling remains necessary. Regression tests cover concurrent capacity queries, both extraction/compaction orderings, a real SQLite restore held after merge until cleanup, failed-job release, and automatic-VACUUM deferral.

Verification

Tested with the repository's CI toolchain: Flutter 3.41.6 / Dart 3.11.4, with the committed dependency lock enforced.

flutter test --no-pub --concurrency=1 --reporter expanded \
  test/storage_operation_test.dart test/storage_operation_integration_test.dart \
  test/gzip_storage_budget_test.dart test/import_container_test.dart \
  test/import_routing_test.dart test/import_data_safety_test.dart \
  test/import_partial_failure_test.dart test/import_bulk_restore_test.dart \
  test/db_paged_import_export_test.dart test/auto_backup_test.dart \
  test/noop_backup_import_test.dart test/compact_database_test.dart \
  test/whoop_reimport_edits_test.dart test/whoop_import_timezone_test.dart \
  test/welcome_import_report_hold_test.dart test/welcome_import_report_headline_test.dart \
  test/backup_cleanup_preferences_test.dart test/backup_crypto_test.dart test/backup

335 passed, with the optional large probe skipped. Coverage includes budget enforcement, storage-error propagation without CSV retries, mixed-selection/decrypted-file cleanup, queue ordering/reentrancy/error release, and real SQLite restore/compaction integration.

LARGE_GZIP_PROBE=1 flutter test --no-pub --concurrency=1 --reporter expanded \
  test/gzip_storage_budget_test.dart --plain-name 'a real 5.5 GiB stream'

The separate large probe passed. It actually generates and extracts a 5.5 GiB (5,905,580,032-byte) synthetic gzip payload, validates wrapped ISIZE and endpoint contents, and exercises checksum verification. The same payload is refused and cleaned up under the unknown-capacity 2 GiB fallback. It is opt-in to avoid writing several GiB on every CI run.

flutter analyze --no-pub
bash .github/scripts/check_sibling_pins.sh
git diff --check

Analysis clean; whitespace check clean. The sibling-pin guard passes with an existing warning that protocol's upstream main has advanced; neither pin nor the lockfile was changed.

Remaining validation

No physical iPhone or copy of the reporter's backup was available. The storage bridge is mocked in the automated tests; the existing iOS implementation and its registration were inspected. The multi-gigabyte probe tests extraction, not a multi-gigabyte SQLite row merge. Confirm the actual backup on iOS with sufficient free storage before merge.

Summary by Sourcery

Restore large gzip backups when device storage permits, and coordinate disk-intensive operations to preserve space for the database merge.

Bug Fixes:

  • Allow gzip backups larger than 2 GiB to be restored when available storage supports extraction, while retaining a bounded fallback when capacity is unknown.
  • Report insufficient storage and disk-full write failures as storage errors, preserving the backup source and cleaning partial extraction output.
  • Keep storage failures visible during backup detection and import routing instead of retrying them as CSV or losing other successful files in the selection.

Enhancements:

  • Serialize disk-intensive restores, gzip extraction, backups, compaction, exports, and database rewrites so they do not budget or consume the same available space concurrently.
  • Use the extraction destination volume when checking available storage; database compaction continues to use its default volume.

Tests:

  • Add coverage for gzip budget boundaries, storage-error routing and cleanup, storage queue behavior, and restore/compaction coordination, including an opt-in multi-gigabyte extraction probe.

Summary by CodeRabbit

  • Bug Fixes
    • Compressed imports now adjust their extraction limit based on available storage, with a fallback when storage information is unavailable.
    • Imports that exceed the available storage limit or encounter a disk-full error now report a storage-related message.
    • Storage errors during file classification are reported, and processing can continue with other files.
    • Disk space checks use the database’s storage volume by default or can check a specified path’s volume.
  • Improvements
    • Storage-intensive operations, including imports, backups, and maintenance, are coordinated to avoid overlapping work.

@coderabbitai

coderabbitai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Storage operations now run through a serialized coordinator. Gzip extraction uses available disk space to set its output limit, and import flows preserve storage errors for callers. Onboarding records classification storage errors against the affected file.

Changes: Storage coordination and import handling

Layer / File(s) Summary
Coordinate storage operations
lib/data/storage_operation.dart, lib/data/db.dart, lib/data/auto_backup.dart, lib/compute/derivation_engine.dart, lib/import/noop_import.dart, lib/import/whoop_import.dart
A zone-owned queue serializes storage operations and supports awaited nested operations. Database, backup, compaction, and import methods use the coordination wrappers. vacuumIfBloated returns -1 when storage is busy.
Calculate and enforce the extraction limit
lib/data/disk_space.dart, lib/import/import_container.dart
freeDiskBytes accepts an optional path and queries that volume. Gzip extraction uses available space to calculate its limit, with a 2 GiB fallback when capacity is unknown. It rejects a zero limit and reports insufficient storage for known-capacity limit breaches and filesystem-full errors.
Propagate import storage errors
lib/import/import_container.dart, lib/ui2/onboarding/welcome.dart
resolveNoopDatabase rethrows storage errors and deletes temporary directories when it does not return an inflated database. Onboarding records classification storage errors for the affected file and continues processing the remaining files.

Estimated code review effort: 3 (Moderate) | ~30 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant inflateGzip
  participant freeDiskBytes
  participant Volume
  participant GzipStream
  inflateGzip->>freeDiskBytes: Request available bytes for destination
  freeDiskBytes->>Volume: Query capacity for selected path
  Volume-->>freeDiskBytes: Return capacity or unknown
  freeDiskBytes-->>inflateGzip: Return bytes or unknown
  inflateGzip->>inflateGzip: Calculate limit and reject zero limit
  inflateGzip->>GzipStream: Extract while counting output bytes
Loading

Suggested reviewers: abdulsaheel

Merge Risk: Low · up to 0291f · assessed changes only

Path filters excluded changed files. This rating applies only to the assessed changes.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: gzip backup restore is now bounded by available storage instead of a fixed 2 GiB limit. The fix(import) prefix matches the import-focused changes. The title does not m…
Linked Issues check Passed [#1031] The issue asks for the technical cause of the rejected restore and whether such a backup can be restored. The cause is the fixed 2 GiB output guard in inflateGzip. The change in lib/import/imp…
Out of Scope Changes check Passed The core changes stay within the restore path for #1031: the gzip budget and fallback message, the ImportStorageException mapping, the disk-space path option, and the propagation of storage failures t…
Full details: Title check

Explanation

The title names the main change: gzip backup restore is now bounded by available storage instead of a fixed 2 GiB limit. The fix(import) prefix matches the import-focused changes. The title does not mention the storage operation serialization, which is a secondary change.

Full details: Linked Issues check

Explanation

[#1031] The issue asks for the technical cause of the rejected restore and whether such a backup can be restored. The cause is the fixed 2 GiB output guard in inflateGzip. The change in lib/import/import_container.dart replaces that fixed guard with gzipInflateByteLimit(freeBytes): max(0, min(freeBytes ~/ 2, freeBytes - 512 MiB)). A backup above 2 GiB now extracts when the destination volume has enough free space. The 2 GiB limit remains only when capacity cannot be queried, and the message names the uncompressed-import workaround. lib/data/disk_space.dart adds an optional path to freeDiskBytes, so the destination volume is queried. The issue sets no further coding acceptance criteria. Physical iPhone validation with the reporter's backup is not a coding requirement and remains unvalidated. Automated tests under test/** are outside the reviewable set, so test results were not independently assessed; this does not change the implementation finding. The storage serialization added at the current head (lib/data/storage_operation.dart and its call sites) is a supporting change for the budget, not a new objective. It was checked under the out-of-scope assessment.

Full details: Out of Scope Changes check

Explanation

The core changes stay within the restore path for #1031: the gzip budget and fallback message, the ImportStorageException mapping, the disk-space path option, and the propagation of storage failures through backup detection and NOOP resolution. The current head adds a main-isolate storage-operation queue. The PR description links this queue to the budget: concurrent restores or VACUUM could spend the same free-space snapshot and the merge/journal headroom. The queue wraps LocalDb export, import, and vacuum paths, DerivationEngine.compactStorage, NOOP and Whoop import, and auto-backup. These call sites match that stated purpose. Automatic VACUUM defers with the existing -1 sentinel, so no unrelated behavior is changed. The breadth of this change is larger than the core fix, so a reviewer should confirm the queue is needed for the budget. No unrelated change was identified in the reviewed summary. Test files under test/** were excluded from review and were not inspected.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • 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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: OpenStrap/edge
  • Branch: main
  • File: .coderabbit.yaml
  • Commit: 97804b4
  • Layers: Repository YAML
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: e851dd86-eb0e-45c6-b966-ccb2dc3e3de8
Commits

Reviewing files that changed from the base of the PR and between c57664a and 0291f35.

Files ignored due to path filters: 1

  • test/auto_backup_test.dart is excluded by !test/**
Files selected for processing: 1

  • lib/data/auto_backup.dart

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@sourcery-ai

sourcery-ai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Expose path-specific free-space queries and storage-aware gzip failures so callers can distinguish exhausted capacity from invalid backup data.

  • lib/data/disk_space.dart L1-4, L16-24
  • lib/import/import_container.dart L73-77, L179-184, L316-331 (+1 small edits)

Uses of the API

Apply the shared storage-operation gate to imports, exports, backups, and compaction so capacity checks remain valid through the disk-heavy work and cleanup.

  • lib/compute/derivation_engine.dart L53, L3763-3769
  • lib/data/auto_backup.dart L333-339, L534-560 (+2 small edits)
  • lib/data/db.dart L11534-11543, L11642-11645, L17183-17188 (+2 small edits)
  • lib/import/noop_import.dart L48, L103-110
  • lib/import/whoop_import.dart L26, L125-132

Implement storage-budgeted gzip extraction, preserve storage errors during backup detection and cleanup, and report per-file storage failures without falling through to CSV routing.

  • lib/data/storage_operation.dart L1-46
  • lib/import/import_container.dart L32-42, L438-447, L556-569 (+7 small edits)
  • lib/ui2/onboarding/welcome.dart L459-471

Tests

Cover storage-budget calculations, error propagation and cleanup, queue ordering and deferral, backup serialization, and large-gzip restore behavior.

  • test/auto_backup_test.dart L15-18, L44-74, L453-530 (+1 small edits)
  • test/gzip_storage_budget_test.dart L1-355
  • test/import_routing_test.dart L116-142, L366-387 (+2 small edits)
  • test/storage_operation_integration_test.dart L1-210
  • test/storage_operation_test.dart L1-101

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@devnoname120
devnoname120 marked this pull request as ready for review December 1, 2026 10:14
@devnoname120

Copy link
Copy Markdown
Contributor Author

Ok I found a workaround: extract the .gz manually and then import the resulting .db. The 2 GB limitation only applies to compressed databases (.db.gz), not uncompressed databases (.db)

@sourcery-ai

sourcery-ai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 0291f35

#1031 Nothing was imported – Unpacks to more than 2 GB, which is not something we can import. · 1 of 2 met · 1 to check by hand

# Requirement Status Notes
1 Explain why the backup was rejected as larger than 2 GB. ✅ Met The change identifies the fixed 2 GiB extraction limit as the cause and replaces it with a limit based on available storage.
2 Provide a way to restore the reported backup of around 5.5 GB. 👀 Check by hand (runtime) Verify on an iPhone with the reporter’s backup and sufficient free space that extraction and the subsequent database merge both complete; automated tests cover large extraction but not that real backup’s merge.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="lib/import/import_container.dart" line_range="409" />
<code_context>
   final destPath = p.join(dir.path, base);
+  final freeBytes = await freeDiskBytes(path: dir.path);
+  final maxBytes = gzipInflateByteLimit(freeBytes);
+  if (maxBytes == 0) throw _gzipNeedsSpace(path);
   final sink = File(destPath).openWrite();
   var written = 0;
</code_context>
<issue_to_address>
**Storage errors become CSV errors**

When a gzipped OpenStrap backup is refused or fails because of its extraction budget and is processed through NOOP resolution or import routing, `resolveNoopDatabase` catches the storage exception and returns `null`, so backup detection or `NoopImporter` treats the file as unrecognized and routes it to CSV import; that hides the storage guidance and can decompress the file a second time before failing.

Preserve and propagate storage-related import exceptions through `resolveNoopDatabase` and the import-routing paths.

Also at `lib/import/import_container.dart:432`.
</issue_to_address>

### Comment 2
<location path="lib/import/import_container.dart" line_range="319" />
<code_context>
-    final v = await _channel.invokeMethod<Object?>(
-      'freeBytes',
-      {'path': await getDatabasesPath()},
-    );
+    final v = await _channel.invokeMethod<Object?>('freeBytes', {
+      'path': path ?? await getDatabasesPath(),
</code_context>
<issue_to_address>
**Concurrent jobs overcommit storage**

When two large gzip restores, or a gzip restore and VACUUM, run concurrently after checking available space, each `inflateGzip` call computes its limit from the same unreserved free-space snapshot, so concurrent restores can each consume half of that space; together they exhaust the headroom and a restore or concurrent compaction fails for lack of storage.

Coordinate disk-space reservations across extraction and compaction jobs, or serialize those operations so their individual budgets cannot consume the same free space.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: lib/import/import_container.dart:409, lib/import/import_container.dart:319


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread lib/import/import_container.dart Resolved
Comment thread lib/import/import_container.dart Resolved
@devnoname120

Copy link
Copy Markdown
Contributor Author

@coderabbitai Updated the PR description to address the inconclusive Out of Scope Changes check. The new Why storage serialization is part of this fix section links the concurrent-budget review finding and explains why each storage-operation call site belongs to the gzip fix: overlapping restores or VACUUM could consume the same measured free space and the headroom reserved for merge/journaling. It also explains the full-job lifetime and derive-lock ordering.

The verification section now records the 335 passing targeted tests and the separate real 5.5 GiB probe. The actual reporter-backup/iPhone validation limitation remains explicit. Please re-evaluate the scope check against the updated description; the code head is unchanged at c57664a.

@coderabbitai

coderabbitai Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -u
echo '=== Current PR metadata and description ==='
gh pr view 1032 --repo OpenStrap/edge --json title,body,headRefOid,baseRefOid,updatedAt --jq '{title,headRefOid,baseRefOid,updatedAt,body}'
echo '=== Changed files ==='
gh api --paginate repos/OpenStrap/edge/pulls/1032/files --jq '.[] | [.filename,.status,(.additions|tostring),(.deletions|tostring)] | @tsv'
echo '=== Checkout revision ==='
git rev-parse HEAD
echo '=== Applicable instruction files ==='
for f in AGENTS.md lib/AGENTS.md lib/data/AGENTS.md lib/import/AGENTS.md lib/compute/AGENTS.md lib/ui2/AGENTS.md lib/ui2/onboarding/AGENTS.md; do
  if [ -f "$f" ]; then echo "=== $f ==="; cat "$f"; fi
done
echo '=== Storage operation outlines ==='
for f in lib/data/storage_operation.dart lib/data/db.dart lib/compute/derivation_engine.dart lib/import/import_container.dart lib/import/noop_import.dart lib/import/whoop_import.dart; do
  echo "=== $f ==="
  ast-grep outline "$f" --items all --match 'StorageOperation|storageOperation|inflateGzip|isEdgeBackup|compactStorage|exportCopy|importFromDbFile|vacuum|importFile' 2>&1 || true
done
echo '=== Queue source ==='
cat -n lib/data/storage_operation.dart
echo '=== Storage budget and queue call sites ==='
rg -n -C 6 '\b(withStorageOperation|tryStorageOperation|gzipInflateByteLimit|_inflateGzip|_isEdgeBackup|_compactStorage|_exportCopy|_importFromDbFile|_vacuumIfBloated|_vacuumAndCheckpoint|_importFiles|_importFile)\b' lib/data/db.dart lib/compute/derivation_engine.dart lib/import/import_container.dart lib/import/noop_import.dart lib/import/whoop_import.dart

Length of output: 43370


@devnoname120 I re-evaluated the scope check against the updated description and the changed call sites at c57664a0ee1290c89c08aaaa77bb2c3297325211.

My assessment: the Out of Scope Changes check passes. The description now explains why the queue and its call sites support the gzip storage budget: overlapping storage jobs could consume the same measured free space and the headroom reserved for the merge. It also explains the job lifetime and derive-lock ordering. The queue is not an OS-level reservation, so ENOSPC handling remains necessary.

The description reports 335 passing targeted tests and a separate 5.5 GiB extraction probe. I did not rerun them. The storage bridge was mocked, and the probe did not test a multi-gigabyte SQLite merge. As stated in the description, confirm the reporter’s backup on an iPhone with sufficient free storage before merge.

This is a reassessment in this reply; it does not update the saved check result.


📝 Learnings were not changed: only organization members or users with write access to this repository can add or remove learnings.

You are interacting with an AI system.

@devnoname120

Copy link
Copy Markdown
Contributor Author

The current-head Actions runs have not executed any jobs: test and PR Agent both report action_required for c57664a0ee1290c89c08aaaa77bb2c3297325211, consistent with the fork-workflow approval gate.

Could a maintainer review and approve those workflow runs so the actual CI results can be evaluated? The author account has no upstream write access. Local verification (335 targeted tests, a separate real 5.5 GiB extraction probe, and clean analysis) is recorded in the PR description; it is not a substitute for the pending upstream CI.

This branch has not been deployed

No deployments
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.

Nothing was imported – Unpacks to more than 2 GB, which is not something we can import.

1 participant