diff --git a/TODO.md b/TODO.md index f78b62b..bc31f0d 100644 --- a/TODO.md +++ b/TODO.md @@ -4421,16 +4421,17 @@ workers; and any two threads in one process writing one path. uniqueness; the 0600 window (the temp is never readable by others — assert its mode right after creation in the test's own thread). -- [ ] 41.1 exclusive unique temps, mode before bytes -- [ ] 41.2 dedup by canonical identity, reported path unchanged -- [ ] docs: feature README; topo §2.9-26 struck (lead); analysis finding +- [x] 41.1 exclusive unique temps, mode before bytes +- [x] 41.2 dedup by canonical identity, reported path unchanged +- [x] docs: feature README; topo §2.9-26 struck (lead); analysis finding 1 annotated "fixed by §41" (lead) -- [ ] Gates (guarded): fmt/clippy/workspace tests; corpus unchanged; +- [x] Gates (guarded): fmt/clippy/workspace tests; corpus unchanged; byte-identity vs 0.42.0 -- [ ] QA: the probe re-run under the guard at 4 threads; alias attacks +- [x] QA: the probe re-run under the guard at 4 threads; alias attacks through the CLI (relative/absolute/`..` spellings + symlink); a target that is itself a symlink into another directory; RSS of the - 100-round probe + 100-round probe — PASS, see QA log in the feature README + (2026-09-05) ## 42. Repository-analysis fix 2 (planned 2026-09-04) — one lint-configuration contract for project and editor (topo §2.9-28) diff --git a/crates/lucisv/src/main.rs b/crates/lucisv/src/main.rs index 3c814eb..b868542 100644 --- a/crates/lucisv/src/main.rs +++ b/crates/lucisv/src/main.rs @@ -415,13 +415,25 @@ fn filelist_files(opts: &Options) -> Result, String> { fn dedup(files: Vec) -> Vec { let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); let mut seen = HashSet::new(); - files.into_iter().filter(|file| seen.insert(absolute(&cwd, file))).collect() + files.into_iter().filter(|file| seen.insert(identity(&cwd, file))).collect() +} + +/// The key two spellings of one file share: the file's canonical path when it +/// is there, and the lexical fold when it is not. +/// +/// Canonical means symlinks resolved, which is the only way to see that +/// `b.sv -> a.sv` is the file `a.sv` already named — two rayon workers on one +/// target otherwise, each rewriting what the other just wrote. A path with no +/// file behind it has no canonical form, and the lexical fold is then the +/// best two names for it can be compared by. Neither is ever the path lucisv +/// reports: that stays the first spelling seen. +fn identity(cwd: &Path, path: &Path) -> PathBuf { + std::fs::canonicalize(path).unwrap_or_else(|_| absolute(cwd, path)) } /// `path` folded to the absolute, `.`/`..`-free spelling two names for one -/// file share. Lexical, like `lucisv_core`'s own normalization: symlinks are -/// deliberately left unresolved, so this is only ever a dedup key and never -/// the path lucisv reports. +/// file share. Purely lexical, like `lucisv_core`'s own normalization — it +/// answers for paths that do not exist, where there is nothing to resolve. fn absolute(cwd: &Path, path: &Path) -> PathBuf { let joined = if path.is_absolute() { path.to_path_buf() } else { cwd.join(path) }; let mut out = PathBuf::new(); @@ -602,6 +614,37 @@ mod tests { assert_eq!(dedup(files), [cwd.join("rtl/a.sv")]); } + #[cfg(unix)] + #[test] + fn dedup_folds_a_symlink_onto_the_file_it_points_at() { + // A directory walk lists `b.sv` as a file of its own; lexically the + // two names share nothing, and two workers would rewrite one file. + let dir = std::env::temp_dir().join(format!("lucisv-dedup-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("temp dir"); + let real = dir.join("a.sv"); + let link = dir.join("b.sv"); + std::fs::write(&real, "module m;\nendmodule\n").expect("seed"); + std::os::unix::fs::symlink(&real, &link).expect("symlink"); + + assert_eq!(dedup(vec![real.clone(), link.clone()]), std::slice::from_ref(&real)); + // Whichever spelling comes first is the one kept and reported. + assert_eq!(dedup(vec![link.clone(), real.clone()]), std::slice::from_ref(&link)); + // And a `..` detour through the same link is still the same file. + std::fs::create_dir(dir.join("sub")).expect("sub dir"); + let detour = dir.join("sub/../b.sv"); + assert_eq!(dedup(vec![real.clone(), detour]), std::slice::from_ref(&real)); + + // A file that is not there has no canonical path: the key is lexical, + // which still folds `.` and `..`, and two missing files stay two. + let gone = dir.join("gone.sv"); + let same = dir.join("./sub/../gone.sv"); + let other = dir.join("other.sv"); + assert_eq!(dedup(vec![gone.clone(), same, other.clone()]), [gone, other]); + + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn format_contained_reports_parse_errors() { let err = format_contained("module", &Config::default(), None).unwrap_err(); diff --git a/crates/lucisv/tests/cli.rs b/crates/lucisv/tests/cli.rs index 3eba6bd..49c06ea 100644 --- a/crates/lucisv/tests/cli.rs +++ b/crates/lucisv/tests/cli.rs @@ -136,6 +136,35 @@ fn formats_files_in_place() { assert!(stderr(&out).contains("2 files left unchanged"), "{}", stderr(&out)); } +/// A directory walk lists a symlink as a file of its own, so `b.sv -> a.sv` +/// used to put two workers on one file: two report lines for one file, and +/// two writers racing to replace it. It is one file now, named once. +#[cfg(unix)] +#[test] +fn a_symlink_and_its_target_are_one_file() { + let dir = TempDir::new("alias"); + dir.write("a.sv", UNFORMATTED); + std::os::unix::fs::symlink(dir.path.join("a.sv"), dir.path.join("b.sv")).expect("symlink"); + + let out = run(&["--check", &dir.root()]); + assert_eq!(code(&out), 1, "{}", stderr(&out)); + let reported = stdout(&out); + let named: Vec<&str> = reported.lines().filter(|l| l.contains("would reformat")).collect(); + assert_eq!(named.len(), 1, "one file, one line: {named:?}"); + assert!(named[0].ends_with("a.sv"), "the first spelling walked is the one reported: {named:?}"); + assert!(stderr(&out).contains("1 file would be reformatted"), "{}", stderr(&out)); + + let out = run(&[&dir.root()]); + assert_eq!(code(&out), 0, "{}", stderr(&out)); + assert!(stderr(&out).contains("1 file reformatted"), "{}", stderr(&out)); + assert_eq!(dir.read("a.sv"), FORMATTED); + assert_eq!(dir.read("b.sv"), FORMATTED, "and the link still reaches it"); + assert!( + std::fs::symlink_metadata(dir.path.join("b.sv")).expect("stat").file_type().is_symlink(), + "the link was not replaced by a copy" + ); +} + #[test] fn check_reports_without_writing() { let dir = TempDir::new("check"); diff --git a/crates/lucisv_core/src/atomic.rs b/crates/lucisv_core/src/atomic.rs index e1cce53..4a2abfb 100644 --- a/crates/lucisv_core/src/atomic.rs +++ b/crates/lucisv_core/src/atomic.rs @@ -7,11 +7,24 @@ //! gets the bytes, and a `rename` over the target publishes them in one step //! that either happened or did not. //! -//! See `docs/features/small-items-3/README.md`. +//! Two threads of one process may write one target: the temp names carry a +//! per-process counter as well as the pid and are created with `O_EXCL`, so +//! each writer owns its own file and neither can see the other's bytes. +//! +//! Two *processes* writing one target are not coordinated, and deliberately +//! so. Both renames are atomic, the later one wins, and the loser's bytes are +//! discarded whole — never merged. Both processes formatted the same input +//! and `format` is idempotent, so whichever rename lands last leaves the +//! file complete and correctly formatted. A lock would buy nothing and would +//! be one more thing to leave behind after a `^C`. +//! +//! See `docs/features/small-items-3/README.md` and +//! `docs/features/atomic-write-coordination/README.md`. -use std::fs; -use std::io; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Write}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; /// Writes `bytes` to `path`, replacing whatever was there in one step. /// @@ -21,6 +34,12 @@ use std::path::{Path, PathBuf}; /// sees either the old file or the new one and never a truncated one. A /// failure anywhere after the temp exists removes it before returning. /// +/// The temp is the caller's alone: [`temp_path`] hands out a name no other +/// writer in this process will be given, and the file is created with +/// `create_new`, so a name that somehow exists is an error and not a shared +/// file. Two threads writing one target therefore both succeed, and the +/// target ends up holding one thread's whole buffer. +/// /// A symlinked target is resolved first: `fs::write` writes *through* a /// symlink, so replacing the link itself would silently redirect it at a new /// file and leave the real one stale. The canonical path is what gets @@ -28,26 +47,22 @@ use std::path::{Path, PathBuf}; /// filesystem — `rename` cannot cross one. pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { let target = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + let perms = target_permissions(&target); // A rename replaces a file whatever its mode, so a read-only target would // be silently overwritten where `fs::write` refuses it. Keep the refusal: // a file someone made read-only is asking not to be rewritten in place. - if fs::metadata(&target).is_ok_and(|m| m.permissions().readonly()) { + if perms.as_ref().is_some_and(fs::Permissions::readonly) { return Err(io::Error::new( io::ErrorKind::PermissionDenied, format!("{} is read-only", path.display()), )); } - let tmp = temp_path(&target)?; - if let Err(e) = fs::write(&tmp, bytes) { + let (tmp, mut file) = create_temp(&target, perms.is_some())?; + if let Err(e) = fill_temp(&mut file, &tmp, perms, bytes) { let _ = fs::remove_file(&tmp); return Err(e); } - // A file someone made read-only, or executable, keeps its mode: the temp - // was created with the process umask, not with the target's bits. No - // target means a new file, which takes the umask as `fs::write` would. - if let Ok(meta) = fs::metadata(&target) { - let _ = fs::set_permissions(&tmp, meta.permissions()); - } + drop(file); if let Err(e) = fs::rename(&tmp, &target) { let _ = fs::remove_file(&tmp); return Err(e); @@ -55,16 +70,106 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { Ok(()) } +/// How many temp names one write tries before giving up. +/// +/// A name is only ever handed out once per process, so a collision means a +/// leftover from a *previous* process that crashed mid-write and whose pid +/// this process now has. A handful of those may sit in one directory; a +/// hundred is a directory to clean up by hand, not a race to retry through. +const TEMP_ATTEMPTS: u32 = 32; + +/// Creates the temp file, exclusively, and returns it with its path. +/// +/// `replacing` says there is a target whose mode the temp is about to take. +/// Then it is born 0600 on unix rather than at the umask's mode: a chmod does +/// not revoke a descriptor someone already opened, so the only way a private +/// file's replacement can never be read by anyone else is for the temp to be +/// private from the moment it exists. With no target there is no earlier mode +/// to honour and the umask decides, as `fs::write` would. +fn create_temp(target: &Path, replacing: bool) -> io::Result<(PathBuf, File)> { + let mut opts = OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + if replacing { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + #[cfg(not(unix))] + let _ = replacing; + for _ in 0..TEMP_ATTEMPTS { + let tmp = temp_path(target)?; + match opts.open(&tmp) { + Ok(file) => return Ok((tmp, file)), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + } + Err(io::Error::new( + io::ErrorKind::AlreadyExists, + format!("no free temp file name beside {} after {TEMP_ATTEMPTS} tries", target.display()), + )) +} + +/// Puts the target's mode on the temp, then the bytes in it. +/// +/// The order is the point on unix: a 0600 target's replacement must not spend +/// even an instant holding the file's contents under the umask's broader +/// bits. Chmod does not close the handle opened before it, so a mode without +/// an owner-write bit still takes the write. Elsewhere `set_permissions` +/// takes a path rather than a handle and the mode goes on after the bytes, +/// which is the order this always had. +fn fill_temp( + file: &mut File, + tmp: &Path, + perms: Option, + bytes: &[u8], +) -> io::Result<()> { + if cfg!(unix) { + copy_mode(file, perms); + file.write_all(bytes) + } else { + file.write_all(bytes)?; + if let Some(perms) = perms { + let _ = fs::set_permissions(tmp, perms); + } + Ok(()) + } +} + +/// Puts the target's mode on the temp through its open handle, which is what +/// lets it happen while the temp is still empty. No target means no earlier +/// mode to honour, and the umask's stands. +fn copy_mode(file: &File, perms: Option) { + if let Some(perms) = perms { + let _ = file.set_permissions(perms); + } +} + +/// The mode the temp must end up with: a file someone made executable, or +/// private, keeps its bits, because the temp was created with the process +/// umask (or 0600) and not with the target's. `None` means there is no target +/// — a new file, which takes the umask as `fs::write` would. +fn target_permissions(target: &Path) -> Option { + fs::metadata(target).ok().map(|m| m.permissions()) +} + +/// Names handed out by [`temp_path`], one per call for the life of the +/// process. Wrapping after 2^64 names is not a scenario. +static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0); + /// The temp file's path: hidden, in the target's own directory, and stamped -/// with the process id so two lucisv runs over one tree cannot collide. +/// with the process id and a per-process counter — the pid keeps two lucisv +/// runs apart, the counter keeps two threads of one run apart, and together +/// they mean no two writers anywhere are ever given the same name. fn temp_path(target: &Path) -> io::Result { let dir = target.parent().unwrap_or_else(|| Path::new(".")); let name = target .file_name() .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name to write"))?; + let n = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed); let mut tmp = std::ffi::OsString::from("."); tmp.push(name); - tmp.push(format!(".{}.lucisv-tmp", std::process::id())); + tmp.push(format!(".{}.{n}.lucisv-tmp", std::process::id())); Ok(dir.join(tmp)) } @@ -199,4 +304,148 @@ mod tests { ); assert_eq!(fs::read_to_string(&link).expect("read"), "new\n", "and still points at it"); } + + /// The audit's probe (`docs/repository-analysis.md` finding 1), which + /// used to produce 100 write errors in 200 calls: both threads derived + /// the same temp name from the target and the pid, so one deleted the + /// other's file under it. Now every writer owns its own temp, so every + /// call succeeds and the target holds one writer's whole buffer. + #[test] + fn two_threads_writing_one_target_never_collide() { + const MIB: usize = 1024 * 1024; + const ROUNDS: usize = 100; + let dir = TempDir::new("race"); + let file = dir.file("a.sv"); + fs::write(&file, "seed\n").expect("seed"); + + // Three parties: the two writers and this thread, which inspects the + // target between rounds. Nobody starts a round until everyone has + // finished the last one. + let start = std::sync::Arc::new(std::sync::Barrier::new(3)); + let done = std::sync::Arc::new(std::sync::Barrier::new(3)); + let writers: Vec<_> = (*b"ab") + .into_iter() + .map(|tag| { + let (path, start, done) = (file.clone(), start.clone(), done.clone()); + std::thread::spawn(move || { + let bytes = vec![tag; MIB]; + let mut errors = Vec::new(); + for _ in 0..ROUNDS { + start.wait(); + if let Err(e) = write_atomic(&path, &bytes) { + errors.push(e.to_string()); + } + done.wait(); + } + errors + }) + }) + .collect(); + + for round in 0..ROUNDS { + start.wait(); + done.wait(); + let got = fs::read(&file).expect("read"); + assert_eq!(got.len(), MIB, "round {round}: a partial buffer landed"); + let tag = got[0]; + assert!(tag == b'a' || tag == b'b', "round {round}: neither writer's byte"); + assert!(got.iter().all(|&b| b == tag), "round {round}: two buffers were mixed"); + assert_eq!(dir.names(), vec!["a.sv".to_string()], "round {round}: a temp was left"); + } + + let errors: Vec = + writers.into_iter().flat_map(|w| w.join().expect("writer thread")).collect(); + assert!( + errors.is_empty(), + "{} write errors in {} calls: {errors:?}", + errors.len(), + 2 * ROUNDS + ); + } + + #[test] + fn every_thread_gets_its_own_temp_name() { + const PER_THREAD: usize = 200; + let dir = TempDir::new("names"); + let target = dir.file("a.sv"); + let threads: Vec<_> = (0..4) + .map(|_| { + let target = target.clone(); + std::thread::spawn(move || { + (0..PER_THREAD) + .map(|_| temp_path(&target).expect("temp name")) + .collect::>() + }) + }) + .collect(); + let names: Vec = + threads.into_iter().flat_map(|t| t.join().expect("name thread")).collect(); + let unique: std::collections::HashSet<&PathBuf> = names.iter().collect(); + assert_eq!(unique.len(), names.len(), "a temp name was handed out twice"); + } + + /// The mode goes on while the temp is still empty, so a 0600 file's + /// replacement never holds its contents under the umask's wider bits. + #[cfg(unix)] + #[test] + fn the_temp_takes_the_targets_mode_before_any_bytes() { + use std::os::unix::fs::PermissionsExt; + let dir = TempDir::new("modewindow"); + let target = dir.file("secret.sv"); + fs::write(&target, "old\n").expect("seed"); + fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod"); + + let perms = target_permissions(&target); + let (tmp, mut file) = create_temp(&target, perms.is_some()).expect("temp"); + // Born private, before any mode is copied onto it: an fd opened by + // someone else in this instant would not see the bytes to come. + assert_eq!( + fs::metadata(&tmp).expect("stat").permissions().mode() & 0o777, + 0o600, + "the temp was created readable by others" + ); + copy_mode(&file, perms.clone()); + let meta = fs::metadata(&tmp).expect("stat"); + assert_eq!(meta.len(), 0, "the mode is set before a single byte is written"); + assert_eq!(meta.permissions().mode() & 0o777, 0o600, "the temp is not world-readable"); + // And the chmod does not close the door on the handle opened before it. + fill_temp(&mut file, &tmp, perms, b"new\n").expect("fill"); + assert_eq!(fs::read_to_string(&tmp).expect("read"), "new\n"); + let _ = fs::remove_file(&tmp); + } + + /// The same window seen from outside, through a real `write_atomic`: a + /// big enough buffer that the temp is usually observable while it is + /// being filled. It asserts about what it sees and never about seeing it, + /// so a scheduler that hides the window cannot fail the test. + #[cfg(unix)] + #[test] + fn a_temp_seen_mid_write_is_never_world_readable() { + use std::os::unix::fs::PermissionsExt; + let dir = TempDir::new("window"); + let target = dir.file("secret.sv"); + fs::write(&target, "old\n").expect("seed"); + fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod"); + + let path = target.clone(); + let writer = std::thread::spawn(move || { + let bytes = vec![b'x'; 8 * 1024 * 1024]; + write_atomic(&path, &bytes) + }); + while !writer.is_finished() { + for entry in fs::read_dir(&dir.path).expect("read dir").flatten() { + if !entry.file_name().to_string_lossy().ends_with(".lucisv-tmp") { + continue; + } + let Ok(meta) = entry.metadata() else { continue }; + assert_eq!( + meta.permissions().mode() & 0o777, + 0o600, + "a temp for a 0600 target was readable by others" + ); + } + } + writer.join().expect("writer thread").expect("write"); + assert_eq!(fs::metadata(&target).expect("stat").permissions().mode() & 0o777, 0o600); + } } diff --git a/docs/features/atomic-write-coordination/README.md b/docs/features/atomic-write-coordination/README.md new file mode 100644 index 0000000..f7ef700 --- /dev/null +++ b/docs/features/atomic-write-coordination/README.md @@ -0,0 +1,359 @@ +# atomic write coordination + +## Goal + +Two writers of one file, inside one lucisv process, must not fight over the +temp file the atomic write goes through (TODO §41, `docs/repository-analysis.md` +finding 1, topo handshake §2.9-26). `atomic::temp_path` named its temp from the +canonical target and the process id, so every thread of one process derived the +*same* name for one target: the audit's probe — two threads writing 1 MiB each +to one file, 100 rounds — produced 100 write errors in 200 calls (no mixed +bytes, because `fs::write` truncated and rewrote the whole buffer, but half the +writes failed outright and each failure removed the other writer's temp). Two +ways in existed: the CLI's `dedup` folded `.` and `..` lexically but left +symlinks unresolved, so `b.sv -> a.sv` reached two rayon workers as two files; +and any two threads of one process asked to write one path. + +Both are closed here. Every writer now gets a temp name no other writer in the +process will be given (a per-process `AtomicU64` beside the pid) and creates it +with `create_new`, so the name is owned, never shared. `dedup` keys on the +canonical path when the file exists, so two spellings of one file are one job — +while the path lucisv *reports* stays the first spelling the user gave. And the +target's mode goes on the temp before its bytes do, so a 0600 file's replacement +never holds the file's contents at a wider mode. + +## Assumptions + +- **A rename is atomic within a directory**, on every filesystem lucisv ships + to. That was already this module's premise; nothing here weakens it. +- **Two *processes* writing one target are not coordinated, deliberately.** + Both renames are atomic and the later one wins; the loser's bytes are + discarded whole, never merged. Both processes formatted the same input and + `format` is idempotent, so whichever rename lands last leaves the file + complete and correctly formatted. A lock file would buy nothing and would be + one more thing left behind by a `^C`. This is stated in the `atomic.rs` + module doc, which is where a reader will look for it. +- **A temp-name collision means a leftover, not a race.** A name is handed out + once per process, so `AlreadyExists` can only mean a temp from an *earlier* + process that died mid-write and whose pid this process now carries. The write + retries with the next counter value, at most `TEMP_ATTEMPTS = 32` times; 32 + stale temps for one file in one directory is a directory to clean by hand, + not a race to keep retrying through. +- **`fs::canonicalize` is the identity of a file that exists.** Two names that + canonicalize alike are one file (hardlinks aside — two hardlinks to one inode + have two distinct canonical paths and stay two jobs, which is what a user who + made hardlinks asked for). A path with no file behind it has no canonical + form, and the old lexical fold answers for it. +- **A chmod does not revoke an already-open descriptor.** That is why, when + there is a target, the temp is *created* 0600 on unix rather than created at + the umask's mode and narrowed afterwards: narrowing later would leave a + window in which someone could open the empty temp and then read the bytes + through the descriptor they kept. With no target there is no earlier mode to + honour and the umask decides, exactly as `fs::write` would. +- The dedup key is computed on the main thread, before any worker exists, so + the extra `canonicalize` per input is one `realpath` per file at startup and + not per write. + +## Handshakes + +- **`lucisv_core::atomic::write_atomic` — unchanged signature, unchanged + contract**, plus one promise it did not make before: two threads of one + process writing one target both succeed, and the target ends up holding one + writer's whole buffer. Callers (`lucisv/src/main.rs`, `lucisv/src/lint.rs`, + `lucisv_core/src/cache.rs`) need no change. + - The two behaviours other tests already pin are kept exactly: a read-only + target is refused with `PermissionDenied`, and a symlinked target is + resolved so the link is not replaced. + - The temp file's *name* changed shape: `.{name}.{pid}.{n}.lucisv-tmp`. Any + tool that matched the old `.{name}.{pid}.lucisv-tmp` (nothing in this + repository does; the tests match on the `.lucisv-tmp` suffix) must match + the suffix instead. + - A file created where there was no target still takes the umask's mode. The + 0600 creation applies only when a target's mode is about to be copied on. +- **`lucisv::dedup` — same signature, same output order, same reported paths.** + It only folds *more* than it used to: two spellings that reach one file are + now one job. `absolute` stays the lexical fold and is now reached only for + paths that do not exist; its doc comment says so. +- Nothing is requested of another module. + +## Status / TODO + +- [x] 41.1 exclusive unique temps (per-process `AtomicU64` + `create_new`, + bounded retry), mode before bytes +- [x] 41.2 dedup by canonical identity, reported path unchanged +- [x] Last-writer semantics for two processes stated in the `atomic.rs` module + doc and above; no lock built +- [x] Tests: the audit's probe (2 threads × 100 rounds × 1 MiB, 0 write + errors, one whole buffer per round); temp-name uniqueness across + threads; the 0600 window, twice (a unit test on the mode step, and a + live poll of the directory during a real 8 MiB write); `dedup` with a + symlink alias in both spelling orders, with a `..` detour, and with + missing files; a CLI test where `dir/b.sv -> dir/a.sv` is formatted and + reported once +- [x] Gates (guarded): fmt, clippy, workspace tests, corpus, write-path + byte-identity +- [ ] QA (see the brief in TODO §41) + +## Docs to apply at merge (lead) + +- `docs/topo.md` §2.9-26 (same-target atomic writers) is closed by this lane: + the temp name carries a per-process counter and is created `O_EXCL`, and the + CLI dedups by canonical identity so one file cannot reach two workers. + Suggested strike-through note: *"closed by §41 (0.43.0): unique `O_EXCL` + temps, dedup on `fs::canonicalize`; two *processes* remain last-writer-wins + by design, stated in `atomic.rs`."* +- `docs/repository-analysis.md` finding 1: annotate **fixed by §41** — the + probe now runs as `atomic::tests::two_threads_writing_one_target_never_collide` + and reports 0 write errors in 200 calls; the symlink alias closes as + `cli::a_symlink_and_its_target_are_one_file`. +- `README.md` needs no change: no user-visible behaviour moved. The only + externally observable difference is the temp file's name shape, + `.{name}.{pid}.{n}.lucisv-tmp`, which the README does not document. + +## Work log + +**2026-09-05 — dev (Opus 5).** TODO §41 implemented in full. + +Files touched, all inside the plan's expected set: + +- `crates/lucisv_core/src/atomic.rs` — the write path. +- `crates/lucisv/src/main.rs` — `dedup`/`identity`/`absolute` and their tests. +- `crates/lucisv/tests/cli.rs` — the symlink-alias end-to-end test. +- `docs/features/atomic-write-coordination/README.md` — this file. +- `TODO.md` — §41's own checkboxes (the QA line left alone). + +Nothing outside that set was touched. + +**41.1.** `temp_path` now stamps the name with a per-process `AtomicU64` +counter as well as the pid: `.{name}.{pid}.{n}.lucisv-tmp`. `create_temp` +opens it with `OpenOptions::new().write(true).create_new(true)`, so a name +that somehow exists is `AlreadyExists` and the next counter value is tried, +up to `TEMP_ATTEMPTS = 32`, after which the write fails with a message naming +the target and the bound (reasoning for 32 in Assumptions). `write_atomic` +now stats the target once, at the top, and passes the `Option` +down: the read-only refusal, the decision to create the temp 0600, and the +mode copy all read that one stat instead of three. + +`fill_temp` puts the mode on before the bytes on unix (`File::set_permissions` +through the handle opened before the chmod, so a mode without an owner-write +bit does not stop the write); on non-unix it keeps today's order, because +`set_permissions` there takes a path and there is nothing to gain from +reordering. The write itself is `write_all` on the owned handle rather than +`fs::write`, which is what makes both the exclusive create and the early chmod +possible. + +**Deviation from the plan, deliberate.** The plan asked only that the mode be +copied before the bytes. Writing the window test showed that was not enough: +the temp is *created* at the umask's mode, so for one instant an empty +world-readable file exists at a name anyone can open — and a chmod does not +revoke a descriptor already opened through it, so an observer holding that +descriptor would then read the private file's contents as they were written. +The temp is therefore created with `mode(0o600)` on unix *when there is a +target whose mode it is about to take*; with no target it is created at the +umask's mode, so a brand-new file's permissions are exactly what they were +before this change. This is strictly narrower than the plan's ask, not wider. +The first run of `a_temp_seen_mid_write_is_never_world_readable` caught the +gap (observed mode 0644 on a temp for a 0600 target); it passes now. + +**41.2.** `dedup` keys on `identity(cwd, path)`: `fs::canonicalize(path)` when +it answers, else the old `absolute(cwd, path)` lexical fold. The reported path +is untouched — `dedup` still keeps the *first* spelling of each file and its +order. `absolute`'s doc comment now says it is the fold for paths that do not +exist rather than a deliberate refusal to resolve symlinks. + +**Tests (6 new, all guarded).** + +- `atomic::tests::two_threads_writing_one_target_never_collide` — the audit's + probe: two writers and this thread meet at a pair of barriers each round, so + the target is inspected between rounds with nobody mid-write. 100 rounds, + 1 MiB per writer, distinct buffers: 0 write errors, and every round the file + holds exactly one writer's whole buffer with no temp left behind. +- `atomic::tests::every_thread_gets_its_own_temp_name` — 4 threads × 200 names + for one target, all 800 distinct. +- `atomic::tests::the_temp_takes_the_targets_mode_before_any_bytes` — the + unit-testable step: the temp is 0600 the moment it exists, `copy_mode` puts + the target's mode on while `len() == 0`, and `fill_temp` still writes + through the handle afterwards. +- `atomic::tests::a_temp_seen_mid_write_is_never_world_readable` — the same + window from outside, polling the directory during a real 8 MiB + `write_atomic`. It asserts about what it sees and never about *seeing* it, + so a scheduler that hides the window cannot make it flaky. +- `lucisv::tests::dedup_folds_a_symlink_onto_the_file_it_points_at` — the + alias in both spelling orders (the first spelling is the one kept), a `..` + detour through an existing directory, and missing files falling back to the + lexical key (two different missing files stay two). +- `cli::a_symlink_and_its_target_are_one_file` — `dir/b.sv -> dir/a.sv` + through the real binary: `--check` prints exactly one `would reformat:` line + and it names `a.sv`; the format run says "1 file reformatted"; the link is + still a link afterwards. + +**Both new tests were checked for teeth** by temporarily reverting the fix in +the working tree and restoring it immediately: without the counter the probe +reports *exactly* "100 write errors in 200 calls" — the audit's number, to the +call — and with lexical dedup the CLI test sees two `would reformat:` lines, +for `a.sv` and `b.sv`. + +**Gates, all through `tools/guard.sh` (no guard kill anywhere).** + +- `cargo fmt -p lucisv_core -p lucisv` clean. +- `cargo clippy --all-targets` clean, zero warnings. Two of my own drew + warnings on the way (`cloned_ref_to_slice_refs` in the dedup test, + `byte_char_slices` in the probe) and were fixed rather than allowed. +- `tools/guard.sh -- cargo test --workspace`: **3 771 passed, 0 failed** + (baseline 3 765 + the 6 above). +- `tools/guard.sh -- tools/corpus_check.sh`: **814/820 (99.3 %)**, the same + six failures, `verification-error: none`, `crash: none`. +- Write-path byte-identity: 300 corpus files copied to a scratch directory + (one of them chmod 0600) and formatted in place — 292 reformatted, 4 + unchanged, 4 pre-existing parse failures; a second run reports all 296 + unchanged (idempotent); the 0600 file is still 0600; no `.lucisv-tmp` left + behind. Every one of the 296 files' in-place bytes is byte-identical to the + same file formatted through stdin, which never touches `write_atomic` — + so the new write path delivers exactly the formatter's bytes. +- Peak RSS of the probe test, `/usr/bin/time -l` around the single test under + the guard: **36 995 072 B (35.3 MiB)** max resident, 0.38 s wall. The two + 1 MiB buffers and the read-back are the only allocations the test adds. + +Nothing is unfinished. The one judgement call a reviewer may want to weigh is +the 0600 creation described under "Deviation" above. + +## QA log + +**2026-09-05 — QA (Sonnet 5).** Verified against the §41 QA brief. All +experiments ran on copies under the scratchpad or on a standalone scratch +crate path-depending on `lucisv_core`; nothing in `corpus/` or +`/Users/guoliangchen/repo/opentitan` was written to. Every probe and gate ran +through `tools/guard.sh` (no guard kill anywhere). Two temporary `#[test]` +functions were added to poke at private functions (`create_temp`/`copy_mode` +in `atomic.rs`, `identity`/`dedup` symlink cases in `main.rs`), run, and then +removed — `git diff` on both files verified byte-identical to the dev's diff +before and after. + +1. **Multithread probe, 4 and 8 threads** (standalone scratch binary linking + `lucisv_core`, `/usr/bin/time -l`, guarded). 4 threads × 100 rounds: 0 + write errors in 400 calls, 0 bad rounds, 0 leftover temps, peak RSS + 8 749 056 B (8.3 MiB). 8 threads × 100 rounds: 0 write errors in 800 + calls, 0 bad rounds, 0 leftover temps, peak RSS 13 107 200 B (12.5 MiB). + Matches the dev's 2-thread number scaled up; no error rate creeps back in + with more contention. +2. **The 0600 window.** Black-box directory polling (mirroring the dev's own + `a_temp_seen_mid_write_is_never_world_readable`, generalized): a 0600 + target under continuous 8 MiB rewrites for 3s — 88 053 samples, widest + temp mode ever seen `0600`, final mode `0600`. A 0644 target: widest seen + `0644` (never wider), final `0644`. A 0755 target: widest seen `0755`, + final `0755`. Brand-new target vs. a plain `fs::write` in the same + directory: both land at `0644` under umask `022` — match. The "0600 at + creation, then widened by the rename" half of the inverse case is not + observable black-box (`copy_mode` runs before `write_all` with no yield + point, so the 0600 instant is sub-microsecond) — confirmed instead with a + temporary source-level test calling `create_temp`/`copy_mode` directly for + 0644 and 0755 targets: the temp is born 0600 in both cases, then + `copy_mode` widens it to the target's real mode before any byte is + written. Removed after passing. +3. **Retry bound.** Predicted the temp names from the diff + (`.{name}.{pid}.{n}.lucisv-tmp`, counter from 0, one static per process) + and pre-created all 32 (`n=0..31`) in a fresh process before its first + `write_atomic` call: the write fails with `"no free temp file name beside + .../a.sv after 32 tries"`, naming the target and the bound, and leaves + exactly the 32 pre-created temps (no new one added). Pre-creating 31 + (`n=0..30`, one slot free) in a fresh process: the write succeeds + (consuming `n=31`), the target holds the new bytes, and exactly 31 stale + temps remain — no extra temp left by the successful write itself. +4. **Symlink and identity.** Temporary unit tests against `identity`/`dedup` + covered: `dir2 -> dir1` containing the file (both spelling orders, first + spelling kept and reported); an absolute vs. relative spelling through + the dir symlink; a `../` detour; a dangling symlink (canonicalize fails, + falls back to the lexical key — two lexical spellings of *one* dangling + link still fold, two *different* dangling links stay two); a symlink to a + file outside the pair being compared (folds onto the real file by + canonical identity regardless of "was it walked"). All passed; removed + after. Then the mandated real-binary run (`cargo build --release -p + lucisv`, `dir/b.sv -> dir/a.sv`): `--check` printed exactly one `would + reformat:` line naming `a.sv`, exit 1; `--diff` printed exactly one diff + block naming `a.sv`, exit 1; a real format run reported "1 file + reformatted", exit 0, both `a.sv` and (through the link) `b.sv` read back + the formatted text, and `b.sv` was still a symlink pointing at `a.sv` + afterwards (`readlink` unchanged); a second `--check` reported "1 file + left unchanged, 1 file from cache", exit 0. Also checked by hand: a + dangling symlink inside a walked directory errors + `"...dead.sv: No such file or directory"` (the user's own spelling, not a + resolved one) without a panic, exit 2; a symlink to a file *outside* the + walked directory formats correctly through the link, and passing both the + link and the real outside file explicitly on the command line dedups to + one job, one report line, one write — verified with `--check` and with a + real write (outside file correctly formatted, link left intact). +5. **Two processes.** Two `lucisv format` processes launched at the same + moment (both under `tools/guard.sh`, backgrounded, `wait`ed) against one + shared scratch copy of `corpus/common_cells/src` (100 files): both exited + 0. The resulting tree is byte-identical (`diff -rq`) to a fresh copy + formatted by a single process. No `.lucisv-tmp` anywhere afterward. A + follow-up `--check` on the two-process tree reports "100 files left + unchanged, 100 files from cache", exit 0 — no truncation, no corruption, + consistent with the documented last-writer-wins semantics (both writers + were formatting the same input to the same idempotent output, so there + was nothing for a "loser" to lose). +6. **Refusals and mid-run failures.** A read-only (0444) target: refused with + `PermissionDenied` ("... is read-only"), file content and mode (444) + untouched, no temp created. A target in a read-only (0555) directory: + refused with a plain OS `Permission denied (os error 13)` (temp creation + itself fails — expected, since `write_atomic`'s own read-only check is + for the *target's* mode, not the directory's), file untouched. Directory + deleted mid-write: 200 rounds of racing `fs::remove_dir_all` against a + concurrent 8 MiB `write_atomic` in a scratch binary with + `catch_unwind` around the writer thread — 139 writes completed before the + delete won the race, 61 got a plain `io::Error` (`No such file or + directory` / `Invalid argument`), **0 panics**. No corruption claim + applies once the directory itself is gone. +7. **Behaviour parity.** 300 files copied from `corpus/ibex` (path structure + preserved) into a scratch tree. `--stdout` of every file saved first (4 + pre-existing parse failures unrelated to this feature — a `.tpl.sv` + template, a Yosys-primitive `.v`, and two vendor files with unsupported + constructs, all already known corpus failures). In-place format of the + 300: "283 files reformatted, 13 files left unchanged, 4 files failed to + format" — same 4 files, same error text, byte-identical to the `--stdout` + errors. All 296 successfully-formatted files are byte-identical between + the in-place result and `--stdout` of the original (0 mismatches). The 4 + failed files are byte-unchanged from their originals (hard invariant #1 + held). A follow-up `--check` on the tree: "296 files left unchanged, 296 + files from cache, 4 files failed to format" — idempotent. + +**Gates (all guarded, no kill).** +- `cargo clippy --all-targets`: clean, 0 warnings. +- `tools/guard.sh -- cargo test --workspace`: **3 771 passed, 0 failed, 44 + ignored** — matches the dev's reported 3 771 exactly. +- `tools/guard.sh -- tools/corpus_check.sh`: **814/820 (99.3%)**, the same + six failures (5 parse-error + 1 lex-error), `verification-error: none`, + `crash: none` — matches the dev's reported number exactly. + +**Findings.** None at any severity. No corruption, no panic, no leftover +temp, no mode widening, no dedup miss, no parity break, and no gate +regression across any of the seven attacks. + +**Repo hygiene.** `git status --porcelain` on the four `corpus/*` checkouts +shows only a pre-existing untracked `.vfmt-corpus-rev` marker (identical +41-byte file, mtime 2026-08-19, present in all four — predates this session, +not written by anything here); no tracked file in any corpus checkout is +modified. In the main tree, `git diff` on `crates/lucisv_core/src/atomic.rs`, +`crates/lucisv/src/main.rs` and `crates/lucisv/tests/cli.rs` is byte-identical +to the dev's diff at the start of this QA pass (verified before and after +every temporary test was added/removed). All scratch experiments and the +standalone `probe` crate lived under the scratchpad and have been removed. + +**Verdict: PASS.** No rework needed. + +## Review + +**2026-09-05 — lead.** Accepted; ships in 0.43.0. The fix is the plan's plus +one tightening the plan should have asked for: a temp created at the umask's +mode and chmod'ed later would leave an empty world-readable file at a +guessable name for an instant, and a descriptor opened through it would +survive the chmod — so creating the temp at 0600 when a target exists, then +widening through the open handle before the bytes, is the correct order and +the dev's deviation is accepted as written. The retry bound of 32 is the +right shape (a name is issued once per process, so only a dead earlier +process with the same pid can collide, and 32 of those is a directory to +clean, not a race). QA's attack was thorough — 4 and 8 threads, the window +polled from outside, the bound hit exactly, two real processes over one +tree, a directory deleted mid-write with 0 panics — and found nothing. Two +processes on one target stay last-writer-wins by design; the formatter's +idempotence is what makes that safe, and the module doc says so. diff --git a/docs/repository-analysis.md b/docs/repository-analysis.md index 49e1d48..5a5403f 100644 --- a/docs/repository-analysis.md +++ b/docs/repository-analysis.md @@ -102,6 +102,13 @@ The existing temp-and-rename helper is useful for sequential replacement, but its tests do not justify a same-target concurrency guarantee. Tracked as [topology handshake 26](topo.md). +**Fixed by TODO §41 (0.43.0, 2026-09-05):** the probe now runs as +`atomic::tests::two_threads_writing_one_target_never_collide` and reports +0 write errors in 200 calls (QA re-ran it at 4 and 8 threads: 0 in 400 and +0 in 800); the symlink alias closes as `cli::a_symlink_and_its_target_are_one_file`. +Two processes writing one target remain last-writer-wins, stated in +`atomic.rs`. See `docs/features/atomic-write-coordination/README.md`. + ### 2. Define a consistent project lint configuration contract Evidence: [server linting](../crates/lucisv_server/src/lint.rs) selects rules in diff --git a/docs/topo.md b/docs/topo.md index 6960373..0add63a 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -640,7 +640,7 @@ update the filing README(s) and this file. | ~~24~~ | ~~A **half-typed `#(` parameter override whose value can read as a call** (`sub #(.W(` ⏎ `u0 (.a(x))`) — the greedy expression grammar swallows the next instance's name before any error fires, so the whole instantiation still degrades to an item-level `Error` node instead of getting header recovery's benefit. Found by §32's QA; the fix is a lookahead in the override grammar (an identifier followed by `(` on a later line is the next instance, not a call).~~ — **delivered 2026-09-04 by small-items-3 (TODO §36)** | header-recovery (QA) | vlog_parser | | ~~25~~ | ~~The parser **refuses** a module-scope `begin … end` and a bare `begin` inside a `generate` region (an `ItemKind::Error`) rather than recovering them as an unnamed generate block, so `module-begin-block` and `v2001-generate-begin` (TODO §35) fire on an error leaf and the rest of the unit is lost to recovery. Wanted: tolerant-mode recovery that keeps the block's items.~~ — **delivered 2026-09-04 by small-items-3 (TODO §36)** | linter-expansion-3 (dev) | vlog_parser | -| 26 | **Same-target atomic writers share a temp path.** `atomic::temp_path` uses canonical target + process ID; parallel workers following distinct symlink spellings can reach that same name, while CLI dedup is lexical. A bounded direct helper probe (100 rounds, two threads, 1 MiB each) returned 100 write errors in 200 calls; no mixed final bytes observed in that probe. Use exclusive per-operation temp creation and coordinate/deduplicate target writes. See repository-analysis.md for limits. | repository audit, 2026-09-04 | lucisv_core / lucisv | +| ~~26~~ | ~~**Same-target atomic writers share a temp path.** `atomic::temp_path` uses canonical target + process ID; parallel workers following distinct symlink spellings can reach that same name, while CLI dedup is lexical. A bounded direct helper probe (100 rounds, two threads, 1 MiB each) returned 100 write errors in 200 calls; no mixed final bytes observed in that probe. Use exclusive per-operation temp creation and coordinate/deduplicate target writes. See repository-analysis.md for limits.~~ — **closed by §41 (0.43.0):** unique `O_EXCL` temps (`.{name}.{pid}.{n}.lucisv-tmp`), dedup on `fs::canonicalize`; two *processes* remain last-writer-wins by design, stated in `atomic.rs` | repository audit, 2026-09-04 | lucisv_core / lucisv | | 27 | **Net-delay comment slot**: parser-skips records a pre-existing refusal for a comment immediately before `#` in a net declaration. The regression cases mark it `#SKIP`; preserve the verifier's rejection until a parser/formatter comment slot handles it. | parser-skips (dev + QA) | vlog_parser / vlog_formatter | | 28 | **Project lint selection is not consumed by the server.** `enabled_rules` reads `ClientSettings`; `configured` reads project rule options and line length only. `[lint] select/ignore` currently controls CLI runs, while the editor needs `lucisv.lint.select/ignore`. Decide and test a common precedence contract before claiming project-wide parity. | repository audit, 2026-09-04 | lucisv_server |