Skip to content

feat(diagnostics): parse LaTeX logs into structured diagnostics - #23

Merged
nishide-dev merged 3 commits into
mainfrom
feat/diagnostics-parser
Sep 30, 2026
Merged

nishide-dev merged 3 commits into
mainfrom
feat/diagnostics-parser

Conversation

@nishide-dev

@nishide-dev nishide-dev commented Sep 30, 2026 •

Copy link
Copy Markdown
Owner

概要

TeX / LaTeX の .log を texrun-core の Diagnostic(severity / kind / message / file / line / raw excerpt)に正規化する parser を新 crate texrun-latex-log として追加する。AI エージェントが生ログ全文を読まなくても、典型的な typo や missing package の修正箇所を判断できる構造化情報を返すことが目的。

変更内容

  • 新 crate crates/texrun-latex-log

    • API: parse_log(&[u8]) -> Vec<Diagnostic> と、設定付きの LogParser(with_workspace_root(&WorkspaceRoot) / with_max_print_line(usize) / with_max_diagnostics(usize))。LogParser::parse は ParsedLog { diagnostics, omitted } を返す
    • 件数上限: 既定 1000 件(DEFAULT_MAX_DIAGNOSTICS)。error を warning / info より優先して残し、超過時は末尾に「N 件省略」の info を 1 件追加。file stack の深さも 1024 で打ち切り(超過分はカウンタで追跡し、その間 file は None)。行は 1 つの buffer に保持
    • 入力はバイト列(非 UTF-8 は lossy 変換)。I/O も process 起動もしない純粋関数で、失敗しない(Result を返さない)。認識できない行は無視し、panic しない
    • message は制御文字を置換し 2 KiB、raw excerpt は 32 行 / 4 KiB で打ち切る
  • 対応パターン

    ログ kind severity
    Undefined control sequence.(context から \foo を抽出して message に含める) undefined_control_sequence error
    LaTeX Error: File `x.sty' not found. / I can't find file missing_file error
    LaTeX Error: / Package x Error: / Class x Error:((x) 継続行を結合) latex_error error
    Emergency stop.、==> Fatal error occurred(stop 未報告時のみ) emergency_stop error
    上記以外の TeX error(Missing $ inserted. 等) other error
    Overfull / Underfull \hbox / \vbox overfull_box / underfull_box warning
    Reference ... undefined / Citation ... undefined undefined_reference / undefined_citation warning
    Rerun / rerun を含む warning(Label(s) may have changed、rerunfilecheck 等) rerun_required info
    その他の LaTeX [Font] Warning / Package x Warning / Class x Warning / pdfTeX warning other warning
    • error は -file-line-error 形式(./main.tex:5: ...)と従来形式(! ... + l.5)の両方に対応
    • There were undefined references. の要約は、個別の warning が出ていれば重複として落とす
  • file / line 推定

    • line: file:line: prefix、l.<n>、on input line <n>、at line(s) <n>
    • file: file:line: prefix、無ければ (./chapters/intro.tex ... ) の file stack(best-effort)。名前が不確かなら推測せず None: file 名の直後が TeX が名前の後に出すもの(行末・)・空白 + (/[/{/</)/行末)でなければ Unknown(pdfTeX は空白・括弧入りの名前を quote せず出すため)、折り返しで切れた可能性がある名前も Unknown。file 名ではない ( は同じ行で閉じなければ捨てる(\typeout{a (b} で子ファイルが開いたままにならない)。認識済みメッセージ(help text、box の中身、Runaway argument? の引数)は stack に流さない
    • 正規化: 相対パスは TeX の cwd = workspace root 相対として WorkspacePath に。絶対パスは with_workspace_root 配下のみ相対化、それ以外(texmf 等)や .. を含むものは None
    • nonstopmode で missing file の直後に出る Emergency stop. の l.<n> を missing file の line に使う。ただし .sty / .cls は LaTeX が optional 引数を先読みして次の行が報告されるため、context 行に \usepackage / \RequirePackage / \documentclass / \LoadClass がある場合のみ採用し、それ以外は None(パッケージ名は message にある)。\input は正しい行なのでそのまま。line を捨てた場合は、同じ位置を報告する直後の Emergency stop. の line も None にする
  • fixture(crates/texrun-latex-log/tests/fixtures/)

    • src/ の小さな文書を dev コンテナ(TeX Live 2024 / pdfTeX 1.40.26 / latexmk 4.86)で compile した実ログを logs/ に保存。再生成は regenerate.sh
    • undefined-control-sequence / missing-package / missing-input / package-error / latex-error / multi-file(\input + サブディレクトリ)/ warnings(ref・cite・overfull・underfull)/ rerun / traditional(-file-line-error なし)/ wrapped(max_print_line 既定値 79) / missing-class / unusual-names(空白入りディレクトリ・括弧入りファイル名)/ unusual-names-traditional / unbalanced-parens(\typeout で不均衡な括弧)
    • ログは byte 単位で保持したいので logs/.editorconfig で trailing whitespace の削除を無効化
  • テスト

    • tests/real_logs.rs: 実ログに対して kind / severity / file / line / message の要点を検証(全文 snapshot には依存しない)
    • tests/synthetic.rs: fixture で出しにくいパターン(package error の継続行と help text 中の )、workspace 内外の絶対パス、従来形式の missing class、macro 内の undefined cs、複数行の rerun warning、非 UTF-8 / 制御文字、巨大行、JSON schema)
    • tests/no_panic.rs(proptest): 任意バイト列、ログ断片の組み合わせ、実ログへのランダム byte 変更・切り詰めで panic せず、出力が上限内であること
  • texrun-core の diagnostic.rs の module doc の参照先を更新(型の変更はなし)

確認方法

  • cargo check --workspace --all-targets --all-features --locked
  • cargo fmt --all -- --check
  • cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
  • cargo test --workspace --locked(host macOS と dev コンテナ Linux の両方)
  • cargo deny --locked check(proptest 追加のため)
  • PROPTEST_CASES=20000 cargo test --release -p texrun-latex-log --test no_panic
  • fixture の再生成: docker-compose run --rm dev crates/texrun-latex-log/tests/fixtures/regenerate.sh

関連 Issue

Closes #7

補足

  • 配置の判断(新 crate): texrun-core は「TeX Live や latexmk を知らない backend 非依存の model」と定義されている。一方でログの書式は TeX engine 固有なので、core には置かず別 crate にした。依存は texrun-core のみ(型の再利用)で、TeX Live engine(Implement the TeX Live engine with latexmk #5)と integration test(Add integration fixtures for common LaTeX scenarios #10)から使う想定。core に dev-dependency(proptest)を持ち込まずに済むことも理由の一つ。
  • 前提とする compile 設定(Implement the TeX Live engine with latexmk #5 と揃える): latexmk -pdf -norc -interaction=nonstopmode -halt-on-error -file-line-error -no-shell-escape、環境変数 max_print_line=10000、cwd = workspace root。engine からは LogParser::new().with_workspace_root(root).with_max_print_line(10000) で呼ぶ想定。
    • with_max_print_line(n) を渡すと、ちょうど n byte の行を TeX の折り返しとみなして次の行と結合する(byte 単位で結合するので、分断された UTF-8 も復元される)
    • 未指定時(折り返し幅が不明)は結合しない。代わりに、ちょうど 79 byte の行に接する file 名は切れている可能性があるので、推測せず file = None にする(wrapped fixture で検証。kind / line は取れる)
  • DiagnosticKind は追加していない: TeX primitive の error(Missing $ inserted. 等)や一般の warning は other + severity で表す。専用 kind が必要になれば fixture と一緒に追加する。
  • 既知の制約
    • file stack は heuristic。不確かな場合は None に倒す方針(誤った file より None)。\typeout{... ) ...} のような閉じ過多の後も None になる
    • TeX の context は error_line / half_error_line(既定 79 / 50)で ... に省略されるため、長い名前の undefined control sequence は名前を取れず Undefined control sequence. になる。Implement the TeX Live engine with latexmk #5 で error_line=254 half_error_line=238 等も設定すると改善する(本 PR では未設定・未検証)
    • pdfTeX warning は行頭に出たものだけを対象にしている(ページ番号 [1 の直後など行の途中に出るものは無視)
    • .blg(BibTeX)は対象外。follow-up: Report BibTeX failures as structured diagnostics #27
    • メモリはログサイズに線形(decode 済み全文 + 1 行 16 byte。短い行ばかりの 100MB で約 0.9GB)。follow-up の余地: 行を逐次 decode し、直近の数十行だけを保持する streaming parser にすればさらに削減できる(crate doc にも記載)
    • with_max_diagnostics は各グループ(error / その他)で log 順に先頭から残し、kind の多様性は考慮しない(doc に記載)
    • diagnostics は集約しない(例: 1 行で Unicode character ... not set up が 60 件)。件数上限で緩和し、表示時の集約は CLI(Add the texrun compile CLI command #6)側の想定
    • file は TeX が読んでいたファイル。生成物のこともある(例: Label multiply defined は main.aux)。doc に明記
  • 並行作業との関係: request.rs・workspace 関連・docs/security.md は変更していない。feat(workspace): add isolated compile workspaces #21(texrun-workspace)/ docs(security): define the MVP security model and execution limits #22 merge 後の main に rebase 済み(root Cargo.toml の members / [workspace.dependencies] の conflict を解消)

🤖 Generated with Claude Code

@nishide-dev nishide-dev left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Verdict: CHANGES_REQUESTED

レビューしました。全体の設計(pure function、&[u8] 入力、失敗しない API、core から分離した crate、構造ベースのテスト + proptest)は妥当で、典型的な typo / missing package についてはかなり良い結果が返ります。一方で、実ログで 存在しない file 名を返すケース と、100MB 級ログで二次時間になるケース を確認したので、この 2 点は直してからマージしたいです。

確認したこと

  • ゲート(clone した PR ブランチ、host macOS): cargo check --workspace --all-targets --all-features --locked / cargo fmt --all -- --check / cargo clippy ... -D warnings / cargo test --workspace --locked すべて pass。CI もすべて green
  • dev コンテナ(TeX Live 2024 / latexmk)で fixture に無い文書を 15 種類ほど compile し、LogParser::new().with_workspace_root(root).with_max_print_line(10000) で parse。モードは -halt-on-error -file-line-error(#5 想定)、-halt-on-error なし、-file-line-error なしの 3 通り
  • 100MB の合成ログで時間と max RSS を測定

実例での結果(抜粋)

ケース 結果
複数 error(\foo・Missing $×2・\baz、halt なし) 4 件とも file/line/cs 名が正しい。classic 形式も同じ
\input{chapters/one} 内の undefined cs chapters/one.tex:4 \undefinedmacro(3 モードとも正しい)
Missing $ inserted / Too many }'s / \begin{itemize} を \end{enumerate} で閉じる file/line とも正しい
Runaway argument(\textbf{ / \frac{1}{2 の閉じ忘れ) File ended while scanning use of \textbf .、file/line は None(TeX が既に main.tex を閉じているので妥当)
hyperref の Token not allowed in a PDF string、Font shape ... undefined、multiply-defined label、undefined ref 全件 kind/line 正しい。label の重複は file = main.aux
日本語 UTF-8(inputenc、Unicode character 日 ... not set up) 文字化けなし、line 正しい。ただし 1 行で 60 件
missing .cls / .sty(tikz, biblatex) message にファイル名が入る。line は \usepackage の次の行(S3)
bibtex(.bib 構文エラーで bibtex 失敗) Citation ... undefined のみ。bibtex 失敗は分からない(スコープ外、N5)
空白を含むファイル my dir/chap one.tex -file-line-error の error は正しいが、warning / overfull と classic 形式の error が file = "my"(M1)
括弧を含むファイル a(1).tex classic 形式・warning で file = "a"、-file-line-error 形式の error は丸ごと検出されない(M1, S2)
\typeout{Note (unbalanced open} を含む \input ファイル 以降の main.tex の warning / overfull が chapters/c.tex に帰属(S4)
\typeout{... ) ... )}(閉じ過多) 以降は file = None(安全側に degrade しており OK)

Issue #7 の完了条件(典型的な typo や missing package で、元ログを読まずに修正箇所を判断できる)は、通常のファイル名なら概ね満たしています。ただし上記の空白・括弧ファイル名で「存在しないファイル」を指すのは、None より悪い(AI が存在しないファイルを探しに行く / 別ファイルを編集する)ので must-fix としました。

性能(release build、100MB 合成ログ)

入力 時間 max RSS 備考
実ログの繰り返し(85k diagnostics) 0.32s 334MB 線形
( のみ 100MB 1.5s 2.7GB file stack の Paren が無制限に積まれる
! x\n 繰り返し 4.0s 4.5GB 26M diagnostics
overfull 繰り返し 0.52s 704MB 1.3M diagnostics
overfull k 件 + There were undefined references. k 件 k=20k: 0.21s / 40k: 0.86s / 80k: 3.4s 二次時間(M2)

must-fix

M1. 空白・括弧を含むファイル名で、存在しないファイルを返す

stack.rs の file_token はファイル名を空白・( で打ち切ります。TeX Live 2024 の pdfTeX はファイル名を quote せずに出力する(quoted_names_may_contain_spaces が想定する ("./my chapter.tex" 形式は実ログに出ません)ので、実際には次のようになります。

 (./my dir/chap one.tex        -> File("./my")  -> file = "my"
) (./a(1).tex                  -> File("./a")   -> file = "a"

-file-line-error の error は prefix から file を取るので正しいのですが、warning / box と classic 形式の error はすべて誤った file になります。Overleaf 由来のプロジェクトや日本語環境では空白入りのディレクトリ名は珍しくないです。

修正案(推測せず Unknown に倒す): token の直後を見て、TeX が実際にファイル名の後に出すもの(行末、)、または空白の後に ( [ { < ) / 行末)以外が続く場合は Entry::Unknown を push する。

let (token, len) = file_token(after);
if patterns::looks_like_file(token) {
    let tail = &after[len..];
    let complete = tail.is_empty()
        || tail.starts_with(')')
        || tail.starts_with(char::is_whitespace)
            && tail.trim_start().chars().next().is_none_or(|c| "([{<)".contains(c));
    let truncated = may_continue && len == after.len();
    self.entries.push(if truncated || !complete { Entry::Unknown } else { Entry::File(token.to_owned()) });
    ...
}

a(1).tex の場合、(1 は Paren として積まれ ) で pop されるので、Unknown はファイルが閉じるまで残り、帰属は None になります。空白入りの場合も同様です。余力があれば「次の区切りまで空白を含めて伸ばし、.tex 等の拡張子で終わる最長の候補」を採る拡張もできますが、まずは None に倒すのが優先です。実ログ fixture(空白入りディレクトリ + 括弧入りファイル、warning と overfull を含む)を追加し、quoted_names_may_contain_spaces は実ログに合わせて見直してください。

M2. There were undefined references. の重複判定が二次時間

parser.rs の warning() は summary を見るたびに self.out.iter().any(...) で全 diagnostics を走査します。先に大量の diagnostics(overfull 等)があり、summary 行が多数あると O(n·m) になります(上の表のとおり、2 倍ごとに 4 倍。100MB 換算で数分単位)。文書側から \typeout で任意に出力できるので、parse は TeX の timeout の後に走ることも考えると塞いでおきたいです。

修正案: Parser に undefined_reported: bool を持たせ、push で kind が UndefinedReference | UndefinedCitation のときに立てる。summary 側はその flag を見るだけにする。回帰テストとして、例えば overfull 50k + summary 50k が 1 秒以内に終わることを確認する test を追加する(#[ignore] なしでも数十 ms で済む規模に)。

should-fix

S1. メモリ使用量に上限が無い(file stack の深さ、diagnostics の件数)

  • FileStack::entries は ( ごとに push されるので、( の多いログで 27 倍程度に膨らみます(100MB → 2.7GB)。TeX 自体の入力ネストは max_in_open(既定 15)で上限があるので、例えば深さ 1024 を超えた ( は push せず overflow: usize を数え、) はまず overflow を減らす、overflow > 0 の間は current() を None にする、で十分です。
  • diagnostics の件数も無制限です(! x 行の繰り返しで 26M 件 / 4.5GB)。AI 向けの出力としても、数万件の overfull をそのまま返すのは目的に反します。LogParser::with_max_diagnostics(n)(既定 1000 程度)を設け、超過分は捨てて、最後に 1 件 Severity::Info / Other で「N 件省略」を push するのはどうでしょう。severity を問わず error を優先的に残す(warning が上限を埋めて後ろの error が消えないようにする)なら、error と warning で別に上限を持つのが簡単です。

S2. -file-line-error の header で path に括弧を含むと error が検出されない

looks_like_header_path が path.contains(['(', ')']) で弾くため、./a(1).tex:2: Undefined control sequence. が error として認識されず、halt なしの実ログで 2 件目の error が丸ごと消えました。TeX の error は必ず行頭から出るので、弾くのは「( で始まる」ケース(既存テストの (./a.tex:5: in a paren)だけで足ります。

!path.starts_with(char::is_whitespace) && !path.starts_with('(') && (path.contains('/') || has_extension(path))

S3. missing .sty / .cls の line が誤った行を指す

\usepackage{tikz}(7 行目)が line = 8、\documentclass{nosuchclass}(1 行目)が line = 2 になります(\usepackage の optional な [date] を先読みするため)。既知の制約として PR に書かれていますが、「誤った line は None より悪い」という観点では、AI が 8 行目を編集しに行く原因になります。

修正案: kind が MissingFile かつ拡張子が sty / cls で、line を Emergency stop 越しの context(crossed_stop)から取った場合は、context 行(l.<n> ...)の本文に \usepackage / \RequirePackage / \documentclass / \LoadClass が含まれるときだけ line を採用し、それ以外は None にする。message にパッケージ名が入っているので、AI は \usepackage{tikz} を検索すれば場所を特定できます。missing-package fixture の期待値も合わせて更新してください。\input{missing} は line が正しいので現状のままで OK です。

S4. 閉じない非ファイル ( があると、後続の出力が子ファイルに帰属する

\input したファイルの中で \typeout{Note (unbalanced open} を実行すると、その後の main.tex の undefined reference / overfull がすべて chapters/c.tex に帰属しました() が Paren を pop してファイル側が残る)。PR に既知の制約として書かれていますが、M1 と同じく「誤った file」を返すケースです。

修正案: 実ログでは非ファイルの (((Font)、(see above)、(1 page, ...) 等)は同じ行で閉じるので、feed の終わりに、その行で開いて閉じなかった Paren を stack から取り除く(Paren は行をまたがない扱いにする)。こうすると、上の例では chapters/c.tex の ) が正しくファイルを閉じます。逆に、行をまたいで閉じる非ファイル括弧があると、今度は親ファイルが早く閉じて None / 親に倒れる方向になりますが、今回試したログ(hyperref、babel、listings、geometry、xcolor 等を含む)ではそのような行は見当たりませんでした。どちらを採るにしても、fixture(\typeout で不均衡な括弧を出す文書)とテストで挙動を固定してください。

nit

  • N1. Runaway argument の文脈が excerpt に入らない: Runaway argument? とその次の行({unterminated \par paragraph two. ...)は error header の前にあるので、raw_excerpt にも message にも入りません。直前の行が Runaway argument? なら excerpt の開始を 2 行前にずらすと、AI がどの引数が閉じていないかを判断しやすくなります。
  • N2. 同じ行の同種 error の連続: 日本語 1 行で Unicode character X not set up が 60 件出ました。parser 側で潰す必要はありませんが、S1 の件数上限と合わせて CLI(#6)側で集約する前提ならその旨を doc に書いておくとよいです。
  • N3. .aux への帰属: Label 'a' multiply defined. が file = main.aux になります。技術的には正しいですが、AI が編集すべきファイルではないので、current file が .aux / .toc / .out 等の生成物のときは file = None にするのが親切です(-outdir 使用時は out/main.aux のようなパスになる点も含めて)。
  • N4. regenerate.sh: 安全性は問題ありません(set -euo pipefail、mktemp -d、quote 済みの rm -rf、shell escape 無効)。細かい点として、(1) コメントが docker compose run になっていますが、現状の環境では docker-compose を案内しているので PR 本文と揃える、(2) main.log が生成されなかったとき cp で abort して temp dir が残るので trap 'rm -rf "$work"' RETURN 等で掃除し、どの fixture で失敗したかを出す、の 2 点です。
  • N5. BibTeX の失敗: .bib の構文エラーで bibtex が失敗しても、main.log からは Citation ... undefined しか分かりません。スコープ外(Issue のとおり後続)で問題ありませんが、#5 / #10 で .blg か latexmk の出力を拾うことを follow-up として Issue に残しておくとよいです。
  • N6. 巨大行の一時メモリ: sanitize は全文字を集めてから truncate し、excerpt も先頭行を丸ごと push してから truncate します。上限 byte に達した時点で打ち切るようにすると、巨大な 1 行でのピークメモリを抑えられます(実測 100MB の 1 行で 316MB RSS なので優先度は低いです)。

その他(問題なし)

  • crate 分割: texrun-core を backend 非依存に保ち、TeX 固有の書式をここに閉じ込める判断に賛成です。依存が texrun-core のみなのも良いです。
  • API: LogParser::new().with_workspace_root(&root).with_max_print_line(10000).parse(&bytes) は #5 から呼びやすく、Result を返さないので compile result を壊しません。with_workspace_root の root は「TeX が見た absolute path」である必要があるので、#5 で root を canonicalize する場合はそれを渡す、と doc に一言あるとよいです。
  • panic 耐性: proptest の 3 戦略(任意 byte、断片の組み合わせ、実ログの変異)は良い構成です。今回の 100MB 合成ログでも panic はありませんでした。
  • 折り返し: max_print_line 未指定時に 79 byte 行に接するファイル名を Unknown にする方針は、誤帰属を避ける点で良い設計です。M1 / S4 も同じ考え方(曖昧なら None)で揃えるのがよいと思います。

🤖 Generated with Claude Code

nishide-dev added a commit that referenced this pull request Sep 30, 2026
…rces

Address the review of #23:

- Treat file names that are not followed by what TeX prints after a
  name (spaces or parentheses in the name, printed unquoted by pdfTeX)
  as unknown instead of guessing a truncated name.
- Discard non-file parentheses left open at the end of a line, so stray
  `(` in document output no longer keeps a child file open.
- Accept parentheses inside `-file-line-error` paths.
- Only report the line of a missing package / class when the stop
  context shows the loading command.
- Track reported undefined references with a flag instead of rescanning
  all diagnostics (quadratic before).
- Bound the file stack depth and the number of diagnostics
  (`LogParser::with_max_diagnostics`, errors kept first, with a notice
  and `ParsedLog::omitted`), store lines in one buffer, and stop early
  when truncating messages and excerpts.
- Include `Runaway argument?` context in the excerpt of the error.
- Add real TeX Live fixtures for these cases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nishide-dev

Copy link
Copy Markdown
Owner Author

レビューありがとうございます。cfff58f で対応しました。

must-fix

  • M1: file 名の直後が「行末 / ) / 空白 + ( [ { < ) / 行末」以外なら Entry::Unknown(file = None)にしました(stack.rs の ends_file_name)。実ログ fixture unusual-names(my dir/chap one.tex、a(1).tex。warning・overfull・error を含む)と、その classic 形式 unusual-names-traditional を追加しています。どちらも誤った my / a にはならず None になります。) の後は main.tex に戻ることも確認しています。quoted_names_may_contain_spaces は「TeX Live 2024 の pdfTeX は出力しない形式」と明記しました。代わりに names_with_spaces_or_parentheses_are_unknown を実ログの形で追加しています。
  • M2: undefined_reported: bool にしました(push で立てます)。回帰テスト many_undefined_summaries_are_linear(overfull 50k + summary 50k)を追加しています。release build で 80k + 80k が 3.4s から 26ms になりました。

should-fix

  • S1:

    • file stack の深さ上限は 1024 です。超えた分は overflow カウンタで数え、) はまずカウンタを減らします。overflow 中の file は None です。

    • LogParser::with_max_diagnostics(n) を追加しました(既定は DEFAULT_MAX_DIAGNOSTICS = 1000)。error と warning / info を別々に上限まで保持し、最後に error を優先して上限を埋めてから log 順に戻します。超過時は info / other の通知を 1 件末尾に追加します。LogParser::parse は ParsedLog { diagnostics, omitted } を返すように変えました(parse_log は従来どおり Vec)。

    • 行を 1 つの buffer + span で保持するようにしました。100MB の実測値:

      入力 対応前 対応後
      ( のみ 2.7GB 302MB
      ! x 繰り返し 4.5GB 0.9GB / 2.7s
      overfull 繰り返し 704MB 270MB
  • S2: header path は ( 始まりだけを拒否するようにしました。./a(1).tex:3: の error は file = a(1).tex で検出されます(fixture で確認)。

  • S3: .sty / .cls の missing file で、line を Emergency stop 越しの context から取る場合は、context 行に \usepackage / \RequirePackage / \documentclass / \LoadClass があるときだけ採用し、それ以外は None にしました。missing-package(l.4 \begin)と新しい missing-class(l.2 \begin)は line = None です。\input の line はそのまま残しています。

  • S4: 行末で閉じていない Paren を捨てるようにしました(「非ファイル括弧は行をまたがない」扱い)。fixture unbalanced-parens(子ファイル内の \typeout{Note (unbalanced open}、main 内の \typeout{A stray ) close})で、前者の後は main.tex、後者の後は None になることを固定しています。

nit

  • N1: 直前に Runaway argument? があれば、その 2 行を error の excerpt に含め、file stack には流さないようにしました(テスト runaway_argument_is_part_of_the_excerpt)。
  • N2: 件数上限で緩和しました。集約しないこと、表示時の集約は CLI(Add the texrun compile CLI command #6)側で行う想定であることを crate doc に記載しています。
  • N3: 報告される file は TeX が読んでいたファイルで、生成物(main.aux など)になる場合があることを doc に明記しました。
  • N4: regenerate.sh のコメントを docker-compose に揃えました。main.log が生成されなかったときは、fixture 名とモードを出して temp dir を掃除してから失敗します。
  • N5: follow-up として Report BibTeX failures as structured diagnostics #27 を作成しました。
  • N6: sanitize と excerpt は、上限の byte 数に達した時点で読むのを止めます。
  • with_workspace_root の doc に「TeX の cwd と同じ綴り(canonicalize するならそのパス)を渡す」と追記しました。

確認

  • ゲートはすべて pass しています: cargo check / fmt --check / clippy -D warnings / test --workspace(いずれも --locked)、cargo deny --locked check、PROPTEST_CASES=10000 の no_panic。
  • origin/main は進んでいなかったので rebase していません。

🤖 Generated with Claude Code

@nishide-dev nishide-dev left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Verdict: CHANGES_REQUESTED

cfff58f を再レビューしました。前回の M1 / M2 / S1 / S2 / S4 と nit はすべて解消を確認しました。退行も見当たりません。残りは S3 の取りこぼし 1 件(小さい should-fix)だけで、これが直れば APPROVE します。

確認したこと

  • ゲート(host macOS、PR head cfff58f): cargo check --workspace --all-targets --all-features --locked / cargo fmt --all -- --check / cargo clippy ... -D warnings / cargo test --workspace --locked すべて pass
  • regenerate.sh を dev コンテナ(docker-compose run --rm dev ...)で実行: 全 fixture が再生成でき、差分は各ログ 1 行(日付の行)だけでした。再生成したログでもテストは pass
  • 前回 compile した 15 ケース × 3 モード(-halt-on-error -file-line-error / halt なし / classic)の実ログと 100MB 合成ログを、新しい API(ParsedLog)で再実行

前回の指摘の解消状況

指摘 前回 今回
M1 空白入り my dir/chap one.tex の warning / overfull / classic error file = "my" file = None。) の後は main.tex に戻る
M1 括弧入り a(1).tex の classic error / warning file = "a" file = None
S2 ./a(1).tex:2: の error(halt なし) 検出されない a(1).tex:2 で検出
M2 overfull k 件 + summary k 件 80k で 3.4s(二次) 20k 6ms / 80k 25ms(線形)
S1 ( のみ 100MB 2.7GB 211MB
S1 ! x 繰り返し 100MB 4.5GB / 26M 件 937MB / 1001 件(omitted = 26213400)
S1 overfull 繰り返し / 実ログ繰り返し 704MB / 334MB 365MB / 288MB(1001 件)
S3 missing biblatex.sty / nosuchclass.cls の MissingFile line 3 / 2(次の行) line = None、message にファイル名あり
S4 子ファイル内 \typeout{Note (unbalanced open} の後の main.tex の ref / overfull chapters/c.tex main.tex:4 / main.tex:6(正しい)
N1 Runaway argument excerpt に入らない Runaway argument? + 引数の行が excerpt の先頭に入る

退行チェック(変化なし、いずれも正しい)

複数 error(\foo、Missing $ ×2、\baz)、\input{chapters/one} 内の error、Missing $、Too many }'s、環境の閉じ間違い、hyperref / font shape / multiply-defined label の warning、日本語 UTF-8(60 件、既定の上限内なので全件)、\includegraphics{nonexistent-image}(main.tex:13、正しい)、\input の missing file(line あり)、bibtex の undefined citation。閉じ括弧過多の \typeout の後は file = None で、前回どおり安全側に倒れています。

この結果から、Issue #7 の完了条件(典型的な typo や missing package について、AI が元ログを全文読まなくても修正箇所を判断できる)は満たしていると判断します。誤った file を返すケースは今回試した範囲では無くなりました。

should-fix

S5. missing package / class の直後の EmergencyStop が、まだ次の行を指している

S3 の対応で MissingFile の line は None になりましたが、直後の Emergency stop. の diagnostic は同じ context(l.<n>、パッケージを読み込んだ行の次の行)から line を取ったままです。

biblatex (\usepackage は 2 行目):
  Error/MissingFile   file=main.tex line=None  LaTeX Error: File `biblatex.sty' not found.
  Error/EmergencyStop file=main.tex line=3     Emergency stop.

missing-package fixture でも EmergencyStop が (main.tex, 4)(\begin{document} の行)であることを real_logs.rs のテストで固定しています。そのテストのすぐ上のコメント自身が「その行は誤った位置を指す」と書いている行です。AI は error 一覧の中で唯一 line を持つ main.tex:4 を修正箇所と読むおそれがあり、S3 で直した問題が残っている形になります。

修正案: error() で、MissingFile の line を stop_context_is_request の判定で捨てたときは、その Emergency stop. の line も採用しないようにする。例えば Parser に suppress_stop_line: Option<usize>(捨てた context の index)を持たせ、次の EmergencyStop(fatal summary でないもの)の処理でその index の context なら line = None にする。file は main.tex のままでよいです。missing-package / missing-class のテストの期待値を (Some("main.tex"), None) に更新してください。\input の missing file の場合(missing-input)は、stop の line も正しいので現状のままで OK です。

nit

  • N7. 行数が多いログの補助メモリ: Lines は decode した全文のコピーに加えて、1 行あたり 16 byte の span を持ちます。短い行ばかりの 100MB(! x\n や (./a.tex\n の繰り返し)で RSS が 0.6〜0.9GB になります。線形で上限もあるので現状で問題はありません。将来ストリーミングにする(行を逐次 decode し、excerpt 用に直近 MAX_CONTEXT_SCAN 行程度だけ保持する)余地がある、と crate doc か #27 に残しておく程度で十分です。
  • N8. 上限が小さいときに残る diagnostics が偏る: with_max_diagnostics(5) で日本語ログを parse すると、同じ Unicode character ... not set up が 5 件残り、行末の \undefinedjp(別の kind の error)は捨てられます。既定値 1000 では起きないので対応は不要です。上限を小さく使う呼び出し側(CLI の要約表示など)向けに、「先頭から log 順に残す。種類の多様性は考慮しない」と doc に一言あるとよいです。

その他(問題なし)

  • ParsedLog { diagnostics, omitted } + #[non_exhaustive] と、省略件数の通知 diagnostic は、#5 / #6 から扱いやすい形です。parse_log が Vec のままなのも良いです。
  • Collector は error と それ以外を別々に上限まで保持し、最後に log 順に戻す実装で、メモリの上限と「warning が後続の error を押し出さない」の両方を満たしています。
  • stack の「非ファイル ( は行をまたがない」扱いは、今回試したログ(hyperref、babel、listings、geometry、xcolor、booktabs、amsmath など)で問題が出ていません。

🤖 Generated with Claude Code

nishide-dev and others added 3 commits September 30, 2026 15:57
Add the texrun-latex-log crate, a pure, panic-free parser that turns TeX
engine logs (arbitrary bytes, non-UTF-8 allowed) into texrun-core
Diagnostics. It recognizes undefined control sequences, missing files,
LaTeX / package / class errors, emergency stops, overfull / underfull
boxes, undefined references / citations and rerun requests, in both the
-file-line-error and the classic `! ...` + `l.N` forms, and attributes
files via a best-effort file stack normalized to workspace paths.

Tests run against real TeX Live 2024 logs generated in the dev container,
hand-written excerpts and proptest-based no-panic properties.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rces

Address the review of #23:

- Treat file names that are not followed by what TeX prints after a
  name (spaces or parentheses in the name, printed unquoted by pdfTeX)
  as unknown instead of guessing a truncated name.
- Discard non-file parentheses left open at the end of a line, so stray
  `(` in document output no longer keeps a child file open.
- Accept parentheses inside `-file-line-error` paths.
- Only report the line of a missing package / class when the stop
  context shows the loading command.
- Track reported undefined references with a flag instead of rescanning
  all diagnostics (quadratic before).
- Bound the file stack depth and the number of diagnostics
  (`LogParser::with_max_diagnostics`, errors kept first, with a notice
  and `ParsedLog::omitted`), store lines in one buffer, and stop early
  when truncating messages and excerpts.
- Include `Runaway argument?` context in the excerpt of the error.
- Add real TeX Live fixtures for these cases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When the line of a missing `.sty` / `.cls` is dropped because TeX
reported the position after LaTeX's look-ahead, the following
`Emergency stop.` repeats that position; drop its line too. Also
document how the diagnostics limit picks what to keep and the memory
profile of the parser.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nishide-dev
nishide-dev force-pushed the feat/diagnostics-parser branch from cfff58f to eeab37e Compare September 30, 2026 06:59
@nishide-dev

Copy link
Copy Markdown
Owner Author

再レビューありがとうございます。eeab37e で対応しました(#21 / #22 merge 後の origin/main に rebase し、Cargo.toml / Cargo.lock の conflict を解消済み)。

  • S5: missing package / class で line を捨てた場合は、直後の Emergency stop. の line も None にしました。missing-package / missing-class の期待値は (main.tex, None) に更新しています。missing-input(\input)は MissingFile / EmergencyStop とも (main.tex, 4) のままで、これもテストに追加しました。
  • N7: streaming 化の余地を crate doc(Volume 節)と PR 本文の follow-up に記載しました。
  • N8: with_max_diagnostics の doc に「各グループで log 順に先頭から残し、kind の多様性は考慮しない」と追記しました。

ゲート(check / fmt / clippy / test、いずれも --locked、および deny)は pass しています。

🤖 Generated with Claude Code

@nishide-dev
nishide-dev merged commit 3cebeba into main Sep 30, 2026
9 checks passed
@nishide-dev
nishide-dev deleted the feat/diagnostics-parser branch September 30, 2026 07:00
@nishide-dev nishide-dev mentioned this pull request Sep 30, 2026
6 tasks done
nishide-dev added a commit that referenced this pull request Sep 30, 2026
## 概要

最初の backend として TeX Live + latexmk の engine(`LatexmkEngine`)を新 crate
`crates/texrun-texlive` に追加する。`docs/security.md` §3 の決定事項(texrun 管理
rc、env allowlist、名前検査、process group の kill、出力上限)に沿って実装した。main の log は
#23 の `texrun-latex-log` で diagnostics に変換する。

## 変更内容

- 新 crate `texrun-texlive`(Unix 専用)
- **crate を分けた理由**: subprocess・rlimit・signal を扱う OS
依存コードなので、`texrun-core`(型だけ)と `texrun-workspace`(入力のコピー)から分けた。将来の sandbox
backend(#26)は別の `TypesetEngine` 実装として並べられる。依存:
`texrun-core`、`texrun-latex-log`、`tempfile`、`rustix`(`process` feature
を追加)。
- `LatexmkEngine` / `LatexmkConfig`(latexmk の明示パス、探索用 `PATH`、rc
の親ディレクトリ、既定 timeout 60 s、`Limits`、`SOURCE_DATE_EPOCH`)
- `probe()`: `latexmk -norc -v` から version(`latexmk 4.86`)を取得する。以降は
`info()` がそれを返す。latexmk が見つからない場合や明示パスが実行ファイルでない場合は
`EngineError::Unavailable`。
- `run()`: `compile()` と同じ処理に加え、stdout / stderr の先頭(各 4 MiB)と latexmk の
PID を返す。`compile()` は `run()` の結果から `CompileResult` だけを返す。
- 起動(§3.5)
- `latexmk -norc -r <rc> -pdf -interaction=nonstopmode -halt-on-error
-file-line-error -no-shell-escape -outdir=<絶対パス> ./<entrypoint
のファイル名>`(`to_cli_arg()` を使う)。cwd は entrypoint のディレクトリ。shell は使わない。
- 起動前に、entrypoint のディレクトリ配下のディレクトリ構造を output dir に作る。output dir
とその祖先、`.texrun` は写さず、symlink はたどらない。
- 名前検査: entrypoint と output dir(workspace 相対)に §3.5 の allowlist
を適用する。ASCII は英数字・空白と `. _ - + , = @ /` だけ許可し、非 ASCII は Cf
と制御文字だけを拒否する。同じ検査を host 側の絶対パス(workspace root、cwd、output dir、rc
パス)にも適用する。
- texrun 管理 rc(`src/rc.rs`)
- 内容は固定で、request 由来の値は埋め込まない。compile ごとに workspace 外の `texrun-rc-*`
一時ディレクトリに書き、compile 後に(失敗時を含めて)削除する。rc の親ディレクトリが workspace 内になる設定は拒否する。
- `texrun_run` sub は `system { $prog } @cmd` で実行する。**戻り値の仕様**: latexmk
はコマンドの戻り値を `system()` と同じ wait status として扱い、rule では 256 で割る(latexmk 4.86
のソースで確認した)。そこで sub は、終了コード `c` なら `c*256`、signal `s` なら
`(128+s)*256`、起動失敗(または引数なし)なら `127*256` を返す。0 を返すのは子プロセスが 0 で終了したときだけ。
- `$pdflatex`(`-no-parse-first-line
-no-shell-escape`)、`$bibtex`、`$makeindex`、`$biber` を `internal
texrun_run` 経由にする。`$kpsewhich`
と、それ以外のコマンド変数(`$hilatex`、`$xdvipdfmx`、`$dvips_landscape`、`$hnt_previewer`、`$*_update_command`、`$pscmd`、`$make`、`$start_NT`
など)はすべて `NONE` にする。フック、filter、`$pre_tex_code`、`@cus_dep_list` は空にする。
- env(§3.4): `env_clear()` した上で
`PATH`、`HOME=<workspace>/.texrun/home`、`openin_any=p`、`openout_any=p`、`max_print_line=10000`、`MKTEX*=0`、`LC_ALL=C`
だけを渡す(`SOURCE_DATE_EPOCH` は opt-in)。**`PATH` からは空の entry と相対パスの entry
を除く**。cwd が workspace 内なので、`.` などが残っていると、入力に含まれるファイルが `pdflatex`
の代わりに実行されうるため(§3.4 の表を更新した)。
- プロセス管理(§3.2・§3.6)
- `process_group(0)` で起動する。stdout / stderr は別スレッドで最後まで読み、先頭 4 MiB
だけ保持する。
  - 1 つの poll ループで、終了・cancel・timeout・出力サイズ(500 ms ごと)を確認する。
- 停止するとき(timeout・cancel・上限超過)と正常終了後に `killpg(SIGKILL)` を送る。途中の return や
panic でも、guard の drop で kill と reap を行う。
- 出力上限を超えたら `Failed` とし、`output limit exceeded: ...` という diagnostic
を付ける。対象は output dir と `HOME` の合計(1 GiB)と、1 ファイルの大きさ(256 MiB)。
- 結果
- outcome は `Succeeded`(exit 0 かつ PDF がある)/ `Failed` / `TimedOut` /
`Cancelled`。`ProcessExit` と elapsed も入れる。
- artifact は `<stem>.pdf` と `<stem>.log`(regular file のときだけ)。`.fls` /
`.fdb_latexmk` / `.aux` は収集しない。
- diagnostics(#23 と接続した)
- `LogParser::new().with_workspace_root(<TeX の
cwd>).with_max_print_line(10000)` で parse する。file には entrypoint
のディレクトリを前置し、workspace root 相対にする。
- log が 16 MiB を超える場合は、末尾 16 MiB だけを parse して info diagnostic
を付ける(parser のメモリは log の大きさに比例するため)。
- `Kpsewhich command needed but not set up` は latexmk の stderr
に出るだけなので、diagnostics には入らない(test で確認)。
- docs
- `docs/security.md`: 次の点を実装に合わせた。`RLIMIT_FSIZE` の設定方法(下記)、rc の全項目と sub
の戻り値、`internal` の引数分割と `"` の関係、host パスの検査、cwd と log の相対パス、PATH から相対
entry を除くこと、Kpsewhich のメッセージが stderr に出ること、reader thread の待ち時間。あわせて、#22
からの申し送りどおり §3.3 を #21 の実装値(`fmt`/`base`/`mem`、`.biber.conf`、走査上限
40,000)に揃えた。
  - `docs/development.md`: ignored test の実行方法を追記した。

## 確認方法

host(macOS、TeX Live なし)とコンテナ(Debian trixie arm64、TeX Live 2024 + latexmk
4.86)の両方で、次を実行して成功した。

- [x] `cargo check --workspace --all-targets --all-features --locked`
- [x] `cargo fmt --all -- --check`
- [x] `cargo clippy --workspace --all-targets --all-features --locked --
-D warnings`(コンテナでは Linux 用の cfg も確認)
- [x] `cargo test --workspace --locked`
- [x] `cargo deny --locked check`(host)
- [x] コンテナで `cargo test --workspace --all-features --locked --
--include-ignored`: `texrun-texlive` の unit test 47 件(ignored の 1 件を含む)と
integration test 16 件がすべて成功した。

TeX Live が無くても動く test(CI の linux / macos で実行される):

- rc の内容(全 `NONE` 変数、sub の shell 非経由と戻り値、合図待ちの有無、`%` placeholder)
- argv、env が allowlist と完全に一致すること、PATH の sanitize、名前検査(許可 / 拒否 / Cf)
- ディレクトリの写し(`.texrun`、output dir の祖先、symlink の扱い)、サイズ集計
- `sh` の孫プロセスを使った timeout / cancel の group kill
- stdout の切り詰め
- latexmk が無い場合の `Unavailable`
- cancel 済みの token では起動しないこと
- 偽の latexmk(shell script)を使った end-to-end: 子プロセスに見える env、argv、cwd、rc
ディレクトリが削除されること

TeX Live が必要な test(`#[ignore]`、`docker compose run --rm dev cargo test
-p texrun-texlive -- --ignored`):

- 最小の article から PDF ができる(artifact は PDF と log だけ。`.texrun` 配下には `home`
と `out` だけが残り、rc は残らない)
- 未定義命令で `Failed` になり、`UndefinedControlSequence` の diagnostic が
`main.tex:4` を指す
- latexmk が無い場合の `Unavailable`(compile と probe)
- `\def\x{\x}\x` で timeout 3 s → `TimedOut`(SIGKILL)になり、`ps` で group
に生きているプロセスが残っていない
- cancel → `Cancelled`。同じく子孫が残らない
- process tree: pdflatex の親が latexmk(group leader)で、group 内に `sh` /
`dash` / `bash` がいない。pdflatex の argv に `-no-parse-first-line
-no-shell-escape` がある
- サブディレクトリの entrypoint(`\input` と `\include{chapters/intro}`):
`chapters/intro.aux` が output dir にでき、undefined reference の file が
`src/chapters/intro.tex` になる
- 日本語と空白を含むファイル名(`論文 ドラフト.tex`)、先頭が `-` のファイル名
- bibtex(`.bbl` ができ、引用が解決される。Kpsewhich のメッセージは stderr にだけ出る)、makeindex
- `\write18` が無効(`runsystem(...)...disabled`、ファイルは作られない)
- output dir の合計の上限と、1 ファイルの上限(Linux では `RLIMIT_FSIZE` によって log
がちょうど上限の大きさで止まる)
- `HOME` に置いた `.latexmkrc` は読まれない
- 合図が無い場合、rc は終了コード 125 で終了し、何も書かない

## レビュー対応(2 回目の commit)

- must-fix: `LatexmkConfig::latexmk` の明示パスは、`locate()` で `canonicalize`
した絶対パスに解決してから確認・起動する。相対パスは texrun の cwd を基準に解決する。拒否ではなく解決を選んだのは、CLI(#6)で
`--latexmk ./bin/latexmk` のように書けると便利だからである。解決できなければ
`Unavailable`。test(相対パスが絶対パスになる、解決できない相対パスは `Unavailable`)と §3.4 を追加した。
- should-fix 1: leader の終了を `waitid(P_PID, EXITED | NOHANG | NOWAIT)`
で検知して、reap せずに zombie のまま残す。`killpg` の後で `wait` によって reap する。timeout /
cancel / 上限超過 / 正常終了のすべてでこの順序になる。§3.6 も改めた。
- should-fix 2: Linux では `RLIMIT_FSIZE` と同時に `RLIMIT_CORE=0`(soft・hard
とも)を設定する。§3.2 に追記した。macOS では停止を `SIGKILL` で行うので core は作られない。ignored の
per-file test では、test process の soft `RLIMIT_CORE` を hard(dev コンテナでは
unlimited)まで上げたうえで、workspace に `core` が無いことを assert する。`RLIMIT_CORE`
の設定を外すとこの test が失敗することも確認した。
- nit:
1. host 側の問題は `Unavailable` にした。対象は、host パス(temp dir
名など)が名前検査を通らない場合と、rc の親ディレクトリが workspace 内にある場合。request 自体の問題は従来どおり
`InvalidRequest`。
  2. `prlimit` で設定する値は、texrun 自身の hard limit との min にした。
3. 起動前に、output dir にある既存の `<stem>.pdf` / `<stem>.log` を削除する。`run()` の
doc に明記し、test を追加した。
  4. `probe()` を呼ぶまで version が `None` であることを `LatexmkEngine` の doc に書いた。
  5. `LatexmkRun::pid` の doc に「診断用。終了後に signal を送る用途に使わない」と書いた。
6. `japanese_and_space_file_names` に全角空白(U+3000)のケースを追加した。unit test では
U+00A0 / U+2002 / U+2028 も許可されることを確認している。
  7. ignored test の命名は、後続への申し送りとして補足に書いた。
8. rc に `%extra_rule_spec = ();` を追加した(latexmk 4.86 の既定値が空の hash
であることを確認した)。

## 関連 Issue

Closes #5

## 補足

- **実現方法を変えた制限: `RLIMIT_FSIZE`**
  - `pre_exec` は `unsafe` なので、`unsafe_code = "forbid"` を維持するために使っていない。
- 代わりに、Linux では spawn 直後に親から `prlimit(2)` を latexmk
に適用する(`rustix::process::prlimit`)。latexmk がそれより前に書き込みや子プロセスの起動をしないよう、rc
の先頭で stdin から合図を 1 行待たせ、`prlimit` の後に親が合図を送る。合図の前に stdin が閉じた場合、rc
は何もせずに終了コード 125 で終わる。
- macOS には `prlimit` が無いので、1 ファイルの上限は 500 ms ごとの poll
でだけ強制する。検出までの間は上限を超えて書かれうる。`docs/security.md` §3.2 に明記した。
- **timeout の既定値**: `CompileOptions.timeout` が `None` のときは、engine 側でも
`LatexmkConfig::default_timeout`(60
s)を適用する。安全側に倒すためで、CLI(#6)が値を入れる前提は変わらない。
- **stdout / stderr の扱い**: backend 非依存の `CompileResult` には field
が無いので、engine 固有の `LatexmkRun` で返している。`Transcript` artifact
としてファイルに書き出すかは #6 で決めてほしい。
- **既知の制約**
- group から抜けたプロセス(新しい session を作ったもの)は追えない。reader thread は kill 後に最大 2
秒だけ待って打ち切る。
- 同じ compile の前の pass で作られた PDF は、後の pass が失敗した場合も artifact
として報告される(`Failed` の部分出力として扱う)。以前の compile で残ったものは、起動前に削除する。
- **#10 / #11 への申し送り(ignored test の運用)**: `cargo test -p texrun-texlive
-- --ignored` で、unit(`gated_rc_does_nothing_without_the_start_token`)と
integration の両方が走る。ignore の理由の文字列は統一してある。ただ、今後ほかの crate に TeX Live
以外の理由で ignored の test が増えると、`--ignored` の対象が混ざる。#10 で方針を決めるときに、test 名の
prefix(例 `texlive_`)か nextest の filter に揃えてほしい。
- **後続 Issue 候補(共通化)**: 次の実装は、PR #31(preview)の外部コマンド起動と重複している。後続 Issue
で共通化する(今回はしない)。
  - process group での起動、`waitid(WNOWAIT)` → `killpg` → reap の順序
  - reader thread による出力の保持量の制限
  - env allowlist
  - timeout / cancel の poll
- **texrun-workspace は変更していない。** integration test では dev-dependency として
`Workspace::create` / `context()` / `request()` を使っている。
- **レビューしてほしい点**: rc の `NONE` 一覧に漏れがないか(latexmk 4.86
のソースから拾った)、`prlimit` と合図待ちによる順序の保証、`PATH` の sanitize。

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
nishide-dev added a commit that referenced this pull request Sep 30, 2026
## 概要

BibTeX が失敗しても、これまでの diagnostics は main の `.log` から出る `Citation ...
undefined` だけで、原因(どの `.bib` のどの行か、BibTeX が失敗したこと自体)が分かりませんでした。BibTeX の
`.blg` と、latexmk が BibTeX について出すメッセージを parse して、構造化 diagnostics
として返すようにします。

## 変更内容

- **`texrun-core`**: `DiagnosticKind::BibtexError`(`.bib` の構文エラー・重複
entry など)と `BibtexFailed`(BibTeX が失敗した /
実行されなかった)を追加しました。`#[non_exhaustive]` と `#[serde(other)] Other`
はそのままで、`schema_version` は据え置きです(値の追加だけなので)。
- **`texrun-latex-log`**: `.blg` parser `BlgParser`(新しい module
`blg`)を追加しました。
- 別 crate にはせず、同じ crate の module にしました。純粋関数・best-effort
という性質が同じで、`sanitize`、excerpt の上限、`Collector`(error 優先の件数上限)をそのまま使えるためです。
  - 認識する内容:

    | `.blg` | kind | severity |
    | --- | --- | --- |
| `I couldn't open database file` / `style file` / `auxiliary file` |
`missing_file` | error |
| `<msg>---line N of file x.bib`(位置が次の行にある形も)、`---while reading
file`、`Sorry---` | `bibtex_error` | error |
| `Warning--I didn't find a database entry for "k"` |
`undefined_citation` | warning |
    | その他の `Warning--` | `other` | warning |
| `(There were N error messages)` / `(That was a fatal error)` / 上の
error | `bibtex_failed` | error の後なら info、それ以外は error |
- **file**: `.blg` 自身が `Database file #n:` / `The style file:` で名前を挙げた
`.bib` / `.bst` で、かつ caller(`BibFiles`)が解決できたときだけ付けます。`.aux` 内の位置(存在しない
database / style の場合)には付けません。
- **line**: file と一緒にだけ付けます。`---line N` は BibTeX がエラーを見つけた行(予期しない token
の行)です。`(Error may have been on previous line)` のときは、message
に「前の行かもしれない」と書きます。warning の `--line N` は `string name "x" is undefined`
のときだけ残します。`I'm ignoring x's extra "year" field` などは、BibTeX
がフィールドの先まで先読みしてから出すので、行がずれることを実ログで確認しました。そのため None にしています(#23 / #40
の「誤った line は None より悪い」)。
- 計算量: 行数に線形です(各行を 1 回見て、message の後ろは定数行だけ先読み)。database / style 名は 64
個まで覚えます。`BibFiles::locate` は名前ごとに 1 回です。crate / module の doc に書きました。
- **`texrun-texlive`**(新しい module `bibtex`。process 関連には触れていません):
- output dir 以下で、この compile の間に書かれた `*.blg` を読みます(mtime が latexmk
の開始以降。`\include` や `bibunits` などで複数の aux があっても拾います)。
- 上限: 走査は 20,000 entry・深さ 16 までで、symlink はたどりません。読むのは 16 file まで、各 1
MiB(先頭)まで。通常ファイルだけを `O_NOFOLLOW | O_NONBLOCK` で open し、`fstat`
でも確認します。diagnostics は 1 file あたり 200 個までです。
- `.bib` / `.bst` 名は、`<entrypoint dir>/<name>` が workspace 内の通常ファイルのときだけ
workspace 相対に変換します。latexmk は BibTeX の `BIBINPUTS` / `BSTINPUTS` の先頭に
entrypoint のディレクトリを置く(実測)ので、そこにあるファイルが BibTeX の読んだものです。installed style や
output dir に生成されたファイルは None です。
- **存在しない `.bib`**: latexmk は BibTeX を実行せず(veto)、exit 0 で終わり、`.blg`
も出ません(実測)。latexmk の出力の `Reason: I am configured only to use bibtex/biber
if all .bib files exist, but the following didn't:`
に続く名前から、`missing_file` の warning を返します。compile 自体は成功扱いのままなので、severity は
warning にしました。
- latexmk の error summary に `Bibtex errors: See file` があるのに `.blg`
を読めなかった場合は、`bibtex_failed` の error を返します。
- `.blg` は artifact に含めません(`docs/security.md` §3.9 の「engine
が報告したものだけ収集」の方針)。内容は diagnostics の `raw_excerpt` に入ります。
- fixture:
- `texrun-latex-log/tests/fixtures/logs/bibtex-*.blg`(dev
コンテナの実ログ。`.bib` の構文エラー、存在しない `.bib`、存在しない entry、存在しない `.bst`、複数 `.bib`)
- `regenerate.sh` に `bibtex` mode(pdflatex 1 pass + `bibtex
main`)を追加しました。latexmk は `.bib` が無いと BibTeX を実行しないので、`.blg` の fixture
にはこの mode を使います。
  - `texrun-texlive/tests/fixtures/bibtex/`(entrypoint ごとに 1 シナリオ)
- test:
- parser: unit test、実ログ test(`tests/real_blg.rs`)、proptest(panic
しない・出力に上限がある)、大きな入力が短時間で終わること
- engine: unit test(再帰的な探索、stale / symlink / FIFO /
件数・深さ・サイズの上限、workspace 外への symlink、console の
parse)と、`require_texlive!()` 方式の scenario test
`tests/bibtex.rs`(構文エラー、存在しない `.bib`、paranoid mode で開けない
`.hidden/refs.bib`、存在しない entry、存在しない `.bst`、サブディレクトリの entrypoint と複数
`.bib`、正常な bibliography では何も出ないこと)
- docs: README(BibTeX 関連の kind)、`docs/security.md`(`.blg` を artifact
にしないことと、読み込みの上限)

## 確認方法

- [x] `cargo check --workspace --all-targets --all-features --locked`
- [x] `cargo fmt --all -- --check`
- [x] `cargo clippy --workspace --all-targets --all-features --locked --
-D warnings`(host とコンテナ)
- [x] `cargo test --workspace --all-features --locked`(host)
- [x] dev コンテナで `TEXRUN_REQUIRE_TEXLIVE=1 TEXRUN_REQUIRE_PREVIEW_TOOLS=1
cargo test --workspace --all-features --locked`(全件 pass)

## 関連 Issue

Closes #27

## 補足

- 構文エラーの line は、BibTeX が報告した「予期しない token の行」です(例: 行 4 の末尾のカンマ抜けは行 5
と報告され、`(the error may be on the previous line)` が付きます)。TeX の `l.N`
と同じ意味なので残しましたが、None にすべきという意見があれば変えます。
- latexmk の console のメッセージ(veto の理由、error summary)は latexmk 4.86
の文言に依存します。文書も console に任意のテキストを出せるので、ここからは file の付かない diagnostic
だけを作ります。
- kpsewhich を無効にしている影響で、texmf 内の `.bib`(`\bibliography{xampl}` など)も
latexmk には「見つからない」扱いになり、BibTeX が実行されません。この PR ではその場合も `missing_file` の
warning として報告します(挙動自体は既存のままです)。
- biber / biblatex は対象外です(Issue のスコープどおり)。

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
nishide-dev added a commit that referenced this pull request Oct 6, 2026
## 概要

`v*` の tag を push するだけで、検証 → engine image の公開 → **release notes 付き** の
GitHub release の作成(source tar 添付)まで完了するようにする。release notes は前の版の tag
から今回の tag までの commit(= squash merge した PR タイトル、Conventional Commits)を
git-cliff で分類して生成し、インストール方法・image の tag / digest・`gh attestation
verify`・source tar の説明を定型で付ける。既存 release の notes だけを作り直す workflow
も追加する(v0.1.0 の notes を埋めるのに使う)。

## 変更内容

- `cliff.toml`(新規): git-cliff の設定。type で分類(`feat` → Features / `fix` →
Bug fixes / `perf` → Performance / `docs` → Documentation /
`refactor`・`test`・`build`・`chore` → Other changes)。`chore(deps)` は
Dependencies に「N dependency updates: #a, #b」の 1 行にまとめる(PR 番号はタイトル行の末尾の
`(#N)` だけから取る。番号の無いものは件数にだけ数える)。`!` / `BREAKING CHANGE:` は Breaking
changes にも載せる。Conventional でない commit も Other changes に残す。**すべての行は
commit のタイトル(1 行目 = PR タイトル)だけから作り**、PR 本文や footer の文面は載せない。末尾の `(#N)` を
PR へのリンクにし、`@name` は mention にならないよう code にし、前の版との compare リンクを付ける。
- `.github/scripts/release-notes-test.sh` /
`release-notes-test.expected.md`(新規): 使い捨ての repository に main の squash
merge と同じ形の fixture の commit(PR 本文付き、実際の Dependabot 形式の本文付き(単独・group)、PR
番号の無い `chore(deps)`、日本語の `BREAKING CHANGE:` footer + attribution、GitHub
の Revert、`@name` を含むタイトル)を作り、notes の「What's changed」を期待値と比べる。PR の
`notes` job で毎回実行する。
- `.github/scripts/release-notes.sh`(新規): `release-notes.sh <tag>
[<digest>]` で notes の Markdown を出力する。
- 安定版は前の安定版から(間の prerelease を畳み込む: `--ignore-tags '^v.*-'`)、prerelease
は直前の tag から、最初の版は全履歴。git-cliff の `--context` から対象 tag の release だけを選んで
`--from-context` で描画するので、HEAD が tag より先(main)でも同じ notes になる。
- tag がまだ無い場合は「最後の tag 〜 HEAD」をその版としてプレビューする。digest を省略すると placeholder。
  - tag が HEAD の祖先でない、semver でない、digest の形式が違う、対象の commit が無い、などはエラー。
- `.github/workflows/engine-image.yml`
  - `publish` が `digest` を output する。
- `release` が checkout(`fetch-depth: 0`)→
git-cliff(`taiki-e/install-action` を SHA
pin、`[email protected]`。install-action が checksum を検証)→ notes 生成(job
summary にも出す)→ release の作成(`--notes-file`。版に `-` があれば prerelease
にする既存の扱いを維持)。
- release が既にある場合(手で作った / 再実行)は、notes を生成したもので **上書き** してから asset を
upload する。
- `.github/workflows/release-notes.yml`(新規): notes の生成だけを行う
workflow。image の公開・release の作成はしない。
- `pull_request`(`cliff.toml`・script・この workflow の変更時): fixture の test
の後、PR の head commit(merge ref ではなく。`Merge … into …` の行が入らない)で、最後の tag(現状
v0.1.0、全履歴)の notes と、次の版(patch + 1)としての「最後の tag 以降」の notes を job summary
と artifact `release-notes` に出す。digest は GHCR から引く(未公開の版は placeholder)。
- `workflow_dispatch`(`tag`、`update`): `update=false`(既定)は dry
run。`update=true` は `gh release edit --notes-file` で既存 release の notes
を置き換える(main か tag 上の実行のみ。image が GHCR に無い版は失敗)。
- 権限: 生成する `notes` job は `contents: read`。書き込む `update` job だけが
`contents: write` で、repository の code は実行しない(artifact を受け取って `gh release
edit` するだけ)。
- docs
- `docs/development.md`: release 手順を「tag を push するだけ」に更新し、「release
notes」節(分類の規則、notes の文面は PR タイトルで決まること、ローカルでの生成方法、作り直し方)を追加。
- `CONTRIBUTING.md`: PR タイトルが release notes の 1 行になること、type /
description の書き方の注意、notes の PR check を追記。
- `docs/security.md`(権限の記述)、`docs/engine-image.md`(digest は release
notes に載る)を追随。

## 設計判断

- **git-cliff を採用**(GitHub の自動生成 + `.github/release.yml` ではなく): この repo
は PR にラベルを付けない運用で、GitHub の自動生成はラベルでしか分類できない。git-cliff は commit の type
で分類でき、PR タイトル = commit タイトルの運用にそのまま合う。API を使わず(`--offline`)git
の履歴だけで決まるので、PR 上やローカルでも同じ結果を再現できる。
- **既存 release の notes は上書き**: notes は git の履歴と公開済みの digest
から決定的に作られるので、再実行で上書きしても結果は同じ。手で先に release を作った場合も、生成した notes に揃える(docs
に明記。公開後の手修正は、作り直すと消える)。
- **CHANGELOG.md は置かない**: tag ごとに CHANGELOG 更新の commit / PR
が必要になり、運用が増えるため。GitHub release を changelog とし、必要なら同じ `cliff.toml` から
`git cliff` でいつでも全履歴を出せる。
- **notes の作り直しは別 workflow**: engine-image.yml の `workflow_dispatch` は
image の公開と結び付いているので、notes だけの経路を分けた。image は再公開せず、digest は GHCR
にある既存の版から引く。
- **notes の生成は image の公開後**: digest が要るため `release` job で生成する。設定の誤りは PR
上の `Release notes / notes` で先に検出する。万一 `release` で失敗しても image は公開済みで、`gh
run rerun --failed` でやり直せる(既存の手順どおり)。
- **git-cliff の版**: `2.14.2` を両 workflow で固定(install-action の manifest の
sha256 で検証)。install-action 自体は SHA pin で、Dependabot の対象。

## 確認方法

- [x] `actionlint`(全 workflow)、`shellcheck
.github/scripts/release-notes.sh`
- [x] ローカルで git-cliff 2.14.2(公式 release の tar を sha512 で確認)を使って生成
  - `release-notes.sh v0.1.0 sha256:b611…` → 下記(v0.1.0 までの全履歴、32 commit)
  - `release-notes.sh v0.1.1` → v0.1.0 以降の差分(この PR の commit のみ)のプレビュー
- 使い捨ての clone で `v0.2.0-rc.1` / `v0.2.0-rc.2` / `v0.2.0` を打って確認: rc.2 は
rc.1 からの差分、v0.2.0 は v0.1.0 からの全部(rc の分を畳み込む)。tag が HEAD の祖先でない場合・semver
でない tag・不正な digest はエラーになる
- `release-notes-test.sh`: 期待値どおり(下記)。修正前の `cliff.toml`
に戻して実行すると、Dependabot の行が `3 dependency updates (Dependabot):,,`
に、Breaking changes が日本語の footer + `🤖 Generated with …` に、Revert
の行が本文付きに、`@octocat` が mention になり、test が失敗することを確認した
  - レビュー対応の後も v0.1.0 の notes は変わらない(前回の出力と diff なし)
- [x] `CONTRIBUTING.md` / `docs/development.md`: タイトルだけが載ること、`@name`
を書かないこと、`jq` が要ること、`update` は通常 `--ref main` で実行すること(v0.1.0 の tag の上には
workflow が無い)、fixture の test を追記
- [x] PR 上の `Release notes / notes` が、v0.1.0 と v0.1.1(プレビュー)の notes を
job summary と artifact に出す(GHCR から v0.1.0 の digest を引く)
- `workflow_dispatch` の dry run は、新規 workflow が default branch に入るまで
dispatch できないため、merge 後に `gh workflow run release-notes.yml --ref main
-f tag=v0.1.0` で確認する(PR 上の `pull_request` の実行が同じ生成を行う)
- tag の push・release の作成 / 編集・publish を有効にした実行はしていない
- Rust のコードは変更していない(cargo の品質ゲートは CI で確認)

### 生成例: v0.1.0(digest は GHCR の実際の値)

<details>
<summary>v0.1.0 の notes(全文)</summary>

````markdown
## What's changed

### Features

- **core**: Define compile domain model and engine interface ([#20](#20))
- **workspace**: Add isolated compile workspaces ([#21](#21))
- **diagnostics**: Parse LaTeX logs into structured diagnostics ([#23](#23))
- **texlive**: Add latexmk engine ([#30](#30))
- **preview**: Render PDF pages to PNG previews ([#31](#31))
- **cli**: Add compile command ([#34](#34))
- **workspace**: Exclude nested output directories by path ([#38](#38))
- **diagnostics**: Locate missing packages and fold fatal errors ([#40](#40))
- **diagnostics**: Report BibTeX failures ([#42](#42))
- **process**: Apply resource limits before exec through a gate ([#44](#44))
- **process**: Limit CPU, memory and process count ([#45](#45))
- **sandbox**: Add a container backend for the TeX engine ([#50](#50))
- **sandbox**: Render previews inside the container ([#52](#52))
- **sandbox**: Reclaim containers left by killed runs and report the process limit ([#53](#53))
- **sandbox**: Reclaim leftovers from a previous boot ([#58](#58))

### Bug fixes

- **workspace**: Refine exclusion and collection edge cases ([#29](#29))
- **texlive**: Restore the build after #39 and #40 ([#43](#43))
- **sandbox**: Accept engine images without labels ([#55](#55))
- **sandbox**: Support rootless Podman and refuse rootless Docker ([#57](#57))
- **sandbox**: Detect OOM kills reliably on Docker ([#61](#61))

### Documentation

- Add contribution guidelines and MIT license ([#15](#15))
- Add initial README ([#18](#18))
- **security**: Define the MVP security model and execution limits ([#22](#22))
- Update README to reflect the completed MVP ([#37](#37))
- Rewrite the README ([#59](#59))

### Other changes

- Initialize repository
- Bootstrap Rust workspace and toolchain ([#16](#16))
- **ci**: Add quality gates and dependency checks ([#19](#19))
- **docker**: Add TeX Live development environment ([#17](#17))
- Add TeX Live integration fixtures and CI job ([#33](#33))
- **process**: Extract shared subprocess execution ([#39](#39))
- **ci**: Publish the engine image to GHCR ([#51](#51))

## Install

```bash
cargo install --locked --git https://github.com/nishide-dev/texrun --tag
v0.1.0 texrun
```

See the [README](https://github.com/nishide-dev/texrun/blob/v0.1.0/README.md#installation) for the requirements and
the tools each backend needs.

## Engine image

The container backend (`--backend container`) runs TeX in the engine image
of this version, `ghcr.io/nishide-dev/texrun-engine:0.1.0` (linux/amd64, linux/arm64). texrun
never pulls it; pull it once:

```bash
docker pull ghcr.io/nishide-dev/texrun-engine:0.1.0
```

Published versions are never overwritten. To use exactly this image, pin its
digest:

```bash
docker pull
ghcr.io/nishide-dev/texrun-engine@sha256:b611748f16d50c00982da2e52b51939d50167bebbc22b35ab8741d1c39e00d1b
texrun compile --backend container --container-image
ghcr.io/nishide-dev/texrun-engine@sha256:b611748f16d50c00982da2e52b51939d50167bebbc22b35ab8741d1c39e00d1b
main.tex
```

The image has an SBOM, SLSA provenance and a signed GitHub artifact
attestation:

```bash
gh attestation verify oci://ghcr.io/nishide-dev/texrun-engine:0.1.0 -R
nishide-dev/texrun
```

## Source of the engine image

`texrun-engine-0.1.0-sources.tar` (below) has the Debian source packages
(`.dsc`, `.orig.tar.*`, `.debian.tar.*`) of every package in the image,
for both platforms, at exactly the installed versions (`packages.txt` and
`SHA256SUMS` inside): the corresponding source of its GPL / AGPL programs.
See [docs/engine-image.md](https://github.com/nishide-dev/texrun/blob/v0.1.0/docs/engine-image.md#licenses).
````

</details>

### 生成例: v0.1.0 以降の main の差分(次の版のプレビュー)

````markdown
## What's changed

### Bug fixes

- **ci**: Build release notes lines from commit titles only

### Other changes

- **ci**: Generate release notes from conventional commits
- **ci**: Write release notes on tag push and add a notes-only workflow

**Full diff**: [v0.1.0...v0.1.1](v0.1.0...v0.1.1)
````

(以下の Install / Engine image / Source は v0.1.0 と同じ形で、digest は
placeholder。squash merge 後は 1 commit になる)

### 生成例: fixture(`release-notes-test.expected.md`)

````markdown
## What's changed

### Breaking changes

- **cli**: Rename --json flag to --format json ([#4](#4))

### Features

- **cli**: Rename --json flag to --format json ([#4](#4))

### Bug fixes

- **diagnostics**: Report the error `@octocat` found ([#7](#7))

### Other changes

- Revert "fix(core): handle empty logs ([#5](#5))" ([#6](#6))

### Dependencies

- 3 dependency updates: [#2](#2), [#3](#3)

**Full diff**: [v0.1.0...v0.2.0](v0.1.0...v0.2.0)
````

## 補足

- merge 後、v0.1.0 の notes を埋めるには: `gh workflow run release-notes.yml
--ref main -f tag=v0.1.0`(dry run、summary で確認)の後に `gh workflow run
release-notes.yml --ref main -f tag=v0.1.0 -f update=true`。
- notes の文面は PR タイトルで決まる。merge 後に誤りに気付いた場合は release を手で編集できるが、作り直すと消える。
- 推奨(任意): `release-notes.yml` の `update` job にも、engine-image.yml と同様に
`environment` を付けることを検討できる(docs/security.md の「release の入口」)。

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

Normalize LaTeX diagnostics into structured errors and warnings

1 participant