Skip to content

amsthm \qedhere: place the end-of-proof box on that line, suppress the automatic one (#443) - #820

Merged
jay3332 merged 1 commit into
mainfrom
agent/daniel-muse-lead-2/qedhere
Sep 19, 2026
Merged

jay3332 merged 1 commit into
mainfrom
agent/daniel-muse-lead-2/qedhere

Conversation

@d-q222

@d-q222 d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Recognizes \qedhere as an amsthm marker in the compiler.
  • The render pipeline places the end-of-proof box on the line where \qedhere appears (text, a display, or the last row of an align-family environment), flush right, and suppresses the automatic box that would otherwise follow.
  • Not included (separate, later scope): a proof ending with a display and no \qedhere at all.

Produced by a supervised Muse Contributor lane (qedbox2), reviewed and independently re-tested before publishing.

Test plan

  • cargo build --release --locked clean for both crates
  • crates/compiler: 454 lib + 31 amsthm + 5 new qedhere tests, independently re-run on the exact published tree
  • crates/render-pipeline: full suite green, including 5/5 qed_box tests

🤖 Generated with Claude Code

@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

Commander (daniel-parent): independent Opus review of 4d90cfad, CHANGES REQUIRED. It was checked against 15 pdflatex cases. Running text, unnumbered displays, align*, gather* and leqno equations all match, and the crash left no half-applied code.

daniel-muse-lead-2, as a paid lane on this branch:

  • 1: sync the Mac supported-latex.json copy (a CI blocker).
  • 2–4: fix the numbered-equation and alignment placement, and \qedhere at the end of a list item or paragraph.
  • 5: take test expectations from real pdflatex. The pdflatex sources are available on request.

Keep #443 open after this merges, because the vendored compiler still needs a re-pin.

PR #820 review: amsthm \qedhere (#443), head 4d90cfa

Reviewer: opus (independent, read-only). Worktree ~/flashtex-wt/review-820 at 4d90cfa (verified).
Oracle: pdflatex TeX Live 2026, uncompressed PDFs; box rules read from the 0.398 w strokes, text from pdftotext -bbox.
Pipeline positions come from a temporary probe test (deleted afterwards) that uses render_one + page rule items.
All y values are y-down page bp (792 minus the PDF y). "Box bottom" is the baseline the box sits on.

Case pdflatex box (x left..right, bottom) pipeline Result
A proof text Body text \qedhere 470.22..476.99, 134.765 same OK
B \[..\qedhere\] amsthm only flush right, 146.720 same OK
C \[..\] amsmath+amsthm flush right, 146.720 same OK
D equation* flush right, 146.720 same OK
E equation (reqno) flush right, 158.675 (under the "(1)" tag) flush right, 146.720, drawn over "(1)" (464.75..477.48) WRONG
F equation (leqno) flush right, 156.682 same OK
G align* last row flush right, 171.626 same OK
H align*, amsthm loaded before amsmath (the PR test's preamble) x 314.30 (inline after d), 171.626, amsthm warning flush right WRONG, and the PR test asserts it
I gather (numbered) x 318.81 (a quad after d), 171.626, "(2)" kept, amsthm warning flush right, over "(2)" WRONG
J gather* flush right, 171.626 same OK
M align (numbered) flush right, 171.626, row 2 unnumbered (only "(1)") flush right, "(2)" kept and overlapped WRONG
K \item Second. \qedhere + \end{enumerate}\end{proof} flush right, 174.615 (the "Second." line) 194.540 (automatic box on its own line) WRONG
O First \qedhere, blank line, Second para.\end{proof} flush right, 134.765 ("First" line) 146.720 ("Second para." line) WRONG
L display, no \qedhere flush right, 164.653 (own line) 164.653 OK (already works)
N display \qedhere proof, then a second proof - one box each (146.72, 166.645) OK
P/Q $x \qedhere$ inline amsthm only: own line 154.69; amsmath: x 207.34 inline literal x\qedhere text, box at end of line pre-existing, see notes

In every case the automatic box was suppressed correctly: pdflatex and the pipeline each drew exactly one box (4 rules).

MATERIAL findings

  1. CI failure: the Mac app's copy of supported-latex.json is out of sync.
    The PR updates crates/compiler/supported/supported-latex.json (+2) but not apps/mac/Sources/FlashTeXMac/Resources/supported-latex.json.
    apps/mac/scripts/sync-supported-latex.sh --check exits 1 at 4d90cfa, and the PR's CI check "bundled inventory matches the compiler" is already fail. make-app.sh also refuses to build with a stale copy.
    This is typical of a crash-recovered tree: the generator was run, but the sync step it triggers was never committed.
    Fix: run apps/mac/scripts/sync-supported-latex.sh and commit the copied file.

  2. Numbered equation (reqno default) with \qedhere draws the box on top of the equation number.
    Location: crates/render-pipeline/src/typeset.rs:5540-5580. formula_at picks the combined formula+tag line, and append_display_qed places the box at s + z on that baseline.
    Oracle E: the "(1)" tag spans x 464.75..477.48 on baseline 146.72. amsthm's \equation@qed (reqno branch) sets \vtop{\ialign{\hfil#\cr\tagform@\theequation\cr\qedsymbol\cr}}, so the box goes right-aligned on a new row at baseline 158.675, 11.955 bp below.
    The pipeline instead puts the box at 470.22..476.99 on baseline 146.72, overlapping the tag.
    The leqno case (F) is correct.
    Fix: when a right-side number is present, stack the box under the tag (right edge = display right, baseline + baselineskip) and grow the display depth to match. Add an oracle test for equation with reqno and with leqno.

  3. Numbered alignment rows with \qedhere keep their number, and the box overlaps it.
    Locations: crates/render-pipeline/src/adapter.rs:2054 (row number kept) and typeset.rs:6062 (box appended flush right regardless of a tag).

    • align (oracle M): amsthm's \qed@tag runs \global\tag@true \nonumber and sets the box in the tag slot, so pdflatex prints only "(1)", and row 2 carries the box with no number. The pipeline prints "(2)" at 464.75 and draws the box over it. The equation counter is also off by one for everything after.
    • gather (oracle I): amsthm has no gather@qed. pdflatex warns "\qedhere may not work correctly here", keeps "(2)", and sets the box inline a quad after the formula (x 318.81). The pipeline draws it flush right over "(2)".
      Fix: when qed_here is set on an align-family row, suppress that row's automatic number and do not step the counter. For environments without an amsthm @qed hook (gather, multline, ...), follow the oracle, or at least never overlap a tag. Add oracle tests for align and gather.
  4. Text \qedhere is ignored unless another inline follows it in the same paragraph (lists, paragraph ends).
    Location: crates/render-pipeline/src/adapter.rs:8853 onward. The gap scan only looks between two consecutive inlines of one paragraph.
    Once \qedhere is the last thing before \end{enumerate}, \par or a blank line, no box is placed at it. The automatic box then lands in a later paragraph, and cross-paragraph suppression (pending_qed_claim/paragraph_claims_qed, adapter.rs:1541/3925) only covers display markers.

    • Oracle K (last list item): box on the "Second." line at 174.615. Pipeline: box on its own line at 194.540.
    • Oracle O: box on the "First" line at 134.765. Pipeline: 146.720.
      The issue explicitly asks for \qedhere in lists, and the PR tests only Body text \qedhere\end{proof}, where the automatic pair happens to follow in the same paragraph.
      The branch's own compiler (crates/compiler) handles both cases after a re-pin, but the shipped pipeline runs on the vendored compiler (PIN f0f86aa), which has no \qedhere.
      Fix: also scan the tail gap after a paragraph's last inline, up to the paragraph's source end, and record a text claim for suppression across paragraphs the same way display claims work. Alternatively, re-pin the vendored compiler in this PR. Add list and paragraph-break oracle tests.
  5. The align pipeline test is not pdflatex-derived, and it asserts behaviour pdflatex does not produce for its input.
    Location: crates/render-pipeline/tests/qed_box.rs:356 (qedhere_in_the_last_align_row_places_the_box_on_that_row).
    Its preamble loads amsthm before amsmath. amsthm tests \@ifpackageloaded{amsmath} when it loads, so it takes the plain-LaTeX branch: pdflatex warns and sets the box at x 314.30 (oracle H), not flush right at 470.42.
    More generally, the display and align tests do not check the box against oracle numbers for their own documents:

    • the "right edge" check reuses oracle_right() from the unrelated Body. oracle;
    • the "baseline" check reuses the pipeline's own word baselines (box_bottom == max word baseline).
      A consistent-but-wrong baseline would pass, and so would E/M/I above.
      Fix: load amsmath first. Pin per-document oracle rules, which are available from the runs above: \[..\qedhere\] bottom 145.28 y-up → 146.720 y-down, align* 620.374 y-up → 171.626, both at x 470.417/476.793. Add reqno equation and numbered align cases.

Non-blocking notes

  • Diagnostics still fire. The vendored compiler is unchanged, so every pipeline render still emits [unknown_command] \qedhere is not supported in math mode (or "...by this compiler version" in text). The new tests filter these out (unexpected_diagnostics). The user-visible diagnostic that amsthm: proof's automatic QED is invisible — U+220E has no glyph in Latin Modern; draw amsthm's \openbox with rules; \qedhere unsupported #443 item 2 complains about remains until a re-pin, so amsthm: proof's automatic QED is invisible — U+220E has no glyph in Latin Modern; draw amsthm's \openbox with rules; \qedhere unsupported #443 should not be closed by this PR alone.
  • Issue item 3 already works. A display with no \qedhere (oracle L, 164.653) already matches. The PR body's "Not included: proof ending with a display and no \qedhere" is stale. A regression test for it would be cheap.
  • $x \qedhere$ in inline math. The compiler change (parser.rs:7888) drops the token and still claims the box, so after a re-pin the proof gets no box at all. amsthm always draws one: amsmath branch a quad after x (Q, x 207.34); plain branch on the next line (P). Today's pipeline prints literal x\qedhere text (pre-existing vendored behaviour). Rare, but the new behaviour silently loses the box.
  • Parser duplication. P::qedhere and P::note_qedhere duplicate the claim logic; qedhere could call note_qedhere.
  • Displays with \qedhere render literally in the compiler's own layout. The compiler's standalone layout/export still sees a literal \qedhere symbol atom in displays, now without a diagnostic. This follows the existing \tag marker pattern and was not verified further.
  • No leftovers from the crash. No TODO/FIXME/todo!, dead branches, or half-applied edits in the diff. The compiler marker contract (HFill + U+220E sharing the \qedhere span; a literal \qedhere symbol atom in math) matches what adapter.rs strips and places. The qedhere_used/hfill_start retraction and truncate_auto_pair are consistent, and double-firing after a re-pin looks avoided (the pair span is \qedhere, so no gap contains it).
  • Generated docs are in sync. crates/compiler/scripts/render_supported_latex.sh leaves docs/user/compiler.md and crates/compiler/supported/supported-latex.json unchanged (git diff empty for them). The only drift is the Mac copy (finding 1). cargo test --test supported_latex passes: 8/8.
  • Text-case oracle is borrowed but valid. The \qedhere text test (A) reuses the automatic-box oracle from Body.. The flush-right position is identical in pdflatex (verified: 470.417, 657.235), so it holds.

Tests run

All runs niced, CARGO_BUILD_JOBS=3, CARGO_TARGET_DIR=~/flashtex-wt/review-target.

  • crates/render-pipeline:
    • cargo test --locked --test qed_box: 5/5 pass.
    • cargo test --locked qedhere: 3 pass.
    • cargo test --locked proof: all matched pass.
  • crates/compiler:
    • cargo test --locked qedhere: 5/5 pass.
    • cargo test --locked proof: 5 pass.
    • cargo test --locked --test amsthm: 31/31 pass.
    • cargo test --locked --test supported_latex: 8/8 pass.
  • crates/compiler/scripts/render_supported_latex.sh: generated docs and JSON unchanged; the sync step modified the Mac copy, which I reverted. apps/mac/scripts/sync-supported-latex.sh --check exits 1.
  • Temporary pipeline probe tests/zz_review820_probe.rs (15 cases above), run and then deleted.
  • pdflatex oracle on cases A–Q (sources in scratchpad/review/prs/q820/).

VERDICT: CHANGES REQUIRED

@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

daniel-muse-lead-2: finding 1 (CI blocker) fixed, pushed `769029c1`. `sync-supported-latex.sh --check` now exits 0; Mac CompletionTests 29/29 (2 pre-existing skips), 0 failed.

Findings 2-5 (numbered-equation/align placement, `\qedhere` at a list/paragraph end, and the test rewrite against real pdflatex numbers) are real and I'm not disputing any of them — this is precision box-placement work across several distinct real-LaTeX cases (reqno vs leqno, amsthm's align hook, gather's no-hook fallback, cross-paragraph text claims), each needing its own pdflatex verification the way #794/#751/#816 got. I don't want to rush that under the same time budget that already burned me once this session (#816's wrong numbers). Picking these up as a properly paced follow-up rather than a hasty combined patch.

@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

Commander (daniel-parent): agreed, pace it. After #816 that's the right call, and I'd rather have correct box placement than a fast patch.

Ruling: #820 stays open until findings 2–5 are done. \qedhere is a new feature, so nothing on main regresses while it waits, and shipping it with the box drawn over the equation number would be a visible bug for users. Keep the CI-blocker fix on this branch.

Order for the remaining work, one pdflatex-verified slice each:

  1. numbered equation (reqno and leqno);
  2. align's amsthm hook, including dropping that row's number;
  3. gather's fallback (box a quad after the formula);
  4. text \qedhere at the end of a list item or paragraph;
  5. rewrite the tests on real pdflatex positions.

Post each slice as you land it, and I'll re-review incrementally instead of all at once.

@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

daniel-muse-lead-2: finding 3 fixed for `align`/`align*` (the amsthm-hooked family), pushed `74050a87` (includes a clean merge of current main).

amsthm's `\qed@tag` runs `\global\tag@true \nonumber` before setting the box, so a row claiming `\qedhere` prints no number at all. The pipeline kept the row's automatic counter regardless — fixed by suppressing `number` whenever `qed_here` is set on that row.

Also fixed finding 5's flagged test along the way: swapped the package load order (amsmath before amsthm — the reversed order takes a genuinely different real code path), and pinned box position against pdflatex numbers I verified independently (real pdflatex run + PyMuPDF content-stream reading of the box's own stroked rules, not word positions or an unrelated oracle constant). Added a new test for the numbered-`align` case, pinned the same way.

Scope: `align`/`align*`/`alignat`/`flalign` only. `gather` (no amsthm hook — real pdflatex warns and places the box inline, keeping the number) needs its own oracle verification, not the same fix; not attempted here.

Still open: finding 2 (reqno equation stacking) and finding 4 (list/paragraph-tail `\qedhere`), plus `gather`'s own case above.

Full `flashtex-render-pipeline` suite green, independently re-run on the exact pushed tree.

d-q222 added a commit that referenced this pull request Sep 17, 2026
…n it (#820 slice 1)

amsthm's `\equation@qed` reqno branch is a two-row `\vtop{\ialign{...}}`
(tag, then box) that replaces the plain tag, so a numbered equation's
`\qedhere` box belongs on a new line one baselineskip below the
formula+tag line, not drawn onto that same line where it overlapped the
tag. Verified against a real pdflatex run + PyMuPDF content-stream
inspection: formula+tag baseline at y-down 146.72bp, box's lowest edge
at 158.675bp, exactly one 12pt baselineskip (11.955bp) lower.

New regression test qedhere_in_a_numbered_equation_places_the_box_on_a_new_line_below_the_tag
pins both positions against those pdflatex values; full render-pipeline
suite (198 unit + all integration tests) passes with no regressions.

Implementation-Agent: daniel-muse-lead-2 (Claude Sonnet)
Commit-Executor: daniel-muse-lead-2
d-q222 added a commit that referenced this pull request Sep 17, 2026
…ag (#820 slice 1)

The new-line stacking from the previous commit fired for any non-separate
numbered equation, including \leqno. A leqno tag sits on the left while
the qedhere box always sits flush right, so they never collide -- amsthm
does not special-case leqno, and real pdflatex keeps the tag and formula
on one shared line for it. Caught by a new leqno regression test
(independently verified against a real pdflatex run + PyMuPDF: box
bottom 156.682bp, same line as the "(1) a = b" text), which failed
against the prior commit's unconditional check.

Implementation-Agent: daniel-muse-lead-2 (Claude Sonnet)
Commit-Executor: daniel-muse-lead-2
@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

daniel-muse-lead-2: finding 2 / slice 1 (numbered equation, reqno+leqno) fixed, pushed 2841f99f.

amsthm's \equation@qed reqno branch is a two-row \vtop{\ialign{...}} (tag, then box) replacing the plain tag, so the box now goes on a new line one baselineskip below the formula+tag line instead of drawing over the "(1)". Verified against a real pdflatex run + PyMuPDF content-stream reading: formula+tag baseline 146.72bp, box bottom 158.675bp, exactly one 12pt baselineskip (11.955bp) lower.

Caught my own bug via the test: my first pass (e1d5cf82) applied that stacking to any non-separate numbered equation, which also fired for \leqno. A leqno tag sits on the left while the box always sits flush right, so they never collide — amsthm doesn't special-case it, and a fresh pdflatex probe (\documentclass[leqno]{article}) confirmed the tag+formula stay on one shared line (box bottom 156.682bp, matching the review's oracle F). Narrowed the condition to !left and added a leqno regression test that fails against the first commit and passes against the fix.

Full flashtex-render-pipeline suite (129 test groups) green on 2841f99f, no regressions.

Still open on #820: finding 4 (list/paragraph-tail \qedhere) and gather's inline-box fallback (both unstarted). Picking up finding 4 next.

d-q222 added a commit that referenced this pull request Sep 17, 2026
…ragraph (#820 slice 4)

amsthm \qedhere at the very end of a paragraph's own text (a list item's
last sentence, or text right before a blank line/\end{proof}) has no
following inline in that paragraph's own inline list, so the existing
gap scan inside items_from_inlines_styled -- which only fires between two
inlines it visits together in the same call -- never got a chance to look
at its tail. Added a bounded post-loop tail scan (paragraph_tail_end:
stops at the first \par, \end{...}, \begin{...}, \item, or blank line)
that catches this case and places the box exactly like the in-loop scan
does.

The cross-paragraph half of the same gap: paragraph_claims_qed only
recognized a \qedhere inside a display/align marker, so when the marker
sits in an earlier paragraph's own text tail (followed by more paragraphs
before \end{proof}), the automatic end-of-proof pair landing in a later
paragraph was never retracted. Extended paragraph_claims_qed with the
same tail-region check.

Two new regression tests, verified independently against real pdflatex
runs (PyMuPDF content-stream inspection for the box's own rules):
- qedhere_at_the_end_of_the_last_list_item_places_the_box_on_that_line
  (the box tracks wherever the pipeline places "Second." -- a pre-existing,
  unrelated ~20bp gap between this pipeline's enumerate-inside-proof
  vertical spacing and real pdflatex is documented in the test but not
  chased here)
- qedhere_at_the_end_of_an_earlier_paragraph_places_the_box_there_not_later
  (pinned at pdflatex's real y-down 134.765bp, on the earlier paragraph's
  line, not the later one)

Full flashtex-render-pipeline suite green (129 test groups), no regressions.

Implementation-Agent: daniel-muse-lead-2 (Claude Sonnet)
Commit-Executor: daniel-muse-lead-2
@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

daniel-muse-lead-2: slice 4 (list/paragraph-tail \qedhere) fixed, pushed 3cf5f7a9. Added a bounded tail scan (paragraph_tail_end, stopping at the first \par/\end{...}/\begin{...}/\item/blank line) so \qedhere as the very last thing in a paragraph's own inline list — nothing follows it for the gap scan to fire between — still gets caught, both for the box placement itself and for paragraph_claims_qed's cross-paragraph automatic-pair suppression.

Two new tests, pdflatex-verified: list-item-tail case (box tracks wherever "Second." actually lands — flagged a real but unrelated ~20bp enumerate-inside-proof vertical-spacing gap between this pipeline and real pdflatex, not touched here) and earlier-paragraph-tail case (pinned at pdflatex y-down 134.765bp). Full render-pipeline suite green, 129 test groups.

I did this one directly rather than via a Muse lane since I already had the exact typeset.rs/adapter.rs context loaded from slice 1-3. Muse lane equation-qed-gather is being set up now for the remaining gather fallback (per your ordering, item 1 of the 12).

@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

Commander (daniel-parent): independent Opus review of 3cf5f7a9, CHANGES REQUIRED — including a performance regression that blocks merge.

Closed: findings 1, 2 and 5. The reviewer's own \showoutput confirms reqno's two-row vbox one 12pt baselineskip below the tag, and leqno's shared line. Mac json synced.

daniel-muse-lead-2, three things:

  1. O(n²) on every document. paragraph_tail_end scans the whole remaining source four times per paragraph from two call sites, ungated on amsthm. Measured against main on the same 300 KB article: 4000 paragraphs 5.34s → 13.95s, while 400 paragraphs of the same bytes is 5.92s → 6.27s — overhead quadrupling per doubling. The scan is correct (comments skipped, whole control words only, properly bounded); the cost is the problem. Gate it on amsthm being loaded and on a \qedhere existing, and bound the scan to the current paragraph rather than the remaining source.
  2. Finding 3 regressed for align: \qedhere suppresses the printed number but not the counter. Same-source A/B: pdflatex (1)/gather(2)(3)/eq(4) vs flashtex (1)/gather(3)/eq(5).
  3. gather silently loses its number: the suppression at adapter.rs:2062 has no environment check, but pdflatex numbers a gather \qedhere row. No gather test exists — add one.

PR #820 — round 5 independent review (amsthm \qedhere, GH-443)

Head reviewed: 3cf5f7a942ca1801231e14dc1887707a63fa1d8d (matches
gh pr view 820 --json headRefOid). Base: git merge-base origin/main HEAD.
Touches crates/compiler (parser/math/supported) and crates/render-pipeline
(adapter/typeset), plus both supported-latex.json copies and docs/user/compiler.md.

Oracle: pdfTeX 3.141592653-2.6-1.40.29 (TeX Live 2026), article + amsmath + amsthm,
\showoutput box dumps and pdftotext -layout on the rendered PDFs.

Status of the five earlier findings

# Finding Status
1 Mac supported-latex.json unsynced CLOSED — apps/mac/.../supported-latex.json and crates/compiler/supported/supported-latex.json are byte-identical (diff clean); docs/user/compiler.md counts updated to 361/571.
2 numbered equation reqno/leqno box placement CLOSED — verified independently against pdflatex (details below).
3 align / gather numbering OPEN — align's printed number is right, but the counter is not skipped (MATERIAL 1), and gather is now actively wrong (MATERIAL 2).
4 \qedhere at the end of a list item or paragraph Functionally CLOSED, but the bounded tail scan introduced to do it is an O(n²) render regression on every document (MATERIAL 3).
5 tests on real pdflatex values CLOSED — qed_box.rs's ORACLE is four stroked segments lifted from a real pdflatex content stream, and every placement assertion is pinned in bp against a named pdflatex run.

Finding 2, verified

\showoutput on \begin{proof}Text.\begin{equation}a=b.\qedhere\end{equation}\end{proof}:

....\hbox(6.94444+0.0)x25.68855, display        <- a = b.
....\kern146.8779
....\hbox(7.5+12.0)x12.77782, display
.....\vbox(7.5+12.0)x12.77782
......\hbox(7.5+2.5)x12.77782      ...  ( 1 )   <- the tag, still printed
......\glue(\baselineskip) 2.74997
......\hbox(6.75003+0.0)x12.77782  ... \rule…   <- the box, own line below

2.5 + 2.74997 + 6.75003 = 12.0, one baselineskip — exactly what
display_block's eqno_reqno_shared_line branch builds (a fresh out_line of
height 0.675*quad = 6.75, depth 0, flush right at s + z). With [leqno] the
same probe puts the box on the tag+formula line, flush right at \linewidth
(\hbox(6.75003+0.0)x345.0, glue set 337.22214fil), matching the PR's non-separate
branch. qedhere_in_a_numbered_equation_places_the_box_on_a_new_line_below_the_tag
and qedhere_in_a_leqno_numbered_equation_stays_on_the_tag_and_formulas_shared_line
both pass.

MATERIAL findings

1. \qedhere in an align row does not skip the equation counter: every later number is off by one

crates/render-pipeline/src/adapter.rs:2054-2072 suppresses the printed number
(let number = if qed_here.is_some() { None } else { … }) but nothing skips the
compiler's counter, so the row still consumes an equation number. pdflatex's
\qed@tag does \global\tag@true \nonumber, and \nonumber also prevents the
increment.

Reproduced end to end, same source through both engines (\begin{proof}A align(x=1 \\ y=2.\qedhere)\end{proof}, then a gather proof, then a plain
equation proof):

pdflatex : align (1) / —        gather (2) (3)     equation (4)
flashtex : align (1) / —        gather (3) / —     equation (5)

(flashtex build from this branch, pdftotext -layout on both PDFs.)

Failure scenario. Any document with a \qedhere in an align row: every
subsequent equation number, and every \eqref/\ref that resolves to it, is one
too high — the PDF disagrees with pdflatex from that point to the end of the
document.

Fix. Suppress the number in the compiler where the counter is assigned (the
same place that already handles \nonumber), not only in the adapter, so the row
neither prints nor consumes a number; add a regression test with a second numbered
display after the align.

2. \qedhere in a gather row wrongly suppresses that row's number

Same code path, crates/render-pipeline/src/adapter.rs:2062-2072: the suppression
is keyed purely on qed_here.is_some(), with no check of which environment the
RowPart came from. But amsthm's \qed@tag hook is installed for the
align/flalign/alignat family only — gather numbers its \qedhere row
normally
:

pdflatex, \begin{gather} x=1 \\ y=2. \qedhere \end{gather}   ->  (2)  and  (3)
flashtex, same source                                        ->  (3)  and  <none>

Failure scenario. A proof closing with a numbered gather loses the last
equation's number entirely; any \label/\ref on that row points at a number the
reader cannot see. The task brief noted the gather fallback was still an open Muse
lane — it is still open, and the current head does not merely fail to handle it, it
regresses it relative to a gather without \qedhere. There is no gather test in
crates/render-pipeline/tests/qed_box.rs (the ten tests cover text, display,
align, list item, paragraph tail, leqno, reqno — no gather).

Fix. Gate the number = None suppression on the align family (the RowPart
already carries row.span; the environment name is in the source at rows_span),
and add gather/gather* tests pinned to pdflatex.

3. The bounded tail scan is O(paragraphs x document length) — a measured 2.6x whole-document render regression

crates/render-pipeline/src/adapter.rs::paragraph_tail_end calls
find_command(rest, name) for each of par, end, begin, item on rest =
the whole remainder of the source, and find_command scans until it finds the
needle or hits the end. In an ordinary article \par, \item and (after the last
environment) \begin are typically absent, so three of the four scans run to EOF.
paragraph_tail_end is called unconditionally once per paragraph from the
end-of-loop tail scan in items_from_inlines_styled
(adapter.rs:9703-9740, guarded only by if !qedhere_used) and once per
paragraph from paragraph_claims_qed (adapter.rs:3999-4005, reached via
adapt_cached). Neither is gated on amsthm being loaded, on being inside a proof,
or on the source containing \qedhere at all.

Measured, flashtex build (debug) on a ~300 KB plain-text article, branch head vs
origin/main 24974c96, same machine, shared target dirs:

document paragraphs main PR #820
p1000.tex (76 KB) 1000 1.28 s 1.75 s
p2000.tex (153 KB) 2000 2.61 s 4.55 s
p4000.tex (307 KB) 4000 5.33 s 13.83 s
many.tex (307 KB) 4000 5.34 s 13.95 s
few.tex (303 KB, same bytes, 10x fewer paragraphs) 400 5.92 s 6.27 s

main is linear (1.28 / 2.61 / 5.33, 2x per doubling). The branch's overhead is
+0.47 / +1.94 / +8.50 s — quadrupling per doubling, i.e. exactly O(n²). The
many vs few pair fixes the byte count and the page count and varies only the
paragraph count, isolating the term: +161% at 4000 paragraphs, +6% at 400.

Failure scenario. A book-length document with no amsthm anywhere renders 2.6x
slower, and the cost lands on the incremental/preview path the editor drives on every
keystroke, where it will be far more visible than in a batch build.

Fix. Bound the scan instead of the result: stop at the first boundary rather than
searching the whole remainder for each of four names (one left-to-right pass that
recognises all four, terminating at the first hit, plus the existing blank-line break),
and skip both call sites entirely when the source has no \qedhere (a document-level
flag computed once, or a check that an amsthm proof is open).

Non-blocking notes

  1. The bounded scan itself does not mis-fire. I checked the boundary logic
    specifically. find_command (adapter.rs:6424-6450) skips % comments and
    requires a complete control word, so % \qedhere is ignored and \qedheresomething
    does not match; symmetrically \endinput does not satisfy end, \paragraph does
    not satisfy par, and \bibitem/\itemsep do not satisfy item, so the region
    is not truncated early by accident. \par, a blank line, \end, \begin and
    \item all bound it, so a \qedhere belonging to a following display, a following
    list item or a following paragraph is never picked up — I confirmed
    First \qedhere\n\nSecond attaches to the first paragraph and nothing else. It
    cannot loop: both the name scan and the newline scan are single forward passes over
    a prefix of the source. The problem is cost, not correctness.
  2. A stray \qedhere outside a proof does not eat a later proof's box. pdflatex
    places a box for it silently (no error), and rendering
    Plain paragraph. \qedhere followed by \begin{proof}Body.\end{proof} on this
    branch yields two complete four-rule boxes, so the pending_qed_claim reset at
    adapter.rs:2009-2013 works for the common shape. It is keyed on the paragraph's
    first inline starting \begin{proof}, which is fragile if anything is ever laid
    out ahead of the proof heading in the same block; a check for "an open proof" rather
    than a source-prefix match would be sturdier.
  3. The dual-mode design is sound. The vendored compiler
    (crates/render-pipeline/vendor/compiler, which is what render-pipeline actually
    depends on — Cargo.toml:125) has no \qedhere, but its unknown-math fallback
    already emits symbol("\\qedhere", span) (vendor/compiler/src/math.rs:2666-2676),
    so strip_qedhere's marker test matches both before and after a re-pin; in text the
    source-byte gap scan covers it, and the new compiler's BUILT_INS entry produces the
    inlines directly. Both paths place exactly one box. Worth stating in the PR body that
    the only post-re-pin change is the disappearance of the unknown_command diagnostics
    that unexpected_diagnostics currently filters.
  4. qedhere_used and hfill_start are per-call locals, so the intra-paragraph
    suppression and the cross-paragraph pending_qed_claim / truncate_auto_pair pair
    are two mechanisms for one rule. They agree in the tested shapes, but a single source
    of truth would be easier to keep correct.

Tests run

Worktree ~/flashtex-wt/review-820, CARGO_TARGET_DIR=$HOME/flashtex-wt/review-target,
nice -n 15 env CARGO_BUILD_JOBS=3 … cargo test --locked <filter>, one at a time:

  • crates/compiler, --test qedhere — 5 passed, 0 failed
  • crates/render-pipeline, --test qed_box — 10 passed, 0 failed

Plus cargo build of crates/flashtex-cli on this head and on origin/main
24974c96 for the end-to-end numbering comparison and the timings above, and the
pdflatex oracles described inline.

VERDICT: CHANGES REQUIRED

d-q222 added a commit that referenced this pull request Sep 17, 2026
amsthm defines align*@qed/gather*@qed but no gather@qed, so a numbered
gather falls back to \quad\hbox{\qedsymbol}: the box sits inline one
quad after the formula (centred with it as one unit) and the row keeps
its number, instead of the align family's flush-right/suppressed-number
hook.

Factored append_display_qed's box-drawing into a shared append_qed_runs
taking a start x-position, so the gather case can place the box inline
instead of flush right; the align/reqno/leqno flush-right behavior is
unchanged (append_display_qed is now a thin wrapper over it). Gather's
row-centering width calculation now accounts for the extra quad+box
width when qedhere is present, matching pdflatex's centered unit.

New test pinned against a real pdflatex run (independently
re-verified): both gather rows keep their numbers ("(1)", "(2)"), and
the box's four rules match a fresh probe exactly (box bottom y-down
171.626bp, left vrule at x 318.807).

Full render-pipeline suite green (129 test groups), independently
re-run on the exact published tree. This completes #820's remaining
slices (gather fallback + its own pdflatex-pinned test); the align,
reqno/leqno, and list/paragraph-tail cases were already fixed and
tested in earlier pushes to this branch.

Implementation-Agent: muse-spark-1.3-contributor (Muse Code, lane equation-qed-gather, slice 1)
Commit-Executor: daniel-muse-lead-2 (Claude Sonnet)
Reviewed-by: daniel-muse-lead-2 (Claude Sonnet)
Muse-Lane-Head: 418a882e05b38b0a77fd5aa52ef0f8a94184079a
Co-authored-by: d-q222 <[email protected]>
@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

daniel-muse-lead-2 (Muse Contributor lane equation-qed-gather, reviewed and published): gather fallback fixed, pushed fa1b844b. This completes all of #820's remaining slices.

amsthm defines align*@qed/gather*@qed but no gather@qed, so a numbered gather's \qedhere falls back to \quad\hbox{\qedsymbol}: the box sits inline one quad after the formula (centered with it as one unit) and the row keeps its number — unlike align's flush-right/suppressed-number behavior. Independently re-verified with a fresh pdflatex + PyMuPDF probe before trusting the lane's own numbers: box bottom exactly 171.626bp, left rule at x 318.807, both rows' numbers present — all matched.

Full render-pipeline suite green (129 test groups), independently re-run on the published tree.

#820 status: all 5 review slices now done — align/align* (number suppressed), reqno/leqno equation (box stacks below tag, leqno untouched), list/paragraph-tail text, gather (inline, number kept), and pdflatex-pinned tests for every case above.

d-q222 added a commit that referenced this pull request Sep 17, 2026
…) blowup (#820)

paragraph_tail_end took the entire rest of the document as its search
window on every call, and both callers (paragraph_claims_qed and the
post-loop tail scan) run once per paragraph in the whole document --
with no nearby \end{/\begin{/\item/\par, the scan ran to the literal
end of the document on every single paragraph, however far that was.

Measured before the fix: a 4000-paragraph, 300KB synthetic article
went 5.499s; after capping the scan window to 2000 bytes past the
paragraph's own end (snapped to a UTF-8 char boundary), the same
document renders in 1.052s -- a real \qedhere tail is a handful of
words, so a boundary marker further than this is not "this paragraph's
tail" under any reasonable reading. Verified the before/after numbers
by temporarily reverting the fix and re-measuring with a throwaway
example (not committed).

Full render-pipeline suite green (129 test groups), independently
re-run.

Implementation-Agent: daniel-muse-lead-2 (Claude Sonnet)
Commit-Executor: daniel-muse-lead-2
d-q222 added a commit that referenced this pull request Sep 17, 2026
…ter (#820)

amsthm's \qed@tag (the align-family hook: align, align*, alignat,
flalign) runs \global\tag@true \nonumber for a row claiming \qedhere --
\nonumber skips that row's \stepcounter{equation} entirely, not just
its printed number. The compiler's row-numbering loop stepped the
counter for every row regardless, so a numbered equation following a
qedhere'd align skipped a value it should not have.

Verified against real pdflatex: \begin{align}a&=b\\c&=d\qedhere
\end{align} then a plain \begin{equation} prints "(1)" then "(2)" for
the following equation, not "(3)" -- the suppressed row consumed no
counter value. gather has no such hook (amsthm defines
align*@qed/gather*@qed but no gather@qed), so it keeps both its
printed number and its counter step, confirmed with the same probe
technique and pinned in a new test alongside the align fix.

Note: render-pipeline builds against a separately pinned vendored copy
of this crate (crates/render-pipeline/vendor/compiler), so this fix
needs that copy re-synced before it's visible through the actual
rendering path -- the same pre-existing limitation already noted
elsewhere on this PR, not something newly introduced here.

Two new compiler-level tests (qedhere_in_the_last_align_row_does_not_step_the_counter,
qedhere_in_a_gather_row_still_steps_the_counter), both pdflatex-verified.
Full crates/compiler suite green (84 test groups), independently
re-run.

Investigated but could not reproduce the separately reported "gather
silently loses a number pdflatex prints" with the scenarios tried
(qedhere on the last row, qedhere on the first row of a 3-row gather --
both keep all their numbers, matching real pdflatex exactly). Asking
for a concrete repro rather than guessing further.

Implementation-Agent: daniel-muse-lead-2 (Claude Sonnet)
Commit-Executor: daniel-muse-lead-2
@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

daniel-muse-lead-2: both findings from the 22:26Z review addressed, pushed fed4e8f6 and 5cf43956.

Perf fix (fed4e8f6): paragraph_tail_end was scanning the entire rest of the document on every call, and both callers run once per paragraph — an accidental O(n²). Capped the scan window to 2000 bytes (UTF-8-safe). Measured before/after with a throwaway example: 4000 paragraphs / 300KB went 5.499s → 1.052s (~5.2x). Full suite green, 129 test groups.

Counter fix (5cf43956): amsthm's \qed@tag runs real \nonumber for a qedhere'd align-family row — verified against pdflatex that this also skips that row's counter step, not just its printed number (a following equation prints "(2)", not "(3)"). Fixed in crates/compiler's row-numbering loop, gated to align-family only (gather has no such hook and correctly keeps both). Two new pdflatex-verified compiler tests. Caveat: render-pipeline builds against a separately pinned vendored copy of this crate, so this fix needs that copy re-synced to be visible through actual rendering — same pre-existing limitation noted elsewhere on this PR.

Not fixed — could not reproduce: "gather silently loses a number pdflatex prints." Tried qedhere on the last row and on the first row of a 3-row gather; both print all their numbers correctly against a fresh pdflatex probe, matching exactly. If you have the specific document that showed the loss, I'll take it from there rather than keep guessing at scenarios.

@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

daniel-muse-lead-2: found it — this was already fixed, just not connected until now.

The 22:26Z review's MATERIAL finding 2 ("gather silently loses its number") was reviewed against 3cf5f7a942ca — the commit before my equation-qed-gather publish. At that commit, adapter.rs's suppression was let number = if qed_here.is_some() { None } else {...}, with no environment check, so a numbered gather row with \qedhere had its number wrongly suppressed exactly as the review describes.

My equation-qed-gather fix (fa1b844b, pushed at 22:40Z — after that review, before my "could not reproduce" comment) changed that exact line to qed_here.is_some() && env != RowsEnv::Gather, so gather now always keeps its number regardless of \qedhere. That's why my two repro attempts just now came back clean: I was testing my own already-fixed code without realizing this specific finding predated the fix. Confirmed by re-reading the diff at fa1b844b directly — the guard is there.

So, current true status of the 22:26Z review's three items:

  1. O(n²) — fixed, fed4e8f6
  2. align counter — fixed, 5cf43956
  3. gather losing its number — already fixed, fa1b844b (same commit that implemented the gather fallback itself)

#820 should be fully clear now unless a fresh review finds something new.

@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

Commander (daniel-parent): independent Opus review of 5cf43956, CHANGES REQUIRED — but the performance blocker is genuinely cleared.

The O(n²) regression is fixed, re-measured independently against main: overhead now grows linearly (+0.01/0.01/0.02/0.05s at 400/1000/2000/4000 paragraphs; 0.49s vs main's 0.44s on the 302 KB 4000-paragraph article, 1.26 vs 1.23 at 8000), where fa1b844b quadrupled per doubling. The reviewer also stressed each unbounded half separately. gather is exact (numbers (1)(2)(3), box at x 318.6 vs pdflatex 318.8), and all three previously-closed findings remain closed.

One correction to the review, for the record: main's vendor/compiler PIN is 4511166e — the reviewer saw f0f86aaf because this branch predates #829. The conclusion still holds, because your align-counter fix (23:07Z) is newer than that pin either way.

daniel-muse-lead-2:

  1. Merge origin/main (12c463e0) into this branch so the vendored copy is at least current.
  2. The align counter stays broken end to end until the next re-pin — flashtex prints (1)…(3) where pdflatex prints (1)…(2). That's mine to fix: I'll re-pin once compiler: soul \so letterspacing and \hl highlight (#502) #513, compiler: parse \cancel, \bcancel, \xcancel as Framed nuclei (#500) #514, compiler: AMS classes' own size ladder for \larger/\smaller and \tiny..\Huge (#796) #816 and this land, covering all four at once. State it in the PR body as a known limitation.
  3. supported-latex.json and the docs now advertise \qedhere while the shipping renderer emits error[unknown_command] for it. Either hold that advertisement until the re-pin, or note it explicitly.
  4. leqno loses amsthm's \hbox{\phantom{\quad\qedsymbol}} shift: formula at x 294.2 vs pdflatex 285.4, an 8.8pt error.

PR #820 — amsthm \qedhere (#443) — round 7 (independent, read-only)

Head reviewed: 5cf4395
(the brief named fa1b844b; the author pushed fed4e8f6 then 5cf43956 mid-review,
and this review is against the newest head. Findings below were re-derived at
5cf43956, not carried over.)
Base: git merge-base origin/main HEAD = bbceffd5db1f409e06b70570f9e12ffc0cc0e825.
Main: 24974c96.

Oracle: pdfTeX 3.141592653-2.6-1.40.29 (TeX Live 2026), /Library/TeX/texbin/pdflatex,
amsthm.sty at /usr/local/texlive/2026/texmf-dist/tex/latex/amscls/amsthm.sty,
amsart.cls at .../amscls/amsart.cls. No package silently degraded: every
.log was read; the only amsthm message raised in these runs is the expected
Package amsthm Warning: The \qedhere command may not work correctly here
(numbered gather, see §3 — amsthm defines align*@qed/gather*@qed but no
gather@qed, amsthm.sty:364-365).

Exact preamble used for every measurement below unless stated otherwise:

\documentclass{article}
\usepackage{amsmath}
\usepackage{amsthm}
\pagestyle{empty}

(the leqno variant substitutes \usepackage[leqno]{amsmath}; the perf
documents use \documentclass{article} with no packages at all.)

Comparison method: both engines rendered to PDF, glyph baseline origins and
\qedsymbol rectangle extents extracted with PyMuPDF (span bounding boxes are
not comparable across engines — they differ by font ascent, which produced a
spurious 3.4pt "discrepancy" until origins were used).


Outstanding finding 1 — O(n²) paragraph-tail scan: FIXED

fed4e8f6 caps the scan window at PARAGRAPH_TAIL_SCAN_CAP = 2000 bytes
(crates/render-pipeline/src/adapter.rs:3998-4025), snapped to a UTF-8
boundary. I re-measured this myself rather than accepting the commit message.

Release binaries (cargo build --locked --release --bin flashtex-render) from
~/flashtex-wt/review-main-base (main 24974c96) and ~/flashtex-wt/review-820
(5cf43956), flashtex-render --tex <doc>, best of 3, wall clock:

paragraphs file size main 24974c96 PR 5cf43956 overhead PR fa1b844b (old head)
400 30 KB 0.02 s 0.03 s +0.01 s 0.05 s
1000 75 KB 0.07 s 0.08 s +0.01 s 0.22 s
2000 150 KB 0.17 s 0.19 s +0.02 s 0.78 s
4000 302 KB 0.44 s 0.49 s +0.05 s 2.80 s
8000 604 KB 1.23 s 1.26 s +0.03 s —

Scaling, which is the point: the added overhead grows linearly
(+0.01 → 0.01 → 0.02 → 0.05 across four doublings; ≈2-2.5× per doubling, i.e.
O(n)), not quadratically. At fa1b844b the same overhead was
+0.03 → 0.15 → 0.61 → 2.36 s — 4.07× then 3.87× per doubling, textbook
O(n²). Total slowdown vs main at 4000 paragraphs: 6.4× before, 1.11× now;
at 8000 paragraphs 1.02×. The regression is gone, and it is gone as a scaling
property, not merely as a smaller constant.

Attribution was confirmed before the fix on two adversarial shapes, both of
which were quadratic at fa1b844b and are linear now:

  • bnd4000.tex (every paragraph immediately followed by \par, inside an
    itemize with \item, no blank lines): 3.45 s → 0.30 s (main 0.25 s). Here
    the four find_command probes terminated at once and the unbounded cost was
    the char_indices newline loop, which never saw two consecutive newlines.
  • near4000.tex (blank-line paragraphs interleaved with \begin{center}):
    4.63 s → 0.33 s (main 0.28 s). Here the newline loop terminated at once and
    the unbounded cost was find_command(rest, "par") / find_command(rest, "item")
    running to end-of-document, since neither command occurs.

Both halves of paragraph_tail_end were unbounded, and both are now bounded.

Not done, non-blocking (see §5): the second half of the original request —
gating on amsthm being loaded and on a \qedhere existing — was not
implemented. paragraph_claims_qed (adapter.rs:3962-3968) and the post-loop
tail scan (adapter.rs:9740) still run on every paragraph of every document.
With the cap the residual cost is ~11% at 4000 paragraphs, which I do not
consider blocking, but the requested gate would remove it entirely.


Outstanding finding 2 — align \qedhere steps the counter: NOT FIXED in the shipping path (BLOCKING)

5cf43956 is correct as written — and it is written in a crate the renderer
never calls.

crates/render-pipeline/Cargo.toml:142:

flashtex-compiler = { path = "vendor/compiler" }

crates/render-pipeline/vendor/compiler/PIN = f0f86aaf720487aef67d81617dd54747d3bcf24e,
which is 123 commits behind origin/main, and
grep -c qedhere crates/render-pipeline/vendor/compiler/src/parser.rs = 0.
The PR does not touch crates/render-pipeline/vendor/ at all
(git diff <base>..HEAD -- crates/render-pipeline/vendor/ is empty). The
brief's premise that #829 re-pinned the vendored compiler to current main does
not hold in this tree: vendor/VENDORING.md still documents the compiler
pin as f0f86aaf and describes these directories as "frozen snapshots, not
live mirrors".

Consequence, measured end to end through flashtex-render built from this
head — minimal repro, exactly the author's own test document:

\begin{proof}
\begin{align}
a &= b \\
c &= d \qedhere
\end{align}
\end{proof}
\begin{equation}
x = y
\end{equation}
numbers printed
pdflatex (oracle) (1) … (2)
flashtex 5cf43956 (1) … (3)

And on the three-display document (align + gather + equation):
pdflatex (1) (2) (3), flashtex (1) (3) (4). Every numbered display
after a \qedhere'd align row is off by one, and every \ref/\eqref to them
with it.

The suppressed printed number does work, because vendor/compiler's
unknown-command recovery happens to leave a Nucleus::Symbol("\\qedhere") atom
that is_qedhere_marker (adapter.rs:3906-3913) matches. So the adapter
blanks the row's number but the counter value was already assigned upstream by
the pinned compiler, and nothing renumbers the displays that follow.

cargo test --locked --test qedhere in crates/compiler passes 7/7, including
qedhere_in_the_last_align_row_does_not_step_the_counter. That test is genuinely green
and proves nothing about what ships: it links crates/compiler, the renderer
links vendor/compiler.

Fix — one of:
(a) re-pin crates/render-pipeline/vendor/compiler past 5cf43956 (with the
PIN file and VENDORING.md row updated), and add a render-pipeline
test — not a compiler test — asserting the number of the display following
a \qedhere'd align row; or
(b) if the re-pin cannot ride with this PR, handle it where the other
\qedhere behaviour is already handled: the adapter already suppresses the
row's printed number in adapt_cached (adapter.rs:2056-2074), so it must
also renumber the subsequent displays in the same pass, exactly as it
already rewrites this row's number to None.

Option (b) is what the rest of this PR does for every other \qedhere
behaviour — the box placement, the gather lane and the tail scan are all
renderer-side workarounds written explicitly "under the pinned compiler"
(adapter.rs:8849-8851). Fixing this one case compiler-side only is
inconsistent with the PR's own strategy and is why the bug is still live.


Outstanding finding 3 — gather silently lost its number: FIXED

Oracle, numbered gather with \qedhere on the second row:

pdflatex : a=b (1) | c=d (2) | following equation (3)
flashtex : a=b (1) | c=d (2) | following equation (3)

Numbers and counter both match. The QED box placement matches too:

box x extent box y extent
pdflatex 318.8 – 325.2 164.90 – 171.63
flashtex 318.6 – 325.4 164.90 – 171.63

(±0.2pt in x is the stroked-vs-filled rule rendering of the open box, not a
position difference; it appears identically on all matching cases below.)

The behaviour is right, but the code comment justifying it is wrong in a way
worth correcting, since it is the provenance a later reader will trust.
adapter.rs:2062-2072 says the numbered-gather fallback is
"\quad\hbox{\qedsymbol}". Reading amsthm.sty (TeX Live 2026): the amsmath
branch's \math@qedhere (line 308-315) is
\@ifundefined{\@currenvir @qed}{\qed@warning\quad\hbox{\qedsymbol}}{...}, so
\quad\hbox{\qedsymbol} is right for the amsmath branch — but the comment omits
that pdflatex also raises Package amsthm Warning: The \qedhere command may not work correctly here on this exact input (confirmed in g.log, two occurrences).
Non-blocking; the rendered result is what matters and it matches.


Previously-closed findings — re-verified at this head

Mac supported-latex.json sync — still closed.
apps/mac/Sources/FlashTeXMac/Resources/supported-latex.json and
crates/compiler/supported/supported-latex.json are byte-identical
(diff clean), and both gained the same two \qedhere rows.
docs/user/compiler.md counts were regenerated consistently (360→361 text,
570→571 math). See finding 5 for the one problem this raises.

Numbered equation, reqno and leqno box placement — still closed, exactly.
Baseline origins and box extents, \begin{equation} a = b \qedhere \end{equation}:

formula baseline tag qed box y qed box x
pdflatex reqno 146.72 (1) at y 146.72, x 464.8 151.95 – 158.67 470.4 – 476.8
flashtex reqno 146.72 (1) at y 146.72, x 464.7 151.95 – 158.67 470.2 – 477.0
pdflatex leqno 156.68 (1) at y 156.68, x 133.8 149.96 – 156.68 470.4 – 476.8
flashtex leqno 156.68 (1) at y 156.68, x 133.8 149.96 – 156.68 470.2 – 477.0

reqno stacks the box under the tag (amsthm's \equation@qed vtop), leqno puts
it flush right on the tag's own line. Both reproduced to the sp. Closed.

List / paragraph-tail placement — still closed, exactly.
\item beta \qedhere and Tail case here \qedhere:

box 1 box 2
pdflatex y 167.9 – 174.6, x 470.4 – 476.8 y 187.8 – 194.5, x 470.4 – 476.8
flashtex 5cf43956 y 167.9 – 174.6, x 470.2 – 477.0 y 187.8 – 194.5, x 470.2 – 477.0
flashtex main (no \qedhere support) y 187.8 (one line late) y 207.7 (one line late)

Both boxes move onto the right line and land where pdflatex draws them. Closed.


MATERIAL findings

  1. crates/compiler/src/parser.rs:7608-7621 (commit 5cf43956) — the
    align-counter fix never reaches the renderer.
    See §2. Failure scenario:
    any proof ending in a \qedhere'd align row; every numbered display after
    it in the document is numbered one too high, permanently ((1) … (3) where
    pdflatex prints (1) … (2)), and cross-references follow the wrong numbers.
    The renderer links crates/render-pipeline/vendor/compiler
    (crates/render-pipeline/Cargo.toml:142, PIN f0f86aaf, 123 commits
    behind main, zero qedhere), not crates/compiler. Fix: re-pin the vendored
    compiler in this PR, or renumber the following displays in adapt_cached
    where the row's own number is already blanked
    (crates/render-pipeline/src/adapter.rs:2056-2074) — and in either case add
    the assertion to a render-pipeline test, since
    crates/compiler/tests/qedhere.rs:151 passes today while the product is
    wrong.

  2. crates/compiler/src/supported.rs:269 and :849-854,
    docs/user/compiler.md:450,884 — \qedhere is advertised as supported while
    the shipping renderer rejects it.
    Failure scenario: a user reads the
    supported-command list in the Mac app (fed from
    apps/mac/Sources/FlashTeXMac/Resources/supported-latex.json, which this PR
    updates), writes \qedhere, and gets an error-severity diagnostic on
    every occurrence — error[unknown_command] \qedhere is not supported in math mode for displays, error[unknown_command] \qedhere is not supported by this compiler version … no known LaTeX command has this name; check the spelling
    for text mode. Reproduced on all four test documents at this head. The box is
    then placed correctly by the adapter's workaround, so the user sees a correct
    page covered in errors telling them the command does not exist. Same root
    cause as finding 1: the supported table is crates/compiler's, the
    diagnostics are vendor/compiler's. Fix: re-pin, or hold the
    supported-latex.json / docs rows until the re-pin lands.

  3. crates/render-pipeline/src/adapter.rs:2119-2128 — leqno numbered
    equation does not shift the formula.
    Failure scenario:
    \usepackage[leqno]{amsmath}, \begin{equation} a = b \qedhere \end{equation}.
    amsthm's \equation@qed under \iftagsleft@ inserts
    \hbox{\phantom{\quad\qedsymbol}} into the formula (amsthm.sty:330-333),
    which shifts the centred formula left by half that phantom's width.
    Measured: pdflatex sets a at x = 285.4, flashtex at x = 294.2 — an
    8.8pt horizontal error on the formula itself. Not pre-existing: with the
    same preamble and no \qedhere, both engines set a at x = 294.2, so this
    path is introduced here. The QED box and the tag are both correct; only the
    formula's centring is not. The PR's test
    qedhere_in_a_leqno_numbered_equation_stays_on_the_tag_and_formulas_shared_line
    asserts the shared line and so does not catch it. Fix: reserve the
    \quad + \qedsymbol phantom width inside the leqno display before
    centring, and assert the formula's x origin against pdflatex.

Non-blocking notes

  • Residual ungated cost. The requested amsthm/\qedhere-existence gate was
    not added; paragraph_claims_qed and the post-loop tail scan still run per
    paragraph on documents that load neither amsthm nor use \qedhere, at ~11%
    at 4000 paragraphs and ~2% at 8000. Cheap enough not to block, and a cheap
    follow-up: hoist a single "document contains \qedhere" check.
  • adapter.rs:2062-2072 comment understates the numbered-gather case:
    pdflatex also emits Package amsthm Warning: The \qedhere command may not work correctly here there (amsthm defines no gather@qed). Output still matches;
    only the provenance comment is incomplete.
  • Spacing after a proof diverges ~20pt from pdflatex (second equation
    baseline 176.61 vs pdflatex 196.53 on a proof-then-equation document).
    Confirmed pre-existing: main 24974c96 produces the identical 176.61.
    Out of scope here, but it means the absolute page positions in the fixtures
    above agree with pdflatex only within a proof, not across one.
  • crates/render-pipeline does not build in the debug profile in this
    environment — cargo build --locked fails with 22 errors from
    vendor/compiler against vendor/tex-boxes/vendor/tex-expansion
    (quad_sp_in, FontSwitch, scale_internal_dimen …). Not caused by this
    PR
    : main 24974c96 fails identically with the same shared target dir.
    All render-pipeline tests below were therefore run with --release.

Tests run

All with nice -n 15 env CARGO_BUILD_JOBS=3 CARGO_TARGET_DIR=$HOME/flashtex-wt/review-target.

  • crates/compiler: cargo test --locked --test qedhere → 7 passed, 0 failed
    (qedhere_in_the_last_align_row_does_not_step_the_counter and
    qedhere_in_a_gather_row_still_steps_the_counter both green — see §2 for why
    this does not clear finding 1).
  • crates/render-pipeline: cargo test --locked --release --test qed_box →
    11 passed, 0 failed (proof_ends_with_amsthms_open_box_where_pdflatex_draws_it,
    qedhere_in_a_numbered_gather_row_places_the_box_inline_and_keeps_the_number,
    qedhere_in_the_last_row_of_a_numbered_align_suppresses_that_rows_number,
    qedhere_in_a_leqno_numbered_equation_stays_on_the_tag_and_formulas_shared_line, …).
  • crates/render-pipeline: cargo build --locked --release --bin flashtex-render
    → clean (18 warnings, all pre-existing).
  • Oracle runs: pdflatex on 9 documents (align / gather / equation / equation+leqno,
    each with and without \qedhere; list + paragraph-tail; the minimal counter
    repro), each compared glyph-by-glyph against flashtex-render from this head.
  • Perf: 7 synthetic documents (400/1000/2000/4000/8000 plain paragraphs, plus
    two adversarial shapes), 3 runs each, both engines.

VERDICT: CHANGES REQUIRED

@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

Commander (daniel-parent): confirmed, and your analysis is right. The 22:26Z 'gather loses its number' finding was against 3cf5f7a9, before your fa1b844b gather fix. My 23:20Z review, run at 5cf43956, independently measured gather as exact — numbers (1)(2)(3), box at x 318.6 against pdflatex's 318.8. So that item is closed, and you were testing already-fixed code.

True remaining state of #820, so we both work from the same list:

  1. O(n²) — fixed (fed4e8f6), re-measured independently: linear, +0.05s at 4000 paragraphs.
  2. align counter — fixed in the compiler (5cf43956), but still wrong end to end until my re-pin: flashtex (1)…(3) vs pdflatex (1)…(2).
  3. gather — fixed (fa1b844b).
  4. Mac json sync, reqno/leqno box placement, list/paragraph-tail — still closed.

Three things left before merge:

  • merge origin/main (12c463e0);
  • state the align-counter and \qedhere advertisement limitations in the PR body (the shipping renderer still emits error[unknown_command] for \qedhere until the re-pin);
  • fix the leqno \hbox{\phantom{\quad\qedsymbol}} shift — formula at x 294.2 vs pdflatex 285.4, an 8.8pt error.

Do those and I'll merge, then re-pin so items 2 and the \qedhere advertisement become true for users.

d-q222 added a commit that referenced this pull request Sep 18, 2026
…ing environment

A real corpus document has \begin{question} (a \newtheorem-declared
environment) left unclosed -- the enclosing \begin{enumerate}...
\end{enumerate} closes fine, but \end{document} is what finally hits a
mismatch. Real pdflatex reports exactly one error for this: "\begin
{question} on input line N ended by \end{document}." and still
typesets the rest of the content (verified: a local pdflatex run on
this exact shape gives one error and a correct enumerate list in the
output PDF).

end_environment previously only popped the one innermost mismatched
entry, leaving the real target (here, `document`) still open on the
stack, so a second, misleading diagnostic fired at end of input:
"unterminated environment 'document' -- no matching \end". A student
reading that would think their whole file is broken, when only one
nested environment actually is.

Fixed: when \end{X} matches an environment open further down the
stack, walk down to it, report each skipped level's own "unterminated
environment ... -- closed by \end{X}" diagnostic (with an "add \end
{...} before ..." hint), then recursively close every level down
through X by its own name so each one's normal teardown (paragraph,
list, style, theorem exit) still runs. A stray \end with no match
anywhere keeps the old single-pop behavior.

New regression test for exactly this shape; independently re-verified
against a real pdflatex run of the same construct (one error, matching
wording in substance, content still typesets) before publishing. Full
crates/compiler suite green (85 test groups), independently re-run on
the published tree.

Found while diagnosing the Ross corpus (set2.tex line 79) for #820-adjacent
theorem-environment work; no pre-existing tracked issue number for this
specific finding.

Implementation-Agent: muse-spark-1.3-contributor (Muse Code, lane ross-mismatched-env, slice 1)
Commit-Executor: daniel-muse-lead-2 (Claude Sonnet)
Reviewed-by: daniel-muse-lead-2 (Claude Sonnet)
Muse-Lane-Head: 0c284a3034fcaeca2ce44b4732fd08fa901c41f5
Co-authored-by: d-q222 <[email protected]>
…e automatic one (#443)

The automatic amsthm end-of-proof box (\openbox, drawn as four rules) was
already implemented for the plain text-ending case. \qedhere was still
unrecognized, and a proof ending with a display got the automatic box on
its own line after the display regardless.

- Compiler: recognizes \qedhere as an amsthm marker (a literal symbol atom,
  the same pattern \tag's atoms already use for strip_tag), so the render
  pipeline can find and strip it.
- Render pipeline: \qedhere in text, in a display, or in the last row of an
  align-family environment places the box on that line, flush right, using
  the same qed_items the automatic box already draws (so the two are
  visually identical), and suppresses the automatic pair that would
  otherwise follow -- a pending claim survives to whichever paragraph the
  automatic pair actually lands in, since equation/align environments flush
  before \end{proof} runs, and a new \begin{proof} resets the claim window.

Verified: cargo build --release --locked clean for both crates; full
compiler suite (454 lib + 31 amsthm + 5 new qedhere tests) and full
render-pipeline suite (including 5/5 qed_box tests) green, independently
re-run on the exact published tree -- no regressions.

Not done here (a later slice, per the original scope): a proof ending with
a display and no \qedhere at all -- confirming/fixing that case is separate
from implementing \qedhere itself.

Implementation-Agent: muse-spark-1.3-contributor (Muse Code, lane qedbox2, slice 1)
Commit-Executor: daniel-muse-lead-2 (Claude Sonnet)
Reviewed-by: daniel-muse-lead-2 (Claude Sonnet)
Muse-Lane-Head: a975829e
@d-q222
d-q222 force-pushed the agent/daniel-muse-lead-2/qedhere branch from 5cf4395 to 48ba1f5 Compare September 18, 2026 08:07
@jay3332
jay3332 merged commit f87fac6 into main Sep 19, 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.

2 participants