Repository navigation
fix: address outstanding Sourcery review findings - #17
Conversation
Reviewer's GuideData structuresAdd a worker event variant for cancellation that completed with a cleanup warning, so callers can distinguish it from ordinary cancellation.
Uses of the APIHandle the new cancellation-warning event in the plain-segment collector and include it among terminal TUI events.
ImplementationValidate cache paths by resolving relative paths and inspecting ancestors, including symlinks and filesystem inspection failures.
Propagate temporary-file cleanup failures through fetch errors and add cleanup helpers that treat missing files as successfully removed.
Retry cache-removal contention, identify managed model selections by normalized paths, clear discarded selections, and guard against starting a duplicate download.
Accept valid scoped IPv6 and IPvFuture URL literals, preserve scoped-host spelling, and improve Windows path completion without probing UNC paths.
Preserve ingest completion state, cancel blocked readers before joining them, and report cancellation cleanup warnings without masking unrelated errors.
UIDisplay cancellation cleanup failures as a message overlay instead of presenting them as ordinary cancellation.
TestsExercise cache readiness for non-directory paths, inspection failures, dangling symlinks, relative paths, symlinked ancestors, and missing ancestor trees.
Verify fallback cleanup removes partial files and reports filesystem failures.
Test cache-removal retries and discarded-model selection behavior across equivalent, case-varied, symlinked, and custom paths.
Route custom-model header rejection through the public validator and verify unreadable headers are rejected.
Cover scoped IPv6 and IPvFuture validation plus Windows drive-relative, UNC, and end-to-end completion behavior.
Test terminal worker-event handling and deterministic cancellation of a reader blocked by backpressure.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars.
|
There was a problem hiding this comment.
Hey - I've found 7 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src/util.rs" line_range="101" />
<code_context>
+ && version.bytes().all(|byte| byte.is_ascii_hexdigit())
+ && !address.is_empty()
+ && address.bytes().all(|byte| {
+ byte.is_ascii_alphanumeric()
+ || b"-._~!pub fn parse_http_url(s: &str) -> Option<(String, String)> {
let s = s.trim();
</code_context>
<issue_to_address>
**Application cannot build**
The malformed `valid_ipvfuture` byte-string expression absorbs the `parse_http_url` declaration and leaves trailing fragments in the expression, so Rust rejects `src/util.rs` and the application cannot build.
Restore the IPvFuture predicate as valid Rust and place the `parse_http_url` declaration outside it.
Also at `src/util.rs:102-121`, `src/util.rs:838-839`.
</issue_to_address>
### Comment 2
<location path="src/worker.rs" line_range="456" />
<code_context>
// a cancelled job can return before the readers see eof. kill the
// decoder so their blocking reads end, then join them: no detached
// reader may outlive the job it was reading for.
+ self.cancel.store(true, Ordering::Relaxed);
kill_all(&self.children);
if let Some(h) = self.reader.take() {
</code_context>
<issue_to_address>
**Jobs finish as cancelled**
When `Ingest::finish()` runs during normal completion, `Ingest::drop` sets the shared cancellation flag after the readers are joined, and `run` checks that flag before reporting the pipeline result, so successful transcriptions are reported as cancelled.
Avoid setting the job-wide cancellation flag when `Ingest` is dropped after normal completion.
</issue_to_address>
### Comment 3
<location path="src/main.rs" line_range="915-916" />
<code_context>
- .and_then(model::remove_model);
+ .and_then(remove_discarded_model);
+ if result.is_ok() && app.model_name.ends_with(&app.download_file) {
+ app.model_name.clear();
+ app.model_label = "-".into();
+ }
app.download_discard = false;
</code_context>
<issue_to_address>
**Custom model selection is cleared**
When a selected custom model path ends with the discarded catalog model's filename, `finish_model_download` uses `ends_with` to match the selected model, so discarding the catalog download clears the unrelated custom model selection and resets its label.
Clear the selection only when it refers to the managed catalog download being discarded.
Also at `src/main.rs:914`.
</issue_to_address>
### Comment 4
<location path="src/doctor.rs" line_range="37" />
<code_context>
}
+ for ancestor in cache.ancestors().skip(1) {
+ match std::fs::symlink_metadata(ancestor) {
+ Ok(metadata) if metadata.is_dir() => {
+ return (
+ Verdict::Warn,
</code_context>
<issue_to_address>
**Valid symlinked caches fail checks**
When the cache path is missing beneath an existing symlink to a directory, `cache_status` uses `symlink_metadata`, which reports the symlink itself, so `metadata.is_dir()` is false and the doctor reports a usable cache location as a failure.
Follow symlinks when checking whether an existing cache-path ancestor is a directory.
Also at `src/doctor.rs:43`.
</issue_to_address>
### Comment 5
<location path="src/util.rs" line_range="838-839" />
<code_context>
+ assert!(is_url("http://[fe80::1%25eth0]/audio.wav"));
+ assert!(is_url("http://[fe80::1%25eth0]:8080/audio.wav"));
+ assert!(is_url("http://[v1.example]/audio.wav"));
+ assert!(is_url("http://[Vf.a:b! assert!(is_url("https://[2001:db8::1]:8443/audio.wav"));
+ assert!(!is_url("http://[not-ip]/audio.wav"));'()*+,;=]/audio.wav"));
+ assert!(!is_url("http://[fe80::1%25]/audio.wav"));
+ assert!(!is_url("http://[fe80::1%25bad%xx]/audio.wav"));
</code_context>
<issue_to_address>
**Test suite cannot build**
When the test suite is compiled, the `url_detection` assertions have mismatched string delimiters and trailing text, so Rust rejects the test module before the tests can run.
Repair the IPvFuture URL test assertions and their string delimiters.
</issue_to_address>
### Comment 6
<location path="src/main.rs" line_range="914-916" />
<code_context>
.ok_or_else(|| "downloaded model is no longer in the catalog".to_string())
- .and_then(model::remove_model);
+ .and_then(remove_discarded_model);
+ if result.is_ok() && app.model_name.ends_with(&app.download_file) {
+ app.model_name.clear();
+ app.model_label = "-".into();
+ }
app.download_discard = false;
</code_context>
<issue_to_address>
**Failed discard leaves a stale model selection**
When a sidecar removal fails after the completed model file was removed, `remove_model` can delete the completed model and then fail while removing a sidecar, returning an error after the model is already gone. Because the selection is cleared only on success, the app retains a selected path that no longer exists.
After a discard attempt, reconcile the selected model against the completed file's actual existence rather than relying only on the aggregate removal result.
</issue_to_address>
### Comment 7
<location path="src/doctor.rs" line_range="348" />
<code_context>
+ #[test]
+ fn cache_status_accepts_missing_parent_trees() {
+ let dir = std::env::temp_dir().join(format!("scribe-doctor-nested-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let cache = dir.join("one").join("two").join("models");
+ assert_eq!(
</code_context>
<issue_to_address>
**Missing-tree test can use stale directories**
When the temporary directory already exists and `remove_dir_all` cannot remove it, when `remove_dir_all` fails, `cache_status_accepts_missing_parent_trees` can see the existing `dir/one/two` parent and pass with the expected `Warn`, so an implementation that rejects missing ancestor trees still passes this test.
Assert that the directory was removed or create a fresh unique temporary directory and verify it is absent before checking the status.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 7 findings to address first, and on discard, the code now retries removal of the downloaded model after a transient cache-lock error, so the cached file may be deleted once another process releases the lock. The model can be downloaded again, but reverting this change would not restore a file already removed.
Blocking findings: src/util.rs:101, src/worker.rs:456, src/main.rs:916, src/doctor.rs:37, src/util.rs:839, and 2 more
|
@sourcery-ai review |
There was a problem hiding this comment.
Hey - I've found 6 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src/util.rs" line_range="825" />
<code_context>
+ assert!(is_url("http://[fe80::1%25eth0]/audio.wav"));
+ assert!(is_url("http://[fe80::1%25eth0]:8080/audio.wav"));
+ assert!(is_url("http://[v1.example]/audio.wav"));
+ assert!(is_url("http://[Vf.a:b! assert!(is_url("https://[2001:db8::1]:8443/audio.wav"));
+ assert!(!is_url("http://[not-ip]/audio.wav"));'()*+,;=]/audio.wav"));
+ assert!(!is_url("http://[fe80::1%25]/audio.wav"));
</code_context>
<issue_to_address>
**Test builds cannot parse URL assertions**
When the test target compiles `src/util.rs`, the new URL assertions contain malformed and nested string literals, so Rust cannot parse the test module and test builds stop before any tests run.
Correct the malformed URL assertion string literals.
</issue_to_address>
### Comment 2
<location path="src/doctor.rs" line_range="35-48" />
<code_context>
+ if std::fs::symlink_metadata(cache).is_ok() {
+ return (Verdict::Fail, "path exists but is not a usable directory");
+ }
+ for ancestor in cache.ancestors().skip(1) {
+ match std::fs::symlink_metadata(ancestor) {
+ Ok(metadata) if metadata.is_dir() || ancestor.is_dir() => {
+ return (
+ Verdict::Warn,
+ "will be created on first download; write access not tested",
+ );
+ }
+ Ok(_) => return (Verdict::Fail, "an ancestor is not a directory"),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+ Err(_) => return (Verdict::Fail, "cannot inspect cache path"),
+ }
}
+ (Verdict::Fail, "no existing parent directory")
}
</code_context>
<issue_to_address>
**Relative cache paths report failure**
When the cache path is relative and its cache directories do not exist, `cache_status` checks the empty ancestor reached by `cache.ancestors().skip(1)`, whose metadata lookup returns `NotFound`, then reports `Fail` even though the current directory can contain the cache; the doctor reports a usable cache as unavailable.
Resolve relative cache paths against the current directory or treat the empty ancestor as the current directory.
</issue_to_address>
### Comment 3
<location path="src/main.rs" line_range="892" />
<code_context>
+fn remove_discarded_model(info: &model::ModelInfo) -> Result<(), String> {
+ let mut last_error = String::new();
+ for attempt in 0..5 {
+ match model::remove_model(info) {
+ Ok(()) => return Ok(()),
+ Err(error) if error.contains("another scribe is using the model cache") && attempt < 4 => {
</code_context>
<issue_to_address>
**Partial download can remain after discard**
When a discard is handled as `DownloadOutcome::Paused` and another process briefly holds the model cache lock, `DownloadOutcome::Paused` handles discard with a single `model::remove_partial` call, while the new retries cover only `remove_model`; a transient cache-lock error therefore leaves the partial download behind and reports cancellation as complete only through an error message.
Apply the transient-lock retry to partial-file removal as well, or share a retry helper for both removal paths.
</issue_to_address>
### Comment 4
<location path="src/fetch.rs" line_range="276" />
<code_context>
-fn cleanup_fallback(fallback: &Path, direct: &Path) {
- let _ = std::fs::remove_file(fallback);
- let _ = std::fs::remove_file(direct);
+fn cleanup_fallback(fallback: &Path, direct: &Path) -> Result<(), String> {
+ let mut failures = Vec::new();
+ for path in [fallback, direct] {
</code_context>
<issue_to_address>
**Fallback cleanup errors stay hidden**
When fallback download completes just as cancellation is requested and removing either file fails, after the fallback process succeeds, `fetch_async` can observe cancellation and remove `path` and `direct` with ignored errors instead of using `cleanup_fallback`; a failed removal leaves a downloaded temporary file behind while the caller sees only `cancelled`.
Use the reporting cleanup helper on this cancellation path and append its error to the cancellation result.
</issue_to_address>
### Comment 5
<location path="src/fetch.rs" line_range="205" />
<code_context>
Err(e) => {
- cleanup_fallback(&fallback, &direct);
- return Err(format!("could not download audio: {e}"));
+ let cleanup = cleanup_fallback(&fallback, &direct);
+ return Err(format!("could not download audio: {e}{}", cleanup_suffix(cleanup)));
}
</code_context>
<issue_to_address>
**Cancellation hides cleanup failures**
When fallback cleanup fails during a cancelled fetch, `cleanup_suffix` adds a removal error to the cancellation result, but `worker::run` maps every result to `Cancelled` when the cancel flag is set; the cleanup error is discarded and the user is not told that the partial download remains.
Preserve and surface cleanup errors even when the fetch was cancelled, while still reporting the job as cancelled.
</issue_to_address>
### Comment 6
<location path="src/model.rs" line_range="1393-1404" />
<code_context>
+ #[cfg(unix)]
#[test]
- fn custom_model_header_read_errors_are_rejected() {
+ fn validate_custom_rejects_unreadable_model_headers() {
let dir = std::env::temp_dir().join(format!("scribe-header-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
- let path = dir.join("truncated.bin");
- fs::write(&path, b"gg").unwrap();
- assert!(read_model_header(&path).is_err());
+ for index in 0..512 {
+ fs::write(dir.join(format!("entry-{index}")), b"x").unwrap();
+ if fs::metadata(&dir).unwrap().len() >= 1024 {
+ break;
+ }
+ }
+ assert!(fs::metadata(&dir).unwrap().len() >= 1024);
+ assert!(read_model_header(&dir).is_err());
+ assert!(validate_custom(&dir).is_err());
fs::remove_dir_all(&dir).unwrap();
}
</code_context>
<issue_to_address>
**Header rejection test accepts unrelated failures**
The test only asserts that `validate_custom(&dir)` returns any error, and the directory can be rejected as an invalid model path before its header is read. The test therefore passes without exercising the public validator’s handling of unreadable headers.
Assert that the validator fails specifically because it cannot read the model header, or use an input that passes its file-type checks but fails during header reading.
</issue_to_address>Sourcery assessment
Approval pending. 6 findings to address first.
Blocking findings: src/util.rs:825, src/doctor.rs:48, src/main.rs:892, src/fetch.rs:276, src/fetch.rs:205, and 1 more
|
@sourcery-ai review |
Sourcery withdrew this approval because the latest commits introduced blocking findings.
|
@sourcery-ai review |
There was a problem hiding this comment.
Hey - I've found 4 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src/util.rs" line_range="102" />
<code_context>
+ && version.bytes().all(|byte| byte.is_ascii_hexdigit())
+ && !address.is_empty()
+ && address.bytes().all(|byte| {
+ byte.is_ascii_alphanumeric()
+ || b"-._~! !version.is_empty()
+ && version.bytes().all(|byte| byte.is_ascii_hexdigit())
</code_context>
<issue_to_address>
**Malformed predicate prevents builds**
The malformed, duplicated fragments in `valid_ipvfuture` make Rust reject `src/util.rs`, so the crate does not build.
Replace the corrupted fragments with a valid address predicate.
Also at `src/util.rs:103-113`.
</issue_to_address>
### Comment 2
<location path="src/main.rs" line_range="946-947" />
<code_context>
+fn clear_discarded_model_selection(app: &mut App, file: &str) {
+ let path = model::cache_dir().join(file);
+ let selected = normalized_path(std::path::Path::new(&app.model_name));
+ if !path.exists() && selected == normalized_path(&path) {
+ app.model_name.clear();
+ app.model_label = "-".into();
+ }
</code_context>
<issue_to_address>
**Symlinked model selection survives discard**
When the selected managed model was opened through a symlinked path, `normalized_path` only removes `.` and `..`, so a selected path that reaches the managed model through a symlink does not compare equal to the cache path. After the discard removes the cached file, the selection remains pointed at the deleted model and a later transcription fails to load it.
Compare the selected path and cache path by resolving their existing parent directories before appending the model filename, or otherwise track managed-model identity independently of its path.
</issue_to_address>
### Comment 3
<location path="src/main.rs" line_range="906" />
<code_context>
+ if error.contains("another scribe is using the model cache") && attempt < 4 =>
+ {
+ last_error = error;
+ std::thread::sleep(std::time::Duration::from_millis(40));
+ }
+ Err(error) => return Err(error),
</code_context>
<issue_to_address>
**Discard fails during longer contention**
When another Scribe process holds the model-cache lock for longer than the retry window, `retry_cache_removal` stops after five attempts spaced 40 ms apart, so a cache lock held for longer than about 160 ms returns an error even if it becomes available shortly afterward; the discard fails and the completed model remains on disk.
Use a longer bounded backoff or let the user retry the discard after a transient lock error.
</issue_to_address>
### Comment 4
<location path="src/doctor.rs" line_range="40" />
<code_context>
+ if cache.is_dir() {
+ return (Verdict::Ok, "directory exists; write access not tested");
+ }
+ if std::fs::symlink_metadata(&cache).is_ok() {
+ return (Verdict::Fail, "path exists but is not a usable directory");
+ }
</code_context>
<issue_to_address>
**Inaccessible cache reported as creatable**
When inspection of the cache path fails with a non-NotFound error while an ancestor is an accessible directory, `symlink_metadata(&cache)` errors other than success are treated like a missing cache path, so an existing parent directory makes `cache_status` return Warn and claim the cache will be created instead of reporting that the path cannot be inspected.
Match on the `symlink_metadata` error and continue to ancestor checks only for NotFound; return Fail for other errors.
</issue_to_address>Sourcery assessment
Approval pending. 4 findings to address first.
Blocking findings: src/util.rs:102, src/main.rs:947, src/main.rs:906, src/doctor.rs:40
There was a problem hiding this comment.
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/util.rs" line_range="103-106" />
<code_context>
+ && !address.is_empty()
+ && address
+ .bytes()
+ .all(|byte| byte.is_ascii_alphanumeric() || b"-._~! && address.bytes().all(|byte| {
+ byte.is_ascii_alphanumeric()
+ || b"-._~!$&'()*+,;=:".contains(&byte)
+ })'()*+,;=:".contains(&byte))
+}
+
</code_context>
<issue_to_address>
**Project cannot build**
`valid_ipvfuture` contains a malformed byte-string expression and mismatched delimiters, so Rust rejects `src/util.rs` and the project cannot build.
Correct the byte-string expression and delimiters in the `valid_ipvfuture` predicate.
</issue_to_address>
### Comment 2
<location path="src/main.rs" line_range="944" />
<code_context>
+fn clear_discarded_model_selection(app: &mut App, file: &str) {
+ let path = model::cache_dir().join(file);
+ let selected = normalized_path(std::path::Path::new(&app.model_name));
+ if !path.exists() && selected == normalized_path(&path) {
+ app.model_name.clear();
+ app.model_label = "-".into();
</code_context>
<issue_to_address>
**Discard leaves stale Windows selection**
When the selected managed-model path and cache path differ only in letter case on Windows, `normalized_path` removes `.` and `..` components but preserves case, so a selected managed-model path whose spelling differs only by case from the cache path does not compare equal on case-insensitive Windows filesystems. After discard removes the file, the app keeps the now-invalid model selection and later transcription fails to load it.
Compare paths using Windows case-insensitive semantics, or use a platform-aware path comparison before retaining the selection.
</issue_to_address>
### Comment 3
<location path="src/main.rs" line_range="943-944" />
<code_context>
+
+fn clear_discarded_model_selection(app: &mut App, file: &str) {
+ let path = model::cache_dir().join(file);
+ let selected = normalized_path(std::path::Path::new(&app.model_name));
+ if !path.exists() && selected == normalized_path(&path) {
+ app.model_name.clear();
+ app.model_label = "-".into();
</code_context>
<issue_to_address>
**Symlinked model selection stays stale**
When the selected model path is a symlink to the managed cache file and that file is discarded, `clear_discarded_model_selection` compares only lexically normalized paths. If the selected model name is a symlink to the cached model, removing the cached file leaves the symlink dangling but unequal to the cache path, so the app keeps a selection that no longer loads.
Resolve or otherwise recognize symlink aliases to the managed file before removal, then clear the selection when its target is discarded.
</issue_to_address>
### Comment 4
<location path="src/main.rs" line_range="1228" />
<code_context>
+ std::env::temp_dir().join(format!("scribe-relative-discard-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ crate::model::set_test_cache_dir(Some(dir.clone()));
+ let path = dir.join(info.file);
+ std::fs::write(&path, b"model").unwrap();
</code_context>
<issue_to_address>
**Parallel discard tests race**
When both discard tests run concurrently, `discard_clears_equivalent_managed_model_selection` and `cancel_after_download_commit_removes_the_completed_model` both change the process-wide cache override; concurrent execution can make cleanup inspect the other test’s directory or reset its override, so otherwise-correct tests fail.
Serialize tests that mutate the cache override, or make the override test-local.
</issue_to_address>
### Comment 5
<location path="src/worker.rs" line_range="1064" />
<code_context>
+ let cancel = Arc::new(AtomicBool::new(false));
+ let reader_cancel = cancel.clone();
+ let reader = thread::spawn(move || {
+ let sent = send_chunk(&tx, Chunk::Samples(vec![1.0]), &reader_cancel);
+ assert!(!sent);
+ 0
</code_context>
<issue_to_address>
**Backpressure is not synchronized**
When the reader has not reached `send_chunk`’s full-channel branch before `Ingest` is dropped, `dropping_ingest_unblocks_a_reader_waiting_on_backpressure` drops `Ingest` without confirming the reader reached a full-channel send; its `assert!(!sent)` therefore also passes if `send_chunk` immediately returns false, without testing that dropping unblocks a blocked reader.
Signal from the reader’s full-channel callback and wait for that signal before dropping `Ingest`.
</issue_to_address>Sourcery assessment
Approval pending. 5 findings to address first.
Blocking findings: src/util.rs:106, src/main.rs:944, src/main.rs:944, src/main.rs:1228, src/worker.rs:1064
summary
Address the outstanding Sourcery findings from the merged maintenance PRs.
verification
CI will run formatting, Clippy, tests, CLI smoke checks and the Rust 1.90 MSRV check.
Summary by Sourcery
Address outstanding maintenance findings across path completion, URL validation, cache management, model lifecycle handling, download cleanup, and cancellation behavior.
Bug Fixes:
Enhancements:
Tests: