393 lines
22 KiB
Markdown
393 lines
22 KiB
Markdown
# safety-net
|
||
|
||
## Goal
|
||
|
||
Make "lucisv can never corrupt code" a *runtime* guarantee instead of a
|
||
test-suite property. Every call to `format_source()` re-lexes its own
|
||
output and compares the token stream (comments included) against the
|
||
input, then formats the output a second time and checks for a fixed
|
||
point. If either check fails the formatted text is thrown away and an
|
||
error is returned, so the CLI leaves the file untouched and exits 2.
|
||
This is TODO.md §1's first three items, and mirrors what Verible does in
|
||
`verilog_equivalence.cc` / its convergence loop.
|
||
|
||
## Assumptions
|
||
|
||
- **Comment/attribute/directive re-indentation is not corruption.** The
|
||
formatter re-indents the continuation lines of multi-line tokens
|
||
(`format.rs::raw_text` emits each line after a `HardLine`, trimming
|
||
its trailing whitespace, and the printer prepends the current indent).
|
||
The checker therefore normalizes multi-line *comments*, *attributes*
|
||
and *directives* by trimming each line at both ends before comparing.
|
||
Single-line items and all other token kinds (identifiers, numbers,
|
||
string literals, …) are compared byte-for-byte.
|
||
- **Comment ordering is part of equivalence.** Comments are flattened
|
||
into the stream in source order (leading comments, then the token,
|
||
then its trailing comment). A comment that changes attachment from
|
||
"trailing of token N" to "leading of token N+1" keeps its position in
|
||
the flattened stream and is accepted; a comment that moves across a
|
||
token is a divergence.
|
||
- **The lexer normalizes some text identically on both sides.** Sized
|
||
based literals lose internal whitespace (`8 'hFF` → `8'hFF`), line
|
||
comments and directives are `trim_end`ed. Both input and output go
|
||
through the same lexer, so this is neutral.
|
||
- **Multiple comments trailing the same token are one item.** The lexer
|
||
merges them into a single `trailing` string joined by a space; the
|
||
comparison sees one merged comment on each side.
|
||
- Comment items are reported with the line/col of the token they are
|
||
attached to (the `Comment` struct carries no position of its own).
|
||
- **`@*` and `@(*)` are the same construct.** The parser folds both into
|
||
`SensList::Star` and the formatter always prints `@(*)`; that is a
|
||
deliberate canonicalization, so both streams rewrite `@ ( * )` to
|
||
`@ *` before comparing. `(*` followed by anything but `)` lexes as an
|
||
attribute token, so the sequence has no other meaning.
|
||
- Cost: verification makes `format_source` parse+print twice and lex
|
||
three more times. Accepted for now; TODO.md already anticipates a
|
||
`--no-verify` escape hatch if it ever matters.
|
||
|
||
## Consequence: known formatter bugs now refuse to produce output
|
||
|
||
The safety net does not fix formatting bugs, it *stops* them. Three
|
||
already-known bugs (all marked `#SKIP` in `tests/cases/`) now make lucisv
|
||
report an error and leave the file untouched instead of writing bad
|
||
output:
|
||
|
||
- **Continuation lines of an indented multi-line block comment gain two
|
||
spaces per pass** (`format.rs::raw_text` keeps a continuation line's
|
||
original leading whitespace and the printer adds the current indent on
|
||
top). Caught by the convergence check:
|
||
`formatting is not idempotent; line 3 changed from " two */" to
|
||
" two */"`. A faithful fix needs the comment's original column so
|
||
`raw_text` can dedent before re-indenting — see Handshakes.
|
||
- **A closing `end : label` is dropped.** Caught by the equivalence
|
||
check: `token stream diverges at index 12: input has symbol ':' at
|
||
4:7, output has keyword 'endmodule' at 5:1`. This one would have
|
||
silently deleted source tokens.
|
||
- Comments lifted out of a concatenation change position within the
|
||
token stream and are caught the same way if they cross a token.
|
||
|
||
This is the intended contract (hard invariant 1: no partial output), but
|
||
it is a visible behavior change: files that lucisv used to rewrite badly
|
||
are now refused with exit code 2.
|
||
|
||
## Handshakes
|
||
|
||
- **Consumes** `vlog_parser::tokenize` (already re-exported from
|
||
`vlog_parser/src/lib.rs`), `vlog_parser::LexError`,
|
||
`vlog_parser::token::{Token, TokenKind, Comment}`. **No change to
|
||
`vlog_parser` was needed.**
|
||
- **Provides / changed contract:** `vlog_formatter::format_source` now
|
||
returns `Result<String, FormatError>` instead of
|
||
`Result<String, vlog_parser::Error>`. `FormatError` is
|
||
`Source(vlog_parser::Error)` | `Verification(VerificationError)` and
|
||
implements `Display` + `std::error::Error`, so every existing
|
||
`{e}`-style error rendering keeps working. Callers that matched on
|
||
`vlog_parser::Error` must now match `FormatError::Source`.
|
||
- **Provides:** `vlog_formatter::verify::{verify_equivalence,
|
||
verify_convergence, VerificationError, Item, ItemKind, Side}` for
|
||
other features (the fixture harness in §5 of TODO.md can call
|
||
`verify_equivalence` per case).
|
||
- **Request to `vlog_parser` (not made, out of scope):**
|
||
`token::Comment` (and the attribute/directive text kept in `Meta`)
|
||
carries no source position, so `format.rs` cannot dedent a multi-line
|
||
comment before re-indenting it. Recording the original column — or the
|
||
byte span TODO.md §6 wants anyway — would let the comment-formatting
|
||
bug above be fixed properly.
|
||
- **`crates/lucisv/src/main.rs`** needed no structural change: it already
|
||
treats a `format_source` error as "report, skip the file, exit 2".
|
||
Two cosmetic edits only — a space after the filename in the error
|
||
line, and the summary now says "failed to format" instead of "failed
|
||
to parse", since a verification failure is not a parse failure.
|
||
|
||
## Status / TODO
|
||
|
||
- [x] `verify.rs` module: flatten source → (tokens + comments) stream.
|
||
- [x] `verify_equivalence(input, output)` with a first-divergence
|
||
description (index, kind, text, positions on both sides).
|
||
- [x] `verify_convergence(first, second)` reporting the first differing
|
||
line.
|
||
- [x] Wire both into `format_source`; new `FormatError` type.
|
||
- [x] Confirm the CLI still leaves files untouched and exits 2.
|
||
- [x] Tests: `crates/vlog_formatter/tests/verification.rs`.
|
||
- [x] `cargo clippy --all-targets` and `cargo test` clean (no new
|
||
warnings; the pre-existing ones in `parser.rs`, `printer.rs` and
|
||
`format.rs::ListItem` were left alone).
|
||
- [x] Formatting: the repo has no `rustfmt.toml` and is *not* clean
|
||
under default `cargo fmt` at baseline (hundreds of diffs in
|
||
untouched files); it is hand-written in rustfmt's
|
||
`use_small_heuristics = "Max"` style. New/edited code is clean
|
||
under that style — `cargo fmt --check -- --config
|
||
use_small_heuristics=Max` reports nothing in `verify.rs`,
|
||
`lib.rs` or `tests/verification.rs`. Running a bare `cargo fmt`
|
||
would have rewritten nine unrelated files, several of them owned
|
||
by another agent, so it was not run. Adding a `rustfmt.toml` is a
|
||
one-line call the lead should make.
|
||
- [x] TODO.md §1 items 1–3 checked off (item 4, panic containment, is
|
||
out of this feature's scope).
|
||
|
||
## Work log
|
||
|
||
### 2026-08-18 — dev agent
|
||
|
||
- Read CLAUDE.md / README.md / TODO.md §1, then the lexer, printer and
|
||
`format_source` to find where output text can legitimately differ
|
||
from input text.
|
||
- Added `crates/vlog_formatter/src/verify.rs`. The comparison stream is
|
||
built from `vlog_parser::tokenize`, which already attaches comments to
|
||
tokens as leading/trailing trivia — flattening them back out in source
|
||
order gives exactly Verible's "whitespace excluded, comments included"
|
||
stream. The `Eof` token is skipped but its leading comments (comments
|
||
at the end of a file) are kept.
|
||
- Decided *against* comparing comment text byte-for-byte: the formatter
|
||
legitimately re-indents continuation lines of block comments,
|
||
attributes and `` `define`` continuations. Normalization is limited to
|
||
those three item kinds and only trims per-line whitespace, so no
|
||
comment content can be lost silently. Recorded under Assumptions.
|
||
- `format_source` split into `format_once` (parse + print, the old body)
|
||
and a verifying wrapper. Order: format once → equivalence → format
|
||
again → convergence. A second pass that fails to *parse* is reported
|
||
as `VerificationError::Reparse`, not as a source parse error, because
|
||
the user's input did parse.
|
||
- Error type change from `vlog_parser::Error` to `FormatError` is the
|
||
one contract change; see Handshakes.
|
||
- Two token-stream divergences showed up immediately in the concurrent
|
||
`tests/cases/` suite: `always @*` formatted as `always @(*)`. The
|
||
parser cannot tell the two spellings apart (`SensList::Star`), so the
|
||
checker canonicalizes them on both sides rather than forcing a
|
||
formatter change. Recorded under Assumptions.
|
||
- Verified the failsafe end-to-end by building a *sabotaged* copy of the
|
||
workspace in a scratch directory (`Fmt::trailing` stubbed out to drop
|
||
trailing comments) and running the real CLI against it: it printed
|
||
`error: drop.sv: verification failed: token stream diverges at index
|
||
6: input has comment '// must survive' ...`, left the file byte-identical
|
||
and exited 2. The repo tree was not modified for this experiment.
|
||
- The checks immediately caught two pre-existing formatter bugs on real
|
||
input (dropped `end : label`, non-convergent block-comment indent).
|
||
Both are already tracked as `#SKIP` cases by the case-tables agent;
|
||
see "Consequence" above. Not fixed here — the safety net's job is to
|
||
detect, and both fixes belong to the formatting rules, one of them
|
||
behind a `vlog_parser` change.
|
||
|
||
## QA log
|
||
|
||
### 2026-08-18 — QA agent
|
||
|
||
**Scope**: verified claims 1–3 in the assignment (runs-on-every-call +
|
||
fail-closed, documented normalizations, the two claimed bug-catches),
|
||
tried to break `verify_equivalence`'s normalization logic with crafted
|
||
(input, output) pairs, checked CLAUDE.md compliance, and ran the full
|
||
tool chain. No blocking issues found; one third latent bug (beyond the
|
||
two documented ones) confirmed caught end-to-end; one small doc-comment
|
||
gap fixed directly.
|
||
|
||
**Tool chain** (workspace root, `cargo build` first):
|
||
- `cargo test` (workspace): **39/39 pass** — 3 `vlog_formatter` unit
|
||
tests, 1 `tests/cases.rs`, 2 `tests/fixtures.rs`, 19
|
||
`tests/verification.rs`, 14 `vlog_parser` unit tests. 0 failed.
|
||
- `cargo clippy --all-targets --workspace`: **0 errors.** Only
|
||
pre-existing warnings, none in `verify.rs`: an `if_same_then_else` x2
|
||
and a `manual_repeat_n` in `vlog_parser`/`vlog_formatter`, plus a
|
||
`dead_code` warning on `ListItem.blank_before` in `format.rs`. None of
|
||
these are in the safety-net diff.
|
||
- `cargo fmt --check -- --config use_small_heuristics=Max`: reports
|
||
diffs in `main.rs`, `format.rs`, `printer.rs`, `ast.rs`, `lexer.rs`,
|
||
`parser.rs`, `tests/cases.rs`, `tests/fixtures.rs` — all pre-existing
|
||
and outside this feature (confirmed the specific edited lines in
|
||
`main.rs`, e.g. `error: {}: {e}` at line 168 and the `"failed to
|
||
format"` summary at line 202, are not among the reported diffs).
|
||
`verify.rs`, `lib.rs`, `tests/verification.rs`: **0 diffs**, both
|
||
before and after the fix below. Matches the README's claim exactly.
|
||
Ran in check mode only, as instructed.
|
||
|
||
**Claim 1 (runs on every call, fail-closed, exit 2, file untouched)** —
|
||
**PASS**. Read `format_source` (`crates/vlog_formatter/src/format.rs:62-68`):
|
||
unconditionally calls `verify_equivalence` then `verify_convergence`
|
||
after every `format_once`; both are `?`-propagated, no bypass path, no
|
||
config flag to skip it. `crates/lucisv/src/main.rs:165-187`: `fs::write`
|
||
is only reached after a successful `format_source`, so any
|
||
`FormatError` (source or verification) leaves the file alone; error
|
||
path increments `errors` and hits `ExitCode::from(2)` at line 210.
|
||
Confirmed live with the real CLI (`target/debug/lucisv`, built from this
|
||
tree) — see the two bug repros below, both exit 2 with byte-identical
|
||
files (`cmp` confirms).
|
||
|
||
**Claim 2 (documented normalizations)** — **PASS**, verified two ways:
|
||
1. Read `verify.rs` line-by-line. `normalize()` (line 222) only trims
|
||
multi-line `Directive`/`Attribute` text; `comment_item()` (line 216)
|
||
always runs comments through `trim_lines`; every other `TokenKind`
|
||
(Ident, Number, String, Symbol, SystemIdent, Keyword) is byte-for-byte.
|
||
`collapse_implicit_sensitivity` (line 198) matches the documented
|
||
`@ ( * )` → `@ *` rewrite exactly, applied symmetrically to both
|
||
streams. Comment position is reported as the owning token's
|
||
line/col (`comment_item`, line 216-218) — matches the Assumptions.
|
||
2. Empirically: built a standalone scratch crate
|
||
(`/private/tmp/.../scratchpad/adversarial`, path-dependency on this
|
||
workspace's `vlog_formatter`/`vlog_parser`, no repo files touched)
|
||
and ran 17 crafted (input, output) pairs directly through
|
||
`vlog_formatter::verify::verify_equivalence`, specifically targeting
|
||
the questions in the assignment:
|
||
- deleted blank line inside a multi-line comment — **caught**
|
||
(line count changes, so the trimmed-and-joined comparison string
|
||
differs)
|
||
- deleted non-blank continuation line — **caught**, same reason
|
||
- reordered continuation lines with distinct content — **caught**
|
||
(order is baked into the joined string)
|
||
- content reflowed across a line boundary (word moved from end of
|
||
line 1 to start of line 2, line count preserved) — **caught**
|
||
(trim only touches leading/trailing whitespace per line, not
|
||
content, so the joined strings differ)
|
||
- `` `define`` with `\` continuation, one continuation line dropped
|
||
— **caught** (`Directive` normalization is the same trim-and-join,
|
||
same argument as above)
|
||
- one of two same-token merged trailing comments dropped — **caught**
|
||
(the merged/joined text literally differs)
|
||
- a comment skipping over an intervening token (trailing of N →
|
||
trailing of N+2, not just the adjacent leading-of-N+1 slot the
|
||
Assumptions call out as accepted) — **caught**, diverges at the
|
||
token that should have been there instead
|
||
- multi-line attribute `(* ... *)` with a continuation line dropped
|
||
— **caught**, same mechanism as directives
|
||
- number literal case change (`8'hff` → `8'hFF`) — **caught**
|
||
(`Number` is not in the `normalize` allowlist, byte-for-byte)
|
||
- a pathological "deletion masked by a duplicate suffix" case
|
||
(`wire a; wire b; wire a; wire b;` → `wire a; wire b;`) — **caught**
|
||
(the index-lockstep comparison isn't a real diff/LCS, so in
|
||
principle a deletion could hide behind a coincidentally-matching
|
||
duplicate; empirically even this adversarial case still diverges,
|
||
just later in the stream, because the tail lengths differ) — worth
|
||
recording as a *theoretical* limitation even though it isn't
|
||
practically exploitable in real Verilog (see Findings)
|
||
- CRLF line endings inside a multi-line comment, legitimate reindent
|
||
only — **accepted** (no false positive; `str::lines()` handles
|
||
`\r\n` correctly)
|
||
- two block comments on the same physical source line, reprinted by
|
||
the formatter on separate lines — **accepted** (no false positive)
|
||
All 17 behaved as expected: no hole found, no false positive found.
|
||
Full harness left at
|
||
`/private/tmp/claude-501/.../scratchpad/adversarial/src/main.rs` for
|
||
reference (outside the repo, per instructions; not part of this
|
||
change).
|
||
|
||
**Claim 3 (catches the two pre-existing bugs)** — **PASS**, confirmed
|
||
end-to-end with the real CLI, not just unit tests:
|
||
- `end : label` drop: `module m; initial begin : blk x = 1; end : blk
|
||
endmodule` → `lucisv` prints `verification failed: token stream
|
||
diverges at index 12: input has symbol ':' at 4:7, output has keyword
|
||
'endmodule' at 5:1`, exit code 2, `cmp` confirms the file is
|
||
byte-identical to the original afterward.
|
||
- Block comment reindent non-convergence: a 3-line indented `/* one /
|
||
two / three */` comment → `lucisv` prints `verification failed:
|
||
formatting is not idempotent; line 3 changed from " two" to
|
||
" two"`, exit code 2, file byte-identical afterward.
|
||
|
||
**Finding (should-fix, informational): a third latent bug the safety
|
||
net also catches.** `always @( /* comment */ * ) ...` — a comment
|
||
between the `(` and the `*` of an explicit-parens implicit-sensitivity
|
||
list — makes the real formatter drop the comment. Root cause:
|
||
`vlog_parser::parser::parse_sens_list`
|
||
(`crates/vlog_parser/src/parser.rs:1546-1558`) calls `eat_sym("*")` /
|
||
`expect_sym(")")` directly when building `SensList::Star`, which
|
||
discards whatever leading comments were attached to those tokens (the
|
||
AST variant carries no comment field), and
|
||
`crates/vlog_formatter/src/format.rs:1111` always prints `SensList::Star`
|
||
as the canonical `@(*)`. Reproduced live: `target/debug/lucisv` on a file
|
||
containing `always @( /* comment inside sensitivity list */ * ) y = a;`
|
||
exits 2 with `token stream diverges at index 5: input has symbol '(' at
|
||
2:11, output has symbol '*' at 2:12`, file left untouched. This is not
|
||
a verify.rs bug — the safety net is doing exactly its job here, the
|
||
same as the two documented cases — but it's a real, previously
|
||
unrecorded gap in `parse_sens_list`/`SensList::Star`, worth a line in
|
||
the "Consequence" section or a TODO.md entry for whoever picks up
|
||
comment-preservation in sensitivity lists. Not fixed here (parser
|
||
change, out of this feature's scope).
|
||
|
||
**CLAUDE.md compliance**:
|
||
- No `unwrap()`/`expect()`/`panic!` in `verify.rs` (only two
|
||
`unwrap_or` calls in `first_line_difference`, which are non-panicking
|
||
combinators, not the banned forms) or in `lib.rs`. `format.rs` has
|
||
two pre-existing bare `.unwrap()` calls (lines 545, 728,
|
||
`items.into_iter().next().unwrap()`, both immediately guarded by
|
||
`if items.len() == 1`) — these predate this feature (unrelated
|
||
`declarators`/`cont_assign` code, not part of the verify/FormatError
|
||
diff) and are out of this feature's stated scope, so left as a
|
||
finding rather than fixed.
|
||
- Public items documented: all of `verify.rs`'s public items had doc
|
||
comments except one field — **fixed directly** (small, unambiguous,
|
||
per the QA-agent allowance): `Item.kind` (`crates/vlog_formatter/src/verify.rs`,
|
||
now line 69-70) was missing a doc comment while its sibling fields
|
||
`text`/`line`/`col` had one; added `/// Whether this entry is a real
|
||
token or a comment recovered from trivia.`. Re-ran `cargo fmt --check`
|
||
and `cargo test -p vlog_formatter --test verification` after the
|
||
change: still 0 diffs, still 19/19 passing.
|
||
- No new dependencies: confirmed by reading all three `Cargo.toml`
|
||
files (`vlog_parser`, `vlog_formatter`, `lucisv`) — `vlog_parser` has
|
||
zero dependencies, `vlog_formatter` depends only on `vlog_parser` via
|
||
a path dependency, `lucisv` depends only on both via path. Matches the
|
||
"no new deps" implicit claim.
|
||
- README sections: all six required sections present (Goal,
|
||
Assumptions, Handshakes, Status/TODO, Work log, QA log); Assumptions
|
||
and Handshakes checked line-by-line against the code as part of Claim
|
||
2 above and found accurate, including the specific `(*` vs `@(*)`
|
||
lexer-ambiguity aside (verified the `peek_at(2) != b')'` guard in
|
||
`crates/vlog_parser/src/lexer.rs:223` really does make `@(*)` with no
|
||
internal spaces fall through to four separate symbol tokens rather
|
||
than being swallowed as an attribute).
|
||
|
||
**Performance** — sane, not pathological. `tests/fixtures/` is 4 files,
|
||
215 lines total. 200 sequential `target/release/lucisv --check` process
|
||
invocations over all 4 files completed in 0.71s wall time (~3.5ms per
|
||
invocation, including process startup, parsing+printing+re-lexing the
|
||
input twice and re-parsing+printing once more per file). No fixture
|
||
triggered a verification failure (`cargo test`'s
|
||
`fixtures_match_snapshots_and_are_idempotent` also confirms this — it
|
||
now goes through the safety net on every run and stays green). Did not
|
||
attempt to construct a pathologically large input; not needed to answer
|
||
"is the ~3x parse cost sane" for files of the size this formatter
|
||
targets.
|
||
|
||
## Review
|
||
|
||
**2026-08-18 — lead. Verdict: accepted and committed as-is.**
|
||
|
||
This is the most important change the project will ever take: the two hard
|
||
invariants are now runtime guarantees, not test-suite hopes. The
|
||
implementation is admirably small (one module, a thin wrapper, no new
|
||
dependencies), the failure messages carry enough position detail to debug
|
||
from, and the sabotaged-formatter end-to-end proof in the work log is
|
||
exactly the level of evidence I want for a claim like "fail-closed".
|
||
|
||
Points I reviewed specifically and accept:
|
||
|
||
1. **The normalizations are sound.** Line-by-line trimmed comparison of
|
||
multi-line comments/directives/attributes cannot hide a deleted,
|
||
reordered, or edited line (line count and content still compare); it
|
||
only forgives re-indentation, which is the formatter's job. The
|
||
`@ ( * )` → `@ *` collapse is a whitelisted canonicalization with no
|
||
alternative lexical meaning. Both are documented as Assumptions.
|
||
2. **Index-lockstep comparison instead of a real diff** (QA's theoretical
|
||
finding): correct trade-off. A masked deletion needs a coincidentally
|
||
matching suffix of equal length, which the differing tail length then
|
||
catches; the simpler code wins per CLAUDE.md. Not worth an LCS.
|
||
3. **The contract change** (`format_source` → `Result<String, FormatError>`)
|
||
was propagated cleanly and the CLI's existing error path was reused
|
||
rather than rebuilt — good restraint.
|
||
4. QA's 17 adversarial pairs and the byte-identical `cmp` checks on the two
|
||
bug repros are convincing; the one QA edit (a missing field doc) was
|
||
appropriate under the small-fix rule.
|
||
|
||
Follow-ups spun out of this review (not blockers):
|
||
|
||
- The **third latent bug** QA found (`@( /* c */ * )` drops the comment in
|
||
`parse_sens_list`, `parser.rs:1546-1558`) joins the four case-tables bugs
|
||
in the bug-fix round. Note the safety net converts all five from silent
|
||
corruption into refusals — working as designed.
|
||
- The dev agent's handshake request stands: `token::Comment` needs a source
|
||
position to fix the block-comment re-indent bug faithfully. That lands in
|
||
the bug-fix feature's scope.
|
||
- `--no-verify` (TODO §1 mentions it) stays unimplemented until someone
|
||
demonstrates a real performance need; the double-format cost is
|
||
negligible at current file sizes.
|
||
- rustfmt.toml has since been added at the repo root (case-tables review),
|
||
resolving this feature's fmt caveat; the repo-wide normalization commit
|
||
follows this one.
|