#993

fix(daemon/remote): a failed or interrupted bundle extract no longer destroys the work tree

Openbeardthelionwants to merge intofrom

Fixes #992.

The bundle extractor deleted a link's live work tree before it had anything to publish, so a failure or a crash in that window left the link holding neither the old tree nor the new one. internal/dictation/download.go promoted a downloaded engine the same way.

Six commits, each with its own regression tests.

Publish by swap, not destroy-then-rename. The live tree moves aside into staging, the clone is renamed into place, and the old tree goes back if that fails. If the restore fails too, staging is kept so the only remaining copy survives and the error names it.

Serialize extracts per link id. In-process, plus a lockutil advisory file lock so a second daemon over the same --bundle-dir is excluded too. The lock dir is dot-prefixed and link ids can no longer start with ., which also keeps ids out of the .staging- namespace they could previously collide with.

Repair on start. Swapping a directory is two renames and cannot be made atomic, so a crash between them still leaves the tree in staging. NewBridge now repairs the bundle dir once before serving: a backup whose link has no live tree is restored, one that is provably older than the live tree is dropped, and a staging dir with no backup is only reaped once it is older than any clone could be. Recovery takes the per-link lock first, so it never touches a link a live extract owns.

Dictation. The promotion is now promoteStagedDir, which sets the previous install aside rather than deleting it and restores it if the rename fails.

Behavior change

sanitizeLinkID now rejects any id starting with ., where it previously rejected only . and ... Nothing documents the charset and a dot-prefixed id was never useful, but an existing link named that way stops working and needs renaming. A work tree already published under such a name is left alone by the repair pass rather than reaped, so upgrading does not delete it.

Verification

Every claim here was run, not argued. Each defect was reproduced first with passing controls, then each guard was ablated individually and confirmed to fail without it, repeated 5 or 10 times where timing mattered.

End to end against a real bridge over TLS via zero daemon serve-remote and zero daemon link: upload, replace, a refused dot-prefixed id, four concurrent uploads of one link id, and two daemons sharing a bundle dir. For crash recovery there is a real control: on a bundle dir left mid-swap, a binary built from main starts and leaves the link gone, while this branch restores it, logs it, and the link accepts a fresh upload afterwards.

gofmt, go vet, go test ./... -race across 85 packages, zero-release build, zero-release smoke and govulncheck all clean on linux/arm64. macOS and Windows are untested locally and rest on CI; the change is built out of directory renames and advisory locks, which is where Windows differs most, so that is the run worth watching.

Known residuals

  • The link marker is written without an fsync, so a power loss (not a process kill) between the marker write and the backup rename leaves a tree recovery cannot attribute. It is kept, not deleted.
  • Advisory locks do not work across hosts on NFS, so two machines mounting one bundle dir can still interleave.
  • promoteStagedDir has the same two-rename window with no repair pass, but the engine is re-downloadable rather than unique user data.

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability when downloading, extracting, or updating bundles and dictation installations.
    • Existing installations are now preserved and restored if an update fails.
    • Interrupted updates can be recovered automatically when the service starts.
    • Concurrent updates are coordinated to prevent incomplete or corrupted installations.
    • Invalid link identifiers are rejected to avoid conflicts with internal recovery data.
  • Reliability

    • Added safer replacement, rollback, cleanup, and timeout handling for staged updates.
    • Improved recovery of interrupted updates while protecting active operations and newer installations.

Activity

76
coderabbitai[bot]3mo ago

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1472e6ff-8c1f-4f1e-b708-a218288c0879

📥 Commits

Reviewing files that changed from the base of the PR and between af745d0c61401e8ccd3253410b724e923dc62b59 and db658d77ca3494ea5d344cd6371af83ab2fcead5.

📒 Files selected for processing (2)
  • internal/dictation/download.go
  • internal/dictation/download_test.go

Included review availability: 3 reviews are currently available. Your included PR review attempts over the past 7 days set your current allowance at 5 reviews per hour.


Walkthrough

Bundle extraction and dictation installation promotion now use staged directory swaps, locking, rollback, and recovery. Bridge startup repairs interrupted bundle swaps, and dot-prefixed link IDs are reserved for internal staging paths.

Changes

Atomic promotion and recovery

Layer / File(s)Summary
Transactional bundle extraction
internal/daemon/remote/bundle.go, internal/daemon/remote/bundle_test.go
Bundle extraction uses separate verification and extraction timeouts, per-link process and advisory locks, staged clones, backup trees, rollback, and failure-path tests.
Startup recovery and namespace protection
internal/daemon/remote/bridge.go, internal/daemon/remote/bundle.go, internal/daemon/remote/bundle_test.go
Bridge startup normalizes and repairs the bundle directory. Recovery evaluates staging markers, backups, live trees, ownership, and age. Dot-prefixed link IDs are rejected.
Transactional dictation installation promotion
internal/dictation/download.go, internal/dictation/download_test.go
Staged installations replace existing trees through a temporary holder. Promotion failures restore the prior installation, and restoration failures retain the holder path.

Estimated code review effort: 4 (Complex) | ~60 minutes

Merge Risk: ⚪ Minimal · up to db658

The PR is merge-ready after normal checks and review; no actionable merge-blocking risk remains.

Sequence Diagram(s)

sequenceDiagram
  participant RemoteBridge
  participant extractBundle
  participant AdvisoryLock
  participant BundleDir
  RemoteBridge->>extractBundle: upload bundle for link ID
  extractBundle->>AdvisoryLock: acquire per-link lock
  extractBundle->>BundleDir: stage cloned tree and set marker
  extractBundle->>BundleDir: move live tree to backup
  extractBundle->>BundleDir: publish staged tree
  extractBundle->>BundleDir: restore or retain backup on failure
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 78.26% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 46 functions across 5 files.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe title clearly describes the primary fix for failed or interrupted remote bundle extraction and matches the main changeset.
Linked Issues check✅ PassedThe pull request addresses issue #992 objectives: rollback-safe bundle and dictation promotion, per-link locking, reserved link ID protection, startup recovery, restoration-failure handling, and regre…
Out of Scope Changes check✅ PassedThe changes remain within issue #992. The implementation, startup recovery, dictation promotion protection, synchronization, and related tests directly support preservation of existing trees and insta…
Full details: Linked Issues check

Explanation

The pull request addresses issue #992 objectives: rollback-safe bundle and dictation promotion, per-link locking, reserved link ID protection, startup recovery, restoration-failure handling, and regression tests.

Full details: Out of Scope Changes check

Explanation

The changes remain within issue #992. The implementation, startup recovery, dictation promotion protection, synchronization, and related tests directly support preservation of existing trees and installations.

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

coderabbitai[bot]3mo ago

Walkthrough

Bundle extraction and dictation installation promotion now use staged directory swaps, locking, rollback, and recovery. Bridge startup repairs interrupted bundle swaps, and dot-prefixed link IDs are reserved for internal staging paths.

Changes

Atomic promotion and recovery

Layer / File(s)Summary
Transactional bundle extraction
internal/daemon/remote/bundle.go, internal/daemon/remote/bundle_test.go
Bundle extraction uses separate verification and extraction timeouts, per-link process and advisory locks, staged clones, backup trees, rollback, and failure-path tests.
Startup recovery and namespace protection
internal/daemon/remote/bridge.go, internal/daemon/remote/bundle.go, internal/daemon/remote/bundle_test.go
Bridge startup normalizes and repairs the bundle directory. Recovery orders stamped staging trees, preserves active extractions, and handles backup ties and per-link isolation. Dot-prefixed link IDs are rejected.
Transactional dictation installation promotion
internal/dictation/download.go, internal/dictation/download_test.go
Engine and model setup recover interrupted promotions before idempotency checks. Staged installations use timestamped holders, rollback, literal path discovery, and holder retention when restoration fails.

Estimated code review effort: 4 (Complex) | ~60 minutes

Merge Risk: 🟡 Moderate · up to 572dc

The PR improves failed-extract recovery, but a retained backup can still be deleted after a later restart, potentially removing the only surviving work tree. The change also leaves test synchronization and static-analysis issues to address, so merge should wait for these bounded correctness and check-cleanliness risks to be resolved or explicitly accepted.

Sequence Diagram(s)

sequenceDiagram
  participant RemoteBridge
  participant extractBundle
  participant AdvisoryLock
  participant BundleDir
  RemoteBridge->>extractBundle: upload bundle for link ID
  extractBundle->>AdvisoryLock: acquire per-link lock
  extractBundle->>BundleDir: stage timestamped clone
  extractBundle->>BundleDir: move live tree to backup
  extractBundle->>BundleDir: publish staged tree
  extractBundle->>BundleDir: restore or retain backup on failure
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check nameStatusExplanation
Linked Issues check✅ PassedThe changes satisfy the coding objectives in [#992]. Bundle extraction now preserves and restores the live tree, serializes same-link operations, rejects dot-prefixed link IDs, performs startup recove…
Out of Scope Changes check✅ PassedThe production and test changes remain within [#992]. The dictation promotion changes are explicitly required by the issue, and the added tests validate the requested rollback, recovery, locking, and …
Docstring Coverage✅ PassedDocstring coverage is 84.13% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 63 functions across 5 files.
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe title clearly identifies the primary fix: failed or interrupted bundle extraction no longer destroys the live work tree. It is concise and directly matches the main objective, although it does not…
Full details: Linked Issues check

Explanation

The changes satisfy the coding objectives in [#992]. Bundle extraction now preserves and restores the live tree, serializes same-link operations, rejects dot-prefixed link IDs, performs startup recovery, and retains data when restoration fails. Dictation engine and model promotion receive equivalent recovery and rollback protection. The added tests cover failure, concurrency, crash recovery, ordering, and path edge cases.

Full details: Out of Scope Changes check

Explanation

The production and test changes remain within [#992]. The dictation promotion changes are explicitly required by the issue, and the added tests validate the requested rollback, recovery, locking, and edge-case behavior. No unrelated code changes are evident.

Full details: Title check

Explanation

The title clearly identifies the primary fix: failed or interrupted bundle extraction no longer destroys the live work tree. It is concise and directly matches the main objective, although it does not mention the related dictation promotion changes.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

coderabbitai[bot]3mo ago

Walkthrough

Bundle extraction and dictation installation promotion now use staged directory swaps, locking, rollback, and recovery. Bridge startup repairs interrupted bundle swaps, and dot-prefixed link IDs are reserved for internal staging paths.

Changes

Atomic promotion and recovery

Layer / File(s)Summary
Transactional bundle extraction
internal/daemon/remote/bundle.go, internal/daemon/remote/bundle_test.go
Bundle extraction uses separate verification and extraction timeouts, per-link process and advisory locks, staged clones, backup trees, rollback, and failure-path tests.
Startup recovery and namespace protection
internal/daemon/remote/bridge.go, internal/daemon/remote/bundle.go, internal/daemon/remote/bundle_test.go
Bridge startup normalizes and repairs the bundle directory. Recovery orders stamped staging trees, preserves active extractions, and handles backup ties and per-link isolation. Dot-prefixed link IDs are rejected.
Transactional dictation installation promotion
internal/dictation/download.go, internal/dictation/download_test.go
Engine and model setup recover interrupted promotions before idempotency checks. Staged installations use timestamped holders, rollback, literal path discovery, and holder retention when restoration fails.

Estimated code review effort: 4 (Complex) | ~60 minutes

Merge Risk: 🟡 Moderate · up to 572dc

The PR improves failed-extract recovery, but a retained backup can still be deleted after a later restart, potentially removing the only surviving work tree. The change also leaves test synchronization and static-analysis issues to address, so merge should wait for these bounded correctness and check-cleanliness risks to be resolved or explicitly accepted.

Sequence Diagram(s)

sequenceDiagram
  participant RemoteBridge
  participant extractBundle
  participant AdvisoryLock
  participant BundleDir
  RemoteBridge->>extractBundle: upload bundle for link ID
  extractBundle->>AdvisoryLock: acquire per-link lock
  extractBundle->>BundleDir: stage timestamped clone
  extractBundle->>BundleDir: move live tree to backup
  extractBundle->>BundleDir: publish staged tree
  extractBundle->>BundleDir: restore or retain backup on failure
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check nameStatusExplanation
Linked Issues check✅ PassedThe changes satisfy the coding objectives in [#992]. Bundle extraction now preserves and restores the live tree, serializes same-link operations, rejects dot-prefixed link IDs, performs startup recove…
Out of Scope Changes check✅ PassedThe production and test changes remain within [#992]. The dictation promotion changes are explicitly required by the issue, and the added tests validate the requested rollback, recovery, locking, and …
Docstring Coverage✅ PassedDocstring coverage is 84.13% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 63 functions across 5 files.
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe title clearly identifies the primary fix: failed or interrupted bundle extraction no longer destroys the live work tree. It is concise and directly matches the main objective, although it does not…
Full details: Linked Issues check

Explanation

The changes satisfy the coding objectives in [#992]. Bundle extraction now preserves and restores the live tree, serializes same-link operations, rejects dot-prefixed link IDs, performs startup recovery, and retains data when restoration fails. Dictation engine and model promotion receive equivalent recovery and rollback protection. The added tests cover failure, concurrency, crash recovery, ordering, and path edge cases.

Full details: Out of Scope Changes check

Explanation

The production and test changes remain within [#992]. The dictation promotion changes are explicitly required by the issue, and the added tests validate the requested rollback, recovery, locking, and edge-case behavior. No unrelated code changes are evident.

Full details: Title check

Explanation

The title clearly identifies the primary fix: failed or interrupted bundle extraction no longer destroys the live work tree. It is concise and directly matches the main objective, although it does not mention the related dictation promotion changes.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

coderabbitai[bot]3mo ago

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Essentials

Run ID: 4674d6c8-cdfd-4c60-bb56-702d58ca727e

📥 Commits

Reviewing files that changed from the base of the PR and between e17255ea40810ae3b9641fa3133a1eee9953a6aa and b57cacb55e8b56f88cb14e951c687ddbb135ea53.

📒 Files selected for processing (2)
  • internal/dictation/download.go
  • internal/dictation/download_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/dictation/download.go
  • internal/dictation/download_test.go

Included review availability: 2 reviews are currently available. Your included PR review attempts over the past 7 days set your current allowance at 5 reviews per hour.


Walkthrough

Bundle extraction and dictation installation promotion now use monotonic staging sequences, locking, rollback, and recovery. Bridge startup repairs interrupted bundle swaps, and dot-prefixed link IDs are reserved for internal paths.

Changes

Atomic promotion and recovery

Layer / File(s)Summary
Sequenced bundle extraction
internal/daemon/remote/bundle.go, internal/daemon/remote/bundle_test.go
Bundle extraction uses sequenced staging directories, separate timeouts, per-link locks, staged publication, rollback, reserved link IDs, and failure-path tests.
Bundle startup recovery
internal/daemon/remote/bridge.go, internal/daemon/remote/bundle.go, internal/daemon/remote/bundle_test.go
Bridge startup normalizes and repairs the bundle directory. Recovery handles legacy names, clock skew, invalid markers, retained backups, parked staging trees, and repeated recovery.
Transactional dictation installation promotion
internal/dictation/download.go, internal/dictation/download_test.go
Engine and model setup restore interrupted promotions before availability checks. Sequenced holders, collision handling, rollback, permissions, legacy ordering, and concurrent allocation are covered by tests.

Estimated code review effort: 4 (Complex) | ~60 minutes

Merge Risk: 🔵 Low · up to b57ca

The change protects existing installations during interrupted promotion, but cleanup failures can still leave preserved installation data undisclosed and accumulate storage. The PR is mergeable with explicit owner awareness or follow-up for this bounded operational risk.

Sequence Diagram(s)

sequenceDiagram
  participant RemoteBridge
  participant extractBundle
  participant AdvisoryLock
  participant BundleDir
  RemoteBridge->>extractBundle: upload bundle for link ID
  extractBundle->>AdvisoryLock: acquire per-link lock
  extractBundle->>BundleDir: create sequenced staging tree
  extractBundle->>BundleDir: publish staged tree
  extractBundle->>BundleDir: recover or retain backup
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe title clearly describes the primary fix: preserving the existing work tree when bundle extraction fails or is interrupted. It is concise and directly related to the changes.
Linked Issues check✅ PassedThe changes address issue #992. They preserve live trees during bundle extraction and dictation promotion, serialize bundle extracts, reject staging-like link IDs, recover interrupted swaps, use monot…
Out of Scope Changes check✅ PassedThe code and test changes remain within the linked issue scope. Bundle recovery, dictation promotion recovery, concurrency protection, startup repair, cleanup behavior, sequence allocation, logging, a…
Docstring Coverage✅ PassedDocstring coverage is 84.38% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 96 functions across 5 files.
Full details: Linked Issues check

Explanation

The changes address issue #992. They preserve live trees during bundle extraction and dictation promotion, serialize bundle extracts, reject staging-like link IDs, recover interrupted swaps, use monotonic exclusive staging allocation, preserve surviving copies, and add extensive regression coverage.

Full details: Out of Scope Changes check

Explanation

The code and test changes remain within the linked issue scope. Bundle recovery, dictation promotion recovery, concurrency protection, startup repair, cleanup behavior, sequence allocation, logging, and related tests all support the stated objectives.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

beardthelion2mo ago

Both merge-readiness items are done, plus the two CodeRabbit findings from this morning, in three commits on a rebased head (06bb09ae).

Windows smoke. The log told a different story than the symlink-privilege guess: on Windows CI os.Symlink succeeds, but a stat through the self-referential bin link reports absence rather than a durable failure, so EnsureLocalEngine read it as "not installed" and the test died at the assertion, not the fixture. Per your option 2, TestEnsureLocalEngineStopsWhenTheInstalledEngineCannotBeProbed is now a two-row table that drives both probe failures through the holderFS seam — a stat fault on the binary, and a readDir fault on the tree — so the contract holds identically on every platform. TestEnsureLocalEngineRefusesACompatPathThatIsASymlink keeps its real link (the production check is lstat, which has no seam) but now skips rather than fails where os.Symlink is unavailable, matching the workspacetrust pattern.

Rebase. Done — clean onto 1e4db7c6, no conflicts; CI is running on the rebased head now.

The two CodeRabbit findings were both real and both small, so they came along rather than waiting for a follow-up: resolveEnginePathsErr no longer drops a flattenSingleChild failure — anything but fs.ErrNotExist propagates, which is exactly the the tree cannot be listed row above (it fails on the unfixed code: the unlistable tree gets set aside and the download proceeds). And maxInstallTagBytes now reserves the widest sibling suffix — the 34-byte sequenced holder — instead of .lock, so an overlong tag is refused where it is set instead of at the holder mkdir after the download.

Full suite is green locally (go test ./... on the rebased head); one unrelated flake in internal/config's provider-command deadline test passed on re-run and touches nothing in this diff.

Vasanthdev20041mo ago

@beardthelion this one is approved, but it's 90 commits behind main and was built with Go 1.26.6, so it only ran the older six-check CI set: no Race Detector, and govulncheck would now fail on the 1.26.6 standard library. Could you merge main? It merges cleanly. If you'd rather I do it, say so; maintainer edits are on for this branch. The push will dismiss the two approvals, and I'll re-review straight after.

beardthelion1mo ago

Merged latest main, CI rerunning.

Vasanthdev20041mo ago

@beardthelion sorry to ask again so soon: #1105 moved the module to github.com/Twigpine/zero a few hours after your merge, and this branch still adds imports with the old path, so it needs main merged once more and those imports renamed. Main won't build until #1153 lands, so it's easiest to do after that.