Skip to content

tikz: blank comments per-picture, not per-document (#650) - #703

Merged
d-q222 merged 2 commits into
mainfrom
agent/daniel-parent/tikz-blank-comments
Sep 17, 2026
Merged

d-q222 merged 2 commits into
mainfrom
agent/daniel-parent/tikz-blank-comments

Conversation

@d-q222

@d-q222 d-q222 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

What

Refs #650 (the renderer reads the frozen vendor/vector-graphics copy, so #650 stays open until that copy is re-pinned). blank_comments now returns Cow<str> (borrowing when the input
has no unescaped %) and scans byte-wise instead of char-by-char. The real
win is in Tikz::render: it used to call blank_comments on the entire
document
once per tikzpicture, so a document with N pictures paid
O(N * document_size). It now blanks only that picture's byte slice
(source[picture.start..picture.end]) and shifts the local indices while
still passing absolute spans into Interp. interp.rs picks up a .as_ref()
at the Cow call site.

Why

Every picture's render pass was re-scanning and re-copying the whole document
just to blank its own comments. On a tikz-heavy document that's quadratic-ish
in the number of pictures for no reason — the picture only ever reads its own
slice.

Call-pattern finding

Tikz::render(source, picture, measurer) receives the whole document and a
PictureSource locating one environment in it, but only ever indexes into
clean using that picture's own byte range. Blanking source in full on
every call was pure waste; blanking source[picture.start..picture.end] is
sufficient and O(picture_size).

Measurement (and why the perf gate's numbers don't apply)

flashtex-perf-bench --only tikz-heavy renders through the frozen
crates/render-pipeline/vendor/vector-graphics mirror, so it does not
exercise this patch at all — an earlier run against that bench looked
slower, but that was noise from a loaded machine (load average >30) hitting
frozen, unrelated code, not a measurement of this change. Those numbers are
intentionally not included here.

Instead, this measures both implementations directly, in
crates/vector-graphics where the change actually lives:
crates/vector-graphics/src/tikz/perf_test.rs keeps a byte-for-byte copy of
the pre-#650 blank_comments and Tikz::render bodies as local baseline
functions, and times old vs. new in the same process, on the same input, in
the same run
, which removes machine-load bias. The fixture is the same
generator flashtex-perf-bench's own tikz-heavy case uses
(crates/perf-bench/src/corpus.rs::tikz_heavy_document), copied in because
flashtex-vector-graphics cannot depend on flashtex-perf-bench.

Machine load was checked before each run (uptime); both runs below were
taken with the 1-minute load average under ~20 on an 18-core, ~20-agent
shared machine. Each figure is a median of 9 timed runs after a warmup pass.

Run 1:

tikz-heavy 120000B doc, 412 pictures, 9 runs each: old median 40.697875ms, new median 988.916µs (41.15x)
tikz-heavy 2000000B doc, 6776 pictures, 9 runs each: old median 12.312556625s, new median 16.515584ms (745.51x)

Run 2 (reproduced):

tikz-heavy 120000B doc, 412 pictures, 9 runs each: old median 39.678375ms, new median 1.0625ms (37.34x)
tikz-heavy 2000000B doc, 6776 pictures, 9 runs each: old median 11.606768917s, new median 19.208375ms (604.26x)
  • The 120,000-byte / 412-picture case is flashtex-perf-bench's actual
    tikz-heavy corpus size (same generator, same target byte count).
  • The 2,000,000-byte / 6,776-picture case is the same generator run
    longer
    (not a different fixture) purely to make the per-picture-count
    scaling visible; flagging plainly that this size is synthesized, not from
    a captured real-world document.
  • Both runs agree on the shape: roughly 40x at ~400 pictures, growing to
    ~600-750x at ~6,800 pictures, consistent with the old code being
    O(N * document_size) and the new code being O(document_size).

This is a real, reproducible improvement, not noise — the Cow/byte-scan
change alone would only help the no-comment fast path; the per-picture
slicing is the change that removes the quadratic-ish blowup.

Important: the pipeline will not see this until
crates/render-pipeline/vendor/vector-graphics is re-pinned.
The perf gate
(flashtex-perf-bench --only tikz-heavy) measures that frozen vendored
mirror, not crates/vector-graphics directly, so this fix is invisible to CI
perf numbers until the mirror is updated.

Overlap check

Test results

From crates/vector-graphics with CARGO_TARGET_DIR=/Users/dqi26/flashtex/target-tikzblank CARGO_BUILD_JOBS=4:

$ cargo test
test result: ok. 36 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s
test result: ok. 12 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
test result: ok. 26 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

(74 passed total across the lib unit tests, tests/json_depth.rs, and
tests/primitives.rs; the 1 ignored is the perf comparison test above, run
separately with --release -- --ignored --nocapture.)

New unit tests in tikz/text.rs (all passing):

test tikz::text::tests::blank_comments_leaves_comment_free_input_unchanged ... ok
test tikz::text::tests::blank_comments_preserves_length ... ok
test tikz::text::tests::blank_comments_keeps_escaped_percent ... ok
test tikz::text::tests::blank_comments_handles_percent_at_end ... ok
test tikz::text::tests::blank_comments_preserves_utf8_byte_offsets ... ok
test tikz::text::tests::blank_comments_handles_crlf_and_unterminated_last_line ... ok

Not done

  • crates/render-pipeline/vendor/vector-graphics is not re-pinned in this
    PR (out of scope here; flagged above as the next step so the perf gate
    actually reflects this change).

Implementation by gpt-5.6-luna (Codex) in a network-isolated worktree;
committed, measured, and pushed by daniel-parent since Codex had no network
access from that worktree.

🤖 Generated with Claude Code

https://claude.ai/code/session_012c9XLkHjePPGBuarrmE2mz

What changed:
- blank_comments now returns Cow<str>, borrowing the input unchanged when
  there is no unescaped `%`, and scans byte-wise instead of char-by-char.
- Tikz::render blanked the ENTIRE document once per picture; it now blanks
  only that picture's byte slice and shifts the local indices, while still
  passing absolute spans into Interp. A document with N pictures was paying
  O(N * document_size) instead of O(document_size).
- interp.rs: `.as_ref()` at the Cow call site.
- Added a #[ignore]'d perf_test.rs that keeps a copy of the pre-#650
  blank_comments/render as a local baseline and times both implementations
  on the same input in the same process, to avoid machine-load bias.

What was run:
- CARGO_TARGET_DIR=/Users/dqi26/flashtex/target-tikzblank CARGO_BUILD_JOBS=4
  cargo test (from crates/vector-graphics): 74 passed, 0 failed, 1 ignored.
- cargo test --release tikz::perf_test -- --ignored --nocapture, run twice:
  - 120,000B tikz-heavy doc (412 pictures): old median ~40ms, new median
    ~1ms (37-41x), across two runs.
  - 2,000,000B tikz-heavy doc (6,776 pictures): old median ~11.6-12.3s, new
    median ~16.5-19.2ms (600-745x), across two runs.
  - Fixture is the same generator flashtex-perf-bench's tikz-heavy case
    uses (crates/perf-bench/src/corpus.rs::tikz_heavy_document), copied in
    because flashtex-vector-graphics cannot depend on perf-bench.
  - flashtex-perf-bench --only tikz-heavy is NOT representative of this
    change: it renders through the frozen
    crates/render-pipeline/vendor/vector-graphics mirror, so it will not
    see this fix until that mirror is re-pinned.

Next step: re-pin crates/render-pipeline/vendor/vector-graphics so the
perf gate can see this.

Implementation-Agent: gpt-5.6-luna (Codex) via daniel-parent
Commit-Executor: daniel-parent subagent
Claude-Session: https://claude.ai/code/session_012c9XLkHjePPGBuarrmE2mz

@d-q222 d-q222 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent verification — VERIFIED

Reviewed on a detached worktree of refs/review/pr-703 (head 37c0ea3c), private
CARGO_TARGET_DIR=/Users/dqi26/flashtex/target-verify-703, CARGO_BUILD_JOBS=4.
Diff is four files under crates/vector-graphics/src/tikz/ — nothing under
vendor/, no generated artefact.

The two things I was asked to check hardest were (a) does the benchmark really
exercise both implementations on identical input, and (b) does the Cow fast
path preserve byte offsets exactly. Both hold.

1. The benchmark is a fair old-vs-new comparison

perf_test.rs:25 old_blank_comments is a byte-for-byte copy of the deleted
char-by-char implementation, and perf_test.rs:54 old_render is the deleted
Tikz::render body (whole-document blanking, absolute offsets). time_old and
time_new are handed the same doc, the same pictures: &[PictureSource]
(one find_pictures call), the same Tikz and the same ApproxMeasurer, both
are warmed once before measuring, both use std::hint::black_box, and the
reported figure is a median of 9. So the two sides do the same work on the same
input in the same process.

More importantly, I proved the two sides produce the same output, which is the
part that makes a speed comparison meaningful at all (see §2). Two caveats worth
recording, neither invalidating the result:

  • all 9 old runs are collected before all 9 new runs (perf_test.rs:144-145)
    rather than interleaved, so thermal/load drift is not cancelled. At a 50×
    effect that cannot flip the sign.
  • the measured win conflates two changes in this PR — per-picture slicing and
    the faster blank_comments. The PR attributes it to the slicing; that is
    where the asymptotics come from, but the constant factor also improved.

Reproduced on this (heavily shared) machine:

$ cd /Users/dqi26/flashtex-wt/verify-703/crates/vector-graphics
$ CARGO_TARGET_DIR=/Users/dqi26/flashtex/target-verify-703 CARGO_BUILD_JOBS=4 \
    cargo test --release tikz::perf_test::per_picture_blanking_old_vs_new -- --ignored --nocapture
tikz-heavy 120000B doc, 412 pictures, 9 runs each: old median 47.843959ms, new median 925.041µs (51.72x)
tikz-heavy 2000000B doc, 6776 pictures, 9 runs each: old median 11.808784917s, new median 14.98675ms (787.95x)
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 38 filtered out; finished in 119.12s

51.72× against the PR's 41.15× on the 120 kB / 412-picture corpus, and 787.95×
against 604.26× at 2 MB. The 37–41× claim is conservative, and the growth of
the ratio with picture count is the O(N·doc) → O(doc) signature the PR describes.

The PR body is also straight about the limitation: flashtex-perf-bench --only tikz-heavy renders through the frozen crates/render-pipeline/vendor/vector-graphics
mirror and will not see this until that mirror is re-pinned. So this is not yet
a user-visible speedup — it is a real one in this crate.

2. The Cow fast path preserves byte offsets exactly — differentially tested

Reading the code first: blank_comments (text.rs:114) fills the comment with
line_end - comment_start bytes of ' ' and re-emits the \n as one byte,
so length is preserved by construction for any UTF-8 content; next_unescaped_percent
(text.rs:98) counts the contiguous run of \ before the % and takes an even
run as unescaped, which is exactly what the old prev_backslash toggle computed;
the backward scan cannot cross a line boundary because \n is not \\.

Rather than take that on trust I added a review-only differential test against
the PR's own old_blank_comments, over the hand-picked edge cases you asked
about plus 20,000 pseudorandom strings built from the atoms
["a","%","\\","\n","\r","é","界","😀"," ","x%y","\\%","\\\\%"], asserting both
byte-equality with the old output and out.len() == input.len():

#[test]
fn review_blank_comments_matches_old_implementation() { /* 20_000 random + 11 fixed cases */ }

fixed cases included "", "%", "node%" (comment at EOF, no newline),
"é%界😀\n后" (multi-byte inside a comment), "a%comment\r\nb%last" (CRLF +
unterminated last line), "draw \\% not a comment", "\\\\% real comment",
"\\\\\\% escaped", "%\n%\n%", "trailing\\".

And a second differential test on Tikz::render vs the PR's old_render, over
six comment-heavy documents — a comment before the picture, a unicode comment
before it, a comment on the options line, a \% outside and inside the picture,
a comment at EOF with no trailing newline, and two pictures in one document:

#[test]
fn review_render_matches_old_render_with_comments_everywhere() { /* 6 docs */ }
$ CARGO_TARGET_DIR=/Users/dqi26/flashtex/target-verify-703 CARGO_BUILD_JOBS=4 cargo test tikz::
test tikz::text::tests::blank_comments_preserves_utf8_byte_offsets ... ok
test tikz::perf_test::review_render_matches_old_render_with_comments_everywhere ... ok
test tikz::perf_test::review_blank_comments_matches_old_implementation ... ok
...
test result: ok. 24 passed; 0 failed; 1 ignored; 0 measured; 14 filtered out; finished in 0.03s

Zero mismatches. Both review-only tests were reverted afterwards
(git checkout HEAD -- crates/vector-graphics/src/tikz/perf_test.rs); the
working tree is clean. The PR's own six unit tests in text.rs:228-277 cover the
same ground and one of them asserts matches!(&out, Cow::Borrowed(_)), i.e. it
pins the fast path itself, not just its output.

3. Slicing the picture instead of the document is sound

render now blanks only source[picture.start..picture.end] and rebases with
a - source_start. This is safe because:

  • find_pictures (mod.rs:140) locates \begin{tikzpicture} in the blanked
    whole document, so a picture can never start inside a comment, and a %
    earlier on the same line would have swallowed the \begin. There is no case
    where a comment opened before picture.start is still open at picture.start.
  • every offset rebased (options.0, options.1, body_start, body_end) is
    constructed by find_pictures to lie within [start, end), so no underflow.
  • the backward backslash scan in next_unescaped_percent now operates on the
    slice, but the slice begins with the literal \begin{tikzpicture}, so no %
    can sit close enough to the slice start for the truncated scan to change its
    parity.
  • spans stay absolute: Interp::new(.., picture.start) and it.picture(.., picture.body_start)
    are unchanged, and the body text handed in is identical, so relative offsets
    and hence absolute spans are unchanged. §2's render differential confirms
    this empirically, not just by argument.

Both in-repo callers pass the same string they derived the PictureSource from
(crates/render-pipeline/src/tikz.rs:144 and crates/render-pipeline/src/typeset.rs:4791),
so the new a - source_start subtraction has no live mismatch risk. It is worth
noting that Tikz::render is pub: an external caller pairing a PictureSource
with a different source would now panic on subtraction overflow rather than
on a slice bound. Both were panics before and after, so this is a note, not a
finding.

4. Other

  • interp.rs:535 and mod.rs:221 correctly adapt to the Cow return with
    as_ref(); there is no other blank_comments caller in the tree outside
    vendor/.
  • No new unwrap/expect on user input. next_unescaped_percent indexes with
    bytes[from..] where from is always a previously found index + 1 or a
    line_end + 1 known ≤ len, so no slice panic.
  • perf_test is #[cfg(test)] and the timing test is #[ignore], so it does
    not slow CI.

Verdict

VERIFIED. The benchmark is fair, the speedup is real and larger than claimed
(51.7× / 788× here vs 41.2× / 604×), and the Cow fast path is byte-identical to
the old implementation over 20,000 random inputs and every edge case named —
multi-byte UTF-8 in a comment, \%, and a comment on the last line with no
trailing newline.

— independently verified by daniel-parent's review lane

@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

Commander (daniel-parent): independent review — CHANGES REQUIRED. (fresh read-only Codex gpt-5.6-luna review of 37c0ea3, findings checked against the code)

  1. crates/vector-graphics/src/tikz/mod.rs:201-214 — the per-picture blank_comments optimization lands only in crates/vector-graphics, which crates/render-pipeline does not use directly; the pipeline links the frozen crates/render-pipeline/vendor/vector-graphics mirror, which this diff doesn't touch. A document with many tikzpictures in the real build still pays the old O(N × document size) cost. Re-pin/update the vendored copy and verify with the pipeline benchmark.

  2. crates/vector-graphics/src/tikz/perf_test.rs:195-222 — per_picture_blanking_old_vs_new is #[ignore]d and has no assert!/assert_eq! at all; it only eprintln!s the old/new ratio. Reverting Tikz::render to whole-document blanking would still pass this test (when run) and never runs by default in CI either way. Add an explicit assertion (e.g. new time meaningfully less than old) or move the comparison into an enforced benchmark gate.

Please push fixes to this branch and comment here; a fresh re-review follows.

— daniel-parent (triage by Claude Sonnet 5)

…ructions

Implementation-Agent: daniel-parent (Claude Opus 5)
Commit-Executor: daniel-parent (Claude Opus 5)
Co-authored-by: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012c9XLkHjePPGBuarrmE2mz
@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

Commander (daniel-parent), independent Opus review of 37c0ea3c: APPROVE. Non-blocking note 3 (machine path) is fixed in d9eac7e3, which touches only doc comments. The body now says Refs #650 instead of Fixes, because the vendored copy still needs re-pinning. Queued for the next merge batch.

PR #703 review — tikz: blank comments per picture, not per document (#650)

Head reviewed: 37c0ea3 (verified in a detached worktree).
Diff: crates/vector-graphics/src/tikz/{text.rs,mod.rs,interp.rs} plus a new #[ignore]d perf_test.rs.

MATERIAL findings

None.

What I checked in the source:

  • blank_comments rewrite (text.rs:98-142). The new scan blanks every byte from the %
    through the byte before \n. The old code wrote len_utf8 spaces per char, which gives the same
    output, so byte offsets are kept for UTF-8 and CRLF input. next_unescaped_percent counts the
    run of backslashes before the % (even count means the % starts a comment). That matches the
    old prev_backslash toggle. The backward walk cannot cross into an earlier line, because the byte
    before copy_from is always \n. All slice bounds hold: from <= len, and
    copy_from = line_end + 1 <= len because line_end < len on that path. There is no panic path.
  • Tikz::render slicing (mod.rs:201-216). find_pictures only reports a \begin{tikzpicture}
    found in the blanked document, so the whole-document scan is never inside a comment at
    picture.start. The slice starts with \begin, so no backslash run crosses the slice start
    either. Blanking the slice therefore gives the same bytes as the matching part of the
    whole-document blanking. options and body both lie inside [start, end], so the
    x - source_start subtractions cannot underflow for a PictureSource produced by
    find_pictures. Interp still gets absolute picture.start and picture.body_start, so spans
    are unchanged.
  • I confirmed equivalence empirically. A throwaway test (appended to perf_test.rs, then
    reverted; worktree status clean afterwards) compared the PR's own copied old_render against the
    new Tikz::render, using the Debug output of the resulting Picture. Inputs: 208 pictures from
    the tikz-heavy generator, plus a hand-written document with comments inside [options], a
    trailing % before \end{tikzpicture}, \%, \\%, UTF-8 inside comments, and a commented-out
    \begin{tikzpicture} in the preamble. It also compared old_blank_comments and the new
    blank_comments on edge strings (\\%a, \%%b\n%, \\\%c, %, the empty string, \n%\n,
    a trailing \, é%\r\n\%). Every output was identical.

Non-blocking notes

  1. "Fixes vector-graphics: tikz::text::blank_comments is ~60% of tikz-heavy render time #650" will close the issue with no effect on the product. As the PR itself says,
    crates/render-pipeline depends on vendor/vector-graphics (render-pipeline/Cargo.toml:137),
    which still has the old whole-document blank_comments (vendor .../tikz/mod.rs:201,
    text.rs:98). The FT-070 tikz-heavy profile that vector-graphics: tikz::text::blank_comments is ~60% of tikz-heavy render time #650 reports will not change until that
    mirror is re-pinned. Suggest changing the keyword to Refs #650, or opening or naming a re-pin
    follow-up before merge, so the 58% hotspot does not look fixed while it is still there.
  2. The PR adds no test that output is unchanged. perf_test.rs has the old implementation
    but only times it and is #[ignore]d. A cheap non-ignored test comparing old_render against
    render on a small document with comments inside a picture that does not start at byte 0 (as
    in the probe above) would guard the offset-shift logic. Today only
    find_pictures_locates_bodies_and_options covers a non-zero start, and it does not render.
  3. perf_test.rs:17 hard-codes CARGO_TARGET_DIR=/Users/dqi26/flashtex/target-tikzblank in a doc
    comment in a public repo. Use a placeholder.
  4. Tikz::render now panics if a caller builds a PictureSource by hand with
    options/body_start below start (usize underflow). The old code only needed the offsets to
    be inside the document. All callers in the repo use find_pictures, but the struct and its
    fields are pub. A debug_assert! or a doc line would make that requirement explicit.
  5. The public signature change String -> Cow<'_, str> is fine. There are no callers outside the
    crate, and unicode-tex has its own keyval::blank_comments.

Tests run (worktree ~/flashtex-wt/review-703, run from crates/vector-graphics, one at a time)

All commands prefixed nice -n 15 env CARGO_BUILD_JOBS=3 CARGO_TARGET_DIR=$HOME/flashtex-wt/review-target.
(The repo root has no workspace Cargo.toml, so these ran from the crate directory with its own
Cargo.lock.)

  • cargo test --locked --lib zz_review_equivalence -- --nocapture (throwaway probe, reverted) →
    1 passed; 208 pictures plus edge strings identical, old vs. new
  • cargo test --locked --lib tikz → 22 passed, 0 failed, 1 ignored (the perf comparison); this
    includes the 6 new blank_comments unit tests and the existing tikz tests

VERDICT: APPROVE

@d-q222
d-q222 merged commit ab35ef8 into main Sep 17, 2026
22 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant