Skip to content

feat(tauri): add the App-owned native database conversion driver - #2158

Merged
shm11C3 merged 2 commits into
developfrom
feat/2135-native-conversion-driver
Sep 20, 2026
Merged

shm11C3 merged 2 commits into
developfrom
feat/2135-native-conversion-driver

Conversation

@shm11C3

@shm11C3 shm11C3 commented Sep 16, 2026 •

Copy link
Copy Markdown
Owner

Summary

Second of three stacked changes for #2135, based on #2155 (App path
resolution and startup authority inspection). Adds the driver that runs
the whole native database conversion in order: preflight, candidate
capture, finalization, pausing every database producer, reconciliation,
durable selection, then resuming every producer.

  • app::native_conversion::run_conversion is the entry point. Paths and
    the workspace directory are caller-supplied parameters rather than
    resolved internally, so the driver never depends on the real app-data
    directory and every scenario below runs against a temporary one.
  • Entry is always decided by re-inspecting on-disk authority
    (inspect_startup_authority, from feat(tauri): own native database path resolution and startup authority #2155), never by trusting what a
    previous call thinks it left behind — a restart after any interruption
    resumes at the right step or discards and restarts, and a second call
    after a successful selection is a no-op. That last case needed a guard
    before touching disk at all: observe_authority has to open the
    native file as a second DuckDB instance to read its metadata, and
    DuckDB refuses a second instance on a file the // #2134 seam: may
    already hold open from a prior call in the same process. Found by the
    "call it twice" test below; see the code comment at the top of
    run_conversion.
  • ConversionCancellation is checked only between steps, never inside
    an awaited Core call: build_candidate_database,
    finalize_candidate_database and reconcile_native_database accept no
    token, and their own documentation warns that dropping the future does
    not stop the blocking write underneath it. Every step's own persisted
    artifact is already exactly what a restart resumes or discards from, so
    there is nothing extra to clean up at a cancellation boundary.
  • Every database producer (ArchiveController, CoolingRollupController,
    StorageHealthController, and now the startup retention cleanup, which
    was previously fire-and-forget) is paused and drained immediately before
    reconciliation and always resumed afterward regardless of outcome —
    reconciliation captures a fresh candidate from the live source, and
    selecting one a writer changed after that capture would silently drop
    whatever was written in between.
  • workers::WorkersState gains a scheduled_cleanup handle so both
    terminate_all (final App shutdown) and this driver's pause/drain can
    wait for a still-running startup retention pass instead of racing it —
    a small pre-existing gap (the pass was previously unjoined even at
    process shutdown) that this change's own "drain every producer"
    requirement exposed.

Why / What / How / Why not

  • Why now: feat(database): own the DuckDB conversion lifecycle and startup recovery in the App #2135 requires a conversion driver that pauses/drains
    producers, handles cancellation and copy failure, and resumes cleanly
    at every persistent boundary, stacked after path resolution.
  • What: the driver and its producer pause/resume helpers, described
    above. Nothing else.
  • How: dependency injection for paths (testability) and re-inspection
    rather than remembered state (correctness after interruption).
  • Why not inject cancellation into Core's candidate/finalize/reconcile
    calls: they do not accept a token, and the module doc explains why
    checking only between steps is the correct boundary rather than a
    workaround. Why not wire this into lib.rs: nothing triggers a
    conversion yet — that explicit user flow is feat(database): surface the DuckDB conversion as an explicit user flow #2136's scope, so wiring it
    here would be dead integration ahead of its caller.

Related Issues

Towards #2135. Stacked on #2155.

Type of Change

  • New feature (feat/ branch)

Test Plan

  • cargo test -p hardware_visualizer --features duckdb-archive --lib -- --test-threads=1 — 334 passed (6 new: fresh conversion; a real ArchiveController drained and a fresh one running afterward; resuming from a finalized-but-unselected file; cancellation before any copy; a missing source database failing cleanly at preflight; a second call after selection being a no-op)
  • Disk-exhaustion refusal with exact numbers is already covered by Core's own preflight.rs tests; this driver's preflight failure path is exercised here via the missing-source case rather than duplicated

Checklist

  • Self-reviewed the code
  • Linting and formatting pass: cargo fmt --all -- --check; cargo clippy -p hardviz-core --features duckdb-archive --all-targets -- -D warnings; cargo clippy -p hardware_visualizer --features duckdb-archive --all-targets -- -D warnings; cargo clippy -p hardware_visualizer --all-targets -- -D warnings (feature off) — all clean
  • Tests pass (see Test Plan)
  • No new warnings or errors

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added native database conversion with progress handling, cancellation, resumable conversions, and recovery for interrupted or failed conversions.
    • Added lifecycle safeguards to coordinate background database activity during conversion.
  • Bug Fixes
    • Prevented storage-device refreshes when SQLite is unavailable for writes or the native database has taken authority.
    • Improved shutdown reliability by ensuring scheduled cleanup finishes before the application exits.
  • Performance
    • Reduced required conversion disk space when resuming from an existing finalized database.

@coderabbitai

coderabbitai Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: shm11C3/HardwareVisualizer/.coderabbit.yml

Review profile: CHILL

Plan: Team

Run ID: 06d030cd-d60f-4792-b699-87f452ac9cca

📥 Commits

Reviewing files that changed from the base of the PR and between 3437114 and 29c2dca.

📒 Files selected for processing (2)
  • src-tauri/src/lib.rs
  • src-tauri/src/workers/mod.rs

Limit details: You’ve used all 4 included reviews currently available. Your 61 included PR review attempts over the past 7 days set your current allowance at 4 reviews per hour.


📝 Walkthrough

Walkthrough

The PR adds an App-owned native database conversion flow with resumable files, cancellation, producer coordination, lifecycle recovery, SQLite write checks, and coordinated startup cleanup. Space planning now accounts for an existing finalized file.

Changes

Native database conversion

Layer / File(s) Summary
Conversion space planning
core/src/infrastructure/database/native_database/preflight.rs
Space planning accepts finalized_already_exists and omits the finalized database estimate for resumed conversions. Tests cover the updated calculations.
Lifecycle authority and SQLite write gating
src-tauri/src/app/native_lifecycle.rs, src-tauri/src/app/database_availability.rs, src-tauri/src/app/mod.rs, src-tauri/src/commands/hardware.rs
Lifecycle checks identify when SQLite remains authoritative. Storage refresh rejects writes when SQLite is unavailable.
Conversion driver and recovery states
src-tauri/src/app/native_conversion.rs
The conversion driver handles preflight, candidate creation, finalization, producer draining, reconciliation, selection, cancellation, recovery, and lifecycle reporting. Tests cover fresh, resumed, cancelled, failed, repeated, and concurrently held conversions.
Cleanup task coordination
src-tauri/src/lib.rs, src-tauri/src/workers/mod.rs
Retention cleanup uses an awaitable runtime task. Worker shutdown stores, removes, and awaits the cleanup handle.

Priority: ➖ Normal

Estimated code review effort: 5 (Critical) | ~90 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant App
  participant run_conversion
  participant WorkersState
  participant NativeDatabase
  participant Lifecycle
  App->>run_conversion: start conversion
  run_conversion->>WorkersState: pause and drain producers
  run_conversion->>NativeDatabase: build and select database
  run_conversion->>Lifecycle: record authority or recovery state
  run_conversion->>WorkersState: resume producers
  run_conversion-->>App: return conversion outcome
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.51% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 49 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main change: adding the App-owned native database conversion driver.
Description check ✅ Passed The description explains the purpose, implementation, scope, related issues, tests, and completed checklist items. It also states why integration is deferred. The related issues are referenced by numb…
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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

@github-actions github-actions Bot added change:feature PR: feature branch work area:tauri Area: Tauri app, commands, app wiring, or bundling labels Sep 16, 2026
@shm11C3
shm11C3 marked this pull request as ready for review September 16, 2026 17:52
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-16T17:58:01.352260Z 4adefdc Draft marked ready
🔒 Security Review ✅ Completed 2026-09-16T17:57:18.958865Z 4adefdc Draft marked ready
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@shm11C3

shm11C3 commented Sep 16, 2026

Copy link
Copy Markdown
Owner Author

Update: #2134 has landed its dispatch boundary at `core/src/infrastructure/database/dispatch.rs` (PRs #2154, #2156, #2157), with `dispatch::init(paths, expected_schema_version) -> bool` at startup next to `db::init`, and `dispatch::reobserve_authority() -> Result<AuthorityState, NativeDatabaseError>` to call after every successful `select_native_database` — it closes any live owner and adopts one fresh `NativeDatabase` only when the state is `NativeSelected`.

This PR does not depend on that branch and is unchanged. For future reference: this PR's `open_selected_database` (called right after `select_native_database` succeeds in `reconcile_and_select`, inside `src-tauri/src/app/native_conversion.rs`) is exactly the call site `dispatch::reobserve_authority()` should replace once both branches land — same trigger (a successful selection), same job (hand the freshly selected database to whatever holds it for consumers), different owner. The `// #2134 seam:` on `NativeLifecycleOwner` in #2155 is the other half of that reconciliation. Left as a follow-up integration rather than changed here, since this PR must not depend on an unlanded branch.

@github-actions

github-actions Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Rust Tauri Coverage Report

Coverage Details
Filename                                             Regions    Missed Regions     Cover   Functions  Missed Functions  Executed       Lines      Missed Lines     Cover    Branches   Missed Branches     Cover
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
_tests/commands/background_image_test.rs                  39                 0   100.00%           6                 0   100.00%          21                 0   100.00%           0                 0         -
_tests/commands/settings_test.rs                         265                 0   100.00%          21                 0   100.00%         207                 0   100.00%           0                 0         -
adapters/tray.rs                                         127               127     0.00%          14                14     0.00%          87                87     0.00%           0                 0         -
adapters/window.rs                                       601               114    81.03%          44                11    75.00%         515                79    84.66%           0                 0         -
app/database_availability.rs                               6                 6     0.00%           2                 2     0.00%           6                 6     0.00%           0                 0         -
app/startup.rs                                           188                87    53.72%          10                 3    70.00%         114                58    49.12%           0                 0         -
cli/mod.rs                                               155                18    88.39%          18                 0   100.00%         109                 9    91.74%           0                 0         -
commands/ambient_sensor.rs                                63                 5    92.06%           8                 3    62.50%          57                 8    85.96%           0                 0         -
commands/background_image.rs                              22                 7    68.18%          11                 5    54.55%          19                 7    63.16%           0                 0         -
commands/cooling_insight.rs                               63                63     0.00%          19                19     0.00%          65                65     0.00%           0                 0         -
commands/external_component_guidance.rs                   42                42     0.00%           9                 9     0.00%          45                45     0.00%           0                 0         -
commands/external_component_setup.rs                      41                41     0.00%          11                11     0.00%          35                35     0.00%           0                 0         -
commands/hardware.rs                                     400               339    15.25%          76                66    13.16%         328               288    12.20%           0                 0         -
commands/settings.rs                                     982               952     3.05%         157               154     1.91%         827               802     3.02%           0                 0         -
commands/system.rs                                        58                44    24.14%          18                15    16.67%          50                37    26.00%           0                 0         -
commands/ui.rs                                            17                17     0.00%           2                 2     0.00%          13                13     0.00%           0                 0         -
commands/updater.rs                                       97                97     0.00%          15                15     0.00%          66                66     0.00%           0                 0         -
enums/error.rs                                            91                 0   100.00%           7                 0   100.00%          76                 0   100.00%           0                 0         -
enums/hardware.rs                                        184                 3    98.37%          15                 0   100.00%         111                 2    98.20%           0                 0         -
enums/settings.rs                                        423                17    95.98%          27                 2    92.59%         279                10    96.42%           0                 0         -
infrastructure/database/migration.rs                     860                 0   100.00%          57                 0   100.00%         698                 0   100.00%           0                 0         -
infrastructure/database/migration_definitions.rs          32                 0   100.00%           2                 0   100.00%         474                 0   100.00%           0                 0         -
lib.rs                                                   395               395     0.00%          17                17     0.00%         268               268     0.00%           0                 0         -
lifecycle.rs                                             307               258    15.96%          35                31    11.43%         219               196    10.50%           0                 0         -
main.rs                                                    8                 8     0.00%           1                 1     0.00%           6                 6     0.00%           0                 0         -
models/archive_history.rs                                115                50    56.52%          10                 7    30.00%         116                58    50.00%           0                 0         -
models/cooling_insight.rs                               1089                34    96.88%          73                 3    95.89%        1098                35    96.81%           0                 0         -
models/environmental_sensors.rs                           52                 0   100.00%           6                 0   100.00%          45                 0   100.00%           0                 0         -
models/external_component_guidance.rs                     60                 4    93.33%           6                 0   100.00%          52                 4    92.31%           0                 0         -
models/external_component_setup.rs                       187                23    87.70%          13                 1    92.31%         156                20    87.18%           0                 0         -
models/hardware.rs                                       481                 3    99.38%          24                 0   100.00%         343                 3    99.13%           0                 0         -
models/hardware_archive.rs                                 8                 0   100.00%           2                 0   100.00%          10                 0   100.00%           0                 0         -
models/settings.rs                                       381                 0   100.00%          21                 0   100.00%         351                 0   100.00%           0                 0         -
models/storage_health.rs                                   7                 0   100.00%           2                 0   100.00%           9                 0   100.00%           0                 0         -
services/archive_history_service.rs                       65                65     0.00%          21                21     0.00%         101               101     0.00%           0                 0         -
services/background_image_service.rs                     208               128    38.46%          21                10    52.38%         115                71    38.26%           0                 0         -
services/cooling_insight_service.rs                       40                40     0.00%          18                18     0.00%          46                46     0.00%           0                 0         -
services/external_component_guidance_service.rs          187                16    91.44%          18                 1    94.44%         120                11    90.83%           0                 0         -
services/external_component_setup_service.rs             167                57    65.87%          17                 5    70.59%         106                32    69.81%           0                 0         -
services/gpu_service.rs                                   45                45     0.00%           7                 7     0.00%          33                33     0.00%           0                 0         -
services/hardware_service.rs                             210               123    41.43%          28                12    57.14%         161                94    41.61%           0                 0         -
services/language_service.rs                             149                 0   100.00%          24                 0   100.00%          87                 0   100.00%           0                 0         -
services/memory_service.rs                                 9                 9     0.00%           2                 2     0.00%           5                 5     0.00%           0                 0         -
services/motherboard_service.rs                            9                 9     0.00%           2                 2     0.00%           5                 5     0.00%           0                 0         -
services/network_service.rs                               34                13    61.76%           4                 1    75.00%          23                 6    73.91%           0                 0         -
services/settings_service.rs                             861               231    73.17%          92                28    69.57%         699               205    70.67%           0                 0         -
services/system_service.rs                                57                57     0.00%           7                 7     0.00%          40                40     0.00%           0                 0         -
services/ui_service.rs                                    45                45     0.00%           8                 8     0.00%          36                36     0.00%           0                 0         -
tray/surface/mod.rs                                        8                 8     0.00%           2                 2     0.00%           5                 5     0.00%           0                 0         -
tray/surface/tauri_surface.rs                             80                80     0.00%           6                 6     0.00%          48                48     0.00%           0                 0         -
tray/widget.rs                                           610                 5    99.18%          51                 1    98.04%         542                 3    99.45%           0                 0         -
utils/color.rs                                            66                 1    98.48%           4                 0   100.00%          26                 0   100.00%           0                 0         -
utils/file.rs                                            224                 5    97.77%          14                 0   100.00%         144                 4    97.22%           0                 0         -
utils/formatter.rs                                        55                 0   100.00%           5                 0   100.00%          39                 0   100.00%           0                 0         -
utils/logger.rs                                           71                71     0.00%           1                 1     0.00%          38                38     0.00%           0                 0         -
utils/tauri.rs                                           311                22    92.93%          42                 1    97.62%         195                14    92.82%           0                 0         -
webview_memory.rs                                         20                20     0.00%           4                 4     0.00%          13                13     0.00%           0                 0         -
workers/mod.rs                                            64                64     0.00%           2                 2     0.00%          36                36     0.00%           0                 0         -
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
TOTAL                                                  11441              3868    66.19%        1159               530    54.27%        9538              3053    67.99%           0                 0         -

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4adefdc37f

ℹ️ 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".

Comment thread src-tauri/src/app/native_conversion.rs Resolved
Comment thread src-tauri/src/app/native_conversion.rs Resolved
Comment thread src-tauri/src/app/native_conversion.rs Resolved
Comment thread src-tauri/src/app/native_conversion.rs Resolved
shm11C3 added a commit that referenced this pull request Sep 16, 2026
Fixes four review findings on #2158 (Codex). Verified each against the
current code before acting; all four were real.

1. (P1) Quiesce the on-demand Storage Health writer.
   commands::hardware::refresh_storage_devices writes through
   refresh_storage_health_for_date directly, on the caller's own request,
   independently of StorageHealthController - so it was not covered by
   pause_and_drain_producers and could commit a row absent from the
   candidate reconciliation had already captured, silently losing it once
   the native database was selected. It is also unsafe once native
   authority is already selected, whether or not a conversion is running:
   the source may already be retired, and refresh_storage_health_for_date
   opens SQLite with create_if_missing. Added
   app::native_lifecycle::sqlite_source_is_authoritative (true only for
   SqliteAuthoritative/ConversionRecoverable) and
   app::database_availability::ensure_sqlite_writable built on it; the
   command now refuses with a typed error for the whole window SQLite is
   not the live source, not just while a conversion is actively
   reconciling.

2. (P2) Discard stale conversion work before restarting. A `resumable:
   false` restart left any `.hardwarevisualizer-duckdb-*` directory
   already in the workspace untouched, so debris from a crashed attempt
   could grow unbounded across repeated restarts and could make the next
   attempt's own preflight fail for lack of space.
   discard_stale_conversion_work removes recognized debris directories
   before preflight measures available space, on every entry (not just
   the non-resuming branch, since a resumable ConversionInProgress can
   also carry leftover reconcile/runtime debris from a later crash).

3. (P2) Budget only remaining work when resuming. A resumed conversion
   skips finalization, but preflight still required
   candidate+finalized+workspace bytes free - since the finalized file
   already exists and the available-space measurement already excludes
   it, this double-counted roughly a full source-sized artifact and could
   refuse a resume the original preflight had already guaranteed enough
   space for. Core's conversion_space_requirement/plan_conversion_space
   gain a finalized_already_exists parameter that zeroes the finalized
   term; the driver passes resume_from_reconciliation.

4. (P2) Record and retry a post-selection open failure. If opening the
   newly selected database failed right after selection committed, the
   driver logged the error but still returned Selected, leaving the owner
   claiming progress with no open database and no way to recover without
   a process restart - `NativeAuthoritative` at entry returned
   AlreadySelected unconditionally, never attempting to open. Added
   LifecycleIssue::NativeOpenFailed and fail_open (distinct from fail:
   the selection itself did not fail); the entry path for
   NativeAuthoritative now always attempts open_selected_database rather
   than assuming success, which also fixes a related case surfaced while
   testing this: a *fresh* NativeLifecycleOwner (a later call, or #2136
   constructing a new one) hitting an already-selected database would
   previously report AlreadySelected without ever opening it, leaving its
   own seam permanently empty.

New tests: discard_stale_conversion_work (removes only recognized debris,
no-op on a clean workspace), a fresh owner correctly opens an
already-selected database instead of assuming it is open, a concurrently
held database is reported ActionRequired rather than silently skipped
(also documents why inspect_startup_authority itself, not the
NativeAuthoritative branch, is what refuses in that specific case -
observe_authority cannot read metadata from a file another instance
holds either), plus Core preflight tests for the finalized_already_exists
parameter and sqlite_source_is_authoritative's decision table.

Test commands: cargo fmt --all -- --check; cargo clippy -p hardviz-core
--features duckdb-archive --all-targets -- -D warnings; cargo clippy -p
hardware_visualizer --features duckdb-archive --all-targets -- -D
warnings; cargo clippy -p hardware_visualizer --all-targets -- -D
warnings (feature off); cargo test -p hardware_visualizer --features
duckdb-archive --lib -- --test-threads=1 (344 passed); cargo run --bin
export_bindings --features bindings-export (no bindings.ts diff).
@github-actions github-actions Bot added the area:core Area: Tauri-independent Core code label Sep 16, 2026
@shm11C3
shm11C3 added this pull request to stack #2166 September 19, 2026 07:46
coderabbitai[bot]
coderabbitai Bot previously approved these changes Sep 19, 2026
coderabbitai[bot]
coderabbitai Bot previously approved these changes Sep 19, 2026
coderabbitai[bot]
coderabbitai Bot previously approved these changes Sep 19, 2026
Base automatically changed from feat/2135-native-conversion-lifecycle to develop September 19, 2026 14:54
shm11C3 added a commit that referenced this pull request Sep 19, 2026
Fixes four review findings on #2158 (Codex). Verified each against the
current code before acting; all four were real.

1. (P1) Quiesce the on-demand Storage Health writer.
   commands::hardware::refresh_storage_devices writes through
   refresh_storage_health_for_date directly, on the caller's own request,
   independently of StorageHealthController - so it was not covered by
   pause_and_drain_producers and could commit a row absent from the
   candidate reconciliation had already captured, silently losing it once
   the native database was selected. It is also unsafe once native
   authority is already selected, whether or not a conversion is running:
   the source may already be retired, and refresh_storage_health_for_date
   opens SQLite with create_if_missing. Added
   app::native_lifecycle::sqlite_source_is_authoritative (true only for
   SqliteAuthoritative/ConversionRecoverable) and
   app::database_availability::ensure_sqlite_writable built on it; the
   command now refuses with a typed error for the whole window SQLite is
   not the live source, not just while a conversion is actively
   reconciling.

2. (P2) Discard stale conversion work before restarting. A `resumable:
   false` restart left any `.hardwarevisualizer-duckdb-*` directory
   already in the workspace untouched, so debris from a crashed attempt
   could grow unbounded across repeated restarts and could make the next
   attempt's own preflight fail for lack of space.
   discard_stale_conversion_work removes recognized debris directories
   before preflight measures available space, on every entry (not just
   the non-resuming branch, since a resumable ConversionInProgress can
   also carry leftover reconcile/runtime debris from a later crash).

3. (P2) Budget only remaining work when resuming. A resumed conversion
   skips finalization, but preflight still required
   candidate+finalized+workspace bytes free - since the finalized file
   already exists and the available-space measurement already excludes
   it, this double-counted roughly a full source-sized artifact and could
   refuse a resume the original preflight had already guaranteed enough
   space for. Core's conversion_space_requirement/plan_conversion_space
   gain a finalized_already_exists parameter that zeroes the finalized
   term; the driver passes resume_from_reconciliation.

4. (P2) Record and retry a post-selection open failure. If opening the
   newly selected database failed right after selection committed, the
   driver logged the error but still returned Selected, leaving the owner
   claiming progress with no open database and no way to recover without
   a process restart - `NativeAuthoritative` at entry returned
   AlreadySelected unconditionally, never attempting to open. Added
   LifecycleIssue::NativeOpenFailed and fail_open (distinct from fail:
   the selection itself did not fail); the entry path for
   NativeAuthoritative now always attempts open_selected_database rather
   than assuming success, which also fixes a related case surfaced while
   testing this: a *fresh* NativeLifecycleOwner (a later call, or #2136
   constructing a new one) hitting an already-selected database would
   previously report AlreadySelected without ever opening it, leaving its
   own seam permanently empty.

New tests: discard_stale_conversion_work (removes only recognized debris,
no-op on a clean workspace), a fresh owner correctly opens an
already-selected database instead of assuming it is open, a concurrently
held database is reported ActionRequired rather than silently skipped
(also documents why inspect_startup_authority itself, not the
NativeAuthoritative branch, is what refuses in that specific case -
observe_authority cannot read metadata from a file another instance
holds either), plus Core preflight tests for the finalized_already_exists
parameter and sqlite_source_is_authoritative's decision table.

Test commands: cargo fmt --all -- --check; cargo clippy -p hardviz-core
--features duckdb-archive --all-targets -- -D warnings; cargo clippy -p
hardware_visualizer --features duckdb-archive --all-targets -- -D
warnings; cargo clippy -p hardware_visualizer --all-targets -- -D
warnings (feature off); cargo test -p hardware_visualizer --features
duckdb-archive --lib -- --test-threads=1 (344 passed); cargo run --bin
export_bindings --features bindings-export (no bindings.ts diff).
@shm11C3
shm11C3 force-pushed the feat/2135-native-conversion-driver branch from 8654c6f to 126e486 Compare September 19, 2026 14:54
Second of three stacked changes for #2135. Adds the driver that runs the
whole conversion in order (preflight, candidate, finalize, pause every
database producer, reconcile, select, resume every producer), calling
Core's operations on paths the caller resolves rather than a hardcoded
location, so it is fully testable without touching the real app-data
directory.

- app::native_conversion::run_conversion is the entry point. Its own entry
  is always decided by re-inspecting on-disk authority
  (inspect_startup_authority), never by trusting a previous call's memory,
  so a restart after any interruption resumes or discards cleanly and a
  second call after a successful selection is a no-op (guarded before
  touching disk at all, since observe_authority cannot safely reopen a
  native file the #2134 seam already holds open - see the code comment
  for the exact hazard this avoids).
- Cancellation (ConversionCancellation) is checked only between steps,
  never inside an awaited Core call: build_candidate_database,
  finalize_candidate_database and reconcile_native_database accept no
  token, and their own documentation warns that dropping the future does
  not stop the blocking write. Every step's own persisted artifact is
  already exactly what a restart resumes or discards from.
- Producers (ArchiveController, CoolingRollupController,
  StorageHealthController, and now the previously fire-and-forget startup
  retention cleanup) are paused and drained immediately before
  reconciliation and always resumed afterward, success or failure -
  reconciliation captures a fresh candidate from the live source, and
  selecting one a writer changed after that capture would silently drop
  whatever was written in between.
- workers::WorkersState gains a scheduled_cleanup handle so both
  terminate_all (final App shutdown) and this driver's pause/drain can
  wait for a still-running startup retention pass instead of racing it.

Six integration tests build a real SQLite source through App's own
migrations and exercise: a fresh conversion end to end; a real
ArchiveController actually drained and a fresh one running afterward;
resuming from a finalized-but-unselected file (skips candidate/finalize);
cancellation before any copy, leaving SQLite authoritative with nothing
written; a missing source database failing cleanly at preflight; and a
second call after selection being a no-op. Core's own preflight tests
already cover disk-exhaustion refusal with exact numbers; this driver's
preflight failure path is exercised here through the missing-source case
instead of duplicating that coverage.

Not wired into lib.rs: #2136 adds the explicit user-triggered flow that
calls run_conversion. Until then this has no effect on any running
installation, matching the previous stacked change.
Fixes four review findings on #2158 (Codex). Verified each against the
current code before acting; all four were real.

1. (P1) Quiesce the on-demand Storage Health writer.
   commands::hardware::refresh_storage_devices writes through
   refresh_storage_health_for_date directly, on the caller's own request,
   independently of StorageHealthController - so it was not covered by
   pause_and_drain_producers and could commit a row absent from the
   candidate reconciliation had already captured, silently losing it once
   the native database was selected. It is also unsafe once native
   authority is already selected, whether or not a conversion is running:
   the source may already be retired, and refresh_storage_health_for_date
   opens SQLite with create_if_missing. Added
   app::native_lifecycle::sqlite_source_is_authoritative (true only for
   SqliteAuthoritative/ConversionRecoverable) and
   app::database_availability::ensure_sqlite_writable built on it; the
   command now refuses with a typed error for the whole window SQLite is
   not the live source, not just while a conversion is actively
   reconciling.

2. (P2) Discard stale conversion work before restarting. A `resumable:
   false` restart left any `.hardwarevisualizer-duckdb-*` directory
   already in the workspace untouched, so debris from a crashed attempt
   could grow unbounded across repeated restarts and could make the next
   attempt's own preflight fail for lack of space.
   discard_stale_conversion_work removes recognized debris directories
   before preflight measures available space, on every entry (not just
   the non-resuming branch, since a resumable ConversionInProgress can
   also carry leftover reconcile/runtime debris from a later crash).

3. (P2) Budget only remaining work when resuming. A resumed conversion
   skips finalization, but preflight still required
   candidate+finalized+workspace bytes free - since the finalized file
   already exists and the available-space measurement already excludes
   it, this double-counted roughly a full source-sized artifact and could
   refuse a resume the original preflight had already guaranteed enough
   space for. Core's conversion_space_requirement/plan_conversion_space
   gain a finalized_already_exists parameter that zeroes the finalized
   term; the driver passes resume_from_reconciliation.

4. (P2) Record and retry a post-selection open failure. If opening the
   newly selected database failed right after selection committed, the
   driver logged the error but still returned Selected, leaving the owner
   claiming progress with no open database and no way to recover without
   a process restart - `NativeAuthoritative` at entry returned
   AlreadySelected unconditionally, never attempting to open. Added
   LifecycleIssue::NativeOpenFailed and fail_open (distinct from fail:
   the selection itself did not fail); the entry path for
   NativeAuthoritative now always attempts open_selected_database rather
   than assuming success, which also fixes a related case surfaced while
   testing this: a *fresh* NativeLifecycleOwner (a later call, or #2136
   constructing a new one) hitting an already-selected database would
   previously report AlreadySelected without ever opening it, leaving its
   own seam permanently empty.

New tests: discard_stale_conversion_work (removes only recognized debris,
no-op on a clean workspace), a fresh owner correctly opens an
already-selected database instead of assuming it is open, a concurrently
held database is reported ActionRequired rather than silently skipped
(also documents why inspect_startup_authority itself, not the
NativeAuthoritative branch, is what refuses in that specific case -
observe_authority cannot read metadata from a file another instance
holds either), plus Core preflight tests for the finalized_already_exists
parameter and sqlite_source_is_authoritative's decision table.

Test commands: cargo fmt --all -- --check; cargo clippy -p hardviz-core
--features duckdb-archive --all-targets -- -D warnings; cargo clippy -p
hardware_visualizer --features duckdb-archive --all-targets -- -D
warnings; cargo clippy -p hardware_visualizer --all-targets -- -D
warnings (feature off); cargo test -p hardware_visualizer --features
duckdb-archive --lib -- --test-threads=1 (344 passed); cargo run --bin
export_bindings --features bindings-export (no bindings.ts diff).
@shm11C3
shm11C3 force-pushed the feat/2135-native-conversion-driver branch from 126e486 to dd831d7 Compare September 19, 2026 14:56
@shm11C3

shm11C3 commented Sep 20, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai approve

@coderabbitai

coderabbitai Bot commented Sep 20, 2026

Copy link
Copy Markdown
Contributor

@shm11C3 Approved.

✅ Action performed

Comments resolved and changes approved.

@shm11C3
shm11C3 merged commit 5fd482b into develop Sep 20, 2026
40 checks passed
@shm11C3
shm11C3 deleted the feat/2135-native-conversion-driver branch September 20, 2026 17:26
shm11C3 added a commit that referenced this pull request Sep 21, 2026
…2164)

* feat(database): checkpoint after native expiry and retire the SQLite source

Adds NativeDatabase::checkpoint (one write-lane CHECKPOINT, per the retention evidence), retires the SQLite source by renaming it in place on a later verified native startup, and records the App lifecycle state vocabulary in the Design Doc. Rebuilt on develop after #2155 and #2158 were squash-merged; the checkpoint tests moved to core/tests/duckdb/native.rs with #2171's test layout.

* docs(design): describe the lifecycle vocabulary as a projection of AuthorityState

Two Core states map onto ConversionRecoverable, and ActionRequired also carries NativeOpenFailed, so 'lossless translation' overstated it.

* test(database): assert the row written before the checkpoint survives it

The fixture already holds process rows, so a non-empty result proved nothing. Also narrow the Design Doc's single-source claim: inspect_startup_authority is the only reader of Core's authority inspection, while the conversion driver and the native open path also produce lifecycle states.

* feat(database): run the application on the selected native backend

Fold the #2135 lifecycle onto the #2134 dispatch boundary: one startup decision (resolve_native_authority) that dispatch only adopts, the conversion driver handing the selected database to dispatch inside the paused block, producers starting on a native-authoritative boot, the expiry pass ending with dispatch::checkpoint, and shutdown closing the boundary after the writers drain. Includes the review fixes for the hand-over (explicit SelectionHandoff, NativeSelected as the only success, short-circuit while dispatch owns the file).

* fix(tauri): keep producers paused when the selected database is not served

Address review on #2164. Inside the paused block ActionRequired means the selection is durable but opening the database or handing it to dispatch failed, so SQLite is stale and dispatch either still routes to it or refuses every consumer. Producers now stay stopped in that case, as they do after a startup that ends in ActionRequired, and the entry path that later completes the hand-over restarts them if none are running. The conversion integration test drains its workers through terminate_all instead of closing dispatch underneath them, and the schema definitions comment names the startup function that replaced initialize_native_database_dispatch.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core Area: Tauri-independent Core code area:tauri Area: Tauri app, commands, app wiring, or bundling change:feature PR: feature branch work

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant