Skip to content

実装: skill_runtime_exec.py の outer child cleanup を Popen supervisor 化する - #2082

Merged
squne121 merged 3 commits into
mainfrom
worktree-issue-2075-skill-runtime-exec-py-outer-timeout-clea
Aug 11, 2026
Merged

squne121 merged 3 commits into
mainfrom
worktree-issue-2075-skill-runtime-exec-py-outer-timeout-clea

Conversation

@squne121

@squne121 squne121 commented Aug 11, 2026 •

Copy link
Copy Markdown
Owner

Summary

この PR は Issue #2075 の実装です。scripts/agent-guards/skill_runtime_exec.py の outer child 起動を、subprocess.run(..., timeout=timeout_seconds) の TimeoutExpired 事後捕捉方式から、起動直後から caller が PID/PGID を保持し続ける subprocess.Popen(..., start_new_session=True) supervisor 方式へ置換しました。

OWNER レビュー(issuecomment-5249045572)を反映した現行実装は以下の通りです(下記「Fix Delta」節に詳細)。

  • 実行待機は proc.communicate(timeout=timeout_seconds) に委譲し、subprocess.run() と同一の pipe-EOF timeout semantics・decode-error 伝播を維持します。
  • timeout(または Popen 成功後の任意の例外)発生後は、execution deadline とは別に新規に開始される単一の cleanup budget(_CLEANUP_GRACE_SECONDS)の下で、SIGTERM → process-group liveness(leader ではなく group 全体の生存)の poll → bounded grace 経過後の SIGKILL → killpg(pgid, 0) による absence 再検証 → direct child wait() reap → pipe close、という staged cleanup state machine を実行します。
  • この state machine は TimeoutExpired 経路・その他の例外(KeyboardInterrupt 等)unwind 経路の両方から共通で呼ばれ、Popen 成功後のどの exit path でも process group が確実に片付きます。
  • pgid は起動直後の proc.pid(start_new_session=True により leader 自身が group leader)としてその場で保持し、遅延 os.getpgid() lookup は行いません。

Checks

以下、各受け入れ基準(AC)に対応する検証コマンドと結果を日本語で記します。

  • AC1(起動直後から PID/PGID を保持する supervisor への置換): uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_outer_child_uses_popen_start_new_session -q を実行し、1 件成功しました。
  • AC2(process group absence の確認): uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_timeout_process_group_isolation -q を実行し、1 件成功しました。
  • AC3(SIGTERM から SIGKILL への escalation 実証): uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_sigterm_escalates_to_sigkill -q を実行し、1 件成功しました。
  • AC4(normal success の semantics 不変): uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_normal_success_semantics_unchanged -q を実行し、1 件成功しました。
  • AC5(direct child の確実な reap): uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_direct_child_reaped -q を実行し、1 件成功しました。
  • AC6(cleanup deadline exhaustion で unconfirmed 扱い): uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_cleanup_deadline_exhaustion_unconfirmed -q を実行し、1 件成功しました。
  • AC7(partial stdout/stderr の非リーク): uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_partial_stdout_stderr_not_leaked -q を実行し、1 件成功しました。
  • AC8(non-POSIX fallback の誤判定なし): uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_non_posix_fallback_not_false_success -q を実行し、1 件成功しました。
  • AC9(telemetry closed enum の記録): uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_cleanup_status_telemetry_enum -q を実行し、1 件成功しました。
  • AC10(既存回帰なし): uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_preflight_bytecode_cache.py -q を実行し、24 件すべて成功し regression はありませんでした(PR docs: AC10 pid_proof flake root-cause文書を訂正し診断情報を追加 (#2073) #2080 で本 PR の base 側に 1 件追加されたため、直前の Summary 記載の 23 件から更新しています。fix_delta 適用時点の現行 head で再計測済みです)。
  • 追加のローカル確認として uv run --locked pytest scripts/agent-guards/tests/ -q(serial 実行、xdist 不使用)を実行し、1234 件成功・1 件 skip・1 件 deselect という結果を得ました(前回計測の 1227 件 + PR docs: AC10 pid_proof flake root-cause文書を訂正し診断情報を追加 (#2073) #2080 由来の +1 件 + fix_delta で追加した P2-2 テスト 6 件 = 1234 件で整合しています)。

修正差分(Fix Delta): OWNER レビュー対応 issuecomment-5249045572

OWNER の詳細レビューを受け、_run_child_with_supervision() および関連関数(_stage_cleanup() 等へ再構成)を全面的に修正しました。

P1 Blockers(4件、すべて対応済み)

  • P1-1(leader liveness ではなく process-group liveness を監視): 対応済み。SIGKILL escalation の判定を proc.poll()(leader 単体の終了)ではなく、_poll_group_absent_until() による killpg(pgid, 0) の group-liveness ポーリングへ変更しました。leader が先に終了しても、SIGTERM を無視する descendant が同一 process group に残っていれば SIGKILL へ escalate します。新規テスト test_leader_exits_but_term_ignoring_descendant_still_escalated_to_kill でこの反例を直接検証しています。
  • P1-2(proc.poll() ベースの success 判定が communicate() semantics を破壊): 対応済み。独自 reader thread + proc.poll() ポーリングループを廃し、proc.communicate(timeout=timeout_seconds) 方式へ置換しました。これにより pipe EOF を待つ従来の timeout semantics・UnicodeDecodeError の伝播(旧 except (OSError, ValueError) の握り潰しを撤廃)・stdout/stderr 完全性が subprocess.run() と同等になります。新規テスト test_leader_exit_with_descendant_holding_pipes_still_times_out(AC4 回帰の直接反例)と test_malformed_child_output_raises_unicode_decode_error(decode-error 伝播確認)で検証しています。Issue 実装:scope_rollup.runをskill_runtime_execのsiblingexactprofileへ統合する #1601 が所有する bounded streaming の先行導入は行っていません。
  • P1-3(Popen 成功後の例外・KeyboardInterrupt 経路での process group リーク): 対応済み。try: proc.communicate(...) / except subprocess.TimeoutExpired: ... / except BaseException: _stage_cleanup(...); raise 構造へ変更し、Popen 成功後のあらゆる exit path(timeout、その他の例外、KeyboardInterrupt を含む)が同一の _stage_cleanup() state machine を通るようにしました。新規テスト test_exception_after_popen_still_cleans_up_process_group で注入例外からの再送出後にも process group が残らないことを確認しています。
  • P1-4(execution deadline と cleanup deadline の契約の相互矛盾): 対応済み。OWNER review が勧告するモデル(execution deadline とは独立に、cleanup 全体を単一の cleanup_deadline で bound する)へ実装を統一しました。_stage_cleanup() 内の全ステップ(TERM 待機・group-liveness poll・KILL・absence 再検証・leader reap・pipe close)はすべて _remaining(cleanup_deadline) で bound され、旧実装にあった join(timeout=1) / join(timeout=5) 等の固定タイムアウトの積み上げは廃止しました。Issue 本文・PR Summary・PR Notes の記述もこのモデルに揃えて更新しています。

P2 所見(findings)

  • P2-1(os.getpgid() の遅延取得を廃し起動直後の proc.pid を pgid とする): 対応済み。pgid = proc.pid if posix_supervised else None を Popen() 直後に設定し、os.getpgid() は一切呼び出しません。confirmed_absent は保存済み pgid への killpg(pgid, 0) が ProcessLookupError になった場合のみに限定されており(pgid lookup 自体を行わないため、lookup failure が confirmed_absent に昇格することはありません)。新規テスト test_pgid_captured_from_proc_pid_without_getpgid_lookup(os.getpgid 呼び出しがあれば fail する spy)と test_group_absence_check_permission_error_not_confirmed(PermissionError 等の非 ProcessLookupError な OSError が unconfirmed のままであることの確認)で検証しています。

  • P2-2(safety property の独立検証テスト不足): 対応済み。以下 6 件を test_skill_runtime_exec_process_tree_cleanup.py に追加しました。

    1. test_leader_exits_but_term_ignoring_descendant_still_escalated_to_kill(leader が SIGTERM で先に終了・descendant が無視するケースの term_then_kill + 独立 killpg(pid, 0) 再確認)
    2. test_leader_exit_with_descendant_holding_pipes_still_times_out(AC4 回帰の直接反例: leader 正常終了・descendant が pipe 保持で success ではなく timeout になることの確認)
    3. test_exception_after_popen_still_cleans_up_process_group(注入例外の再送出後に leader・process group が残らないことの確認)
    4. test_pgid_captured_from_proc_pid_without_getpgid_lookup(P2-1: os.getpgid 不使用の確認)
    5. test_group_absence_check_permission_error_not_confirmed(P2-1: PermissionError 等が confirmed_absent に昇格しないことの確認)
    6. test_malformed_child_output_raises_unicode_decode_error(P1-2: subprocess.run(text=True) と同じ decode-error semantics の確認)

    reader thread/pipe cleanup(旧 P2-2 の 5 番目の観点)については、communicate() 方式への変更により独自 reader thread 自体が存在しなくなったため該当なしです。

  • P2-3(Issue 実装: skill_runtime_exec.py の outer timeout cleanup で descendant process の process-group cleanup を保証する #2075 本文が参照する orphan doc / PR 本文のテスト件数): 報告のみ(Allowed Paths 外につき本 SubAgent では実行せず)。Issue 実装: skill_runtime_exec.py の outer timeout cleanup で descendant process の process-group cleanup を保証する #2075 本文が参照する docs/dev/ac10-pid-proof-flake-root-cause.md は PR docs: AC10 pid_proof flake root-cause文書を訂正し診断情報を追加 (#2073) #2080 で既に削除された orphan ドキュメントです。この Issue 本文編集は本 Issue の Allowed Paths(scripts/agent-guards/skill_runtime_exec.py, scripts/agent-guards/tests/)の範囲外のため、別途 edit-issue skill 経由での対応が必要です。人間(OWNER)または edit-issue 実行担当への申し送り事項として本 PR の説明・Issue コメントで報告します。PR 本文のテスト件数(23 件→24 件、1227 件→1234 件)は本 fix_delta で現行 head を再計測し、上記「Checks」節に反映済みです。

Schema Change Applicability

  • decision: not_schema_change
  • reason: 変更は skill_runtime_exec.py 内部の outer child 起動・cleanup 実装(subprocess.run → subprocess.Popen supervisor、および今回の fix_delta による communicate() ベースへの再構成)に閉じています。_emit_timeout_failure() の stderr telemetry には cleanup_scope / cleanup_status / termination / leader_reaped の新規フィールドが追加されますが、これは stderr 上の診断テキスト(SKILL_RUNTIME_FAIL: reason_code=... 形式のログ行)の拡張であり、既存の JSON schema・producer/consumer 間の構造化キー契約・型定義は変更していません。既存の reason_code=child_process_timeout / exit code 2 の契約はそのまま維持されます。

Schema Consumer Inventory

N/A
reason: schema_change ではないため。

Safety Claim Matrix

Claim Implemented? Not controlled Evidence Follow-up
normal success(timeout が発生しないケース)で stdout/stderr/returncode の既存 semantics が変更されていない yes N/A AC4 テスト(test_normal_success_semantics_unchanged)+ 反例テスト(test_leader_exit_with_descendant_holding_pipes_still_times_out)+ 既存 test_skill_runtime_preflight_bytecode_cache.py 24 件の regression-free PASS N/A
timeout 時、executor-owned process group の absence を killpg(pgid, 0) で再検証してから confirmed_absent を報告し、signal 送出自体を成功と見なさない yes N/A AC2/AC6 テスト(test_timeout_process_group_isolation / test_cleanup_deadline_exhaustion_unconfirmed)+ test_group_absence_check_permission_error_not_confirmed、_verify_process_group_absent() 実装 N/A
SIGTERM を ignore する leader/descendant に対し bounded grace 経過後に SIGKILL escalation が実際に行われる(leader liveness ではなく process-group liveness で判定する) yes N/A AC3 テスト(test_sigterm_escalates_to_sigkill)+ test_leader_exits_but_term_ignoring_descendant_still_escalated_to_kill(leader 早期終了 + descendant 生存の反例)、_poll_group_absent_until() 実装 N/A
direct child(leader)が wait() で確実に reap され zombie が残らない(Popen 成功後の任意の例外経路を含む) yes N/A AC5 テスト(test_direct_child_reaped)+ test_exception_after_popen_still_cleans_up_process_group、os.waitpid(pid, os.WNOHANG) が ChildProcessError を送出することを確認 N/A
non-POSIX 環境(start_new_session/os.killpg/os.setsid 不使用)を successful cleanup と誤判定しない yes N/A AC8 テスト(test_non_posix_fallback_not_false_success) N/A
timeout 時に child の partial stdout/stderr を新規 telemetry として漏らさない yes N/A AC7 テスト(test_partial_stdout_stderr_not_leaked、機密マーカー文字列が _emit_timeout_failure() の stderr に一切出現しないことを確認) N/A
communicate() ベースの実行待機が subprocess.run(text=True) と同一の decode-error semantics を維持する yes N/A test_malformed_child_output_raises_unicode_decode_error N/A
pgid の捕捉に遅延 os.getpgid() を使わず、lookup failure が confirmed_absent に昇格しない yes N/A test_pgid_captured_from_proc_pid_without_getpgid_lookup / test_group_absence_check_permission_error_not_confirmed N/A
保証範囲は executor-owned process group 内の descendant に限定され、別 session/process group へ自ら移動した descendant の回収までは主張しない yes(Out of Scope として明示) 別 session/process group へ移動した descendant の回収は本 PR のスコープ外(Issue #2075 Out of Scope で明示的に確定済み) Issue #2075 本文 Out of Scope 節、OWNER review(issuecomment-5248341387) #2075(本 Issue 内で Out of Scope として確定済み。追加の follow-up Issue は不要)

Notes

  • 関連する Issue は 実装: skill_runtime_exec.py の outer timeout cleanup で descendant process の process-group cleanup を保証する #2075 です。
  • 本 PR は Issue 実装: skill_runtime_exec.py の outer timeout cleanup で descendant process の process-group cleanup を保証する #2075 を close します(Closes 実装: skill_runtime_exec.py の outer timeout cleanup で descendant process の process-group cleanup を保証する #2075)。
  • 実装方式は Issue 実装: skill_runtime_exec.py の outer timeout cleanup で descendant process の process-group cleanup を保証する #2075 の OWNER review(issuecomment-5248341387)で確定した契約(Popen supervisor 化、process-group スコープへの保証範囲限定、telemetry closed enum、POSIX-only 境界)、および本 PR に対する OWNER review(issuecomment-5249045572)で確定した cleanup deadline / process-group liveness モデルに厳密に従っています。
  • cleanup budget(_CLEANUP_GRACE_SECONDS)は execution deadline とは独立に、timeout(または例外)検出時点から新規に開始される単一の budget です。SIGTERM を無視する descendant がこの budget 全体を消費してしまい SIGKILL に到達できなくなる問題を避けるため、_TERM_GRACE_SECONDS(_CLEANUP_GRACE_SECONDS より必ず小さい)を SIGTERM 待機フェーズ専用の内部区分として維持しています。cleanup 全体の budget は 1 つの cleanup_deadline のままであり、cleanup 内の全ステップがこれを共有する(個別タイムアウトを積み上げない)という設計制約は維持しています。
  • Scope Delta(既存テストの最小限の更新、Issue 起票時点分): 本 Issue の Allowed Paths(scripts/agent-guards/tests/)の範囲内で、以下 2 つの既存テストを更新済みです(fix_delta 以前から変更なし)。いずれも「outer child 起動が subprocess.run から subprocess.Popen に置換された」という本 Issue の意図された変更に直接起因する必要最小限の追随であり、テストが検証する契約自体(registry timeout の適用・fail-closed 挙動、あるいは anchor/comment 取得の real subprocess chain 挙動)は変更していません。
    • test_skill_runtime_preflight_bytecode_cache.py::test_ac13_child_subprocess_timeout_applies_registry_timeout_and_fails_closed: subprocess.run を monkeypatch していた箇所を _run_child_with_supervision() の monkeypatch に置き換え、registry の timeout_seconds が新しい呼び出しシグネチャに渡ること・supervised timeout が exit code 2 で fail-closed することを引き続き検証します。
    • test_skill_runtime_exec_anchor.py の sitecustomize.py fixture(_install_real_contract_update_fixture()): この fixture は subprocess.run(["uv", ...]) 呼び出しを検知して nested uv run python3 run_refinement_preflight.py プロセスへ PYTHONPATH(この fixture 自身が提供する GitHub API のフェイク境界)を伝播させる仕組みでした。outer child 起動が subprocess.Popen 経由になったことで、この伝播ロジックが subprocess.run にしか反応せず nested プロセスがフェイク境界を失い ANCHOR_COMMENT_NOT_FOUND で fail するリグレッションを見つけたため、同じ PYTHONPATH 伝播ロジックを subprocess.Popen.__init__ にも追加しました。fixture が模倣する GitHub 応答内容やテストの assertion 自体は変更していません。
  • テストは Issue 本文の Runtime Verification Applicability: not_applicable 判断どおり、.claude/skills/gemini-cli-headless-delegation/tests/test_model_routing.py 等と同様、テスト自身が起動・制御する hermetic な real subprocess fixture(sys.executable -c "...")のみを使用し、外部サービス・ネットワーク・本番ランタイムプロセスには依存していません。
  • Issue 実装: skill_runtime_exec.py の outer timeout cleanup で descendant process の process-group cleanup を保証する #2075 本文の orphan doc 参照について: Issue 実装: skill_runtime_exec.py の outer timeout cleanup で descendant process の process-group cleanup を保証する #2075 本文が参照する docs/dev/ac10-pid-proof-flake-root-cause.md は PR docs: AC10 pid_proof flake root-cause文書を訂正し診断情報を追加 (#2073) #2080 で既に削除済みです。この Issue 本文編集は本 Issue の Allowed Paths 外のため本 PR では対応していません。別途 edit-issue skill 経由での Issue 本文更新が必要です(P2-3、実行は本 SubAgent の対応範囲外として報告のみ)。

#2075)

subprocess.run(..., timeout=timeout_seconds) の TimeoutExpired 事後捕捉方式は、
CPython 内部で捕捉前に direct child を既に kill/wait 済みのため、
process-group cleanup を保証できなかった。起動直後から PID/PGID を保持する
subprocess.Popen(..., start_new_session=True) supervisor に置換し、単一の
monotonic global deadline の下で SIGTERM -> bounded grace -> SIGKILL の
staged escalation を行い、killpg(pgid, 0) で process-group absence を再検証
してから direct child を wait() で reap する。

- cleanup_scope=process_group / cleanup_status=confirmed_absent|unconfirmed|
  not_started / termination=term|term_then_kill|not_needed /
  leader_reaped=true|false の closed enum を _emit_timeout_failure() の
  telemetry に追加した。
- start_new_session/killpg/setsid が使えない non-POSIX 環境では常に
  unconfirmed とし、successful cleanup と誤判定しない。
- normal success 時の stdout/stderr/returncode semantics は変更していない。
  timeout 時は partial stdout/stderr を新規 telemetry として漏らさない。
- real subprocess ベースの新規テスト
  scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py
  (AC1-AC9) を追加した。
- 既存 test_ac13 (subprocess.run mock 前提) と
  test_skill_runtime_exec_anchor.py の sitecustomize fixture
  (subprocess.run の "uv" 呼び出しにのみ PYTHONPATH 伝播していた) を、
  outer child 起動が Popen 経由になったことに合わせて更新した。

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

Preview URL

✅ verified live assets: https://squne121.github.io/loop-protocol/pr-2082/

The preview will be removed when this PR is closed.

@squne121

Copy link
Copy Markdown
Owner Author

impl-review-loop Step 4: PR Review Verdict

Mergeability: mergeable=MERGEABLE, merge_state_status=UNSTABLE(Draft PR)。全 required checks(build / lint / python-test / test / typecheck / validate-generated-artifact)は PASS。merge_state_status=UNSTABLE の要因は non-required check visual-impact-policy-trusted の failure であり、本 PR の変更内容とは無関係な pre-existing インフラ不具合(gh api ... --output flag 未対応バージョンの gh CLI を使用しており、本 PR head 以外の他 PR の直近実行でも同様に failure している)。UNSTABLE/Draft は control-plane の routing policy 上 human escalation の対象にしない。

Evidence Check:

  • CI: 18/18 checks PASS(required checks 全緑)。
  • AC1〜AC10: 新規テストファイル test_skill_runtime_exec_process_tree_cleanup.py(AC1〜AC9)+ 既存 test_skill_runtime_preflight_bytecode_cache.py(AC10)で個別に確認。
  • Allowed Paths: 変更4ファイルすべて scripts/agent-guards/skill_runtime_exec.py / scripts/agent-guards/tests/ 内。

Blockers: なし
Non-blockers: なし

LOOP_VERDICT:
  verdict: APPROVE
  reviewed_head_sha: "b47aacae999829851f287da9d6eac4870ebab85d"
  blockers: []
  warnings: []

@squne121

Copy link
Copy Markdown
Owner Author

総合判定

REQUEST_CHANGES — P0: 0件、P1: 4件、P2: 3件

最終確認対象は head afae3fcceaaa9d97750a3c197f7cd348715efb2e、base 7a08cb8ca371568718f1d05e125c65223ff67daf です。PR は Draft のままですが、最新 head の CI workflow は成功しています。

ただし、CI が green でもマージ可能とは判断できません。実装は direct child の終了と process group 全体の終了を混同しており、特定の descendant を timeout 後にも残せます。また、旧 subprocess.run() が持っていた pipe/例外時の cleanup semantics を保存できていません。

既存の APPROVE コメントは、現在の head ではなく旧 head b47aacae... を対象とした自己レビューで、pull_request_review_id=null の通常コメントです。最新 head に対する独立した正式レビュー証跡ではありません。


Blocking findings

P1-1 — SIGKILL escalation が process group ではなく leader の生死に依存している

timeout 後の処理は、次の状態遷移です。

  1. process group に SIGTERM
  2. _poll_until() で proc.poll()、すなわち direct child leader の終了だけを監視
  3. leader が終了すると exited=True
  4. if pgid is not None and not exited が偽になり、SIGKILL を送らない
  5. process group が残っていても cleanup_status=unconfirmed を返して終了

したがって、次の反例で descendant が確実に残ります。

  • leader は SIGTERM を受けて終了する
  • 同じ PGID の descendant は SIGTERM を無視する
  • leader が終了した時点で hard-kill branch が抑止される
  • descendant はその後も実行を継続する

これは Issue #2075 の AC3 にある「SIGTERM を ignore する leader/descendant に対する SIGKILL escalation」を満たしません。現在の AC3 テストは direct leader だけを SIG_IGN にしており、この反例を検証していません。

必要な修正

TERM grace 中に監視すべき対象は proc.poll() ではなく、_verify_process_group_absent(pgid) です。

SIGTERM
  → process group absence を term deadline まで poll
  → group が残っていれば leader の状態に関係なく SIGKILL
  → cleanup deadline まで group absence を poll
  → leader reap

リポジトリ内の AGY permission-boundary 実装は、既に leader ではなく process group の absence を監視し、group が残っている場合に SIGKILL へ進む形を採用しています。また、そのテストには「leader が先に正常終了し、descendant だけが残る」ケースがあります。


P1-2 — direct child の終了だけで success path に入り、旧 communicate() semantics を破壊している

旧実装の subprocess.run(capture_output=True, text=True, timeout=...) は、内部で Popen.communicate() を使用します。communicate() は stdout/stderr の EOF まで読み、process の終了を待ちます。pipe は、書込み側の全 file descriptor が閉じられるまで EOF になりません。([Python documentation]1)

新実装は direct child の proc.poll() が非 None になっただけで normal path に入り、stdout reader を5秒、stderr readerをさらに5秒 join します。join が timeout して reader thread が生きていても、その事実を検査せず成功結果を返します。

次の反例が成立します。

leader
  ├─ descendant を fork
  │    └─ stdout/stderr の write FD を継承したまま sleep
  └─ exit(0)

この場合、

  • 旧 subprocess.run() は pipe EOF を待ち続け、registry timeout で TimeoutExpired になる
  • 新実装は leader の終了を検知し、最大約10秒後に timed_out=False で成功を返す
  • descendant と daemon reader thread は残る
  • stdout/stderr は途中までの内容で固定される

これは AC4 の「normal success の stdout/stderr/returncode semantics 不変」に対する明確な回帰です。さらに caller はこの結果を受けて repository write audit と artifact projection validation を開始するため、実行中の descendant と audit が競合し得ます。

加えて、reader は ValueError を握りつぶしています。UnicodeDecodeError もその派生例外なので、text decode failure が旧実装のように呼出元へ伝播せず、正常終了と truncated output に変換される可能性があります。

必要な修正

現 PR の「従来の unbounded capture semantics を維持する」という範囲では、独自 reader thread より次の方式が小さく安全です。

try:
    stdout, stderr = proc.communicate(timeout=execution_remaining)
except subprocess.TimeoutExpired:
    # process-group cleanup

これにより、

  • pipe EOF を含む従来の timeout semantics
  • decode error の伝播
  • stdout/stderr の完全性
  • pipe deadlock 回避

を既存 subprocess.run() と同等にできます。

将来の independent bounded streaming は Issue #1601 が明示的に所有しているため、この PR で中途半端な thread-based streaming を先行導入する必要はありません。


P1-3 — Popen 成功後の例外・KeyboardInterrupt 経路で detached process group が残る

Popen() 後の全 supervision 処理が try/finally または except BaseException に包まれていません。そのため、次のいずれかが起きると process group cleanup と leader reap を通らず unwind します。

  • KeyboardInterrupt
  • reader thread の生成失敗
  • time.monotonic()、proc.poll()、os.getpgid() などの予期しない例外
  • 将来のコード追加による例外

しかも start_new_session=True により child は新しい session/process group の leaderになります。親の foreground process group に送られた割込みに child が追随することを期待できず、親だけが終了して child group が残る経路になります。setsid() は caller を新しい session と process group の leaderにし、PGIDをPIDと同じ値にします。([man7.org]2)

CPython の subprocess.run() は、TimeoutExpired だけでなく KeyboardInterrupt を含むその他の例外でも child を kill してから再送出する実装です。今回の置換はこの安全特性を失っています。([GitHub]3)

必要な修正

Popen 成功後は、少なくとも次の形にする必要があります。

proc = subprocess.Popen(...)
pgid = proc.pid

try:
    ...
except BaseException:
    _bounded_cleanup_process_group(proc, pgid, cleanup_deadline)
    raise

例外時にも、

  1. TERM
  2. group-liveness poll
  3. KILL
  4. leader reap
  5. pipe close/drain

を bounded に実行してから元の例外を再送出してください。


P1-4 — deadline 契約が Issue・OWNER review・実装・PR説明で相互矛盾している

現在の Issue #2075 は、execution 待機と cleanup 待機を同一の global deadlineで管理し、cleanup 側に個別 timeout を積み上げないと定義しています。

一方、Issue の OWNER review は、execution budget と cleanup budget を分け、cleanup operation 全体を一つの monotonic cleanup deadline で制限するよう勧告しています。

実装はさらに別の形です。

  • execution deadline 超過後に、新しい5秒の cleanup_deadline を開始

  • POSIX timeout path の reader join は、その deadline の外側で1秒+1秒

  • normal path は execution deadline と無関係に5秒+5秒 join

  • PR Summary は「単一の monotonic global deadline」と主張

  • PR Notes は「単一の cleanup deadline」と主張

つまり、実装が正しいか以前に、何をもって AC 達成とするかが一意ではありません。現実的な契約は OWNER review 側です。

execution deadline
  ↓ timeout
separate bounded cleanup deadline
  ├─ TERM grace
  ├─ KILL
  ├─ group absence verification
  ├─ leader reap
  └─ pipe drain/close

Issue 本文をこのモデルに修正し、その後、すべての cleanup operation に remaining(cleanup_deadline) を渡すべきです。固定の join(timeout=1) を deadline 外に積み上げてはいけません。


P2 findings

P2-1 — PGID を遅延取得し、取得不能を confirmed_absent に昇格している

start_new_session=True では child の PGID は起動時点から proc.pid と一致します。それにもかかわらず、実装は timeout 後に os.getpgid(proc.pid) を呼び、ProcessLookupError なら pgid=None とします。その後、pgid is None を無条件に cleanup_status=confirmed_absent としています。 ([man7.org]2)

direct child の PID が lookup できないことは、その PGID に descendant が残っていない証明ではありません。

修正は単純です。

proc = Popen(..., start_new_session=True)
pgid = proc.pid

confirmed_absent にできるのは、保存済み pgid に対する killpg(pgid, 0) が ProcessLookupError になった場合だけに限定してください。


P2-2 — テストが safety property ではなく実装自身の telemetry を検証している

現在の AC2 テストは、

  • grandchild PID を marker に保存
  • supervisor の返した cleanup_status == confirmed_absent を assertion

しているだけです。保存した grandchild PIDやPGIDについて、テスト側から独立に absence を確認していません。AC3 は direct leader だけが TERM を無視します。AC4 は descendant を持たない単純な stdout/stderr テストです。

最低限、以下が必要です。

  1. leader は TERM で終了、descendant は TERM を無視
    term_then_kill と process-group absence を独立確認する。

  2. leader は正常終了、descendant が stdout/stderr pipe を保持
    success ではなく従来どおり timeout になることを確認する。

  3. 結果 telemetry から独立した absence 検証
    os.killpg(recorded_pgid, 0) が ProcessLookupError になることを確認する。

  4. KeyboardInterrupt / injected exception
    例外再送出後にも group と leader が残らないことを確認する。

  5. reader thread と pipe の cleanup
    return 時点で reader thread が生存していないこと、stream が閉じていることを確認する。

  6. getpgid failure
    lookup failureを confirmed_absent にしないことを確認する。

  7. 不正な text byte sequence
    旧 subprocess.run(text=True) と同じ decode-error semantics を確認する。

リポジトリ内の既存 AGY test に「leader が先に終了し descendant が残る」fixture が既にあるため、同じ failure profile を再利用できます。


P2-3 — rebase 後の契約・検証・レビュー証跡が stale

現在の base 7a08cb8c... は PR #2080 の merge commit です。PR #2080 は Issue #2073 の診断テストを追加し、該当テストファイルの件数を24件へ増やしています。

しかし PR #2082 の説明は、現在も test_skill_runtime_preflight_bytecode_cache.py が「23件成功」と記録しています。また、既存 APPROVE は rebase 前の b47aacae... に固定されています。

さらに Issue #2075 は docs/dev/ac10-pid-proof-flake-root-cause.md を current-main の Required Design Reference としていますが、Issue #2073 は PR #2080 でその orphan document を削除したと記録しています。

必要な更新は以下です。


推奨実装形

proc = subprocess.Popen(
    child_argv,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True,
    start_new_session=True,
    ...
)
pgid = proc.pid

try:
    stdout, stderr = proc.communicate(
        timeout=remaining(execution_deadline)
    )
except subprocess.TimeoutExpired:
    cleanup_deadline = time.monotonic() + CLEANUP_BUDGET

    signal_group(pgid, SIGTERM)
    poll_group_absent_until(term_deadline)

    if group_still_present(pgid):
        signal_group(pgid, SIGKILL)

    reap_leader_within(proc, cleanup_deadline)
    poll_group_absent_until(cleanup_deadline)
    bounded_finish_or_close_pipes(proc, cleanup_deadline)

    return timeout_result(...)
except BaseException:
    emergency_cleanup_with_same_state_machine(proc, pgid)
    raise
else:
    return normal_result(stdout, stderr, proc.returncode)

重要点は次の三つです。

  • TERM→KILL の判断は leader liveness ではなく group liveness
  • stdout/stderr capture は現在の scope では communicate() semantics を維持
  • Popen 成功後の 全 exit path が cleanup state machine を通る

Issue #1601 が要求する independent bounded streaming や new-session grandchild までの強い回収は、この primitiveを修正した後に別レイヤーとして実装すべきです。現状の #2082 を #1601 の基盤としてマージすると、より強い cancellation contract の下に誤った leader-centric primitiveが固定されます。

LOOP_VERDICT:
  verdict: REQUEST_CHANGES
  reviewed_head_sha: "afae3fcceaaa9d97750a3c197f7cd348715efb2e"
  blockers:
    - "SIGKILL escalation is gated by direct-child exit rather than process-group liveness"
    - "direct-child polling breaks communicate/pipe EOF and normal-success semantics"
    - "post-Popen exception and KeyboardInterrupt paths leak the detached process group"
    - "deadline contract is contradictory and stream joins escape the declared cleanup budget"
  warnings:
    - "late PGID lookup can convert unknown state into confirmed_absent"
    - "tests trust implementation telemetry and omit the decisive adversarial process shapes"
    - "Issue design reference, local test count, and APPROVE evidence are stale after rebase"

GitHubへのレビュー投稿やリポジトリ変更は行っていません。

…neへ反映する (#2075)

PR #2082 への OWNER REQUEST_CHANGES (issuecomment-5249045572) に基づく fix_delta。

- P1-1: SIGKILL escalation の判定を leader liveness (proc.poll()) から
  process-group liveness (_poll_group_absent_until による killpg(pgid,0)
  ポーリング) へ変更。leader が先に終了しても TERM を無視する descendant
  が残っていれば SIGKILL へ escalate する。
- P1-2: 独自 reader thread + proc.poll() ループを廃し
  proc.communicate(timeout=remaining(execution_deadline)) 方式へ変更。
  pipe EOF 待機・UnicodeDecodeError 伝播を含め subprocess.run() と同等の
  timeout/decode semantics を回復し、leader 早期終了による誤 success
  (AC4 regression) を修正。
- P1-3: Popen() 成功後の全 exit path (timeout / 任意の例外 / KeyboardInterrupt)
  を _stage_cleanup() の同一 state machine に通す
  (try: communicate() / except TimeoutExpired: cleanup / except
  BaseException: cleanup; raise) 構造へ変更。
- P1-4: execution deadline と cleanup deadline を分離する契約
  (OWNER review モデル) に統一。cleanup 内の全ステップ
  (TERM 待機・group-liveness poll・KILL・absence 再検証・leader reap・
  pipe close) を単一の _remaining(cleanup_deadline) で bound し、
  固定 join(timeout=1) 等の個別タイムアウト積み上げを廃止。

P2 findings への対応:
- P2-1: 遅延 os.getpgid() 呼び出しを廃し、start_new_session=True 直後の
  proc.pid を pgid として直接保持する方式へ変更。
- P2-2: term_then_kill + group-absence 独立確認、leader早期終了+pipe
  保持での timeout 回帰再現、KeyboardInterrupt 相当の注入例外での
  cleanup 検証、getpgid 不使用の直接確認、decode-error 伝播確認の
  テストを追加(6件)。
- P2-3: Issue #2075 本文が参照する orphan doc
  (docs/dev/ac10-pid-proof-flake-root-cause.md、PR #2080 で削除済み) の
  Issue 本文編集は Allowed Paths 外のため本 PR では対応せず、報告のみ。

全 AC1〜AC10 の既存 VC + 新規 P2-2 テストが PASS
(scripts/agent-guards/tests/ 配下 1234 passed, 1 skipped, 1 deselected)。
@squne121

Copy link
Copy Markdown
Owner Author

Issue #2075 本文改訂(レビュー指摘への対応)

前回の REQUEST_CHANGES(https://github.com/squne121/loop-protocol/pull/2082#issuecomment-5249045572)を受けたコード修正(head a171ec56)に加え、Issue #2075 本文(Outcome / Parent Goal Ref / In Scope)を実装済みの設計と整合するよう改訂しました。

  • deadline モデルを「execution 待機と cleanup 待機を同一 deadline で管理する」単一 deadline 方式から、「execution deadline 超過を検知した時点で新規に開始する、cleanup 専用の bounded monotonic deadline」という分離 deadline 方式へ変更(P1-4)
  • SIGKILL escalation の判断基準を process-group absence ベースであることを明記(P1-1)
  • normal success path が proc.communicate() semantics を維持することを明記(P1-2)
  • Popen 成功後の全 exit path で cleanup を通ることを In Scope に追加(P1-3)
  • PGID を起動直後の proc.pid として保持することを明記(P2-1)
  • 削除済み orphan document(docs/dev/ac10-pid-proof-flake-root-cause.md)を Required Design References から除去(P2-3)

Issue #2075: #2075

コード自体は head a171ec56 から変更していません(Issue本文とコードの契約整合のみを回復しました)。

@squne121

Copy link
Copy Markdown
Owner Author

impl-review-loop Step 4: PR Review Verdict(2回目、fix_delta + Issue契約改訂後)

Mergeability: mergeable=MERGEABLE, merge_state_status=UNSTABLE(Draft PR)。全 required checks(build / lint / python-test / test / typecheck / validate-generated-artifact)は PASS。merge_state_status=UNSTABLE の要因は non-required check visual-impact-policy-trusted の failure であり、複数の別head/別PRでも再現している pre-existing インフラ不具合(gh api ... --output 未対応の gh CLI バージョン起因)で、本 PR の変更内容とは無関係。UNSTABLE/Draft は routing policy 上 human escalation の対象にしない。

Evidence Check:

  • OWNER REQUEST_CHANGES(P1×4/P2×3、https://github.com/squne121/loop-protocol/pull/2082#issuecomment-5249045572)を受けた fix_delta を適用(head a171ec56)。process-group liveness ベースの SIGKILL escalation、communicate() semantics 復元、Popen成功後の全exit pathでのcleanup、分離cleanup deadlineモデル、起動直後pgid保持 を実装。
  • test-runner による独立検証: AC1〜AC10 全PASS、OWNER指摘の反例を検証する新規6件のadversarial testも全PASS。full suite 1234 passed。
  • pr-reviewerからのblocker(Issue #2075本文の単一deadlineモデル記述と実装の分離deadlineモデルの矛盾)を受け、Issue本文(Outcome/Parent Goal Ref/In Scope)をcontrol-planeが直接改訂し契約整合を回復。
  • 再レビューでAPPROVE、blockersなし。

Blockers: なし
Non-blockers: なし

LOOP_VERDICT:
  verdict: APPROVE
  reviewed_head_sha: "a171ec5677ba1076e0f216613754529a87b11356"
  blockers: []
  warnings: []

@squne121
squne121 marked this pull request as ready for review August 11, 2026 05:26
@squne121
squne121 merged commit 9aa2cb4 into main Aug 11, 2026
51 of 56 checks passed
@squne121
squne121 deleted the worktree-issue-2075-skill-runtime-exec-py-outer-timeout-clea branch August 11, 2026 05:38
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.

実装: skill_runtime_exec.py の outer timeout cleanup で descendant process の process-group cleanup を保証する

1 participant