From d62f649b22cf78a27794241f4c7d2c3dd554a312 Mon Sep 17 00:00:00 2001 From: "orbit[gemini-4-hydrogen-high]" Date: Sun, 22 Nov 2026 00:23:35 -0800 Subject: [PATCH] fix: rust-cli-template: lock tests count waits instead of [ORB-26751] rust-cli-template: lock tests count waits instead of timing them; escape record text on stderr Completed all three items: Orbit-Task: ORB-26751 Orchestrated-By: Orchestrated-By: opus --- crates/tmpl-cli-core/src/note.rs | 6 +-- crates/tmpl-cli-core/src/store/fsio.rs | 36 ++++++++++---- crates/tmpl-cli-core/src/store/mod.rs | 24 +++++++++- crates/tmpl-cli-core/src/store/tests/store.rs | 18 +++---- crates/tmpl-cli/src/commands/tests/note.rs | 14 +++--- crates/tmpl-cli/src/output/mod.rs | 13 +++-- crates/tmpl-cli/src/output/render.rs | 4 +- crates/tmpl-cli/tests/cli.rs | 47 +++++++++++++++++++ 8 files changed, 126 insertions(+), 36 deletions(-) diff --git a/crates/tmpl-cli-core/src/note.rs b/crates/tmpl-cli-core/src/note.rs index 122fb4b..35c3fcb 100644 --- a/crates/tmpl-cli-core/src/note.rs +++ b/crates/tmpl-cli-core/src/note.rs @@ -19,7 +19,7 @@ use time::OffsetDateTime; #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum NoteError { /// The id was not a positive integer. - #[error("invalid note id '{0}': expected a positive integer such as 1")] + #[error("invalid note id {0:?}: expected a positive integer such as 1")] InvalidId(String), /// The title was empty or only whitespace. #[error("title is empty: pass some text, e.g. \"Buy milk\"")] @@ -35,12 +35,12 @@ pub enum NoteError { EmptyBody, /// The tag had characters outside `a-z`, `0-9` and `-`, or a bad length. #[error( - "invalid tag '{0}': use 1-{max} lowercase letters, digits or '-'", + "invalid tag {0:?}: use 1-{max} lowercase letters, digits or '-'", max = Tag::MAX_CHARS )] InvalidTag(String), /// The priority was not one of [`Priority::NAMES`]. - #[error("invalid priority '{0}': expected one of low, normal, high")] + #[error("invalid priority {0:?}: expected one of low, normal, high")] InvalidPriority(String), } diff --git a/crates/tmpl-cli-core/src/store/fsio.rs b/crates/tmpl-cli-core/src/store/fsio.rs index 32cad2a..45ca344 100644 --- a/crates/tmpl-cli-core/src/store/fsio.rs +++ b/crates/tmpl-cli-core/src/store/fsio.rs @@ -256,7 +256,22 @@ impl LockGuard { /// /// `label` says what the holder is doing; it is recorded with the pid and /// time so a writer that times out can say who is in the way. + #[cfg_attr( + not(test), + expect(dead_code, reason = "unobserved lock helper used by fsio tests") + )] pub(super) fn acquire(path: &Path, label: &str, wait: Duration) -> Result { + Self::acquire_observing(path, label, wait, || {}) + } + + /// Take the lock at `path`, invoking `on_contended` once if acquisition + /// encounters an active holder (`WouldBlock`). + pub(super) fn acquire_observing( + path: &Path, + label: &str, + wait: Duration, + on_contended: impl FnOnce(), + ) -> Result { // Never create or truncate through a link (STD-05 R7). match fs::symlink_metadata(path) { Ok(meta) => refuse_symlink(path, &meta)?, @@ -271,18 +286,23 @@ impl LockGuard { .open(path) .map_err(|e| Error::io("open lock file", path, e))?; let started = Instant::now(); + let mut on_contended = Some(on_contended); loop { match file.try_lock() { Ok(()) => break, - Err(TryLockError::WouldBlock) if started.elapsed() < wait => { - std::thread::sleep(LOCK_POLL); - } Err(TryLockError::WouldBlock) => { - return Err(Error::Locked { - path: path.to_path_buf(), - holder: read_holder(&mut file), - waited_ms: started.elapsed().as_millis(), - }); + if let Some(notify) = on_contended.take() { + notify(); + } + if started.elapsed() < wait { + std::thread::sleep(LOCK_POLL); + } else { + return Err(Error::Locked { + path: path.to_path_buf(), + holder: read_holder(&mut file), + waited_ms: started.elapsed().as_millis(), + }); + } } Err(TryLockError::Error(e)) => return Err(Error::io("lock", path, e)), } diff --git a/crates/tmpl-cli-core/src/store/mod.rs b/crates/tmpl-cli-core/src/store/mod.rs index f9ee4ce..598f2f5 100644 --- a/crates/tmpl-cli-core/src/store/mod.rs +++ b/crates/tmpl-cli-core/src/store/mod.rs @@ -36,6 +36,8 @@ use format::StoreDocument; use fsio::LockGuard; use std::fs; use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; use time::OffsetDateTime; @@ -68,6 +70,7 @@ pub struct Loaded { pub struct Store { root: PathBuf, lock_wait: Duration, + contended_lock_waits: Arc, } impl Store { @@ -78,6 +81,7 @@ impl Store { Self { root: root.into(), lock_wait: DEFAULT_LOCK_WAIT, + contended_lock_waits: Arc::new(AtomicUsize::new(0)), } } @@ -88,6 +92,13 @@ impl Store { self } + /// Count of contended lock acquisitions observed through this store handle + /// (and clones of it), used by tests instead of timing lock deadlines. + #[must_use] + pub fn contended_lock_waits(&self) -> usize { + self.contended_lock_waits.load(Ordering::Relaxed) + } + /// The data directory. #[must_use] pub fn root(&self) -> &Path { @@ -188,11 +199,20 @@ impl Store { } fn lock(&self, label: &str) -> Result { - LockGuard::acquire(&self.root.join(LOCK_FILE), label, self.lock_wait) + LockGuard::acquire_observing(&self.root.join(LOCK_FILE), label, self.lock_wait, || { + self.contended_lock_waits.fetch_add(1, Ordering::Relaxed); + }) } fn audit_lock(&self, label: &str) -> Result { - LockGuard::acquire(&self.root.join(AUDIT_LOCK_FILE), label, self.lock_wait) + LockGuard::acquire_observing( + &self.root.join(AUDIT_LOCK_FILE), + label, + self.lock_wait, + || { + self.contended_lock_waits.fetch_add(1, Ordering::Relaxed); + }, + ) } fn load(&self) -> Result { diff --git a/crates/tmpl-cli-core/src/store/tests/store.rs b/crates/tmpl-cli-core/src/store/tests/store.rs index 08fc8e3..7f24843 100644 --- a/crates/tmpl-cli-core/src/store/tests/store.rs +++ b/crates/tmpl-cli-core/src/store/tests/store.rs @@ -59,22 +59,21 @@ fn record_audit_appends_one_line_per_event_and_creates_the_directory() { #[test] fn record_audit_succeeds_while_the_store_lock_is_held() { // Defect 1: a command that timed out on the store lock must still write - // its failure audit line without waiting a second lock deadline. + // its failure audit line without waiting on the store lock a second time. let dir = super::private_tempdir(); - let deadline = Duration::from_millis(80); - let store = Store::open(dir.path()).with_lock_wait(deadline); + let store = Store::open(dir.path()).with_lock_wait(Duration::ZERO); let _held = LockGuard::acquire(&dir.path().join(".lock"), "test", Duration::from_secs(1)).unwrap(); - let started = std::time::Instant::now(); let err = store .add(new_note("blocked"), OffsetDateTime::UNIX_EPOCH) .unwrap_err(); assert_eq!(err.code(), "store_locked"); + assert_eq!(store.contended_lock_waits(), 1); store.record_audit(&event("note add")).unwrap(); - let elapsed = started.elapsed(); - assert!( - elapsed < deadline * 2, - "add + record_audit waited more than one deadline: {elapsed:?}" + assert_eq!( + store.contended_lock_waits(), + 1, + "record_audit must not contend on the held store lock" ); let text = std::fs::read_to_string(store.audit_path()).unwrap(); assert_eq!(text.lines().count(), 1, "got {text:?}"); @@ -83,7 +82,7 @@ fn record_audit_succeeds_while_the_store_lock_is_held() { #[test] fn record_audit_waits_for_the_audit_lock() { let dir = super::private_tempdir(); - let store = Store::open(dir.path()).with_lock_wait(Duration::from_millis(60)); + let store = Store::open(dir.path()).with_lock_wait(Duration::ZERO); let _held = LockGuard::acquire( &dir.path().join(".audit.lock"), "test", @@ -92,6 +91,7 @@ fn record_audit_waits_for_the_audit_lock() { .unwrap(); let err = store.record_audit(&event("note add")).unwrap_err(); assert!(matches!(err, Error::Locked { .. }), "got {err:?}"); + assert_eq!(store.contended_lock_waits(), 1); assert!(!store.audit_path().exists()); } diff --git a/crates/tmpl-cli/src/commands/tests/note.rs b/crates/tmpl-cli/src/commands/tests/note.rs index 712235d..eb9dbf9 100644 --- a/crates/tmpl-cli/src/commands/tests/note.rs +++ b/crates/tmpl-cli/src/commands/tests/note.rs @@ -83,7 +83,7 @@ fn lock_timeout_audited_command_waits_one_deadline_and_records_one_failure_line( use crate::app::Context; use crate::commands::run_with; use std::fs::OpenOptions; - use std::time::{Duration, Instant}; + use std::time::Duration; use tmpl_cli_core::Store; let dir = tempfile::tempdir().unwrap(); @@ -104,28 +104,26 @@ fn lock_timeout_audited_command_waits_one_deadline_and_records_one_failure_line( .unwrap(); lock_file.try_lock().unwrap(); - let deadline = Duration::from_millis(80); - let store = Store::open(dir.path()).with_lock_wait(deadline); + let store = Store::open(dir.path()).with_lock_wait(Duration::ZERO); let ctx = Context::with_store(store, Some(String::from("alice"))); let cmd = command(&["tmpl-cli", "note", "add", "blocked"]); - let started = Instant::now(); let mut audit_written_before_finish = false; let err_code = run_with(cmd, &ctx, |outcome| { // The audit guard must not have dropped before finish runs. audit_written_before_finish = ctx.store().audit_path().exists(); outcome.unwrap_err().code() }); - let elapsed = started.elapsed(); assert_eq!(err_code, "store_locked"); assert!( !audit_written_before_finish, "finish must run before the audit guard drops" ); - assert!( - elapsed >= deadline && elapsed < deadline * 2, - "expected roughly one deadline ({deadline:?}), took {elapsed:?}" + assert_eq!( + ctx.store().contended_lock_waits(), + 1, + "failing audited command must wait on the store lock once, not twice" ); let audit_raw = std::fs::read_to_string(ctx.store().audit_path()).unwrap(); diff --git a/crates/tmpl-cli/src/output/mod.rs b/crates/tmpl-cli/src/output/mod.rs index b7a4756..26685c8 100644 --- a/crates/tmpl-cli/src/output/mod.rs +++ b/crates/tmpl-cli/src/output/mod.rs @@ -91,7 +91,8 @@ pub(crate) fn finish_parse_error(err: &clap::Error, args: &[OsString]) -> ExitCo let message = first.strip_prefix("error: ").unwrap_or(first); write_json_error(message, "usage_error"); } else { - let _ = io::stderr().lock().write_all(rendered.as_bytes()); + let sanitized = render::sanitize_for_display(&rendered); + let _ = io::stderr().lock().write_all(sanitized.as_bytes()); } ExitCode::from(code) } @@ -108,10 +109,10 @@ fn emit(sink: &Sink, output: &Output) -> io::Result<()> { // never fail a command whose payload is fine. let mut err = io::stderr().lock(); for warning in warnings { - let _ = writeln!(err, "warning: {warning}"); + let _ = writeln!(err, "warning: {}", render::sanitize_for_display(warning)); } if let Some(notice) = notice { - let _ = writeln!(err, "{notice}"); + let _ = writeln!(err, "{}", render::sanitize_for_display(notice)); } } let mut out = io::stdout().lock(); @@ -139,7 +140,11 @@ fn report_error(json: bool, err: &CliError) { if json { write_json_error(&message, err.code()); } else { - let _ = writeln!(io::stderr().lock(), "error: {message}"); + let _ = writeln!( + io::stderr().lock(), + "error: {}", + render::sanitize_for_display(&message) + ); } } diff --git a/crates/tmpl-cli/src/output/render.rs b/crates/tmpl-cli/src/output/render.rs index 752342b..d4246d5 100644 --- a/crates/tmpl-cli/src/output/render.rs +++ b/crates/tmpl-cli/src/output/render.rs @@ -95,8 +95,8 @@ pub(crate) fn note_detail(out: &mut dyn Write, sink: &Sink, note: &NotePayload) } /// Neutralize control characters other than newline and tab so terminal -/// escape sequences and carriage returns cannot reach stdout raw. -fn sanitize_for_display(text: &str) -> String { +/// escape sequences and carriage returns cannot reach stdout or stderr raw. +pub(super) fn sanitize_for_display(text: &str) -> String { let mut out = String::with_capacity(text.len()); let mut chars = text.chars().peekable(); while let Some(c) = chars.next() { diff --git a/crates/tmpl-cli/tests/cli.rs b/crates/tmpl-cli/tests/cli.rs index 2d2e9b8..830e898 100644 --- a/crates/tmpl-cli/tests/cli.rs +++ b/crates/tmpl-cli/tests/cli.rs @@ -541,6 +541,53 @@ fn bad_records_warn_on_reads_fail_on_show_and_refuse_writes_without_touching_sto ); } +#[test] +fn bad_record_control_characters_are_escaped_on_stderr() { + let fx = Fixture::new(); + std::fs::create_dir_all(fx.root()).unwrap(); + support::make_private(&fx.root()); + let store_path = fx.root().join("notes.json"); + let raw = r#"{ + "format": 1, + "notes": [ + {"id": 1, "title": "Good note", "body": null, "tags": ["home"], "priority": "normal", "created_at": "2026-01-02T03:04:05Z"}, + {"id": 2, "title": "Bad tag", "body": null, "tags": ["bad\u001b[31mtag"], "priority": "normal", "created_at": "2026-01-02T03:04:05Z"}, + {"id": 3, "title": "Bad\u001b[31mtitle", "body": null, "tags": [], "priority": "normal", "created_at": "2026-01-02T03:04:05Z"}, + {"id": 4, "title": "Bad priority", "body": null, "tags": [], "priority": "bad\u001b[31mprio", "created_at": "2026-01-02T03:04:05Z"} + ] +}"#; + std::fs::write(&store_path, raw).unwrap(); + support::make_private(&store_path); + + let assert_clean_stderr = |args: &[&str], expected_code: i32| { + let out = fx.run(args); + assert_eq!(out.status.code(), Some(expected_code), "{args:?}"); + let bad_byte = out + .stderr + .iter() + .copied() + .find(|&b| b < 0x20 && b != b'\n' && b != b'\t'); + assert_eq!( + bad_byte, + None, + "{args:?} emitted raw control byte in stderr: {:?}", + String::from_utf8_lossy(&out.stderr) + ); + out + }; + + let list_plain = assert_clean_stderr(&["note", "list"], 0); + assert!(text(&list_plain.stderr).contains("warning:")); + assert_clean_stderr(&["note", "list", "--json"], 0); + assert_clean_stderr(&["note", "add", "Should not write"], 1); + assert_clean_stderr(&["note", "add", "Should not write", "--json"], 1); + assert_clean_stderr(&["note", "show", "2"], 1); + assert_clean_stderr(&["note", "show", "3"], 1); + assert_clean_stderr(&["note", "show", "4"], 1); + assert_clean_stderr(&["note", "show", "bad\x1bid"], 2); + assert_clean_stderr(&["note", "add", "Bad arg", "--tag", "bad\x1btag"], 2); +} + #[test] fn help_states_defaults_for_tag_and_json() { let fx = Fixture::new();