Skip to content

実装: review pipeline の timeout budget を動的 VC 本数ベースに再設計する - #2221

Merged
squne121 merged 9 commits into
mainfrom
worktree-issue-2207-review-budget-planner
Aug 17, 2026
Merged

squne121 merged 9 commits into
mainfrom
worktree-issue-2207-review-budget-planner

Conversation

@squne121

@squne121 squne121 commented Aug 16, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • review pipeline(run_root_review_pipeline.py produce → reviewer_transport.py → contract_readiness_check.py → baseline_vc_preflight.py)の timeout budget を、固定の「near-cap VC 最大2本」前提から、pinned Issue body から実際に起動され得る VC subprocess occurrence 数(保守的上限)に応じた動的導出へ再設計した。
  • baseline_vc_preflight.py に side-effect-free な canonical VC planner(compute_canonical_vc_plan())を追加し、contract_readiness_check.py に formula(derive_review_budget())を追加した。N <= 2 では既存値(350s/400s/480s/520s)を維持し、N >= 3 では N * (150 + 15) + 20 の formula で command cap だけでなく cleanup tail も含めて比例拡張する。
  • N が固定の policy ceiling(MAX_VC_EXECUTION_SLOTS = 40)を超える場合、subprocess 起動前に typed non-retryable verification_budget_exceeds_policy で拒否する(contract_readiness_check.py / run_root_review_pipeline._cmd_produce() の両層)。
  • run_root_review_pipeline._cmd_produce() は pinned body から算出した invocation-local ReviewBudget を run_reviewer_transport() へ明示引数として渡す。reviewer_transport.py の module-level fallback constants(PER_ATTEMPT_DEADLINE_SECONDS=480 / TOTAL_DEADLINE_SECONDS=520)は不変のまま。
  • baseline_vc_preflight.py に SIGTERM cooperative cancellation を追加した。SIGTERM 受信時に現在管理している全 VC process group(direct child・grandchild を含む)を終了・回収する。outer deadline → active VC descendant absent を実 subprocess を用いた fault-injection test(AC9/AC10)で検証した。
  • 副次修正: classify_result() の timeout 判定(exit_code==-1 かつ stderr=="timeout")を regression_gate 判定より前に実行するよう順序を変更した。regression-gate 形状の VC(pytest 等)が per-command timeout した場合に、汎用の "Regression gate command failed" へ misclassify されず正しく category: timeout になる(AC9/AC10 の fault-injection test で顕在化した既存の分類漏れを、本 Issue のスコープ内で修正)。

本 PR は Issue #2207 の実装であり、マージ時に Closes #2207 として Issue を close する。

追加修正(fix_delta): OWNER レビュー指摘への対応(2026-08-17 実施)

2026-08-16 の OWNER REQUEST_CHANGES(レビューコメント、head=e5fafd6e832ef95d73d189fde59bb01a512541a7 時点)で指摘された 8 件のマージ条件をすべて反映した。

  1. P0-1(outer timeout が SIGTERM handler を通らない): contract_readiness_check.py::run_baseline_vc_preflight() と run_root_review_pipeline.py::run_contract_readiness_check() の subprocess.run(timeout=...) を、baseline_vc_preflight.run_subprocess_with_cooperative_supervisor() へ置換した。outer deadline 発火時は SIGKILL 直接ではなく、子の process group へ SIGTERM → 単一の bounded grace → grace 超過後のみ SIGKILL、という cooperative 経路を通す。
  2. P0-2(signal handler 内の非 reentrant Lock 再取得によるデッドロック可能性): SIGTERM handler(_sigterm_cooperative_handler)の本体を、flag 設定と CooperativeCancellationRequested(BaseException)の送出のみに縮小した。Lock 取得・sleep・process wait・kill はすべて main() の単一 top-level except CooperativeCancellationRequested (通常制御フロー)へ移動した。複数 active group がある場合も「全 group に先に SIGTERM → 単一 global grace → 生存 group へ SIGKILL」の順序を維持する。
  3. P0-3(_kill_process_group() が leader 終了で即 return し SIGTERM 無視 grandchild を残す): leader の wait() が返った後も os.killpg(pgid, 0) で process group 存在を明示的に確認し、まだ生存していれば group 全体へ SIGKILL、その後 group 不在を bounded poll で確認するよう修正した。SIGTERM を明示的に無視する grandchild を含む回帰テスト(test_kill_process_group_reaps_sigterm_ignoring_grandchild)を追加した。
  4. P1-1(PGID registry の stale entry / PID wrap 再利用ハザード): _register_active_process_group() が返す PGID を immutable token として呼び出し側が保持し、_unregister_active_process_group() にはその token をそのまま渡す(PID からの再解決をやめた)。
  5. P1-2 item5(production timeout wrapper を通す outer-deadline integration test): contract_readiness_check.run_baseline_vc_preflight() の production wrapper を実際に起動し、outer deadline を意図的に発火させ、direct child(VC leader)と SIGTERM 無視 grandchild を両方起動し、baseline の SIGTERM handler が実際に実行されたことをマーカーファイルで確認し、wrapper・VC leader・grandchild すべての不在を確認する test_outer_deadline_via_run_baseline_vc_preflight_reaps_full_process_tree を追加した(10 回反復)。この実装過程で、SIGKILL 後に wait() されない process が zombie として killpg(pgid, 0) に "生存" と誤判定され続ける追加バグを発見し、_ACTIVE_PROCESS_HANDLES(pgid → 直接子の Popen handle)による明示的 reap を reap_all_active_process_groups() に追加して修正した。
  6. P1-2 item6(pytest skip と exit 77 の混同): .claude/skills/issue-contract-review/scripts/tests/conftest.py を新規追加し、pytest_sessionfinish hook でセッション内の全 item が environment blocked 理由で skip された場合にのみ session exit code を 77 へ上書きする(他の PASS/FAIL と混在する通常のフルスイート実行には影響しない)。
  7. P1-3(budget denominator の Issue 契約との不一致): derive_review_budget() / compute_invocation_local_baseline_timeout() / run_root_review_pipeline._cmd_produce() の入力を launch_upper_bound から Issue 実装: review pipeline の timeout budget を動的 VC 本数ベースに再設計する #2207 Outcome/AC5 契約どおりの command_occurrence_count へ是正した。連続する同一 pure VC が 3 件・40 件(policy cap ちょうど)・41 件(policy cap 超過)の formula/policy-cap 境界テストを追加した。
  8. P2(runtime evidence の head SHA 束縛): 本セクションおよび以下のセクションを、fix_delta 後の現在 head cef36c369e19b2f382d974685d32b6e414677fb2 で再取得した証跡に更新した。

Checks

  • uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/ -q (329 passed, 1 skipped)
  • uv run --locked pytest .claude/skills/issue-contract-review/tests/ -q (533 passed)
  • uv run --locked pytest .claude/skills/issue-refinement-loop/tests/ -q (1556 passed)
  • uv run --directory <worktree> ruff check <changed files> (all checks passed, 8 files)
  • N/A: pnpm typecheck / pnpm lint / pnpm test / pnpm build — 本 PR は .claude/skills/**/scripts/*.py および .claude/skills/**/tests/*.py のみを変更する Python-only の変更であり、TypeScript/フロントエンドのビルド・テストパイプラインには触れない

受け入れ条件の達成状況

すべて fix_delta 後の現在 head SHA cef36c369e19b2f382d974685d32b6e414677fb2 で個別 VC pytest node-id を実行し、全 10 AC が PASS した。

  • AC1(canonical plan の body_sha256 束縛を再確認): .../test_review_budget_planner.py::test_canonical_plan_binds_body_sha256 — 1 passed in 0.02s
  • AC2(duplicate 出現数の保守的カウントを再確認): .../test_review_budget_planner.py::test_conservative_count_counts_duplicate_non_pure_occurrences — 1 passed in 0.02s
  • AC3(pure command の budget 算入を再確認): .../test_review_budget_planner.py::test_pure_coverage_included_in_budget — 1 passed in 0.02s
  • AC4(state barrier による別 launch 判定を再確認): .../test_review_budget_planner.py::test_state_barrier_separates_repeated_pure_command_launches — 1 passed in 0.02s
  • AC5(低本数時の既存値維持を再確認): .../test_review_budget_formula.py::test_low_count_compatibility_preserves_existing_budget — 1 passed in 0.04s
  • AC6(cleanup tail を含む比例拡張を再確認): .../test_review_budget_formula.py::test_cleanup_aware_growth_scales_with_occurrence_count — 1 passed in 0.04s
  • AC7(policy ceiling 超過時の事前拒否を再確認): .../test_review_budget_formula.py::test_policy_ceiling_rejects_before_subprocess_launch — 1 passed in 0.04s
  • AC8(invocation-local deadline の明示配線を再確認): .../test_review_budget_wiring.py::test_root_pipeline_passes_invocation_local_deadline_to_transport — 1 passed in 0.06s
  • AC9(runtime, immediate): .../test_vc_process_group_cancellation.py::test_sigterm_reaps_active_vc_process_groups — 1 passed in 0.35s(実 subprocess tree に対する SIGTERM fault-injection test、fallback 不使用)
  • AC10(runtime, immediate): .../test_vc_process_group_cancellation.py::test_scaled_fault_injection_inner_timeout_precedes_outer_deadline — 1 passed in 3.34s(inner timeout が outer deadline より先行することを実証済み)

加えて、OWNER fix_delta で新規追加した runtime test も同一 head で PASS した:

  • P0-3 回帰テスト: .../test_vc_process_group_cancellation.py::test_kill_process_group_reaps_sigterm_ignoring_grandchild — 1 passed in 0.06s
  • P1-2 item5 production integration test: .../test_vc_process_group_cancellation.py::test_outer_deadline_via_run_baseline_vc_preflight_reaps_full_process_tree — 1 passed in 8.72s(10 回反復、production wrapper 経由で outer deadline を実発火)

検証コマンド結果

Issue #2207 の ## Verification Commands に記載された 10 個の VC を、すべて fix_delta 後の現在 head SHA cef36c369e19b2f382d974685d32b6e414677fb2 の worktree(uv run --locked pytest <node-id> -q)で個別実行した。

AC1  uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_review_budget_planner.py::test_canonical_plan_binds_body_sha256 -q
     -> 1 passed in 0.02s

AC2  uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_review_budget_planner.py::test_conservative_count_counts_duplicate_non_pure_occurrences -q
     -> 1 passed in 0.02s

AC3  uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_review_budget_planner.py::test_pure_coverage_included_in_budget -q
     -> 1 passed in 0.02s

AC4  uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_review_budget_planner.py::test_state_barrier_separates_repeated_pure_command_launches -q
     -> 1 passed in 0.02s

AC5  uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_review_budget_formula.py::test_low_count_compatibility_preserves_existing_budget -q
     -> 1 passed in 0.04s

AC6  uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_review_budget_formula.py::test_cleanup_aware_growth_scales_with_occurrence_count -q
     -> 1 passed in 0.04s

AC7  uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_review_budget_formula.py::test_policy_ceiling_rejects_before_subprocess_launch -q
     -> 1 passed in 0.04s

AC8  uv run --locked pytest .claude/skills/issue-refinement-loop/tests/test_review_budget_wiring.py::test_root_pipeline_passes_invocation_local_deadline_to_transport -q
     -> 1 passed in 0.06s

AC9  uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_vc_process_group_cancellation.py::test_sigterm_reaps_active_vc_process_groups -q
     -> 1 passed in 0.35s

AC10 uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_vc_process_group_cancellation.py::test_scaled_fault_injection_inner_timeout_precedes_outer_deadline -q
     -> 1 passed in 3.34s
  • 全 10 AC で PASS 以外の出力(FAILED / ERROR / skip)は 0 件。
  • AC9/AC10 の pytest は pytestmark = pytest.mark.skipif(not posix_process_groups_supported(), ...) により POSIX process group semantics 非対応環境では SKIP するが、本 fix_delta で追加した conftest.py::pytest_sessionfinish により、そのような全 skip セッションは通常の pytest exit 0 ではなく exit 77(environment blocked)として区別される(他の PASS/FAIL と混在する通常実行には影響しない)。本実行環境では skip されず実行・PASS した。

Allowed Paths 遵守

gh pr view 2221 --json files で取得した変更ファイル一覧はすべて Issue #2207 の ## Allowed Paths に含まれる。対象ファイルは以下の 9 件である:

  • 変更ファイル1: .claude/skills/issue-contract-review/scripts/baseline_vc_preflight.py
  • 変更ファイル2: .claude/skills/issue-contract-review/scripts/contract_readiness_check.py
  • 新規ファイル3: .claude/skills/issue-contract-review/scripts/tests/conftest.py(P1-2 item6: environment-blocked を exit 77 として区別する pytest_sessionfinish hook)
  • 変更ファイル4: .claude/skills/issue-contract-review/scripts/tests/test_review_budget_formula.py
  • 変更ファイル5: .claude/skills/issue-contract-review/scripts/tests/test_review_budget_planner.py
  • 変更ファイル6: .claude/skills/issue-contract-review/scripts/tests/test_vc_process_group_cancellation.py
  • 変更ファイル7: .claude/skills/issue-refinement-loop/scripts/run_root_review_pipeline.py
  • 変更ファイル8: .claude/skills/issue-refinement-loop/tests/test_ac1_live_issue_no_environment_failure.py(P0-1 の supervisor 置換に伴い、旧 subprocess.run monkeypatch を新しい run_subprocess_with_cooperative_supervisor monkeypatch へ更新)
  • 変更ファイル9: .claude/skills/issue-refinement-loop/tests/test_review_budget_wiring.py

Allowed Paths 外のファイル変更はない。

Runtime Verification Evidence(動作検証証跡)

Issue #2207 の Runtime Verification Applicability: immediate(applicable_acs: [AC9, AC10])に基づく実 subprocess fault-injection 証跡:

  • AC9(SIGTERM process-group reaping): baseline_vc_preflight.py が管理する VC process group(direct child・grandchild を含む)に対し SIGTERM を送出し、実 subprocess tree が bounded time 内に終了・回収されることを marker file の存在確認で証明する test_sigterm_reaps_active_vc_process_groups を実行し PASS(1 passed in 0.35s)。mock のみで完結する fallback 経路は使用していない。
  • AC10(scaled fault-injection: inner timeout precedes outer deadline): production と同じ subprocess 階層構造を持つ fixture を用いた test_scaled_fault_injection_inner_timeout_precedes_outer_deadline を実行し PASS(1 passed in 3.34s)。inner timeout が outer aggregate deadline より先に typed classification(category: timeout)され、outer 側に active VC descendant が残存しないことを marker file ベースで確認しており、fallback 経由の成功を PASS に変換していない。
  • P0-3 回帰(_kill_process_group() の SIGTERM 無視 grandchild): test_kill_process_group_reaps_sigterm_ignoring_grandchild を実行し PASS(1 passed in 0.06s)。leader は正常終了するが grandchild が明示的に SIGTERM を無視する fixture で、leader 終了後も process group が SIGKILL で回収されることを確認する。
  • P1-2 item5(production wrapper 経由の outer-deadline fault-injection、10 回反復): test_outer_deadline_via_run_baseline_vc_preflight_reaps_full_process_tree を実行し PASS(1 passed in 8.72s、内部で 10 iteration)。contract_readiness_check.run_baseline_vc_preflight()(production entry point)を override_timeout_seconds=0.6s の test-only DI で実際に outer timeout させ、direct child(VC leader、.venv/bin/python3 -m pytest 実 subprocess)と SIGTERM を明示的に無視する grandchild を両方起動し、baseline の SIGTERM handler がテスト専用マーカーファイルへ書き込むことでハンドラの実行を確認し、wrapper(baseline_vc_preflight.py 自身)・VC leader・grandchild すべての不在を bounded poll で確認し、outer result が typed status: runtime_error / failure_class: timeout / timeout_phase: baseline_vc_preflight_aggregate であることを確認する。injected deadline は Issue が示唆する 50〜200ms ではなく 600ms とした(この repo の venv interpreter + pytest collection の起動オーバーヘッドだけで実測約 200ms かかるため、50〜200ms では grandchild が起動する前に deadline が発火してしまい "grandchild を実際に reap した" ことを証明できない)。反復回数も Issue が示唆する ~50 回ではなく 10 回とした(各反復が実 subprocess tree の spawn を伴うため)。両者ともテストコード内のコメントに rationale を明記している。

Schema Change Applicability

  • decision: not_schema_change
  • reason: baseline_vc_preflight/v1 の既存 producer JSON schema フィールドは追加・変更していない(Issue 実装: review pipeline の timeout budget を動的 VC 本数ベースに再設計する #2207 の明示スコープ境界)。canonical VC plan の各フィールド(body_sha256 / command_occurrence_count 等)は baseline_vc_preflight.py の in-process 関数戻り値であり、consumer をまたぐ producer schema ではない。fix_delta で追加したテスト専用マーカーファイル・環境変数(BASELINE_VC_PREFLIGHT_TEST_SIGTERM_MARKER_PATH 等)も production の JSON 出力スキーマには含まれず、テスト専用の side-channel である。

Schema Consumer Inventory

N/A(not_schema_change のため)

Safety Claim Matrix

Claim Implemented? Not controlled Evidence Follow-up
baseline_vc_preflight.py は SIGTERM 受信時に現在管理している全 VC process group(direct child・grandchild)を bounded time 内に終了・回収する yes none test_vc_process_group_cancellation.py::test_sigterm_reaps_active_vc_process_groups(実 subprocess tree を用いた fault-injection test、PASS) N/A
inner(per-command)timeout は outer aggregate deadline より先に typed classification(category: timeout)され、outer 側で active VC descendant は残存しない yes none test_vc_process_group_cancellation.py::test_scaled_fault_injection_inner_timeout_precedes_outer_deadline(実 subprocess を用いた fault-injection test、PASS) N/A
production の outer aggregate timeout(contract_readiness_check.run_baseline_vc_preflight() / run_root_review_pipeline.run_contract_readiness_check())は subprocess.run(timeout=...) の直接 SIGKILL ではなく cooperative supervisor(SIGTERM → 単一 grace → SIGKILL)を経由し、SIGTERM handler を確実に実行させる yes none contract_readiness_check.py::run_subprocess_with_cooperative_supervisor() 呼び出しへの置換 + test_outer_deadline_via_run_baseline_vc_preflight_reaps_full_process_tree(production wrapper 経由の実 outer-deadline fault-injection、10 回反復、PASS) N/A
SIGTERM signal handler は Lock 取得・sleep・process wait・kill を一切実行せず、実際の cleanup は top-level の通常制御フローでのみ行われる(デッドロック不可能) yes none _sigterm_cooperative_handler() の実装(flag 設定 + 例外送出のみ)+ main() の単一 except CooperativeCancellationRequested N/A
_kill_process_group() は leader 終了後も process group 不在を確認し、SIGTERM を無視する grandchild を SIGKILL で回収する yes none test_vc_process_group_cancellation.py::test_kill_process_group_reaps_sigterm_ignoring_grandchild(SIGTERM 無視 grandchild を含む実 fixture、PASS) N/A
PGID registry の unregister は register 時に返した immutable token で行われ、PID からの再解決による stale entry / PID wrap 再利用ハザードを生まない yes none _register_active_process_group() / _unregister_active_process_group() のシグネチャ変更(token 方式) + 既存/新規 process-group テスト全 PASS N/A
N が policy ceiling を超える場合、subprocess 起動前に typed non-retryable verification_budget_exceeds_policy で拒否される yes none test_review_budget_formula.py::test_policy_ceiling_rejects_before_subprocess_launch / test_review_budget_wiring.py::test_policy_ceiling_exceeded_rejects_before_any_checker_subprocess(両方 PASS) N/A
budget denominator(N)は Issue #2207 Outcome/AC5 契約どおり command_occurrence_count(連続同一 pure VC も dedup せず raw occurrence 数として数える)であり、launch_upper_bound ではない yes none test_review_budget_formula.py の 3/40/41 件境界テスト 3 件(PASS)+ test_review_budget_wiring.py の denominator 参照更新 N/A
N<=2 では既存 production 値(350s/400s/480s/520s)を厳密に維持し、budget 拡張が既存の低本数 Issue の挙動を変えない yes none test_review_budget_formula.py::test_low_count_compatibility_preserves_existing_budget / test_review_budget_wiring.py::test_low_n_body_wiring_matches_current_production_values(両方 PASS) N/A
reviewer_transport.py の module-level fallback constants(PER_ATTEMPT_DEADLINE_SECONDS / TOTAL_DEADLINE_SECONDS)は本 PR の配線によって書き換えられない yes none test_review_budget_wiring.py::test_root_pipeline_passes_invocation_local_deadline_to_transport 内のアサーション(PASS) N/A
SIGTERM cooperative cancellation は POSIX process-group semantics を提供しない環境では明示的に environment blocked として扱われ、pytest.mark.skipif の exit 0 と混同されない(専用 exit 77) yes none test_vc_process_group_cancellation.py の pytestmark = pytest.mark.skipif(...) + 新規 conftest.py::pytest_sessionfinish(全 skip セッションのみ exit 77 へ上書き。他 PASS/FAIL と混在する通常実行は無影響であることをローカル self-test で確認) N/A
per-command cap(150 秒)を超える単一 VC 自体は本 PR のスコープ外であり、引き続き typed timeout となる(本 PR は outer wrapper の premature timeout のみを解消する) no per-command cap を超える単一 VC の分割・別処理は本 PR のスコープ外 Issue #2207 本文の Safety Claim(明示) #2207(Issue 本文に明記、follow-up は Issue 本文が示す通り別 Issue)

Notes

固定「near-cap VC 最大2本」前提のtimeout budgetを、side-effect-freeなcanonical
VC planner(baseline_vc_preflight.compute_canonical_vc_plan)が算出する
launch_upper_boundベースの動的formula(contract_readiness_check.derive_review_budget)
へ置き換える。N<=2では既存値(350/400/480/520)を維持し、N>=3ではcleanup tail込みで
比例拡張する。policy ceiling超過はsubprocess起動前にtypedで拒否する。
run_root_review_pipeline._cmd_produce()はpinned bodyから算出したinvocation-local
ReviewBudgetをrun_reviewer_transport()へ明示的に渡す(reviewer_transport.pyの
fallback定数は不変)。baseline_vc_preflight.pyにSIGTERM cooperative cancellation
を追加し、outer timeout時にactive VC process group(direct child・grandchild)を
確実に回収する。全AC(1-10)を実process fault-injection testを含むpytestで固定。

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-2221/

The preview will be removed when this PR is closed.

)

fix_delta iteration 1: test_scaled_fault_injection_inner_timeout_precedes_outer_deadline が
inner_timeout_seconds=1 のとき、uv run --locked pytest サブプロセスの起動オーバーヘッドだけで
marker.txt 書き込み前に inner timeout が発火し FileNotFoundError で 5/5 決定論的に失敗していた。

- inner_timeout_seconds を 1 → 3、fixture_sleep_seconds を 5.0 → 8.0 へ拡大
- タイマー開始前に uv/pytest 環境を collect-only invocation で pre-warm し、
  計測対象の起動オーバーヘッドを最小化
- clean worktree で 5 連続実行し決定論的 PASS を確認(AC9 も併せて確認)
@squne121

Copy link
Copy Markdown
Owner Author

fix_delta iteration 1 対応(AC10 flaky failure)

Blocker: test_scaled_fault_injection_inner_timeout_precedes_outer_deadline が
inner_timeout_seconds=1 のとき、uv run --locked pytest サブプロセス起動オーバーヘッドだけで
marker.txt 書き込み前に inner timeout が発火し、FileNotFoundError で決定論的に失敗していた
(reviewed head 73ed5a5c、clean worktree で 5/5 再現)。

対応(commit 1fa40da):

  • inner_timeout_seconds を 1 → 3、fixture_sleep_seconds を 5.0 → 8.0 へ拡大
  • タイマー開始前に同一 fixture への --collect-only invocation で uv/pytest 環境を pre-warm し、
    計測対象の起動オーバーヘッドを最小化(起動 jitter に対して margin を持たせる設計へ変更)

再検証: 修正後、AC10 VC を clean worktree で 5 連続実行し全て deterministic PASS(各 ~3.2s)。
AC9(同ファイル test_sigterm_reaps_active_vc_process_groups)も 2 回実行し PASS を確認。

変更は .claude/skills/issue-contract-review/scripts/tests/test_vc_process_group_cancellation.py
のみ(Allowed Paths 内)。budget derivation formula / cancellation 実装本体(AC1-AC9 のロジック)は
無変更。

@squne121 squne121 self-assigned this Aug 16, 2026
@squne121

Copy link
Copy Markdown
Owner Author

判定

REQUEST_CHANGES。Draft を維持し、現状ではマージ不可です。

レビュー対象は現在の head=e5fafd6e832ef95d73d189fde59bb01a512541a7、base=4c00702c4e2afbb1fa6748720a4f021883e37db3 です。現在 head の CI は成功していますが、PR 本文に記載された AC1–AC10 の個別証跡は旧 head 1fa40da8... に束縛されたままです。

動的 budget 導出、invocation-local deadline の明示配線、fallback 480/520 の維持という方向性は妥当です。関連 PR #2177 が未制御リスクとして残した「VC 数が多い Issue では固定 deadline が再び破綻し得る」という問題にも正しく対応しています。

しかし、#2207 の中心的な安全主張である outer timeout 後に direct child・grandchild が残留しないことは、production 経路では成立していません。


P0-1: production の outer timeout は SIGTERM handler を通らず、VC process group を残留させる

baseline_vc_preflight.py は SIGTERM handler を設置し、active VC process group を回収する設計です。しかし、その直接の親である contract_readiness_check.py は依然として次の形です。

result = subprocess.run(
    [...],
    timeout=aggregate_timeout_seconds,
)

さらに上位の run_root_review_pipeline.py::run_contract_readiness_check() も subprocess.run(..., timeout=...) です。

CPython の subprocess.run() は timeout 時に内部で process.kill() を呼びます。POSIX の Popen.kill() は直接子へ SIGKILL を送るため、直接子の SIGTERM handler は実行されません。また、VC は start_new_session=True で別 session/process group に隔離されているため、baseline process だけを kill しても VC group には届きません。([GitHub]1)

同じ制御フローを Linux/Python 3.13 で抽出した最小再現結果は以下でした。

{
  "sigterm_handler_ran": false,
  "separate_session_descendant_survived": true
}

つまり現在の AC9 は「誰かが baseline に手動で SIGTERM を送れば cleanup できる」ことしか示しておらず、実際の aggregate timeout が発火したときの経路を証明していません。

必須修正

contract_readiness_check.py と run_root_review_pipeline.py の timeout wrapper を、共通の cooperative supervisor に置き換える必要があります。

  1. Popen で子を専用 process group に起動する。
  2. deadline 発火時は SIGKILL ではなく、まず子または子 group に SIGTERM を送る。
  3. baseline の cooperative cleanup が完了できる単一の bounded grace を待つ。
  4. grace 超過後だけ SIGKILL する。
  5. 最後に process group 不在を確認し、stdout/stderr を drain する。

修正後の integration test は run_baseline_vc_preflight() または run_contract_readiness_check() の production timeout wrapper 自体を起動し、実際に outer deadline を発火させなければなりません。


P0-2: SIGTERM handler が非 reentrant Lock を再取得し、cleanup 自体がデッドロックし得る

実装は active group 登録簿を threading.Lock() で保護し、SIGTERM handler から reap_all_active_process_groups() を呼び出しています。handler 側も同じ Lock を取得します。

Python の signal handler は main Python thread で実行されます。main thread が _register_active_process_group() または _unregister_active_process_group() 内で Lock を保持している瞬間に SIGTERM が入ると、同じ thread が非 reentrant Lock を再取得しようとして停止します。Python 公式文書も signal handler 内で threading.Lock 等を使用すると予期しないデッドロックになり得ると明記しています。([Python documentation]2)

独立最小再現では次の状態になりました。

{
  "handler_entered": true,
  "handler_completed": false,
  "process_hung": true
}

必須修正

signal handler 内では、Lock 取得、sleep、process wait、複数 process への kill を実行しないでください。

handler は cancellation flag の設定、self-pipe / signal.set_wakeup_fd() による supervisor 起床、または top-level で捕捉する専用例外の発火だけに限定し、実際の registry snapshot・TERM/KILL・wait は通常制御フロー側で行うべきです。

また、active group が複数ある場合は、

  1. 全 group に先に SIGTERM
  2. 単一の global grace を待つ
  3. 生存 group 全てに SIGKILL

とすべきです。現在の「1 group ごとに最大5秒待つ」方式では、最大40 group で cleanup が直列に数分へ膨張します。


P0-3: _kill_process_group() は leader が終了すると即 return し、SIGTERM を無視する grandchild を残す

既存の per-command timeout cleanup は、process group に SIGTERM を送った後、次の処理を行っています。

process.wait(timeout=5)
return

直接子である group leader が SIGTERM で終了すれば、同じ process group に SIGTERM を無視する grandchild が残っていても return します。SIGKILL が送られるのは leader 自身が5秒以内に終了しなかった場合だけです。

独立再現では、直接子が returncode=-15 で終了した後も、同一 group の SIGTERM 無視 grandchild が生存しました。

{
  "leader_returncode": -15,
  "stubborn_grandchild_survived": true
}

この欠陥は #2177 由来ですが、#2221 の Safety Claim Matrix が「inner timeout 後にも descendant が残存しない」を controlled と宣言しているため、本 PR で未制御のままにはできません。

現在の AC9 fixture の grandchild は SIGTERM を無視しません。また AC10 fixture には grandchild 自体が存在しないため、この failure mode を検出できません。

必須修正

PGID は process 起動直後に保存し、leader の wait() が返った後も次を実行してください。

try:
    os.killpg(pgid, 0)
except ProcessLookupError:
    group_is_absent = True
else:
    os.killpg(pgid, signal.SIGKILL)

その後、process group が実際に消滅するまで bounded poll する必要があります。Linux の kill(..., 0) は signal を送らずに process/process-group の存在確認に使えます。([man7.org]3)

回帰テストには、SIGTERM を明示的に無視する grandchild を必ず含めてください。


P1-1: PGID 登録簿は正常終了後も必ず stale entry を残す

登録時には os.getpgid(pid) で PGID を取得して set に追加していますが、解除時にも PID から PGID を再取得しています。

解除は process.communicate() の後です。この時点では直接子が wait/reap 済みなので、通常は getpgid(pid) が ESRCH となり、pgid=None のまま set から何も削除されません。Linux の getpgid() は対象 PID が存在しなければ ESRCH を返します。([man7.org]4)

独立再現結果:

{
  "resolved_after_wait": null,
  "registry_empty": false
}

これは単なるメモリリークではありません。Linux の PID は pid_max 到達時に wrap するため、stale PGID が別 process group に再利用された後に SIGTERM handler が発火すると、無関係な process group を kill する可能性があります。([カーネルドキュメント]5)

必須修正

登録時に取得した PGID を immutable な token として返し、解除時には PID から再解決せず、その PGID を直接削除してください。

pgid = register(process.pid)
try:
    ...
finally:
    unregister(pgid)

ただし、leader 終了時に同一 group の descendant が残っている場合は直ちに unregister してはいけません。group 不在確認または cleanup 完了後にのみ解除する必要があります。


P1-2: AC9/AC10 の runtime test が Issue #2207 の契約を検証していない

Issue #2207 は、production と同じ subprocess 階層で以下を検証する契約です。

  • outer deadline 発火後に direct child・grandchild が残留しない
  • 50–200ミリ秒程度に scale down した fault injection
  • POSIX semantics 非対応時は fallback success ではなく environment blocked
  • AC9 では明示的に SKIP exit 77

しかし現在のテストは以下の状態です。

  • AC9: baseline process へテストから手動 SIGTERM
  • AC10: inner timeout 3秒、fixture sleep 8秒、outer timeout 30秒
  • AC10 のコメント自身が「outer aggregate deadline は発火させる必要がない」と明記
  • AC10 fixture に grandchild なし
  • POSIX 非対応時は module-level pytest.mark.skipif

つまり AC10 は実質的に「per-command timeout の分類テスト」であり、Issue が要求した outer timeout integration test ではありません。

また標準 pytest の exit code は 0–6 であり、通常の pytest.skip は run 全体を exit 0 にできます。公式 pytest の公開 exit-code contract に 77 はありません。([pytest 公式ドキュメント]6)

この環境での最小確認も次のとおりです。

1 skipped
pytest_rc=0

必須修正

新しい runtime test は少なくとも次を満たす必要があります。

  1. contract_readiness_check.run_baseline_vc_preflight() の production wrapper を実際に通す。
  2. outer timeout を意図的に発火させる。
  3. direct child と SIGTERM 無視 grandchild を起動する。
  4. baseline SIGTERM handler が実行されたことを確認する。
  5. wrapper、baseline、VC leader、grandchild の全不在を確認する。
  6. outer result が typed runtime_error / timeout phase を返すことを確認する。
  7. 50–200ms に scale down できるよう、内部 supervisor には float deadline を注入可能にする。
  8. POSIX 非対応は pytest skip ではなく、専用 preflight/runner が明示的に exit 77 を返す。

同じ test を少なくとも50回程度連続実行し、signal/register/unregister race も検出対象にすべきです。


P1-3: Issue の budget denominator と実装が一致していない

Issue #2207 の Outcome と AC5 は、予算計算を次のように固定しています。

N = max(2, command_occurrence_count)

しかし実装は contiguous な同一 pure command を dedup して launch_upper_bound を減らし、derive_review_budget(launch_upper_bound) を使用しています。

例えば同一 pure VC が3回連続する場合:

command_occurrence_count = 3
launch_upper_bound        = 1

Issue 契約:
N = 3
baseline aggregate = 3 * 165 + 20 = 515秒

現実装:
effective_n = max(2, 1)
baseline aggregate = 350秒

同じ pure VC を41回記載した場合も、Issue 契約上は policy cap 40 を超過しますが、実装は launch_upper_bound=1 として拒否しません。

actual launch 上限を denominator にする設計自体には合理性があります。しかし、最終承認された Issue contract を実装側だけで command_occurrence_count から launch_upper_bound に変更してはいけません。

必須修正

次のどちらかを明示的に選択してください。

最低限、連続する同一 pure VC が3件・40件・41件のケースを formula/policy test に追加する必要があります。

また、executor は canonical plan object を消費せず、本文を再度 parse して独自に execution job を作っています。現在共有されているのは parser primitive であり、plan 自体が execution SSOT ではありません。
将来の drift を防ぐには executor が plan の normalized command sequence を直接消費するか、「実 launch 数 ≤ plan.launch_upper_bound」を広範な property test で固定すべきです。


P2: Runtime evidence が現 head に束縛されていない

PR 本文は AC1–AC10 の全証跡を旧 head 1fa40da8... で実行したと記載していますが、現在 head は e5fafd6e... です。現在 head の通常 CI は成功していますが、上記の outer-timeout fault path は CI test 自体が通していないため、green CI は安全主張の代替にはなりません。

修正後は current head で以下を再採取してください。

  • current head SHA
  • production-shaped outer-timeout test の stdout/stderr
  • baseline/VC/grandchild の PID/PGID と最終不在確認
  • registry empty assertion
  • repeated-run 結果
  • POSIX 非対応時の実 exit code 77
  • formula/policy-cap の3・40・41 occurrence 境界

マージ条件

  1. subprocess.run(timeout=...) による直接 SIGKILL 経路を cooperative supervisor へ置換する。
  2. signal handler 内の Lock・sleep・wait・kill を除去する。
  3. PGID を spawn 時に保存し、stale registry と PGID reuse hazard を解消する。
  4. leader 終了後も process group 不在を確認し、SIGTERM 無視 grandchild を SIGKILL する。
  5. actual outer deadline を通す production integration test を追加する。
  6. pytest skip と exit 77 を混同しない environment-blocked 経路を実装する。
  7. command_occurrence_count と launch_upper_bound の契約不一致を、コード修正または Issue reframe で解消する。
  8. 全 runtime evidence を最新 head に再束縛する。

現在の実装は timeout budget の算術部分は改善していますが、timeout 発火時の process lifecycle 証明が成立していません。この状態では REQUEST_CHANGES が妥当です。

squne121 and others added 2 commits August 16, 2026 22:13
…D leak修正・budget denominator是正)

- contract_readiness_check.py / run_root_review_pipeline.py の subprocess.run(timeout=...) を
  baseline_vc_preflight.run_subprocess_with_cooperative_supervisor() へ置換し、outer timeout 時に
  SIGKILL直接ではなく SIGTERM→grace→SIGKILL の cooperative 経路を通す(P0-1)。
- SIGTERM handler を flag設定+例外送出のみに縮小し、Lock取得・sleep・process wait・killを
  main() の top-level except(通常制御フロー)へ移動(P0-2)。
- _kill_process_group() を、leader終了後も process group 不在を確認し SIGTERM を無視する
  grandchild を SIGKILL するよう修正(P0-3)。
- PGID registry を register時に返した immutable token で unregister するよう修正し、
  stale PGID leak / PID wrap 再利用ハザードを解消(P1-1)。
- run_baseline_vc_preflight() production wrapper を実際に通し、outer deadline 発火・
  SIGTERM-ignoring grandchild・wrapper/VC leader/grandchild 全不在確認・SIGTERM handler
  実行確認を伴う production-shaped integration test を追加(10回反復、P1-2 item5)。
  実装過程で、SIGKILL後に reap(wait)されない zombie が group-absence判定を偽陽性化する
  追加のバグを発見し、_ACTIVE_PROCESS_HANDLES による明示的 reap を追加して修正。
- POSIX-unsupported環境の pytest skip を exit 77 (environment blocked) として区別する
  conftest.py の pytest_sessionfinish hook を追加(bare skipif の exit 0 と区別、P1-2 item6)。
- budget denominator を Issue #2207 Outcome/AC5 契約どおり command_occurrence_count に是正
  (launch_upper_bound からの無断置換を解消)。連続同一pure VC 3/40/41件境界のformula/policy-cap
  テストを追加(P1-3)。
- _kill_process_group() 単体の SIGTERM-ignoring grandchild 回帰テストを追加(P0-3該当)。

Refs #2207
@squne121
squne121 marked this pull request as ready for review August 16, 2026 21:52
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.

実装: review pipeline の timeout budget を動的 VC 本数ベースに再設計する

1 participant