TODO §41 (docs/features/atomic-write-coordination). Closes topo §2.9-26
and repository-analysis finding 1.
`atomic::write_atomic` names its temp `.{name}.{pid}.{n}.lucisv-tmp` with
a per-process counter and opens it create-new (O_EXCL), retrying a used
name up to 32 times; on unix the temp is created 0600 when a target
exists and takes the target's mode through the open handle before the
bytes are written, so a 0600 file never has a readable moment. The CLI's
`dedup` keys on the canonical path when the file exists, so a symlink
alias reaches one worker; the reported path is the first spelling. Two
processes on one target remain last-writer-wins (rename is atomic, the
formatter idempotent), stated in the module doc. The audit's probe is a
test: 0 write errors in 200 calls.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
22 KiB
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
formatis 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 theatomic.rsmodule 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
AlreadyExistscan 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 mostTEMP_ATTEMPTS = 32times; 32 stale temps for one file in one directory is a directory to clean by hand, not a race to keep retrying through. fs::canonicalizeis 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::writewould. - The dedup key is computed on the main thread, before any worker exists, so
the extra
canonicalizeper input is onerealpathper 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-tmpsuffix) 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.
- The two behaviours other tests already pin are kept exactly: a read-only
target is refused with
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.absolutestays 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
- 41.1 exclusive unique temps (per-process
AtomicU64+create_new, bounded retry), mode before bytes - 41.2 dedup by canonical identity, reported path unchanged
- Last-writer semantics for two processes stated in the
atomic.rsmodule doc and above; no lock built - 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);
dedupwith a symlink alias in both spelling orders, with a..detour, and with missing files; a CLI test wheredir/b.sv -> dir/a.svis formatted and reported once - 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 createdO_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): uniqueO_EXCLtemps, dedup onfs::canonicalize; two processes remain last-writer-wins by design, stated inatomic.rs."docs/repository-analysis.mdfinding 1: annotate fixed by §41 — the probe now runs asatomic::tests::two_threads_writing_one_target_never_collideand reports 0 write errors in 200 calls; the symlink alias closes ascli::a_symlink_and_its_target_are_one_file.README.mdneeds 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/absoluteand 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<Permissions>
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_modeputs the target's mode on whilelen() == 0, andfill_tempstill 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 MiBwrite_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.svthrough the real binary:--checkprints exactly onewould reformat:line and it namesa.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 lucisvclean.cargo clippy --all-targetsclean, zero warnings. Two of my own drew warnings on the way (cloned_ref_to_slice_refsin the dedup test,byte_char_slicesin 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-tmpleft behind. Every one of the 296 files' in-place bytes is byte-identical to the same file formatted through stdin, which never toucheswrite_atomic— so the new write path delivers exactly the formatter's bytes. - Peak RSS of the probe test,
/usr/bin/time -laround 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.
- 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. - 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 seen0600, final mode0600. A 0644 target: widest seen0644(never wider), final0644. A 0755 target: widest seen0755, final0755. Brand-new target vs. a plainfs::writein the same directory: both land at0644under umask022— match. The "0600 at creation, then widened by the rename" half of the inverse case is not observable black-box (copy_moderuns beforewrite_allwith no yield point, so the 0600 instant is sub-microsecond) — confirmed instead with a temporary source-level test callingcreate_temp/copy_modedirectly for 0644 and 0755 targets: the temp is born 0600 in both cases, thencopy_modewidens it to the target's real mode before any byte is written. Removed after passing. - 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 firstwrite_atomiccall: 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 (consumingn=31), the target holds the new bytes, and exactly 31 stale temps remain — no extra temp left by the successful write itself. - Symlink and identity. Temporary unit tests against
identity/dedupcovered:dir2 -> dir1containing 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):--checkprinted exactly onewould reformat:line naminga.sv, exit 1;--diffprinted exactly one diff block naminga.sv, exit 1; a real format run reported "1 file reformatted", exit 0, botha.svand (through the link)b.svread back the formatted text, andb.svwas still a symlink pointing ata.svafterwards (readlinkunchanged); a second--checkreported "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--checkand with a real write (outside file correctly formatted, link left intact). - Two processes. Two
lucisv formatprocesses launched at the same moment (both undertools/guard.sh, backgrounded,waited) against one shared scratch copy ofcorpus/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-tmpanywhere afterward. A follow-up--checkon 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). - 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 OSPermission denied (os error 13)(temp creation itself fails — expected, sincewrite_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 racingfs::remove_dir_allagainst a concurrent 8 MiBwrite_atomicin a scratch binary withcatch_unwindaround the writer thread — 139 writes completed before the delete won the race, 61 got a plainio::Error(No such file or directory/Invalid argument), 0 panics. No corruption claim applies once the directory itself is gone. - Behaviour parity. 300 files copied from
corpus/ibex(path structure preserved) into a scratch tree.--stdoutof every file saved first (4 pre-existing parse failures unrelated to this feature — a.tpl.svtemplate, 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--stdouterrors. All 296 successfully-formatted files are byte-identical between the in-place result and--stdoutof the original (0 mismatches). The 4 failed files are byte-unchanged from their originals (hard invariant #1 held). A follow-up--checkon 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.