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_textemits each line after aHardLine, 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 aretrim_ended. 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
trailingstring 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
Commentstruct carries no position of its own). @*and@(*)are the same construct. The parser folds both intoSensList::Starand 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_sourceparse+print twice and lex three more times. Accepted for now; TODO.md already anticipates a--no-verifyescape 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_textkeeps 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 soraw_textcan dedent before re-indenting — see Handshakes. - A closing
end : labelis 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 fromvlog_parser/src/lib.rs),vlog_parser::LexError,vlog_parser::token::{Token, TokenKind, Comment}. No change tovlog_parserwas needed. - Provides / changed contract:
vlog_formatter::format_sourcenow returnsResult<String, FormatError>instead ofResult<String, vlog_parser::Error>.FormatErrorisSource(vlog_parser::Error)|Verification(VerificationError)and implementsDisplay+std::error::Error, so every existing{e}-style error rendering keeps working. Callers that matched onvlog_parser::Errormust now matchFormatError::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 callverify_equivalenceper case). - Request to
vlog_parser(not made, out of scope):token::Comment(and the attribute/directive text kept inMeta) carries no source position, soformat.rscannot 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.rsneeded no structural change: it already treats aformat_sourceerror 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
verify.rsmodule: flatten source → (tokens + comments) stream.verify_equivalence(input, output)with a first-divergence description (index, kind, text, positions on both sides).verify_convergence(first, second)reporting the first differing line.- Wire both into
format_source; newFormatErrortype. - Confirm the CLI still leaves files untouched and exits 2.
- Tests:
crates/vlog_formatter/tests/verification.rs. cargo clippy --all-targetsandcargo testclean (no new warnings; the pre-existing ones inparser.rs,printer.rsandformat.rs::ListItemwere left alone).- Formatting: the repo has no
rustfmt.tomland is not clean under defaultcargo fmtat baseline (hundreds of diffs in untouched files); it is hand-written in rustfmt'suse_small_heuristics = "Max"style. New/edited code is clean under that style —cargo fmt --check -- --config use_small_heuristics=Maxreports nothing inverify.rs,lib.rsortests/verification.rs. Running a barecargo fmtwould have rewritten nine unrelated files, several of them owned by another agent, so it was not run. Adding arustfmt.tomlis a one-line call the lead should make. - 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_sourceto find where output text can legitimately differ from input text. - Added
crates/vlog_formatter/src/verify.rs. The comparison stream is built fromvlog_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. TheEoftoken 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
`definecontinuations. 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_sourcesplit intoformat_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 asVerificationError::Reparse, not as a source parse error, because the user's input did parse.- Error type change from
vlog_parser::ErrortoFormatErroris the one contract change; see Handshakes. - Two token-stream divergences showed up immediately in the concurrent
tests/cases/suite:always @*formatted asalways @(*). 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::trailingstubbed out to drop trailing comments) and running the real CLI against it: it printederror: 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#SKIPcases 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 avlog_parserchange.
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 — 3vlog_formatterunit tests, 1tests/cases.rs, 2tests/fixtures.rs, 19tests/verification.rs, 14vlog_parserunit tests. 0 failed.cargo clippy --all-targets --workspace: 0 errors. Only pre-existing warnings, none inverify.rs: anif_same_then_elsex2 and amanual_repeat_ninvlog_parser/vlog_formatter, plus adead_codewarning onListItem.blank_beforeinformat.rs. None of these are in the safety-net diff.cargo fmt --check -- --config use_small_heuristics=Max: reports diffs inmain.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 inmain.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:
- Read
verify.rsline-by-line.normalize()(line 222) only trims multi-lineDirective/Attributetext;comment_item()(line 216) always runs comments throughtrim_lines; every otherTokenKind(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. - Empirically: built a standalone scratch crate
(
/private/tmp/.../scratchpad/adversarial, path-dependency on this workspace'svlog_formatter/vlog_parser, no repo files touched) and ran 17 crafted (input, output) pairs directly throughvlog_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)
`definewith\continuation, one continuation line dropped — caught (Directivenormalization 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 (Numberis not in thenormalizeallowlist, 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\ncorrectly) - 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.rsfor 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 : labeldrop:module m; initial begin : blk x = 1; end : blk endmodule→lucisvprintsverification failed: token stream diverges at index 12: input has symbol ':' at 4:7, output has keyword 'endmodule' at 5:1, exit code 2,cmpconfirms the file is byte-identical to the original afterward.- Block comment reindent non-convergence: a 3-line indented
/* one / two / three */comment →lucisvprintsverification 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!inverify.rs(only twounwrap_orcalls infirst_line_difference, which are non-panicking combinators, not the banned forms) or inlib.rs.format.rshas two pre-existing bare.unwrap()calls (lines 545, 728,items.into_iter().next().unwrap(), both immediately guarded byif items.len() == 1) — these predate this feature (unrelateddeclarators/cont_assigncode, 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 fieldstext/line/colhad one; added/// Whether this entry is a real token or a comment recovered from trivia.. Re-rancargo fmt --checkandcargo test -p vlog_formatter --test verificationafter the change: still 0 diffs, still 19/19 passing. - No new dependencies: confirmed by reading all three
Cargo.tomlfiles (vlog_parser,vlog_formatter,lucisv) —vlog_parserhas zero dependencies,vlog_formatterdepends only onvlog_parservia a path dependency,lucisvdepends 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 thepeek_at(2) != b')'guard incrates/vlog_parser/src/lexer.rs:223really 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:
- 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. - 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.
- 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. - QA's 17 adversarial pairs and the byte-identical
cmpchecks 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 inparse_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::Commentneeds 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.