Skip to content

Serialize model cache downloads and removals - #2

Open
ChrisX101010 wants to merge 2 commits into
programmersd21:mainfrom
ChrisX101010:fix/model-cache-lock
Open

ChrisX101010 wants to merge 2 commits into
programmersd21:mainfrom
ChrisX101010:fix/model-cache-lock

Conversation

@ChrisX101010

@ChrisX101010 ChrisX101010 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Use the same per-model file lock for downloads and both cache removal paths.
The OS releases the lock when the handle closes, so active downloads keep the
lock regardless of how long they take. Cache removal reports contention
without changing either the finished model or the partial download.

Validation

  • cargo fmt --check
  • cargo test --locked
  • Tests cover exclusive locking, preserving the model and partial file during
    a download, and removal after the lock is released.

Summary by Sourcery

Serialize per-model downloads and cache removal operations so active or partial model data remains protected from concurrent changes.

Bug Fixes:

  • Prevent model cache removal from deleting completed models or partial downloads while another process is downloading the same model.
  • Preserve download completion, pause, and failure handling when download results are returned directly from the worker.

Enhancements:

  • Serialize downloads and cache removals with persistent per-model OS-level locks while retaining compatibility with legacy lock markers.
  • Report cache-lock contention clearly and reject unsafe lock paths.

Build:

  • Add the Unix rustix filesystem dependency required for cache locking.

Tests:

  • Add coverage for download-lock contention, protected cache files during active downloads, legacy lock behavior, and invalid lock paths.

Chores:

  • Simplify download error propagation by returning worker outcomes instead of using temporary error files.

@sourcery-ai

sourcery-ai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Use a persistent OS-managed per-model lock for downloads and cache removals, while coordinating with legacy lock markers and keeping removal failures from modifying cached files.

  • src/model.rs L683-700, L710-760, L766-792 (+2 small edits)

UI

Return download completion, pause, and failure outcomes directly to the TUI so it can update download state and messages without relying on progress sentinels or cache error notes.

  • src/main.rs L304-312, L318-324, L885-939 (+8 small edits)

Configuration

Add the Unix filesystem-locking dependency needed to open the persistent cache lock safely.

  • Cargo.toml L51-53

Tests

Add a test-only cache-directory override and test that public removals respect active locks, contend with legacy markers, and reject an invalid lock path.

  • src/model.rs L415-426, L1303-1380

Verify that the TUI displays a download failure supplied directly by the worker result.

  • src/main.rs L1053-1065

Update the YouTube ID test to use the direct Option::is_none assertion.

  • src/util.rs L694

Lock files and vendored code

Record the dependency-resolution changes for the new Unix filesystem-locking dependency.

  • Cargo.lock L2580

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

@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 2f432a81-45eb-48f4-9d91-ffc628074441
  • 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

@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 5 issues

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

## Individual Comments

### Comment 1
<location path="src/model.rs" line_range="720" />
<code_context>
-            Err(e) => Err(format!("cannot create download lock: {e}")),
+            .create(true)
+            .truncate(false)
+            .open(dir.join(format!(".{file}.cache.lock")))
+            .map_err(|e| format!("cannot open model cache lock: {e}"))?;
+        match lock.try_lock() {
</code_context>
<issue_to_address>
**Concurrent versions corrupt cached models**

When an older process and this version access the same model cache, `DownloadLock` opens `.{file}.lock` in the older version but `.{file}.cache.lock` here, so the locks do not contend and both processes can modify the same partial or finished model concurrently, leaving it corrupted or incomplete.

Use a lock path compatible with the older version for cache operations, and ensure this version uses that lock for downloads and removals.
</issue_to_address>

### Comment 2
<location path="src/model.rs" line_range="681" />
<code_context>
+            dir.join(info.file),
+            dir.join(format!("{}.part", info.file)),
+            dir.join(format!(".{}.error", info.file)),
+        ],
+    )
+}
</code_context>
<issue_to_address>
**Removed caches regain error notes**

When a download fails while removal runs or wins the lock race, the download caller writes the `.error` note after `download_from` releases `DownloadLock`, so `remove_cached_files` can delete the note before the UI reads it or finish first and have the caller recreate it; the UI shows a generic error or a removed cache retains stale error metadata.

Keep error-note creation and cache removal within the same per-model lock so the note cannot be lost or recreated outside the serialized operation.

Also at `src/model.rs:696`, `src/model.rs:722`.
</issue_to_address>

### Comment 3
<location path="src/model.rs" line_range="690-694" />
<code_context>
+    file: &str,
+    paths: impl IntoIterator<Item = PathBuf>,
+) -> Result<(), String> {
+    if !dir
+        .try_exists()
+        .map_err(|e| format!("cannot inspect model directory: {e}"))?
+    {
+        return Ok(());
+    }
+    let _lock = DownloadLock::acquire(dir, file)?;
</code_context>
<issue_to_address>
**Removal skips the shared lock**

When the cache directory does not yet exist and a download creates it while removal is running, `remove_cached_files` returns before acquiring `DownloadLock`, so a concurrent `download_from` can create the directory, acquire the lock, and leave a model in the cache after removal reports success.

Create the cache directory before acquiring the lock for removal, or otherwise synchronize the absent-directory case with downloads.
</issue_to_address>

### Comment 4
<location path="src/model.rs" line_range="720" />
<code_context>
-            Err(e) => Err(format!("cannot create download lock: {e}")),
+            .create(true)
+            .truncate(false)
+            .open(dir.join(format!(".{file}.cache.lock")))
+            .map_err(|e| format!("cannot open model cache lock: {e}"))?;
+        match lock.try_lock() {
</code_context>
<issue_to_address>
**Model operations hang on FIFO lock**

When another local user who can write to the configured shared cache directory precreates the per-model lock path as a FIFO, `OpenOptions::open` blocks while opening the FIFO, before `try_lock` runs, so a removal call on the TUI thread hangs and downloads cannot acquire the lock.

Open the lock file in a way that cannot block on special files, and reject lock paths that are not regular files.
</issue_to_address>

### Comment 5
<location path="src/model.rs" line_range="1258" />
<code_context>
+        let lock = DownloadLock::acquire(&dir, file).unwrap();
+
+        for paths in [vec![partial.clone()], vec![model.clone(), partial.clone()]] {
+            let err = remove_cached_files(&dir, file, paths).unwrap_err();
+            assert!(err.contains("another scribe"));
+        }
</code_context>
<issue_to_address>
**Public removals go untested**

When either public removal function stops delegating to the helper, if `remove_partial` or `remove_model` stops delegating to `remove_cached_files`, this test still passes: at line 1258 it calls the helper directly, as it does for the later removal assertions, so broken public removals can leave cached files in place unnoticed.

Exercise both public removal functions using a test-configurable cache directory.
</issue_to_address>

Sourcery assessment

Approval pending. 5 findings to address first.

Blocking findings: src/model.rs:720, src/model.rs:681, src/model.rs:694, src/model.rs:720, src/model.rs:1258


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

Comment thread src/model.rs Resolved
Comment thread src/model.rs Resolved
Comment thread src/model.rs Resolved
Comment thread src/model.rs Resolved
Comment thread src/model.rs Resolved

@programmersd21 programmersd21 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thanks, Chris. I audited the patch against the existing cache/download flow. I agree with the five blocking findings already raised by Sourcery; they are real correctness gaps, not style concerns:

  1. The lock filename changes from .{file}.lock to .{file}.cache.lock, so older Scribe processes do not contend with this version and can still modify the same cache concurrently.
  2. The .error note is written outside the new lock lifetime. A concurrent removal can race with that write, deleting a note before it is read or allowing stale metadata to reappear after removal.
  3. remove_cached_files returns when the cache directory is absent without synchronizing with a concurrent download that may create it immediately afterward.
  4. Opening the lock path can block if it is a FIFO or another special file. Validate that the lock path is a regular file using a nonblocking-safe open strategy before attempting the lock.
  5. The new test exercises remove_cached_files directly, not the public remove_partial and remove_model entry points. Add tests that call both public functions through a configurable cache directory.

Please address these together and add regression coverage for cross-version lock compatibility, error-note/removal ordering, the absent-directory race, special lock-file types, and both public removal APIs. I am holding approval until these are fixed and CI is green.

Keep the OS lock for current processes and guard legacy downloaders at the old lock path. Deliver download failures directly to the TUI and exercise both public removal methods.

@programmersd21 programmersd21 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

The five earlier Sourcery findings are now marked addressed, and the new CI run has passed formatting, Clippy, and the Rust 1.90 MSRV check. The full test suite is still running, so this is not ready to merge yet.

I also found a separate regression in the latest src/main.rs patch: three user-facing strings that previously contained · now contain the mojibake text · (the pause status, pause toast, and cancel status). Please restore the intended UTF-8 separator in all three places. After that, let CI finish and rerun the final review before merging.

Copy link
Copy Markdown
Owner

The latest CI run is fully green, and the five earlier locking findings are addressed. I found four remaining UTF-8 regressions in src/main.rs: the intended · separator is encoded as · in the pause status, pause toast, and cancel status strings. I attempted to correct the file, but GitHub denied write access to the fork. Please enable “Allow edits from maintainers” on this PR or push a commit restoring those four occurrences to ·. I will re-audit the resulting commit before approval.

Copy link
Copy Markdown
Owner

CI is now green on the current head, but this PR is not mergeable against the updated main after PR #1 was merged. The four mojibake separators are also still present in src/main.rs (· instead of ·). Please rebase/update this branch on the latest main, fix those four strings, and push the updated commit. I’ll re-check CI and mergeability after that.

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.

2 participants