Files
lucioandClaude Fable 5.1 3b08c0753c Same-target atomic writers: exclusive per-operation temps, mode before bytes, CLI dedup by canonical identity
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]>
2026-09-05 00:40:48 -05:00

360 lines
22 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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<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_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.