Skip to content

feat(sandbox): reclaim containers left by killed runs and report the process limit - #53

Merged
nishide-dev merged 8 commits into
mainfrom
feat/sandbox-cleanup
Oct 3, 2026
Merged

nishide-dev merged 8 commits into
mainfrom
feat/sandbox-cleanup

Conversation

@nishide-dev

Copy link
Copy Markdown
Owner

概要

texrun が強制終了(SIGKILL など)されたときに残る sandbox の container と preview の scratch directory を、次に container backend を使う texrun が回収するようにしました。あわせて、compile の container がプロセス数の上限(--pids-limit)に達したことを cgroup の pids.events から読み、resource_limit の diagnostic にします。#50 からの申し送り 2 件も対応しました。

変更内容

  • 作成者の識別(texrun_sandbox::Creator、owner.rs)
    • PID、process の開始時刻(Linux は /proc/<pid>/stat。他の OS は無し)、host の識別子(Linux は boot ID + PID namespace、macOS は OS 名 + host 名の FNV-1a hash)の組です。
    • 「作った texrun が終わった」と判定するのは、同じ host で、kill(pid, 0) が ESRCH の場合か、PID は使われているが開始時刻が違う場合(PID の再利用)だけです。判断できない場合は生きているとみなします(残す側)。
  • 残った container の回収(Runtime::reclaim_left_containers、reclaim.rs)
    • container に label org.texrun.sandbox.{pid,started,host,uid} を付けるようにしました。
    • ContainerEngine は runtime を検出した直後(CLI では probe の最初)に 1 回、best effort で回収します。
    • 消すのは、label が揃っていて .uid と .host が自分のものであり、名前が texrun-<pid>- で、作った texrun が終わっていて、止まっている(exited / dead / created、Podman の stopped / configured)container だけです。rm は --force 無しで実行するので、確認の後に動き出したものは runtime が拒否します。
    • 動いているもの(deadline 前の compile、寿命の残る preview の session)は消しません。止まった後の実行で消えます。
  • preview の scratch directory の回収(texrun-preview の fsops::reclaim_scratch_dirs)
    • 名前を texrun-preview-<pid>-<開始時刻|x>-<host>-<random> にしました。preview の container の scratch を作る前に、その親を fd で走査します。
    • 消すのは、名前がこの形式どおりで、fstatat(AT_SYMLINK_NOFOLLOW) で見て symlink でない directory、所有者が euid、mode 0700 で、作った texrun が終わっているものだけです。中身ごと、保持した fd から unlinkat / openat(O_NOFOLLOW) で消し、symlink はたどりません。
  • プロセス数の上限の報告(ContainerSpec::report_pids。engine は常に有効)
    • container の main process を /bin/sh の小さな script にしました。latexmk が終わったら、残ったプロセスを kill -1 で止め、pids.events の max を読みます。
    • latexmk が自分で終わった場合は、nonce 付きの 1 行を stderr の最後に書きます。texrun はその行を取り除き(latexmk の出力には残りません)、結果に使います。
    • texrun が止める場合(timeout・cancel・出力上限)は、rm --force の前に kill --signal TERM を送ります。script は終了コード(90 / 91)で結果を返し、texrun はそれを wait で読みます。perl は拒否された fork を再試行し続けるので、上限に達した compile の多くはこの経路で報告されます。
    • 上限に達した cgroup では、外から exec で読む方法が失敗しうることを実測で確認したので、この方式にしました。preview の session では判定しません(理由は docs に記載)。
    • 報告は container の中の同じ uid の shell が行うので、助言的な情報と位置づけ、docs に明記しました。上限そのものは kernel が掛けます。
  • feat(sandbox): add a container backend for the TeX engine #50 からの申し送り
    • cgroup v1 で swap accounting の無い host では常に exit 3 になることを、§2「sandbox backend でも保証しないもの」に書きました。CLI でも、RESTRICTIONS_NOT_APPLIED を含む Unavailable には専用の hint を出します。
    • inspect_after_exit の rustdoc に、OOMKilled の読み直しを exit 137 に限る前提と、deadline で終わった場合も最大 1 秒待つことを書きました。
  • docs
    • docs/security.md の §2(5、検証の表、保証しないもの)と §4(engine image、ライフサイクル、preview)を更新しました。
    • docs/development.md の残った container の項と、Dockerfile のコメント(/bin/sh)も更新しました。

確認方法

  • 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 --all-features --locked(macOS、TEXRUN_REQUIRE_SANDBOX=1)
  • cargo deny --locked check、actionlint
  • host(macOS、OrbStack / Docker 29.4)で engine image を rebuild し、CI の sandbox job と同じ container test を実行しました。全て pass し、終了後に label の付いた container は 0 件でした。
    • texrun-sandbox: 29 + 18 件
    • texrun-texlive の container / scenarios / security: 14 / 11 / 14 件
    • texrun-preview の container / real_tools: 4 / 13 件
    • CLI の container: 8 件
  • 追加した主な test:
    • apps/texrun/tests/container.rs
      • a_container_left_by_a_killed_run_is_reclaimed_once_it_stopped: compile 中の texrun を SIGKILL します。次の実行では動作中の container が残り、止めた後の実行で消えることを確かめます。
      • a_preview_left_by_a_killed_run_is_reclaimed: preview 中に SIGKILL します。session container と scratch directory が残り、次の実行で両方消えることを確かめます。
    • crates/texrun-sandbox/tests/container.rs
      • only_stopped_containers_of_gone_texrun_processes_are_reclaimed: 実 daemon で、残すべき 6 種(動作中、生きている texrun、別 uid、別 host、名前違い、label 不足)が残ることを確かめます。
      • a_reached_process_limit_is_reported_*: 2 経路それぞれで報告されることを確かめます。
    • crates/texrun-texlive/tests/container.rs
      • the_process_limit_is_reported_from_the_container: resource_limit の diagnostic が付き、報告の行が stderr に残らないことを確かめます。

関連 Issue

Closes #49

補足

  • label の偽装: label は何も認証しません。同じ daemon に container を作れるのは daemon の所有者(Docker では root 相当)か、rootless Podman のその user 自身で、どちらも元からこれらの container を消せます。上の条件で、texrun が消すのを「同じ user・host の、終わった texrun が作った、止まっている container」に限ります。Reclaim leftover sandbox containers and report the process limit in containers #49 より前の texrun が作った container(.host 無し)や、古い名前の scratch directory は回収しません。
  • 回収しないもの: workspace の texrun-ws-*(host backend と共通)と、output root の中の .texrun-preview-*。
  • texrun-sandbox/src/lib.rs の既定 image まわり(chore(ci): publish the engine image to GHCR #51 の範囲)は触っていません。mod と pub use の追加と、lifecycle の doc 1 文の変更だけです。

🤖 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

PR #53(#49: 残った container と preview の scratch の回収、container の process 上限の報告)のレビューです。回収と報告の設計は安全側に倒れていて、must-fix はありません。should-fix が 2 件(1 件は公開 API の値の不整合、1 件は docs の正確さ)あるので CHANGES_REQUESTED にします。どちらも小さな修正です。

実行結果

51dc032(PR の head)を clone して、PR の Dockerfile から engine image を build しました(--label org.opencontainers.image.version=0.1.0 付き)。host は macOS、OrbStack です。

  • cargo fmt --check / cargo clippy --workspace --all-targets --all-features --locked -D warnings / cargo test --workspace --all-features --locked: すべて pass
  • container test(TEXRUN_REQUIRE_SANDBOX=1、review 用の image)
    • texrun-sandbox: unit 31 + container 19、pass
    • texrun-texlive の container / scenarios / security: 14 / 11 / 14、pass(host-only は SKIPPED)
    • texrun-preview の container / real_tools: 4 / 13、pass
    • CLI の container: 8、pass
  • SIGKILL を使う CLI の 2 件と、sandbox の回収・pids 報告の 3 件を 5 回ずつ繰り返しました。すべて pass で、終了後に label org.texrun.sandbox の container は 0 件でした。
  • CI はすべて green です。

確認した点(問題なし)

container の回収の判定

  • ps の label filter と inspect の再確認で、次の全てを満たすものだけを消します: org.texrun.sandbox=1、.uid が自分の euid、.host が一致、名前が texrun-<label の pid>- で始まる、作った texrun が gone、止まっている。paused / restarting / removing / running は対象外です。rm に --force を付けないので、確認の後に start されたものは runtime が拒否します。
  • Creator::is_gone は、同じ host で ESRCH の場合か、Linux で開始時刻が違う場合だけ true を返します。zombie、EPERM、開始時刻が読めない場合、macOS で PID が使われている場合はいずれも「生きている」になり、残す側に倒れます。PID が再利用された場合も、macOS では残るだけで、誤って消すことはありません。
  • Docker socket を共有する別 container の texrun は、PID namespace の inode が host の識別子に入るので、互いに回収しません。--pid=host や --pid=container: で namespace を共有する場合は PID が比較可能なので、判定は正しいです。runtime は unix:// だけなので、別マシンの texrun と host 名が衝突する経路もありません。
  • label の偽装: label は作成時に作成者しか付けられず、後から変えられません。なので、条件を満たすように偽装できるのはその container の作成者自身だけで、消えるのはその本人の止まった container です。docs の評価(daemon の所有者は元から消せる)と合わせて妥当だと思います。#49 より前の container(.host 無し)を回収しないことも明記されています。

scratch directory の回収

  • 保持した親の fd から、名前の形式(creator tag と 16 桁の hex)、statat(AT_SYMLINK_NOFOLLOW) で見た directory であること、euid 所有、group / other の権限が無いこと、creator が gone であることを全て確かめます。そのうえで remove_tree(unlinkat と openat(O_NOFOLLOW | O_DIRECTORY)、深さの上限は 32)で消します。
  • 親は sticky な /tmp か、macOS の per-user $TMPDIR です。他人が、確認した entry を差し替えることはできません。
  • 中は 0700 なので、書けるのは同じ uid(動作中かもしれない、gone な creator の preview container の tool)だけです。symlink はたどらないので、tree の外は消えません。unit test も symlink(中と entry 自体)、file、0755、別 prefix・別 host・古い名前を確かめていて、十分です。

process 上限の報告

  • kill -1 は init と shell 自身を除きます。trap ... TERM は wait 中に即座に処理されます。r の中は builtin とリダイレクトだけで fork しないので、上限に達した cgroup でも動きます。この設計は正しいと思います。
  • 終了コード 90 / 91 は、texrun が止めた経路(exit_code が None)でしか読まないので、latexmk 自身の終了コードとは衝突しません。exit 137 / 152 などの 128 + signal も、これまでどおり $s で伝わります。
  • nonce 行の除去: printf '\n...' で始めた改行ごと除くので、latexmk の stderr が改行で終わる場合も終わらない場合も、元のバイト列に戻ります(unit test と実機の test で確認)。最後の行で、nonce が一致し、数字であるものだけを取るので、文書の出力が偶然この行の形になって誤判定することはありません。同じ uid のプロセスが妨げたり偽ったりできることは、rustdoc と §2 で advisory として明記されています。
  • probe も process::run を通るので、報告の行は probe の stderr にも残りません。/bin/sh の要件は Dockerfile のコメントと §4 の「image に期待するもの」に追加されています。
  • cgroup v1 で swap accounting が無い host の hint(RESTRICTIONS_NOT_APPLIED で判定、汎用の Unavailable の arm より前)と、inspect_after_exit の rustdoc(exit 137 に限る前提、deadline の場合の 1 秒)は、#50 の申し送りどおりです。

テスト

  • only_stopped_containers_of_gone_texrun_processes_are_reclaimed は、残すべき 6 種(running、生きている texrun、別 uid、別 host、名前違い、label 不足)と、回収する 2 種(exited、created)を実 daemon で確かめていて、十分です。
  • CLI の SIGKILL の 2 件では、別 test の texrun が先に回収しうることも考慮されていて、繰り返しても安定していました(nit 1 を除く)。

should-fix

1. 報告の行を除いた後も CapturedOutput::total_bytes がその行を数えたままで、container の compile では is_truncated() が常に true になる

process::run の container.take_pids_report(&mut finished.stderr.bytes) は、bytes だけを truncate して、total_bytes は変えていません。そのため、latexmk が自分で終わった container の compile では、LatexmkRun::stderr(texrun_texlive::CapturedOutput、公開 API)が total_bytes > bytes.len() になり、is_truncated() が常に true を返します。今は CLI でこの値を使っていませんが、「プロセスが書いた量」という field の意味が、container backend でだけ崩れます。

修正案:

  • take_pids_report が &mut CapturedOutput を受け取り、除いたバイト数を total_bytes から saturating_sub で引く。または process.rs の呼び出し側で同じことをする。
  • the_process_limit_is_reported_from_the_container の 2 つ目(既定の上限で成功する compile)に assert!(!run.stderr.is_truncated()) を足す。unit test の the_pids_report_is_taken_from_the_end_of_stderr でも total_bytes を確かめる。

2. 「次の texrun が回収する」が成り立たない場合を docs に書く(再起動、macOS の host 名の変更)

host の識別子は、Linux では boot ID と PID namespace、macOS では host 名から作ります。そのため、次の場合の残りものは、条件が元に戻らない限り回収されません(残す側なので安全上の問題はありません)。

  • Linux の host を再起動した場合: 停止した container は daemon に残りますが、boot ID が変わるので .host が一致しません。電源断や kernel panic で texrun が強制終了した場合が、まさにこれに当たります。
  • macOS で host 名(uname -n)が変わった場合: network によって変わることがあります。
  • PID namespace が毎回新しくなる環境(使い捨ての container の中の texrun など): その texrun が残したもの。

一方で §2 の 5 は「次に texrun が container backend を使うまで残る」と書いています。これだと、常に回収されるように読めます。

修正案: §2 の 5(または §4「container のライフサイクル」)と development.md の該当項に、「host の識別子が変わった場合(Linux の再起動、macOS の host 名の変更、PID namespace の異なる環境)の残りものは回収しない。docker ps -a --filter label=org.texrun.sandbox で見つけて手で消す」と一文を足してください。boot が違えば作成者は確実に終わっているので、「同じマシンの前の boot」を識別して回収するかどうかは、別 Issue で検討する価値があると思います(machine の識別子を別の label にするなど。ただし、socket を共有する VM や container との区別が要ります)。

nit

  1. a_preview_left_by_a_killed_run_is_reclaimed の待ち方。 今は scratch directory を見つけてから 300 ms 待って SIGKILL しています。そのため、Session::start が create を起動する前に kill すると container ができず、wait_for("the preview container") が 60 秒で失敗します(手元の 5 回では起きませんでしたが、負荷の高い CI では起きえます)。先に containers_of(pid, Some("running")) が 1 件になるのを待ってから kill し、その後に scratch の存在を確かめる順にすると、確実になります。
  2. stop_for_report の最悪の待ち時間。 kill(timeout 5 秒)と wait(timeout 5 秒)を別々に待つので、最悪 10 秒になります。§4 の「wait(最大 5 秒)」と合いません。1 つの deadline を共有するか、docs を「最大 10 秒」にしてください。cancel の応答時間にも効きます。
  3. host の preview でも scratch を回収している。 render.rs の output root が無い経路(temp dir に作る host の preview)でも、reclaim_scratch_dirs が呼ばれます。§4「scratch directory の回収」の「preview の container の scratch を作る前に」とずれているので、どちらかに合わせてください(host の経路でも回収してよいと思います)。
  4. remove_tree に件数の上限が無い。 深さは 32 で止まりますが、1 directory あたりの entry 数には上限がありません。回収するのは侵害されえた preview tool が書けた tree なので、entry 数(例: 合計 100k)にも上限を設け、超えたら残して次回に回すと、preview の開始が長く止まることを避けられます。Drop の経路も同じなので、既存の挙動として別 Issue でもかまいません。
  5. /bin/sh の無い custom image(--container-image)。 probe の container の起動に失敗して、「latexmk -v ... did not report a version」になります。image の要件は §4 にありますが、hint か Unavailable の reason に「image に /bin/sh などが必要(docs/security.md §4)」とあると、原因を追いやすくなります。
  6. stderr が capture の上限を超えた場合。 latexmk が自分で終わっても、報告の行は capture に入らないので、上限に達したことは報告されません。また、行の途中で切れた場合は、その断片が stderr に残ります。rustdoc には「truncated の場合は None」とありますが、§4 の報告の項にも一言あるとよいです。

nishide-dev added a commit that referenced this pull request Oct 3, 2026
## 概要

`Runtime::image` が `{{.Id}} {{json .Config.Labels}}` で image
を確認していたため、Docker 29 では label の無い image(`docker build docker/engine`
したローカル image など)で `Labels` キーが存在せず template が失敗し、image が
unavailable(exit 3)と判定されていた。`{{json .Config}}` を読み、`Labels`
の欠落・`null`・空を「version label 無し」として扱う。

## 変更内容

- `crates/texrun-sandbox/src/runtime.rs`: inspect の format を `{{.Id}}
{{json .Config}}` に変更。`parse_image` は config を `serde_json::Value`
として読み、`Labels` が欠落(Docker 29)/ `null`(古い Docker、Podman)/ `{}`
の場合と、config 自体が `null` の場合を label 無しとして扱う。version label が文字列でない場合も
version 無し。`Labels` が object でない等の不正な出力は従来どおり
unavailable。新しい依存は追加していない(`serde_json` は既存)。
- unit test: `Labels` の欠落・`null`・空・他の label のみ・あり、config `null`、不正な形式の各
JSON。
- container test(`crates/texrun-sandbox/tests/container.rs`): 空の tar を
`import` した image で、label 無し・他の label のみ・version label あり(`--change
LABEL ...`)をそれぞれ `Runtime::image` で確認(engine image の label
の有無に依存しない、test 後に image を削除)。
- CLI の container test: `engine.version` が `image without a version
label` か `image version ...` で終わることを確認。
- CI の `sandbox` job: build した engine image に label が無いことを確認する step
を追加(container テスト全体が label 無しの image=ローカル build と同じ条件で走ることを保証)。
- `docs/development.md`: ローカル / CI の image に label が無く、`engine.version`
が `image without a version label` になることを追記。

## 確認方法

- [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`
- [x] `cargo test --workspace --all-features --locked`
- [x] `cargo deny --locked check`
- [x] `actionlint`
- [x] host(macOS、OrbStack の Docker 29.4.0)で label 無しの `docker build -t
texrun-engine:nolabel docker/engine` を作り、旧 format が `map has no entry
for key "Labels"`
で失敗することを確認した上で、`TEXRUN_SANDBOX_IMAGE=texrun-engine:nolabel
TEXRUN_REQUIRE_SANDBOX=1 TEXRUN_REQUIRE_TEXLIVE=1
TEXRUN_TEST_BACKEND=container` で CI の `sandbox` job と同じ
test(`texrun-sandbox`、`texrun-texlive` の container / scenarios /
security、`texrun-preview` の container / real_tools、`texrun` の
container)が全て通ることを確認
- [x] `texrun compile --json --backend container --container-image
texrun-engine:nolabel` が成功し、`engine.version` が `latexmk 4.86 (docker
29.4.0, image texrun-engine:nolabel 7fe11aa04d7d, image without a
version label)` になることを確認

## 関連 Issue

Closes #54

## 補足

- 変更は `Runtime::image` 周辺に限定しており、#53(#49)の reclaim / owner / container
の変更とは重ならない想定。
- Podman は手元に無いため実機では未確認。Podman の `{{json .Config}}` は `Labels` を `null`
または object で出すので、unit test でその形式を扱っている。

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
nishide-dev and others added 7 commits October 4, 2026 04:36
…imit report

Also explains, in the docs and the CLI hint, why hosts with cgroup v1
and no swap accounting cannot use the container backend, and documents
when inspect_after_exit reads the OOM flag again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- take_pids_report takes the CapturedOutput and keeps total_bytes in
  step with the removed line; a truncated capture is left as it is
- kill and wait of the pids report share one 5 s deadline
- remove_tree visits at most 100k entries per tree
- the probe error names what a custom image must provide
- the killed-preview test waits for the preview container first
- docs: leftovers after a host identity change (reboot, host name,
  new PID namespace) must be removed by hand (#56); scratch reclaim
  also runs for the host preview in the temp dir; the report line is
  lost when stderr exceeds the capture limit

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nishide-dev
nishide-dev force-pushed the feat/sandbox-cleanup branch from 2af0c29 to f48cbeb Compare October 3, 2026 19:38
Another texrun may remove its container between ps and inspect, which
fails inspect for the whole chunk; the left containers in it were then
skipped (seen in the verify (arm64) job).

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

@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: APPROVE

PR #53 の再レビューです(head 97e637c。main(#55 を含む)に rebase 済み)。前回の should-fix 2 件と nit 1〜6 はすべて解消していて、退行もありません。追加の修正(batch の inspect が失敗したときに 1 件ずつ inspect し直す)も、消す対象を広げていません。APPROVE とします。

実行結果

  • cargo fmt --check / cargo clippy --workspace --all-targets --all-features --locked -D warnings / cargo test --workspace --all-features --locked: すべて pass
  • engine image は、version label を付けずに build しました(texrun-engine:review53b。#55 によりこれで probe を通ります)。これを使い、TEXRUN_REQUIRE_SANDBOX=1 で container test を実行しました。
    • texrun-sandbox: unit 33 + container 20、pass
    • texrun-texlive の container / scenarios / security: 14 / 11 / 14、pass(host-only は SKIPPED)
    • texrun-preview の container / real_tools: 4 / 13、pass
    • CLI の container: 8、pass
  • 次の test を 5 回ずつ繰り返しました。すべて pass で、終了後に label org.texrun.sandbox の container は 0 件でした。
    • CLI の SIGKILL の 2 件
    • texrun-sandbox の回収・pids 報告の 3 件と、a_container_removed_meanwhile_does_not_hide_the_others
  • 実 daemon で、存在する ID と存在しない ID を 1 回の docker inspect に並べました。存在する方は出力されますが、command 全体が exit 1 になります。そのため、修正前は chunk 全体が skip されていたことを確認しました。
  • CI はすべて green です(build (dry run)、test (linux / macos)、verify (amd64 / arm64) を含む)。

前回の指摘の確認

  • S1(total_bytes): 解消。 take_pids_report(&mut CapturedOutput) が、除いたバイト数を total_bytes から引くようになりました。capture が truncate されている場合は、何も除かずに None を返します。行は先頭から保持される capture の末尾に無いはずなので、この扱いは妥当です。unit test、sandbox の container test、texlive の container test(!run.stderr.is_truncated())で確かめています。
  • S2(docs): 解消。 §2 の 5、§4(container と scratch の両方)、development.md に、host の識別子が変わった場合(Linux の再起動、macOS の host 名の変更、PID namespace の異なる環境)は回収せず手で消すことが書かれました。follow-up として #56 が作られています。
  • nit 1: preview の container が running になるのを待ってから kill し、その container 1 件だけが残ることを確かめる順になりました。
  • nit 2: kill と wait が 1 つの deadline(合計 5 秒)を共有するようになり、docs も合っています。
  • nit 3: docs が「container の preview と、output root の無い host の preview の前」になりました。
  • nit 4: remove_tree に、1 つの tree あたり 100,000 entry の予算が付きました。Drop の経路にも同じく効きます。test も追加されています。
  • nit 5: probe が失敗したときの reason に、image の要件(/bin/sh を含む)と docs の参照が付きました。
  • nit 6: §4 に、capture の上限を超えた場合の扱いが書かれました。

追加修正(1 件ずつの inspect へのフォールバック)の評価

  • フォールバックで変わるのは「どの container の情報を取れるか」だけです。取れた各行は、これまでと同じ candidate(label、uid、host、名前、停止状態)、Creator::is_gone、--force 無しの rm を全て通らないと消されません。
  • ID は ps --no-trunc の完全な 64 桁なので、1 件ずつの inspect が別の container を指すことはありません。出力の各行には、その container 自身の .Id が入っています。消えた ID は失敗して除かれるだけです。
  • そのため、「消してはいけないもの」を消す方向には働きません。最悪でも 1 chunk あたり 64 回の inspect が増えるだけで、これはまれな競合の場合に限られます。
  • fake runtime の unit test が、消えた ID は rm されず、残った方は回収されることを確かめていて、十分です。

nit(任意。merge を止めるものではありません)

  1. reclaim_scratch_dirs の rustdoc は「up to MAX_REMOVE_ENTRIES entries per directory」と書いていますが、実装の予算は 1 つの tree(remove_tree の 1 回の呼び出し)ごとです。docs §4 の「1 つの tree でたどる entry は最大 100,000 個」に合わせて、rustdoc も「per tree」にしてください。
  2. 回収の inspect に --type container を付けると、container 以外の object を名前や ID で引く可能性を、形の上でも閉じられます。今でも、--no-trunc の ID と .State.Status の template により、実害は無いと考えます。

@nishide-dev
nishide-dev merged commit 02057a6 into main Oct 3, 2026
17 checks passed
@nishide-dev
nishide-dev deleted the feat/sandbox-cleanup branch October 3, 2026 20:10
nishide-dev added a commit that referenced this pull request Oct 3, 2026
## 概要

host の識別子(Linux は boot ID + PID namespace、macOS は host
名)が変わった後でも、**同じマシン** の残りもの(停止した sandbox container と preview の scratch
directory)を回収できるようにします。Linux の再起動(電源断・kernel panic を含む)と macOS の host
名の変更が対象です。判定できない場合はこれまでどおり残します(安全側)。

## 変更内容

- `Creator` に machine と boot の識別子(どちらも `Option`、texrun 用の接頭辞付き FNV-1a
hash)を追加
- **Linux**: `/etc/machine-id`(32 桁の hex。全 0 / `uninitialized`
は不可)。texrun が **初期 PID namespace**(`pid:[4026531836]`)にいて、container
の中でない(`/.dockerenv`・`/run/.containerenv` が無い)場合だけ記録する。boot は
`/proc/sys/kernel/random/boot_id`。
- **macOS**: `IOPlatformUUID`。`/usr/sbin/ioreg -rd1 -c
IOPlatformExpertDevice` を path で起動(shell 無し、空の環境、timeout 5 秒、出力 64 KiB
まで、`texrun_process::run` 経由)。`unsafe` は使わない。boot は記録しない。
- 判定(`owner::relation`、`Creator::is_gone(created)`)
  - 同じ host → 従来どおり PID・開始時刻で判定
  - 同じ machine・どちらも boot 無し(macOS)→ PID で判定(host 名の変更に対応)
- 同じ machine・boot が違う(Linux)→ 残りものが **今の boot の開始(`/proc/stat` の
`btime`)より前に作られた** 場合だけ回収(container は `inspect` の `.Created`、scratch
directory は `ctime`)。machine-id を共有する別の kernel(複製した VM など)が runtime の
socket を共有していても、動いている texrun のものを消さないため
- それ以外(別 machine、片方に machine / boot が無い、同じ machine・同じ boot で host 違い、壊れた
label)→ 残す
- container の label に `org.texrun.sandbox.machine` / `.boot`
を追加(分かる場合のみ)。`ps` の絞り込みは `.uid` までにし(前の boot のものは `.host` が違うため)、host /
machine の照合は `candidate` で行う
- scratch directory の名前を
`texrun-preview-<pid>-<start|x>-<host>-<machine|x>-<boot|x>-<random>`
に。#49 形式(machine / boot 無し)の名前も読み、従来どおり host だけで判定する
- 互換性: #49 形式の label / 名前は新しい要素が無いものとして扱い、同じ host のものだけを従来どおり回収する。#49
以前(`.host` 無し・random だけの名前)は回収しない(変更なし)
- PR #53 再レビューの nit 2 件: `reclaim_scratch_dirs` の rustdoc を「per
tree」に修正、回収の `inspect` に `--type container`
- `.Created` の RFC 3339 parser を追加(Docker の `Z`、Podman の `{{json
.Created}}` の offset 付きの両方)
- docs: `docs/security.md` §2「sandbox backend で追加で保証する」の 5、§4「container
のライフサイクル」「scratch directory の回収」、検証の表、`docs/development.md` を更新
- runtime の検出や `HostConfig` の照合(#47 の範囲)には触れていません

## 確認方法

- [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`
- [x] `cargo test --workspace --all-features --locked`(host: macOS)
- [x] `cargo deny --locked check`
- [x] host の Docker(OrbStack)で container test(`docker build -t
texrun-engine:latest docker/engine`、`TEXRUN_REQUIRE_SANDBOX=1`)
  - `texrun-sandbox`: unit 40 + container 21(3 回繰り返し)
- `texrun-texlive` の `container` / `scenarios` / `security`: 14 / 11 /
14
  - `texrun-preview` の `container` / `real_tools`: 4 / 13
  - CLI の `container`: 8
  - 終了後に label `org.texrun.sandbox` の container は 0 件
- [x] dev コンテナ(`docker-compose run --rm dev cargo test --workspace
--all-features --locked`): すべて pass

追加した test:

- `owner.rs`: 識別子の組み合わせごとの `relation`(同 host、同 machine・別 boot →
OtherBoot、別 machine、片側の machine / boot 欠落、同 machine・同 boot・別 host →
Unknown、macOS の machine のみ)、`before_boot`、作成時刻が今の boot 以降なら別 boot
でも回収しない、`machine-id` と `ioreg` 出力の検証、tag の新旧形式
- `reclaim.rs`: 同じ machine で host 違いの label の候補判定(壊れた label・別
machine・#49 形式は残す)、`.Created` の parse
- `fsops.rs`: #49 形式の名前は従来どおり回収、別 boot(`ctime` が今の boot 以降)・別 machine
は残す、macOS では host 名の変わった同じ machine のものを回収
- container test
`containers_of_this_machine_are_judged_by_boot_and_creation`: label
を偽装した停止 container で、同 machine・別 boot(今作ったもの)、別 machine、壊れた label、machine
無しの別 host は残し、macOS では同 machine・別 host(dead PID)を回収することを実 daemon で確認

## 関連 Issue

Closes #56

## 補足

- **残すもの(docs に明記)**: PID namespace が毎回新しくなる環境(使い捨ての container、dev
コンテナ)。container の `machine-id` は image のものを多くの container で共有しうるので、別の
kernel の texrun と区別できないため、machine を記録しません。`machine-id` /
`IOPlatformUUID` が読めない環境も同様です。
- Linux の別 boot の判定で `.Created < btime` を要求するのは、`machine-id` が同じ別の
kernel が socket を共有しているという想定しにくい構成への保険です。電源断から再起動までの間に作られた container
も、作成時刻は boot より前なので回収されます。
- scratch directory の削除が entry 数の上限で途中で止まった場合、別 boot のものは `ctime`
が更新されるので以後は回収されません(手で消す。docs に記載)。
- `inspect` の format に `{{json .Created}}` を追加しました。Podman では `.Created`
が time 型ですが、JSON にすると RFC 3339 になるので同じ parser で読めます(Podman
実機では未確認。読めなければ `None` で、別 boot の回収だけが行われない側に倒れます)。
- 既存の container test
`only_stopped_containers_of_gone_texrun_processes_are_reclaimed` は、並行する別
test の回収と競合しうるので、返り値の件数の assert を外し、container の有無だけで確認するようにしました。

🤖 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.

Reclaim leftover sandbox containers and report the process limit in containers

1 participant