Repository navigation
実装: skill_runtime_exec.py の outer child cleanup を Popen supervisor 化する - #2082
Conversation
#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]>
Preview URL✅ verified live assets: https://squne121.github.io/loop-protocol/pr-2082/ The preview will be removed when this PR is closed. |
impl-review-loop Step 4: PR Review VerdictMergeability: Evidence Check:
Blockers: なし LOOP_VERDICT:
verdict: APPROVE
reviewed_head_sha: "b47aacae999829851f287da9d6eac4870ebab85d"
blockers: []
warnings: [] |
総合判定
最終確認対象は head ただし、CI が green でもマージ可能とは判断できません。実装は direct child の終了と process group 全体の終了を混同しており、特定の descendant を timeout 後にも残せます。また、旧 既存の Blocking findingsP1-1 — SIGKILL escalation が process group ではなく leader の生死に依存しているtimeout 後の処理は、次の状態遷移です。
したがって、次の反例で descendant が確実に残ります。
これは Issue #2075 の AC3 にある「SIGTERM を ignore する leader/descendant に対する SIGKILL escalation」を満たしません。現在の AC3 テストは direct leader だけを 必要な修正 TERM grace 中に監視すべき対象は リポジトリ内の AGY permission-boundary 実装は、既に leader ではなく process group の absence を監視し、group が残っている場合に SIGKILL へ進む形を採用しています。また、そのテストには「leader が先に正常終了し、descendant だけが残る」ケースがあります。 P1-2 — direct child の終了だけで success path に入り、旧
|
…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)。
Issue #2075 本文改訂(レビュー指摘への対応)前回の REQUEST_CHANGES(https://github.com/squne121/loop-protocol/pull/2082#issuecomment-5249045572)を受けたコード修正(head
コード自体は head |
impl-review-loop Step 4: PR Review Verdict(2回目、fix_delta + Issue契約改訂後)Mergeability: Evidence Check:
Blockers: なし LOOP_VERDICT:
verdict: APPROVE
reviewed_head_sha: "a171ec5677ba1076e0f216613754529a87b11356"
blockers: []
warnings: [] |
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 伝播を維持します。_CLEANUP_GRACE_SECONDS)の下で、SIGTERM→ process-group liveness(leader ではなく group 全体の生存)の poll → bounded grace 経過後のSIGKILL→killpg(pgid, 0)による absence 再検証 → direct childwait()reap → pipe close、という staged cleanup state machine を実行します。TimeoutExpired経路・その他の例外(KeyboardInterrupt等)unwind 経路の両方から共通で呼ばれ、Popen 成功後のどの exit path でも process group が確実に片付きます。proc.pid(start_new_session=Trueにより leader 自身が group leader)としてその場で保持し、遅延os.getpgid()lookup は行いません。Checks
以下、各受け入れ基準(AC)に対応する検証コマンドと結果を日本語で記します。
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 件成功しました。uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_timeout_process_group_isolation -qを実行し、1 件成功しました。uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_sigterm_escalates_to_sigkill -qを実行し、1 件成功しました。uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_normal_success_semantics_unchanged -qを実行し、1 件成功しました。uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_direct_child_reaped -qを実行し、1 件成功しました。uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_cleanup_deadline_exhaustion_unconfirmed -qを実行し、1 件成功しました。uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_partial_stdout_stderr_not_leaked -qを実行し、1 件成功しました。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 件成功しました。uv run --locked pytest scripts/agent-guards/tests/test_skill_runtime_exec_process_tree_cleanup.py::test_cleanup_status_telemetry_enum -qを実行し、1 件成功しました。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件、すべて対応済み)
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でこの反例を直接検証しています。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 の先行導入は行っていません。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 が残らないことを確認しています。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に追加しました。test_leader_exits_but_term_ignoring_descendant_still_escalated_to_kill(leader が SIGTERM で先に終了・descendant が無視するケースのterm_then_kill+ 独立killpg(pid, 0)再確認)test_leader_exit_with_descendant_holding_pipes_still_times_out(AC4 回帰の直接反例: leader 正常終了・descendant が pipe 保持で success ではなく timeout になることの確認)test_exception_after_popen_still_cleans_up_process_group(注入例外の再送出後に leader・process group が残らないことの確認)test_pgid_captured_from_proc_pid_without_getpgid_lookup(P2-1:os.getpgid不使用の確認)test_group_absence_check_permission_error_not_confirmed(P2-1:PermissionError等がconfirmed_absentに昇格しないことの確認)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-issueskill 経由での対応が必要です。人間(OWNER)またはedit-issue実行担当への申し送り事項として本 PR の説明・Issue コメントで報告します。PR 本文のテスト件数(23 件→24 件、1227 件→1234 件)は本 fix_delta で現行 head を再計測し、上記「Checks」節に反映済みです。Schema Change Applicability
skill_runtime_exec.py内部の outer child 起動・cleanup 実装(subprocess.run→subprocess.Popensupervisor、および今回の 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
test_normal_success_semantics_unchanged)+ 反例テスト(test_leader_exit_with_descendant_holding_pipes_still_times_out)+ 既存test_skill_runtime_preflight_bytecode_cache.py24 件の regression-free PASSkillpg(pgid, 0)で再検証してからconfirmed_absentを報告し、signal 送出自体を成功と見なさないtest_timeout_process_group_isolation/test_cleanup_deadline_exhaustion_unconfirmed)+test_group_absence_check_permission_error_not_confirmed、_verify_process_group_absent()実装test_sigterm_escalates_to_sigkill)+test_leader_exits_but_term_ignoring_descendant_still_escalated_to_kill(leader 早期終了 + descendant 生存の反例)、_poll_group_absent_until()実装wait()で確実に reap され zombie が残らない(Popen 成功後の任意の例外経路を含む)test_direct_child_reaped)+test_exception_after_popen_still_cleans_up_process_group、os.waitpid(pid, os.WNOHANG)がChildProcessErrorを送出することを確認start_new_session/os.killpg/os.setsid不使用)を successful cleanup と誤判定しないtest_non_posix_fallback_not_false_success)test_partial_stdout_stderr_not_leaked、機密マーカー文字列が_emit_timeout_failure()の stderr に一切出現しないことを確認)communicate()ベースの実行待機がsubprocess.run(text=True)と同一の decode-error semantics を維持するtest_malformed_child_output_raises_unicode_decode_erroros.getpgid()を使わず、lookup failure がconfirmed_absentに昇格しないtest_pgid_captured_from_proc_pid_without_getpgid_lookup/test_group_absence_check_permission_error_not_confirmedNotes
Popensupervisor 化、process-group スコープへの保証範囲限定、telemetry closed enum、POSIX-only 境界)、および本 PR に対する OWNER review(issuecomment-5249045572)で確定した cleanup deadline / process-group liveness モデルに厳密に従っています。_CLEANUP_GRACE_SECONDS)は execution deadline とは独立に、timeout(または例外)検出時点から新規に開始される単一の budget です。SIGTERM を無視する descendant がこの budget 全体を消費してしまい SIGKILL に到達できなくなる問題を避けるため、_TERM_GRACE_SECONDS(_CLEANUP_GRACE_SECONDSより必ず小さい)を SIGTERM 待機フェーズ専用の内部区分として維持しています。cleanup 全体の budget は 1 つのcleanup_deadlineのままであり、cleanup 内の全ステップがこれを共有する(個別タイムアウトを積み上げない)という設計制約は維持しています。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.pyfixture(_install_real_contract_update_fixture()): この fixture はsubprocess.run(["uv", ...])呼び出しを検知して nesteduv 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 自体は変更していません。Runtime Verification Applicability: not_applicable判断どおり、.claude/skills/gemini-cli-headless-delegation/tests/test_model_routing.py等と同様、テスト自身が起動・制御する hermetic な real subprocess fixture(sys.executable -c "...")のみを使用し、外部サービス・ネットワーク・本番ランタイムプロセスには依存していません。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-issueskill 経由での Issue 本文更新が必要です(P2-3、実行は本 SubAgent の対応範囲外として報告のみ)。