Skip to content

compiler: \AtBeginDocument's hook typesets ahead of the body instead of being dropped - #499

Merged
GoKubar merged 5 commits into
mainfrom
agent/daniel-muse-lead/atbegindoc
Sep 15, 2026
Merged

GoKubar merged 5 commits into
mainfrom
agent/daniel-muse-lead/atbegindoc

Conversation

@d-q222

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

Copy link
Copy Markdown
Contributor

Scope

Fixes #458. \AtBeginDocument{HOOKA}\begin{document}Body\end{document} was rendering Body (hook content silently dropped as preamble) instead of HOOKABody. crates/compiler/src/expansion.rs only, plus tests. No crates/tex-expansion/ changes — the engine's own \AtBeginDocument/\@begindocumenthook kernel semantics are correct and out of scope.

Root cause: the engine emits the hook's expanded output before the real \begin{document} re-emission that flips the converter's document_begun flag, so the hook's tokens land in conv.out while the parser still treats everything as preamble.

Fix: a HOST_PRELUDE wrapper marks each \AtBeginDocument-queued chunk with \flashtexatbeginstart/\flashtexatbeginend; the converter buffers marked tokens (atbegin_capturing/atbegin_buffer, via a new emit() sink) instead of pushing them straight to conv.out, and flushes the buffer immediately after the real \begin{document} closes.

Two-slice history, self-caught bug: slice 1's wrapper used a bare \xdef, which — unlike real TeX's \g@addto@macro/\toks@ idiom — fully expands the hook chunk at \AtBeginDocument call time instead of deferring to \begin{document} time. I caught this in review with a live repro (\newcommand{\deferred}{FIRST}\AtBeginDocument{\deferred}\renewcommand{\deferred}{SECOND} gave "FIRSTBody" instead of the correct "SECONDBody") and sent it back for slice 2, which routes the append through \toks@ like the kernel does. I also fixed one cosmetic issue directly (a literal \n escape instead of a real line break in the HOST_PRELUDE string constant — functionally fine, since Rust does interpret \n in a non-raw string, but inconsistent with the surrounding multi-line layout).

Overlap check

git branch -a --list '*atbegin*' '*begindoc*' — no other branch. coord.py claims — GH-ATBEGINDOC held only by me, with --branch set. No open PR/issue references \AtBeginDocument besides #458.

Test results

Full cargo test in crates/compiler (fresh CARGO_TARGET_DIR, untruncated): 57/57 test binaries test result: ok, 0 failures. kernel_untested_a: 29 passed (includes 4 new tests: the original bug repro, two-hooks-in-order, hook-with-space, plus 3 added in review-driven slice 2: deferred-redefinition repro, macro-defined-after-registration, multi-hook deferred composition). \AtEndDocument's existing test unchanged and passing.

Mutation check (independently re-run by the reviewer, not just Muse's own): with the \toks@-based fix reverted to an eager-expansion variant, atbegindoc_hook_uses_the_definition_current_at_begin_document fails (left: ["Body"] / right: ["SECONDBody"]); restored with a fresh build, it passes (1 passed; 0 failed).

Not done

Ordinary preamble text outside an \AtBeginDocument hook is still silently dropped exactly as before (unchanged, correct behavior — verified by a dedicated regression test).

🤖 Generated with Claude Code

…-ATBEGINDOC, fixes #458)

The engine runs \@begindocumenthook ahead of the real \begin{document}
re-emission (kernel-faithful), so hook tokens reached the parser before
it recognized the body and were dropped as preamble. HOST_PRELUDE now
wraps each queued chunk in flashtexatbeginstart/end markers; Converter
buffers marked tokens and re-emits them right after the real
\begin{document} closes. Post-begin calls bypass the wrapper via the
engine's \let to \@Firstofone, as in LaTeX.

Implementation-Agent: muse-spark-1.3-contributor
…H-ATBEGINDOC, fixes #458)

Un-ignore the bug-report test (HOOKABody, no diagnostics); add multiple
hooks in registration order, spaced hook, begin+end combined, post-begin
immediate run, and ordinary-preamble-still-dropped regression coverage.

Implementation-Agent: muse-spark-1.3-contributor
…-ATBEGINDOC)

The HOST_PRELUDE append used a bare xdef, which fully expanded the new
chunk at registration time, so a hook referencing a preamble macro baked
in its registration-time value instead of resolving at begin-document
time like the kernel's g@addto@macro. Route the append through the
toks@ register (via a flashtexaddtobeginhook helper taking the hook
token as a parameter, since @ is Other when the host prelude runs): the
old hook expands exactly once into the register while the new chunk and
markers are stored unexpanded, and xdef reads the register back frozen.

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

d-q222 commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

daniel-parent review (subagent)

Verdict: READY

  1. Verified independently against real pdflatex (TeX Live 2026, not just the PR's own account) all three subtle semantic claims in the body:
    • Deferred-redefinition: \newcommand{\deferred}{FIRST}\AtBeginDocument{\deferred}\renewcommand{\deferred}{SECOND}\begin{document}... really does expand \deferred at \begin{document} time in real LaTeX (\typeout inside the hook prints SECOND) — the kernel's \toks@-based \g@addto@macro idiom really does defer expansion of the appended chunk, exactly as slice 2's fix claims. This matches atbegindoc_hook_uses_the_definition_current_at_begin_document.
    • \AtBeginDocument called after \begin{document} really does run its argument immediately, in source order (BEFORE/LATEHOOK/AFTER in that order) — matches at_begin_document_after_begin_runs_immediately.
    • Multiple hooks really do run in registration order, each reading the current value of a redefined macro at execution time, not registration time — matches atbegindoc_multiple_hooks_defer_and_keep_registration_order (real LaTeX: both A and B print 2, not 1/2).
  2. Ran cargo test --test kernel_untested_a in a clean detached worktree (fresh CARGO_TARGET_DIR): 29/29 passed, matching the PR's reported count.
  3. Traced every self.out.push site in the patched expansion.rs: all now route through the new emit()/drain_atbegin() sinks — only the two sink-internal pushes remain, so nothing bypasses the AtBeginDocument capture/replay.
  4. No vendor/ edits; inventory files correctly untouched (nothing to regenerate for this change). GH-ATBEGINDOC claim history shows a clean claim/close.
  5. Non-blocking integration note: compiler: feed a bare \refstepcounter into the following \label #486 (also open, also draft) touches the same shared regions of expansion.rs — the Converter struct's field list, clean(), HOST_PRELUDE, and all four Expansion{...} struct-literal sites (expand_project/finish/finish_diagnostics). Whichever of compiler: \AtBeginDocument's hook typesets ahead of the body instead of being dropped #499/compiler: feed a bare \refstepcounter into the following \label #486 merges second will need a small, mechanical rebase to reconcile the two new fields side by side. Nothing to change in either PR now.

@d-q222
d-q222 marked this pull request as ready for review September 15, 2026 06:20
GoKubar pushed a commit that referenced this pull request Sep 15, 2026
… ignore reason (#524)

* test: refresh stale ignored compiler reasons

What changed:
- Updated the HW2 page-count and AtBeginDocument ignored-test reasons with observed failures at 36fe7ec.

What was run:
- CARGO_TARGET_DIR=/Users/dqi26/flashtex/target-ignores cargo test --manifest-path crates/compiler/Cargo.toml hw2_matches_the_reference_page_count -- --ignored --exact: 3 runs, each failed with expected 3 pages and got 4.
- CARGO_TARGET_DIR=/Users/dqi26/flashtex/target-ignores cargo test --manifest-path crates/compiler/Cargo.toml at_begin_document_hook_content_is_typeset_before_the_body -- --ignored --exact: 3 runs, each failed with expected [HOOKABody] and got [Body].
- CARGO_TARGET_DIR=/Users/dqi26/flashtex/target-ignores cargo test --manifest-path crates/document-runtime/Cargo.toml compare_validation -- --ignored --exact: 3 runs, zero tests selected; the source is an opt-in .rs.txt scratch harness, not a package test.

Next step:
- Keep both tests ignored until their observed compiler/page-layout blockers are fixed.

Implementation-Agent: codex gpt-5.6-luna (max)
Commit-Executor: codex (this session)
Lane-Owner: daniel-parent (mac-m5pro-dq222)

* test: refresh render-pipeline stale ignores

What changed:
- Un-ignored the passing \@setlength preamble test.
- Updated the \input preamble test reason with its observed panic.

What was run:
- CARGO_TARGET_DIR=/Users/dqi26/flashtex/target-ignores cargo test --manifest-path crates/render-pipeline/Cargo.toml adapter::tests::preamble_scan_does_not_see_input_files -- --ignored --exact: 3 runs, each failed with the intentional panic at src/adapter.rs:7602.
- CARGO_TARGET_DIR=/Users/dqi26/flashtex/target-ignores cargo test --manifest-path crates/render-pipeline/Cargo.toml adapter::tests::preamble_scan_does_not_see_at_setlength -- --ignored --exact: 3 runs passed.
- CARGO_TARGET_DIR=/Users/dqi26/flashtex/target-ignores cargo test --manifest-path crates/render-pipeline/Cargo.toml adapter::tests::preamble_scan_does_not_see_at_setlength -- --exact: passed after removing ignore.

Next step:
- Revisit the remaining \input preamble blocker when adapter support exists.

Implementation-Agent: codex gpt-5.6-luna (max)
Commit-Executor: codex (this session)
Lane-Owner: daniel-parent (mac-m5pro-dq222)

* test: leave the AtBeginDocument ignore to #499

What changed:
- restore kernel_untested_a.rs's ignore reason; open PR #499 un-ignores that test itself, so editing the line here would only conflict.

What was run:
- git diff origin/main -- crates/compiler/tests/kernel_untested_a.rs: empty

Next step:
- open the stale-ignores PR.

Implementation-Agent: claude-opus-5 (daniel-parent)
Commit-Executor: daniel-parent
Claude-Session: https://claude.ai/code/session_012c9XLkHjePPGBuarrmE2mz
Both sides appended to crates/compiler/src/expansion.rs: this branch's
\AtBeginDocument toks-register hook wrapper plus atbegin capture state,
and main's \refstepcounter/\@CurrentLabel marker shim plus its
current_label_log. Kept both prelude chunks, both struct fields, both
marker match arms, and merged clean() to require all captures idle.
Regenerated supported-latex artefacts (byte-identical) and verified the
Mac bundled copy sync.

Implementation-Agent: fable-rebase-a
Commit-Executor: fable-rebase-a (direct; Cursor usage limit)
@GoKubar
GoKubar merged commit 685bb07 into main Sep 15, 2026
10 of 21 checks passed
GoKubar added a commit that referenced this pull request Sep 15, 2026
Clean merge (#606 rubber lengths, #576 kern spans, #499, #624); no conflicts.

Implementation-Agent: fable-rebase-c
Commit-Executor: fable-rebase-c (direct; Cursor usage limit)
@GoKubar
GoKubar deleted the agent/daniel-muse-lead/atbegindoc branch September 16, 2026 04:16
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.

\AtBeginDocument hook content is dropped as preamble instead of being typeset

2 participants