Skip to content

実装: command-level timeout budget に history-based (P50/P95) estimator を追加する #2254

Closed

Description

@squne121

Machine-Readable Contract

contract_schema_version: v1
issue_kind: implementation
parent_issue: "none"
goal_ref: "ローカルの反復 VC 実行について、実測 success duration と timeout の right-censored lower-bound から、既存 static timeout policy を自動的に引き上げる advisory・raise-only な local command-level timeout history estimator を実装する。可変 store は root-owned producer が実行開始時に一度だけ読んで immutable snapshot 化し、全 consumer が同一 snapshot から同一 canonical VC plan(同一 plan_digest)を生成する。history が利用不能・stale・破損している場合は workflow を止めず既存 static_policy / static_fallback へ non-blocking に劣化する。CI job/step 単位の ci_runtime_baseline_v1 との統合はスコープ外とする。"
change_kind: code

Parent Issue

none

Parent Goal Ref

  • Goal: なし(単独改善)
  • Desired Destination: なし(単独改善)

Current Validated Scope

  • .claude/skills/issue-contract-review/scripts/baseline_vc_preflight.py の command_timeout_budget/v1 生成ロジックに、ローカル per-repository の history-based(nearest_rank_v1 percentile)estimator source を追加する設計・実装
  • history 永続化・percentile 計算・snapshot 生成ロジックを baseline_vc_preflight.py に詰め込まず、新規モジュール .claude/skills/issue-contract-review/scripts/vc_runtime_history.py へ分離して実装する
  • immutable history snapshot 方式: root-owned producer が実行開始時に history store を一度だけ読み、history_snapshot/v1 の canonical JSON(snapshot_as_of_utc / 対象 record / environment fingerprint / snapshot digest を含む)を確定し、全 consumer(contract_readiness_check.py / run_contract_review_once.py / run_root_review_pipeline.py)にその同一 snapshot(または snapshot file と digest)を配線して渡す実装。plan 確定後に発生した command 実行結果は現在実行中の plan に反映せず、次回 invocation からのみ利用する
  • timeout censored サンプルの扱い: timeout は「除外すべき汚染データ」ではなく right-censored data(真の実行時間 > applied_timeout_ms という下限のみ判明しているデータ)として扱い、timeout_backoff_floor = min(MAX_PER_COMMAND_TIMEOUT_SECONDS, previous_applied_timeout_seconds * 2) による bounded backoff を次回 budget に反映する実装
  • raise-only precedence: resolved = min(MAX_PER_COMMAND_TIMEOUT_SECONDS, max(static_base, history_candidate, timeout_backoff_floor))(explicit_override が優先)を実装し、history が static_policy / static_fallback の値を引き下げないことを保証する実装
  • command_group_key(command 種別のグルーピング)と environment_fingerprint(sample 互換性判定)と execution_id(1 回の実 launch を一意識別)を別概念として分離実装し、compute_execution_key_hash()(timeout 等の実行パラメータを含む既存の execution-identity 概念)を history grouping key に流用しない実装
  • 過去実測 execution time を永続化するための history store の設計・実装(ローカル per-repository SQLite。$XDG_STATE_HOME/loop-protocol/vc-runtime-history/<sha256(realpath(git-common-dir))>.sqlite3、XDG_STATE_HOME 未設定時は ~/.local/state を使用し、repo-tracked path 外・Allowed Paths guard 対象外の runtime state として扱う)
  • history-based source が信頼できない場合(sample 不足・stale・schema 不明・破損・fingerprint 不一致等)に static_fallback へ確実に non-blocking フォールバックする deterministic な cold-start / degradation 経路の実装
  • 上記に対応する pytest(.claude/skills/issue-contract-review/scripts/tests/ 配下への新規テストファイル追加、既存 test_command_timeout_budget.py への追加、および 4 consumer 配線の scaled runtime integration test)

Remaining Parent Gaps

なし

Outcome

command_timeout_budget/v1(.claude/skills/issue-contract-review/scripts/baseline_vc_preflight.py の compute_canonical_vc_plan() が生成する canonical VC plan の一部、Issue #2233 / PR #2245 で導入)に、既存の explicit_override / static_policy(STATIC_PER_COMMAND_TIMEOUT_POLICY による exact-match 値)/ static_fallback(DEFAULT_TIMEOUT_SECONDS)に加えて、ローカル per-repository SQLite に永続化された過去実測 execution time に基づく history_estimate source(nearest_rank_v1 percentile + timeout backoff)が実装され、.claude/skills/issue-contract-review/scripts/tests/ 配下の新規/既存 pytest が全て PASS している状態。

history-based source は、immutable_history_snapshot(producer が一度だけ読み、全 consumer が同一 plan_digest を再計算できる)、command_group_key / environment_fingerprint / execution_id の identity 分離、nearest_rank_v1(minimum 5 eligible success samples、TTL 30 日、最新 50 件、1.5 倍 safety margin、整数演算 rounding)、timeout の right-censored lower-bound backoff、raise-only precedence(historyは既存 static timeout を引き下げない)、1 actual subprocess launch = 1 sample、DB locked/corrupt/stale/unknown-schema 時の non-blocking static fallback を満たしたときのみ採用される。

Runtime Verification Applicability

decision: immediate
reason: >
  本 Issue は単なるパーセンタイル計算関数の追加ではなく、実際の subprocess duration 採取・並行書き込み・lock
  contention・atomic commit・producer から 4 consumer への snapshot 伝播・timeout 後の次回 budget
  backoff・store 破損時の degradation を扱う。fixture JSON からの percentile 計算 unit test だけでは
  production wiring を証明できないため、`not_applicable` は不正確と判断する。ただし 20-run CI calibration
  のような長期性能実験までは不要である。
applicable_acs:
  - AC9
execution_environment: >
  ローカルの一時ディレクトリ(`tmp_path` 等の pytest fixture)に隔離した SQLite history store と、実 subprocess
  (短時間コマンド)を 1 回起動する開発ローカル環境。ネットワーク・外部サービスへの依存はない。
skip_conditions: >
  SQLite(Python 標準ライブラリ `sqlite3`)または subprocess 起動が利用できない実行環境では SKIP exit 77 とし、
  `_fallback: true` を記録する。SKIP はテスト失敗として扱わずに証跡へ理由を残す。
fallback_policy: >
  history store 不在・SQLite 不可時は VC 内で degraded fallback 経路(static へのフォールバック)を FAIL 判定
  として明示的に検証し、無条件の SKIP exit 0 による骨抜きを行わない。
artifact_requirements: >
  VC 実行ログ(PASS/FAIL/SKIP・Exit Code・Reason)を artifacts/ 配下に保存し、pr-review-judge が引用できる形で
  PR 本文 `## Runtime Verification Evidence` セクションへ inline 化する。
  • if immediate: AC9(Production wiring)を動作検証 AC とし、<!-- runtime-verification: true --> タグを付与する。対応 VC は実 subprocess を 1 回起動して sample を保存し、次 invocation で production compute_canonical_vc_plan() が history snapshot を反映して budget を変化させることを確認する(正常系)。history store が存在しない cold-start 状態からの degraded fallback(異常系)を同一テストモジュール内の別ケースとして含める。証跡保存・Stop Condition 連動は docs/dev/runtime-verification-policy.md に従う。

In Scope

  • ローカル per-repository SQLite history store(vc_runtime_history.py)の設計・実装。schema は最小限(sample_id / command_group_key / environment_fingerprint / observed_at_utc / status(success|failed|timed_out|cancelled) / duration_ms / applied_timeout_ms / command_hash / writer_version)とし、汎用的な provenance_json 箱を作らない
  • immutable history snapshot(history_snapshot/v1)の生成と、contract_readiness_check.py / run_contract_review_once.py / run_root_review_pipeline.py への snapshot 伝播 additive wiring(4 consumer 配線ロジック全体の再設計ではなく、同一 snapshot を受け渡す最小限の追加配線)
  • command_group_key(argv・repo-relative cwd・command family から算出。option 順序や shell 構文を勝手に正規化しない)と environment_fingerprint(platform/arch/runner class/command family に応じた lock digest・tool version のみを対象とし、全環境変数・token・credential・temporary path・GITHUB_RUN_ID・PID・日時等の volatile 値は含めない)の分離実装
  • nearest_rank_v1 percentile 契約の固定実装: eligible samples は exit 0 の成功 sample のみ、window は同一 environment_fingerprint かつ TTL 30 日以内の新しい順最大 50 件、minimum success samples は 5、P95 = sorted_samples[ceil(0.95 * n) - 1]、candidate_seconds = ceil(observed_p95_ms * 1.5 / 1000)(整数演算での丸め方式を固定する)
  • timeout サンプルの right-censored lower-bound 扱いと timeout_backoff_floor = min(MAX_PER_COMMAND_TIMEOUT_SECONDS, previous_applied_timeout_seconds * 2) の実装。cancelled / process launch failure サンプルは estimator から除外し、failed(non-zero exit)サンプルは診断用に記録するが duration percentile からは除外する
  • raise-only precedence の実装: resolved = explicit_override if explicit_override is not None else min(MAX_PER_COMMAND_TIMEOUT_SECONDS, max(static_base, history_candidate, timeout_backoff_floor))。history が static_base 以下の場合は provenance の source を static_policy または static_fallback のまま維持し、history_estimate を name-only で名乗らない
  • 1 actual subprocess launch = 1 sample の保証(同一 execution を複数 AC が参照しても history row は 1 件のみ。execution_id の一意性実装)
  • SQLite の atomic write semantics(1 execution につき短い INSERT 1 トランザクション、busy timeout 0.25〜1 秒、既定 rollback journal mode、lock 時は待たず non-blocking で static fallback)の実装
  • history store の非 cryptographic な健全性チェック(schema version 不明時は history を無視、型・status・duration range 検証、duplicate sample_id 拒否、負数・異常に大きい値の拒否、command_group_key/environment_fingerprint 不一致の拒否、DB 破損・lock・permission error は advisory 扱いで static へフォールバック、history は最大 MAX_PER_COMMAND_TIMEOUT_SECONDS までの raise-only、history 障害だけを理由に review を block しない)
  • docs/dev/ci-performance.md(ci_runtime_baseline_v1 schema の正本)との関係整理: 本 Issue の history store は ci_runtime_baseline_v1 の schema・store を再利用せず独立実装とする(粒度が per-job/per-step と per-command で異なるため)。この判断理由を .claude/skills/issue-contract-review/references/vc-preflight.md に明文化する
  • .claude/skills/issue-contract-review/references/vc-preflight.md への history_estimate source 契約(identity 分離・percentile 契約・raise-only precedence・snapshot 方式・degradation 経路)の記載

Out of Scope

  • command_timeout_budget/v1 schema 自体の破壊的変更(既存 explicit_override / static_policy / static_fallback source と provenance フィールド構造は維持し、history_estimate を新規 source として追加する)
  • PR feat: canonical VC plan に command-level timeout budget を追加する (#2233) #2245 の iteration 過程で production schema から明示的に除去された当時の history_estimate 実装をそのまま復活させること(当時の実装は sample_count=1 / observed_p95_ms=estimated_seconds*1000 という実際の evidence を伴わない provenance を偽装していたため、OWNER レビューで reject された。本 Issue は genuine な evidence(実サンプル収集・最小 5 sample・staleness 判定・right-censoring backoff を満たした上での算出)に基づく history_estimate を新規設計する)
  • MAX_PER_COMMAND_TIMEOUT_SECONDS / MAX_TOTAL_VERIFICATION_BUDGET_SECONDS 等の hard policy ceiling 値そのものの変更(既存の policy ceiling 機構は変更せず、history-based estimate もこの ceiling を超えられない前提を維持する)
  • STATIC_PER_COMMAND_TIMEOUT_POLICY の削除、または history による自動的な timeout 引き下げ(history は raise-only のみ。既に確立された static policy 値(例: 420 秒)を history が下回る値で置き換えることは本 Issue のスコープ外とし、別 Issue に分離する)
  • CI history との統合: GitHub Actions run をまたぐ history 永続化、ci_runtime_baseline_v1(docs/dev/ci-performance.md)の schema 変更、GitHub cache/artifact を用いた cross-run collector の実装は本 Issue のスコープ外とする。本 Issue は ローカル command-level のみ をスコープとし、CI 実行では history が存在しないため常に static_policy / static_fallback へ non-blocking に劣化する。CI cross-run persistence が必要と判明した場合は実需要を確認した上で別 Issue に分離する
  • ci_runtime_baseline_v1 の bootstrap-3-runs / decision-baseline-20-runs ポリシー自体の再設計
  • HMAC・署名・秘密鍵管理を用いた cryptographic tamper-proofing(同一ユーザー権限で動くローカル DB に対して cryptographic guarantee を提供することはできないため、本 Issue では簡易な整合性チェック(schema version・型・range・重複排除)のみを実装する)
  • third-party statistics library への依存追加(nearest_rank_v1 は標準ライブラリの範囲で実装する)
  • contract_readiness_check.py / run_contract_review_once.py / run_root_review_pipeline.py の配線ロジック全体の再設計(Issue 実装: canonical VC plan に command-level timeout budget を追加し、全 review wrapper に同一 budget を配線する #2233 / PR feat: canonical VC plan に command-level timeout budget を追加する (#2233) #2245 で確立済みの「同一 plan-derived budget を消費する」契約は維持し、本 Issue は immutable snapshot を伝播させる最小限の additive wiring のみを追加する)

Acceptance Criteria

  • AC1: Snapshot determinism: 同一 pinned Issue body +同一 history snapshot から contract_readiness_check.py / run_contract_review_once.py / run_root_review_pipeline.py を含む全 4 consumer が同一 plan_digest を生成し、snapshot 生成後に history store が更新される、または TTL 境界を通過しても、既に確定した plan の plan_digest が変化しないことを検証する pytest が存在する
  • AC2: Identity separation: command_group_key / environment_fingerprint / execution_id が別概念として実装コード上で分離され、applied_timeout_ms などの実行パラメータ変更が command_group_key を変化させない(同一 command の history が引き続き参照できる)ことを検証する pytest が存在する
  • AC3: Estimator contract: nearest_rank_v1(eligible = exit 0 成功 sample のみ、TTL 30 日、最新 50 件、minimum success samples 5、P95 = sorted_samples[ceil(0.95 * n) - 1]、candidate_seconds = ceil(observed_p95_ms * 1.5 / 1000) の整数演算)が固定契約としてコード・vc-preflight.md・pytest で一致して検証されている
  • AC4: Raise-only precedence: explicit_override > max(static_base, history_candidate, timeout_backoff_floor)(MAX_PER_COMMAND_TIMEOUT_SECONDS で clamp)が実装され、history_candidate が static_base を下回る場合に resolved timeout が static_base 未満へ下がらないことを検証する pytest が存在する
  • AC5: Timeout censoring: timed_out status のサンプルが right-censored lower-bound として timeout_backoff_floor = min(MAX_PER_COMMAND_TIMEOUT_SECONDS, previous_applied_timeout_seconds * 2) に反映され、次回 invocation の resolved timeout が増加すること、および cancelled / launch failure サンプルが estimator から除外され failed(non-zero exit)サンプルが duration percentile を汚染しないことを検証する pytest が存在する
  • AC6: One launch, one sample: 同一 execution_id の subprocess 実行結果が複数 AC(複数 command occurrence)から参照されても、history store には 1 件の sample row のみが保存されることを検証する pytest が存在する
  • AC7: Atomic local persistence: SQLite history store への 2 プロセス並行 INSERT 後も、全 sample が保存され DB schema が有効であること、および lock 発生時に待機せず non-blocking で static fallback することを検証する pytest が存在する
  • AC8: Non-blocking degradation: history store が missing / locked / corrupt / unknown schema / invalid row / environment_fingerprint 不一致 / stale のいずれの場合でも static_policy / static_fallback source へ deterministic にフォールバックし、history 障害だけを理由に review 全体が block されないことを検証する pytest が存在する
  • AC9 : Production wiring: 実 command を 1 回起動し、sample 保存後の次 invocation で production compute_canonical_vc_plan() が history snapshot を利用して budget を変化させる runtime integration test が .claude/skills/issue-contract-review/tests/test_history_snapshot_production_wiring.py に存在し、history store 不在時の degraded fallback(異常系)も同一テストモジュールで検証されている
  • AC10: Scope boundary: ci_runtime_baseline_v1 の schema・store を再利用しない判断理由(粒度が per-job/per-step と per-command で異なること)が .claude/skills/issue-contract-review/references/vc-preflight.md に明文化され、CI cross-run history 永続化が Out of Scope であることが同ドキュメントおよび実装 PR 本文に記載されている

Verification Commands

# AC1
$ uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_command_timeout_budget_history_estimate.py -v -k snapshot_determinism
# AC2
$ uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_command_timeout_budget_history_estimate.py -v -k identity_separation
# AC3
$ uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_command_timeout_history_store.py -v -k nearest_rank
# AC4
$ uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_command_timeout_budget_history_estimate.py -v -k raise_only_precedence
# AC5
$ uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_command_timeout_budget_history_estimate.py -v -k timeout_censoring_backoff
# AC6
$ uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_command_timeout_history_store.py -v -k one_launch_one_sample
# AC7
$ uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_command_timeout_history_store.py -v -k atomic_concurrent_write
# AC8
$ uv run --locked pytest .claude/skills/issue-contract-review/scripts/tests/test_command_timeout_history_store.py -v -k non_blocking_degradation
# AC9
$ uv run --locked pytest .claude/skills/issue-contract-review/tests/test_history_snapshot_production_wiring.py -v
# AC10
$ rg -n "ci_runtime_baseline_v1" .claude/skills/issue-contract-review/references/vc-preflight.md

Allowed Paths

  • .claude/skills/issue-contract-review/scripts/baseline_vc_preflight.py
  • .claude/skills/issue-contract-review/scripts/vc_runtime_history.py
  • .claude/skills/issue-contract-review/scripts/contract_readiness_check.py
  • .claude/skills/issue-contract-review/scripts/run_contract_review_once.py
  • .claude/skills/issue-refinement-loop/scripts/run_root_review_pipeline.py
  • .claude/skills/issue-contract-review/scripts/tests/test_command_timeout_budget.py
  • .claude/skills/issue-contract-review/scripts/tests/test_command_timeout_budget_history_estimate.py
  • .claude/skills/issue-contract-review/scripts/tests/test_command_timeout_history_store.py
  • .claude/skills/issue-contract-review/tests/test_run_contract_review_once_wrapper_wiring.py
  • .claude/skills/issue-contract-review/tests/test_history_snapshot_production_wiring.py
  • .claude/skills/issue-contract-review/references/vc-preflight.md

Stop Conditions

  • Allowed Paths 外の変更が必要と判明した場合
  • In Scope の固定契約(キー集合・スキーマ・型定義)の変更が必要になった場合
  • nearest_rank_v1 percentile 契約・raise-only precedence の固定値の変更が必要になった場合
  • 新規 Issue の起票が必要と判断した場合(スコープ分割が発生する場合)
  • 後続 Phase / 別スコープへの波及が判明した場合
  • nested SubAgent delegation が必要になった場合
  • 外部サービス利用・権限昇格・既存テスト大規模改変が必要になった場合
  • CI cross-run history(GitHub Actions run をまたぐ永続化)の実装が必要と判明した場合は、本 Issue のスコープに含めず別 Issue に分離する
  • HMAC・署名・秘密鍵管理を用いた cryptographic tamper-proofing が必要と判明した場合は実装前に Issue コメントで理由を明記してから進める(本 Issue の想定では不要と判断している)

Required Skills

なし

Required Design References

  • .claude/skills/issue-contract-review/references/vc-preflight.md
  • docs/dev/ci-performance.md
  • docs/dev/runtime-verification-policy.md

Scope Delta(任意)

N/A

Background

Issue #2233(実装: canonical VC plan に command-level timeout budget を追加し、全 review wrapper に同一 budget を配線する、CLOSED、PR #2245 でマージ済み)は、固定 150 秒の per-command timeout が正当な長時間 VC(実測 271.31 秒の uv run --locked pytest .claude/skills/issue-refinement-loop/tests -v)を誤って kill する構造的バグを、STATIC_PER_COMMAND_TIMEOUT_POLICY という trusted・hand-curated な static policy テーブル(例: 420 秒)と、決定論的な static_fallback source によって解消した。

#2233 の ## Out of Scope はこの history-based estimator の完全実装を明示的に別 Issue へ分離することを述べている:

history-based(過去実測 P50/P95 等)estimator の完全実装(command identity・環境 fingerprint・minimum samples・TTL・poisoning 防止を含む calibration 基盤は別 Issue に分離する)

さらに PR #2245 の Safety Claim Matrix は、271.31 秒問題の解消について「history-based estimator(P50/P95 calibration)自体は Out of Scope(static policy が代替の trusted authority)」「別 Issue(history-based estimator)」と follow-up を明記している。

本 Issue はその follow-up として、static_fallback / static_policy を補完しうる history-based estimator を設計・実装する。なお PR #2245 の iteration 過程では、history_estimate source が一度実装されたが、sample_count=1 / observed_p95_ms=estimated_seconds*1000 という実際の evidence を伴わない provenance を偽装していたため production schema から明示的に除去された経緯がある。本 Issue はこの反省を踏まえ、genuine な evidence に基づく history_estimate を設計してから再導入する。

Refs #2233, Refs PR #2245

2026-08-29 全面改訂の経緯(issue-refinement-loop Step 2 REQUEST_CHANGES)

issue-refinement-loop の Step 2 review(issue-reviewer subagent)で、OWNER が以下の anchor comment を通じて本 Issue に REQUEST_CHANGES を投稿した:

#2254 (comment)

指摘された P0 blocker(要約):

  1. mutable history を各 consumer が独立に読むと compute_canonical_vc_plan() の純粋性が崩れ、参照タイミング差で vc_plan_digest_mismatch が発生しうる(immutable snapshot 方式が必要)
  2. timeout サンプルを単純除外すると、実際に既存 timeout を超過し続けているコマンドが永遠に history から学習されず cold-start ループに陥る(right-censored lower-bound として backoff に反映する必要)
  3. static_policy / static_fallback と history-based estimator の優先順位が未定義であり、history が既存の trusted static policy(例: 420 秒)を引き下げうる(raise-only precedence を明示する必要)
  4. 本文の Allowed Paths が CI infra を含まない一方で ci_runtime_baseline_v1(docs/dev/ci-performance.md、GitHub Actions job/step 粒度)との統合可否が曖昧(ローカル command-level のみへスコープを明確化し、CI history 統合は Out of Scope とする必要)

本改訂では、上記 P0 に加え、compute_execution_key_hash() を history grouping key に流用しない identity 分離(P1)、nearest_rank_v1 percentile 契約の明文化(P1)、tampering 防止を cryptographic guarantee から簡易整合性チェックへ縮小(P1)、1 launch = 1 sample の重複カウント防止(P1)も反映した。

Delivery Rule

1 Issue = 1 PR とする。worktree を作成して作業し、PR は Draft で作成する。

Notes for Reviewer

Activity

  1. added
    phase/implementation
    agent/implementer
    enhancement
    triage-required
    follow-up
    on Aug 18, 2026
  2. squne121 commented on Aug 28, 2026

    @squne121
    OwnerAuthor

    判定

    REQUEST_CHANGES — 現在の Issue 契約のまま実装へ渡すべきではありません。

    狙い自体は有用です。しかし現状は、可変な履歴データを canonical plan の生成途中で読む設計と、4 consumer が同一 plan_digest を再計算・照合する既存契約が衝突しています。さらに、timeout サンプルを除外できる AC6 では、この機能が解決したい「実行時間が既存 timeout を超えるコマンド」を履歴から学習できません。

    2026年8月29日時点で、Issue #2254 は open、コメントはなく、#2254 を紐づけた実装 PR も見つかりませんでした。したがって、以下はコードレビューではなく Issue 契約・設計の実装前レビューです。

    主要判定

    重要度 | 問題 | 現状の影響 -- | -- | -- P0 | mutable history と plan_digest が両立しない | 履歴機能自身が vc_plan_digest_mismatch を起こし得る P0 | timeout を通常統計から除外するだけ | 150秒で kill される271秒コマンドを永遠に学習できない P0 | static_policy と history の優先順位が未定義 | 既に直した420秒 policy をhistoryが引き下げ得る P0 | local履歴かCI横断履歴か未決定 | Allowed Paths内ではCI永続化を実装できない P1 | runtime verification が not_applicable | 並行書き込み・実配線・lock時劣化をfixtureだけで済ませている P1 | identity/fingerprint が過剰かつ曖昧 | cohort断片化、秘密・volatile env混入、自己参照が起き得る P1 | P95の算出法が未定義 | 実装者ごとに異なるtimeoutが生成される P1 | tamper防止が過剰設計 | workflowを止めるハーネスへ発展しやすい P1 | 1実行と複数command occurrenceの区別がない | 同じ実行結果を複数sampleとして水増しできる

    Runtime Verification は immediate または scaled に変更するのが妥当です。


    P1-2. compute_execution_key_hash() をhistory grouping keyに使ってはいけない

    既存ドキュメントでは、command_identity_hash と compute_execution_key_hash() は別概念です。

    • command_identity_hash: command text の識別

    • compute_execution_key_hash(): argv、cwd、env、timeout、state epochなどを含む実行単位の識別

    compute_execution_key_hash() に timeout が含まれるなら、historyでtimeoutを150秒から300秒へ変更した瞬間に別keyになります。

    timeout=150 → key A → timeout
    historyで300へ変更
    timeout=300 → key B → key Aのhistoryを参照できない

    これは自己破壊的です。

    推奨する3層分離

    1. command_group_key
       同じ種類のcommandをまとめる安定キー
    
    1. environment_fingerprint
      sampleの互換性を判定するキー

    2. execution_id
      1回の実launchを重複なく識別するID

    推奨形は次です。

    command_group_key = sha256(canonical_json({
    "argv": parsed_argv,
    "repo_relative_cwd": repo_relative_cwd,
    "command_family": command_family,
    }))

    environment_fingerprint = sha256(canonical_json({
    "platform": platform,
    "arch": arch,
    "runner_class": runner_class,
    "relevant_lock_digest": relevant_lock_digest,
    "relevant_tool_versions": relevant_tool_versions,
    }))

    注意点は以下です。

    • 全環境変数をfingerprintへ入れない。

    • token、credential、temporary pathを保存しない。

    • GITHUB_RUN_ID、PID、日時などvolatile値を入れない。

    • Python commandだけにPython/uv/pytest/uv.lockを使う。

    • pnpm commandにはNode/pnpm/pnpm-lock.yamlを使う。

    • option順序やshell構文を勝手に正規化しない。

    • exact HEAD SHAはgroupingではなくprovenanceに置く。

    現在のIssueはPython系fingerprintを全commandへ要求しており、pnpm commandのhistoryが無関係なpytest更新で無効になる設計です。command familyごとのfingerprintが必要です。


    P1-3. 「P95」の計算法が未定義

    Python標準の statistics.quantiles() は既定で exclusive 法を使い、inclusive 法とは結果が異なります。また公式ドキュメントは、意味のある結果にはデータ点数が区間数 n より多いことを推奨しています。n=100 のP95を少数sampleへそのまま適用する設計は不適切です。(Python documentation)

    Issueには以下がありません。

    • percentile method

    • sample window

    • minimum sample count

    • inclusive/exclusive

    • rounding

    • safety margin

    • P50とP95のどちらをbudgetに使うか

    • status eligibility

    • 同一run重複の扱い

    推奨する固定契約

    趣味開発用timeout estimatorなら、複雑な補間は不要です。

    method:
    nearest_rank_v1

    eligible samples:
    exit 0 の成功sampleのみ

    window:
    同じenvironment fingerprint
    TTL 30日以内
    新しいものから最大50件

    minimum success samples:
    5

    P95:
    sorted_samples[ceil(0.95 * n) - 1]

    P50:
    診断表示のみ

    candidate:
    ceil(P95_ms * 1.5 / 1000)

    automatic behavior:
    raise-only

    n=5〜19 ではnearest-rank P95は実質的に最大値になるため、少数sample時にも保守的です。しかもhistoryはtimeoutを引き下げないので、sample数が少なくてもworkflow safetyを悪化させません。

    float誤差を避けるなら、整数演算にしてください。

    candidate_seconds = (
    observed_p95_ms * 3 + 2 * 1000 - 1
    ) // (2 * 1000)

    P50はobservabilityには有用ですが、timeoutの決定値としては不要です。既存 command_timeout_budget/v1 に無理にP50 fieldを追加せず、snapshot/evidence側へ置く方が安全です。


    P1-4. AC8 の tampering 防止は、現状の表現だと過剰設計

    同一ユーザー権限で動くlocal DBに、秘密鍵や外部trust rootを置かず「改竄を証明」することはできません。row hash chainやHMACを追加しても、鍵やcodeを変更できる主体には再計算されます。

    この個人趣味開発で必要なのは cryptographic tamper-proofing ではなく、破損・異常値・誤書き込みでworkflowを壊さないことです。

    AC8は次へ置き換えるべきです

    - schema versionが未知ならhistoryを無視

    • 型・status・duration rangeを検証
    • duplicate sample_idを拒否
    • 負数/異常に大きい値を拒否
    • command_group_keyとfingerprint不一致を拒否
    • DB破損・lock・permission errorはadvisory
    • historyは最大600秒までのraise-only
    • history障害時は必ずstatic policyへ戻る
    • history障害だけを理由にreviewをblockしない

    ファイルpermissionを0600相当にするのは妥当ですが、HMAC、key management、署名基盤は不要です。


    P1-5. 同じsubprocess実行を複数sampleとして数える危険がある

    canonical plan は command occurrence を持ち、pure command の重複実行をまとめる経路があります。

    history writer がresult itemごとに記録すると、1回しか起動していないcommandが、複数ACに現れただけで複数sampleになります。

    AC1: pytest foo
    AC2: pytest foo

    実際のlaunch: 1回
    result item: 2件
    誤ったsample_count: 2

    必須修正

    • 1sampleは 1 actual subprocess launch。

    • execution_id を一意にする。

    • 複数occurrenceが同じexecutionを参照しても、history rowは1件。

    • retryは別sampleだが、同じretry結果のaliasは重複させない。

    • sample_count はeligibleな一意成功execution数。


    P1-6. 壊れたhistoryがhard blockerを発火させてはいけない

    現在は、解決されたtimeoutが600秒を超えると CommandTimeoutExceedsPolicyError を subprocess起動前に返します。これはrepo-ownedなexplicit override/static policyには妥当です。

    しかしhistory rowの異常値をそのままresolverへ渡すと、履歴DBの破損だけでレビュー全体をblockできます。

    history sourceについては、次のように扱うべきです。

    raw candidate > 600:
    history recordをinvalidまたはpolicy-limitedとして扱う
    candidateを600以内に制限
    non-blocking advisoryを出す

    DB破損/schema不一致:
    historyを不採用
    staticへfallback

    historyは trusted policy authority ではなく、あくまで advisory input です。history failureが既存static fallbackより悪い結果を作らないことをAC化してください。


    推奨実装

    Store は local SQLite が最も妥当

    JSON file+renameでも単一writerのatomicityは作れますが、複数プロセスのread-modify-writeでは更新消失を防ぐためのlock処理が別途必要です。SQLiteのtransactionはprogram crash、OS crash、電源断でもall-or-nothingを保証します。Python標準ライブラリだけで利用できます。(SQLite)

    この用途ではWALは不要です。

    • writeはcommand完了時の小さな1 transactionだけ

    • readはinvocation開始時の1回

    • lock時は待たずstatic fallbackできる

    • throughputは不要

    SQLite公式も、WALはreader/writer concurrencyを高める一方、同一host制約や追加管理を持ち、writerは同時に1つだけと説明しています。さらに2026年には、複数connectionで同時write/checkpointした場合の稀なWAL bugが3.51.3等で修正されています。デフォルトrollback journalの方が、この用途では単純です。(SQLite)

    推奨設定

    journal_mode:
    default rollback journal

    busy timeout:
    0.25〜1秒

    lock時:
    warning/advisory + static fallback

    transaction:
    1 actual executionにつき短いINSERT 1回

    DB failure:
    command result自体は変更しない

    Pythonの sqlite3.connect(timeout=...) は、lock時に OperationalError を出すまでの待機時間を設定できます。既定5秒はこのworkflowには長いため、短く明示する方がよいです。(Python documentation)

    保存場所

    repo外のper-repository stateを推奨します。

    $XDG_STATE_HOME/
    loop-protocol/
    vc-runtime-history/
    <sha256(realpath(git-common-dir))>.sqlite3

    XDG_STATE_HOME がなければ ~/.local/state を使います。

    これにより、

    • git statusを汚さない

    • worktree間で共有できる

    • clone間では混ざらない

    • Allowed Paths guardの対象外であるruntime stateとして扱える

    という利点があります。

    最小schema

    CREATE TABLE samples (
    sample_id TEXT PRIMARY KEY,
    command_group_key TEXT NOT NULL,
    environment_fingerprint TEXT NOT NULL,
    observed_at_utc TEXT NOT NULL,
    status TEXT NOT NULL CHECK (
    status IN ('success', 'failed', 'timed_out', 'cancelled')
    ),
    duration_ms INTEGER,
    applied_timeout_ms INTEGER NOT NULL,
    command_hash TEXT NOT NULL,
    writer_version TEXT NOT NULL
    );

    CREATE INDEX samples_lookup
    ON samples (
    command_group_key,
    environment_fingerprint,
    observed_at_utc
    );

    provenance_jsonを何でも入る箱として最初から作るより、必要なfieldだけ固定した方が破損・driftを防げます。

    Snapshot

    {
    "schema": "vc_command_runtime_snapshot/v1",
    "as_of_utc": "2026-08-29T00:00:00Z",
    "estimator_version": "nearest_rank_v1",
    "groups": [
    {
    "command_group_key": "...",
    "environment_fingerprint": "...",
    "eligible_success_count": 8,
    "timeout_count": 1,
    "observed_p50_ms": 266100,
    "observed_p95_ms": 274500,
    "timeout_backoff_floor_seconds": 300
    }
    ]
    }

    estimator_input_digest はDB file bytes、mtime、SQLite page layoutではなく、この canonical evidence object をhashしてください。


    Issue #2254 の推奨スコープ差し替え

    Revised Goal

    ローカルの反復VC実行について、実測成功durationとtimeout lower-boundから、既存static timeoutを自動的に引き上げるadvisory・raise-only estimatorを実装する。可変storeはrootでimmutable snapshot化し、全consumerが同一snapshotから同一canonical planを生成する。historyが利用不能な場合はworkflowを止めず既存static policyへ劣化する。

    Revised In Scope

    - local per-repository SQLite history

    • immutable history snapshot
    • snapshot digestのconsumer伝播
    • command grouping identity
    • environment compatibility fingerprint
    • nearest_rank_v1
    • minimum samples / TTL / bounded window
    • success duration sampling
    • timeout lower-bound + bounded backoff
    • one row per actual subprocess launch
    • DB locked/corrupt/stale時のnon-blocking static fallback
    • scaled runtime integration tests

    Revised Out of Scope

    - GitHub Actions runをまたぐhistory永続化
    
  3. ci_runtime_baseline_v1のschema変更
  4. GitHub cache/artifact collector
  5. timeoutの自動引き下げ
  6. STATIC_PER_COMMAND_TIMEOUT_POLICYの削除
  7. HMAC、署名、秘密鍵管理
  8. 20-run CI calibration
  9. third-party statistics dependency
  10. 必須Allowed Paths追加

    .claude/skills/issue-contract-review/scripts/vc_runtime_history.py
    .claude/skills/issue-contract-review/scripts/contract_readiness_check.py
    .claude/skills/issue-contract-review/scripts/run_contract_review_once.py
    .claude/skills/issue-refinement-loop/scripts/run_root_review_pipeline.py
    .claude/skills/issue-contract-review/tests/test_run_contract_review_once_wrapper_wiring.py
    .claude/skills/issue-contract-review/scripts/tests/test_command_timeout_budget_history_estimate.py
    .claude/skills/issue-contract-review/scripts/tests/test_command_timeout_history_store.py

    巨大な baseline_vc_preflight.py にstore、schema、migration、percentile、snapshot処理をすべて詰め込まず、vc_runtime_history.py へ分離すべきです。


    改訂版Acceptance Criteria

    1. Snapshot determinism
      同一Issue body+同一history snapshotから全4 consumerが同一 plan_digest を生成し、snapshot生成後にDB更新またはTTL境界通過があっても現在のplanが変わらない。

    2. Identity separation
      command_group_key、environment_fingerprint、execution_id が別概念として実装され、timeout変更でhistory groupが変わらない。

    3. Estimator contract
      nearest_rank_v1、minimum 5、TTL 30日、最新50件、1.5倍margin、integer roundingがコード・docs・testで固定される。

    4. Raise-only precedence
      explicit_override > max(static_base, history, timeout_backoff) が検証され、historyがstatic timeoutを引き下げない。

    5. Censoring
      timeoutが lower-bound/backoffとして次回budgetを引き上げ、cancelledとnon-zero failureが成功percentileを汚染しない。

    6. One launch, one sample
      同一executionを複数ACが参照してもsampleは1件だけ保存される。

    7. Atomic local persistence
      2プロセス並行INSERT後も全sampleが保存され、DB schemaが有効である。

    8. Non-blocking degradation
      missing、locked、corrupt、unknown schema、invalid row、fingerprint mismatch、staleのすべてでstatic sourceへ戻り、history障害だけではreviewをblockしない。

    9. Production wiring
      実commandを1回起動し、sample保存後の次invocationでproduction compute_canonical_vc_plan() がhistoryを利用するintegration testがある。

    10. Scope boundary
      ci_runtime_baseline_v1 はprovenance慣習のみ参照し、schema/storeは再利用しない理由と、CI cross-run persistenceがOut of ScopeであることをdocsとPR本文に記載する。


    最終評価

    このIssueを全面的に捨てる必要はありません。ただし、現在の「P50/P95 calibration基盤、CI baseline再利用、tampering防止、atomic store」を一括で実装すると、個人趣味開発としては基盤コストが高く、既存workflowを止める新しい故障点を増やします。

    最も有用な形は次です。

    verdict: REQUEST_CHANGES
    implementation_ready: false
    recommended_scope: local_advisory_raise_only
    required_before_implementation:
    • immutable_history_snapshot
    • timeout_censoring_backoff
    • explicit_raise_only_precedence
    • local_only_storage_decision
    • consumer_snapshot_wiring
    • non_blocking_degradation
    • scaled_runtime_integration

    推奨は #2254 を「local adaptive timeout cache」に狭めて全面改訂することです。
    その改訂を行わないなら、現在のtrusted static policyを維持して not planned にする方が、現行契約のまま複雑なhistory基盤を実装するより品質・有用性ともに上です。

    # 判定

    REQUEST_CHANGES — 現在の Issue 契約のまま実装へ渡すべきではありません。

    狙い自体は有用です。しかし現状は、可変な履歴データを canonical plan の生成途中で読む設計と、4 consumer が同一 plan_digest を再計算・照合する既存契約が衝突しています。さらに、timeout サンプルを除外できる AC6 では、この機能が解決したい「実行時間が既存 timeout を超えるコマンド」を履歴から学習できません。

    2026年8月29日時点で、Issue #2254 は open、コメントはなく、#2254 を紐づけた実装 PR も見つかりませんでした。したがって、以下はコードレビューではなく Issue 契約・設計の実装前レビューです。

    主要判定

    重要度 問題 現状の影響
    P0 mutable history と plan_digest が両立しない 履歴機能自身が vc_plan_digest_mismatch を起こし得る
    P0 timeout を通常統計から除外するだけ 150秒で kill される271秒コマンドを永遠に学習できない
    P0 static_policy と history の優先順位が未定義 既に直した420秒 policy をhistoryが引き下げ得る
    P0 local履歴かCI横断履歴か未決定 Allowed Paths内ではCI永続化を実装できない
    P1 runtime verification が not_applicable 並行書き込み・実配線・lock時劣化をfixtureだけで済ませている
    P1 identity/fingerprint が過剰かつ曖昧 cohort断片化、秘密・volatile env混入、自己参照が起き得る
    P1 P95の算出法が未定義 実装者ごとに異なるtimeoutが生成される
    P1 tamper防止が過剰設計 workflowを止めるハーネスへ発展しやすい
    P1 1実行と複数command occurrenceの区別がない 同じ実行結果を複数sampleとして水増しできる

    P0 findings

    P0-1. mutable history を各 consumer が直接読むと canonical plan が非決定的になる

    PR #2245 で確立された現行契約は、baseline_vc_preflight.py、contract_readiness_check.py、run_contract_review_once.py、run_root_review_pipeline.py が、同一の pinned Issue body から同じ canonical plan を作り、full-envelope の plan_digest を照合するものです。現在の実装コメントにも、4 consumer が同じ producer を使い、digest 不一致を subprocess 起動前に拒否する契約が明記されています。

    Issue #2254 は、その compute_canonical_vc_plan() 内で history を選択するとしています。しかし各プロセスが mutable store を別々の時点で読むと、次の競合が発生します。

    親プロセス:
      history generation 10 を読む
      plan_digest = A
    
    別セッション:
      command結果を書き込み
      history generation 11 になる
    
    子プロセス:
      generation 11 を読む
      plan_digest = B
    
    結果:
      vc_plan_digest_mismatch
      VCを1本も実行せず停止
    

    書き込みがなくても、TTL の境界をまたぐだけで同じ問題が起きます。

    親: 11:59:59 時点では sample が有効
    子: 12:00:01 時点では sample が stale
    

    これは推論ですが、既存 digest 契約と #2254 の TTL 要件から直接導かれる構造的な競合です。

    必須修正

    canonical plan を次の純粋関数にしてください。

    plan = f(
        pinned_issue_body,
        immutable_history_snapshot,
        snapshot_as_of_utc
    )
    

    推奨フローは以下です。

    1. root-owned producer が、実行開始時に history を一度だけ読む。
    2. history_snapshot/v1 の canonical JSON を生成する。
    3. snapshot_as_of_utc、対象 record、environment fingerprint、snapshot digest を固定する。
    4. 全 consumer に同じ snapshot または snapshot file+digest を渡す。
    5. command 実行結果の書き込みは plan 確定後に行い、現在実行中の plan には反映しない。
    6. 新しい sample は次回 invocation から利用する。

    この修正には少なくとも次のファイル変更が必要です。

    .claude/skills/issue-contract-review/scripts/contract_readiness_check.py
    .claude/skills/issue-contract-review/scripts/run_contract_review_once.py
    .claude/skills/issue-refinement-loop/scripts/run_root_review_pipeline.py
    

    したがって、現在の「4 consumer 配線は再設計しない」という Out of Scope と、狭すぎる Allowed Paths は成立しません。配線全体を作り直す必要はありませんが、snapshot を伝播させる最小限の additive wiring は必須です。


    P0-2. timeout は「除外すべき汚染データ」ではなく右打ち切りデータ

    AC6 は timeout/cancelled を P50/P95 から除外、または別集計にするとしています。しかし timeout は単なる失敗値ではありません。

    150秒で timeout した場合、観測できた事実は次です。

    真の実行時間 > 150秒
    

    統計上、これは右打ち切りデータです。NIST は、固定時間まで観測してそれより長い値が不明になるケースを right-censored data と説明しています。SciPy の定義でも、右打ち切り時の観測値は真の未知値の下限です。(NIST)

    今回の起点となったコマンドは、実測約271秒に対して150秒で kill されていました。PR #2245 では、この問題を exact static policy の420秒で解消しています。

    timeout sample を完全除外すると、未知の遅いコマンドは次のループに入ります。

    1回目: 150秒でtimeout → 除外
    2回目: history sampleなし → 150秒
    3回目: 150秒でtimeout → 除外
    ...
    

    つまり history-based estimator が、最も必要なケースで永久に cold-start のままになります。

    必須修正

    status ごとの意味を明示してください。

    status estimator上の扱い
    success / exit 0 P50/P95 の duration sample
    failed / non-zero 診断用に記録、duration percentile からは除外
    timed_out lower_bound_ms = applied_timeout_ms として記録し、次回budgetをbackoff
    外部 cancelled estimatorから除外
    process launch failure estimatorから除外

    趣味開発向けの単純で安全な backoff は次で十分です。

    timeout_backoff_floor =
        min(MAX_PER_COMMAND_TIMEOUT_SECONDS,
            previous_applied_timeout_seconds * 2)
    

    したがって150秒で timeout したコマンドは、次回300秒になります。これで約271秒のコマンドは、historyがまだ成功sampleを持っていなくても次回完走できます。

    Survival analysis や SciPy 依存を導入する必要はありません。右打ち切りを下限として扱う bounded backoff だけで、実用上の問題は解消できます。


    P0-3. static_policy と static_fallback が Issue 内で混同されている

    現在の production source は明確に分かれています。

    • explicit_override
    • static_policy
    • static_fallback

    STATIC_PER_COMMAND_TIMEOUT_POLICY に exact match したコマンドは static_policy です。どの policy にも一致しない場合の150秒が static_fallback です。現在の precedence は、明示 override、static policy、fallback の順です。

    一方、Issue #2254 の Outcome では static_fallback(STATIC_PER_COMMAND_TIMEOUT_POLICY) と書かれており、2つの source が混同されています。

    このままでは、次のどちらも「ACを満たした実装」と主張できます。

    A: history > static_policy > fallback
    B: static_policy > history > fallback
    

    Aを採用すると、既に271秒問題を直した420秒の trusted policy を、少数のwarm-cache sampleから算出した300秒前後の値で引き下げる可能性があります。

    必須の precedence

    この Issue では historyはtimeoutを引き下げず、引き上げ専用 にするべきです。

    if explicit_override is not None:
        resolved = explicit_override
    else:
        static_base = static_policy.get(command, DEFAULT_TIMEOUT_SECONDS)
        resolved = max(
            static_base,
            history_candidate,
            timeout_backoff_floor,
        )
        resolved = min(resolved, MAX_PER_COMMAND_TIMEOUT_SECONDS)

    source 判定は次です。

    historyがbaseを上回った:
      source = history_estimate
    
    historyがbase以下:
      source = static_policy または static_fallback
    

    これにより、履歴が少ない、偏っている、stale、破損している場合でも既存挙動を悪化させません。

    STATIC_PER_COMMAND_TIMEOUT_POLICY の削除や、historyによる自動縮小は別 Issue に分離すべきです。


    P0-4. local history と CI cross-run history が同じ Issue に混在している

    ci_runtime_baseline_v1 は、GitHub Actions の job/step 単位の elapsed time を artifact として保存する既存契約です。run ID、job、runner image、step ID、elapsed time を持ち、性能比較用に20 runのP50/P95を使います。VC command単位のmutable lookup storeとは、粒度・利用時点・更新方法が異なります。

    GitHub Actions の cache は既存keyの内容を更新できず、新しいkeyが必要です。また、別workflow runのartifact取得にはtokenとrun identifierが必要です。したがって、cacheやartifactを単純なmutable history DBとして扱うことはできません。([GitHub Docs]2)

    現行 Allowed Paths には .github/workflows/、collector、artifact schema が含まれていません。よってCI runをまたぐhistoryは、現契約内では実装不能です。

    推奨スコープ

    Issue #2254 は local-first に限定してください。

    対象:
      Claude Code / ローカル preflight の反復実行
    
    永続化:
      ローカルの per-repository SQLite
    
    CI:
      historyなし
      static_policy/static_fallbackへ自動劣化
    
    将来:
      実需要が確認できた場合だけ、
      immutable per-run sample artifact + collector を別Issue化
    

    これは「CIでは機能しない欠陥」ではありません。今回解決したい主なワークフローがローカルのエージェント実行なら、むしろ余計なworkflow・token・artifact処理を入れない方が有用です。


    P1 findings

    P1-1. Runtime Verification Applicability: not_applicable は不正確

    この Issue は、単なるパーセンタイル関数の追加ではありません。

    • 実際の subprocess duration の採取
    • 並行書き込み
    • lock contention
    • atomic commit
    • parent/child 間のsnapshot伝播
    • timeout後の次回budget変更
    • store破損時のdegradation

    を扱います。fixture JSONからP95を算出するunit testだけでは、production wiringを証明できません。

    PR #2245 でも、一度はテストがPASSしていたにもかかわらず、後の敵対的レビューで「4 consumerが実際には新budgetを使っていない」「271秒問題が直っていない」「production wiringを通っていない」と判定され、REQUEST_CHANGES になっています。

    また、このリポジトリの性能系Issueでは、固定SHA・raw sample・same-clock・immutable manifestなど、集計値だけでなく実測経路の検証を要求する方向に改善されています。

    ただし20-run CI検証までは不要

    このIssueで必要なのは長期性能実験ではなく、scaled runtime integrationです。

    最低限、次を実プロセスで検証してください。

    テスト 必須確認
    concurrent writers 2プロセス同時writeで破損・lost updateがない
    snapshot stability snapshot後にDBを更新しても全consumerのdigestが同じ
    real observation 実command実行後に1sampleだけ保存される
    timeout adaptation timeout後の次回planでbudgetが増える
    degraded mode DB locked/corrupt/unknown schemaでもstaticへ戻り、レビューを止めない

    Runtime Verification は immediate または scaled に変更するのが妥当です。


    P1-2. compute_execution_key_hash() をhistory grouping keyに使ってはいけない

    既存ドキュメントでは、command_identity_hash と compute_execution_key_hash() は別概念です。

    • command_identity_hash: command text の識別
    • compute_execution_key_hash(): argv、cwd、env、timeout、state epochなどを含む実行単位の識別

    compute_execution_key_hash() に timeout が含まれるなら、historyでtimeoutを150秒から300秒へ変更した瞬間に別keyになります。

    timeout=150 → key A → timeout
    historyで300へ変更
    timeout=300 → key B → key Aのhistoryを参照できない
    

    これは自己破壊的です。

    推奨する3層分離

    1. command_group_key
       同じ種類のcommandをまとめる安定キー
    
    2. environment_fingerprint
       sampleの互換性を判定するキー
    
    3. execution_id
       1回の実launchを重複なく識別するID
    

    推奨形は次です。

    command_group_key = sha256(canonical_json({
        "argv": parsed_argv,
        "repo_relative_cwd": repo_relative_cwd,
        "command_family": command_family,
    }))
    
    environment_fingerprint = sha256(canonical_json({
        "platform": platform,
        "arch": arch,
        "runner_class": runner_class,
        "relevant_lock_digest": relevant_lock_digest,
        "relevant_tool_versions": relevant_tool_versions,
    }))

    注意点は以下です。

    • 全環境変数をfingerprintへ入れない。
    • token、credential、temporary pathを保存しない。
    • GITHUB_RUN_ID、PID、日時などvolatile値を入れない。
    • Python commandだけにPython/uv/pytest/uv.lockを使う。
    • pnpm commandにはNode/pnpm/pnpm-lock.yamlを使う。
    • option順序やshell構文を勝手に正規化しない。
    • exact HEAD SHAはgroupingではなくprovenanceに置く。

    現在のIssueはPython系fingerprintを全commandへ要求しており、pnpm commandのhistoryが無関係なpytest更新で無効になる設計です。command familyごとのfingerprintが必要です。


    P1-3. 「P95」の計算法が未定義

    Python標準の statistics.quantiles() は既定で exclusive 法を使い、inclusive 法とは結果が異なります。また公式ドキュメントは、意味のある結果にはデータ点数が区間数 n より多いことを推奨しています。n=100 のP95を少数sampleへそのまま適用する設計は不適切です。([Python documentation]3)

    Issueには以下がありません。

    • percentile method
    • sample window
    • minimum sample count
    • inclusive/exclusive
    • rounding
    • safety margin
    • P50とP95のどちらをbudgetに使うか
    • status eligibility
    • 同一run重複の扱い

    推奨する固定契約

    趣味開発用timeout estimatorなら、複雑な補間は不要です。

    method:
      nearest_rank_v1
    
    eligible samples:
      exit 0 の成功sampleのみ
    
    window:
      同じenvironment fingerprint
      TTL 30日以内
      新しいものから最大50件
    
    minimum success samples:
      5
    
    P95:
      sorted_samples[ceil(0.95 * n) - 1]
    
    P50:
      診断表示のみ
    
    candidate:
      ceil(P95_ms * 1.5 / 1000)
    
    automatic behavior:
      raise-only
    

    n=5〜19 ではnearest-rank P95は実質的に最大値になるため、少数sample時にも保守的です。しかもhistoryはtimeoutを引き下げないので、sample数が少なくてもworkflow safetyを悪化させません。

    float誤差を避けるなら、整数演算にしてください。

    candidate_seconds = (
        observed_p95_ms * 3 + 2 * 1000 - 1
    ) // (2 * 1000)

    P50はobservabilityには有用ですが、timeoutの決定値としては不要です。既存 command_timeout_budget/v1 に無理にP50 fieldを追加せず、snapshot/evidence側へ置く方が安全です。


    P1-4. AC8 の tampering 防止は、現状の表現だと過剰設計

    同一ユーザー権限で動くlocal DBに、秘密鍵や外部trust rootを置かず「改竄を証明」することはできません。row hash chainやHMACを追加しても、鍵やcodeを変更できる主体には再計算されます。

    この個人趣味開発で必要なのは cryptographic tamper-proofing ではなく、破損・異常値・誤書き込みでworkflowを壊さないことです。

    AC8は次へ置き換えるべきです

    - schema versionが未知ならhistoryを無視
    - 型・status・duration rangeを検証
    - duplicate sample_idを拒否
    - 負数/異常に大きい値を拒否
    - command_group_keyとfingerprint不一致を拒否
    - DB破損・lock・permission errorはadvisory
    - historyは最大600秒までのraise-only
    - history障害時は必ずstatic policyへ戻る
    - history障害だけを理由にreviewをblockしない
    

    ファイルpermissionを0600相当にするのは妥当ですが、HMAC、key management、署名基盤は不要です。


    P1-5. 同じsubprocess実行を複数sampleとして数える危険がある

    canonical plan は command occurrence を持ち、pure command の重複実行をまとめる経路があります。

    history writer がresult itemごとに記録すると、1回しか起動していないcommandが、複数ACに現れただけで複数sampleになります。

    AC1: pytest foo
    AC2: pytest foo
    
    実際のlaunch: 1回
    result item: 2件
    誤ったsample_count: 2
    

    必須修正

    • 1sampleは 1 actual subprocess launch。
    • execution_id を一意にする。
    • 複数occurrenceが同じexecutionを参照しても、history rowは1件。
    • retryは別sampleだが、同じretry結果のaliasは重複させない。
    • sample_count はeligibleな一意成功execution数。

    P1-6. 壊れたhistoryがhard blockerを発火させてはいけない

    現在は、解決されたtimeoutが600秒を超えると CommandTimeoutExceedsPolicyError を subprocess起動前に返します。これはrepo-ownedなexplicit override/static policyには妥当です。

    しかしhistory rowの異常値をそのままresolverへ渡すと、履歴DBの破損だけでレビュー全体をblockできます。

    history sourceについては、次のように扱うべきです。

    raw candidate > 600:
      history recordをinvalidまたはpolicy-limitedとして扱う
      candidateを600以内に制限
      non-blocking advisoryを出す
    
    DB破損/schema不一致:
      historyを不採用
      staticへfallback
    

    historyは trusted policy authority ではなく、あくまで advisory input です。history failureが既存static fallbackより悪い結果を作らないことをAC化してください。


    推奨実装

    Store は local SQLite が最も妥当

    JSON file+renameでも単一writerのatomicityは作れますが、複数プロセスのread-modify-writeでは更新消失を防ぐためのlock処理が別途必要です。SQLiteのtransactionはprogram crash、OS crash、電源断でもall-or-nothingを保証します。Python標準ライブラリだけで利用できます。(SQLite)

    この用途ではWALは不要です。

    • writeはcommand完了時の小さな1 transactionだけ
    • readはinvocation開始時の1回
    • lock時は待たずstatic fallbackできる
    • throughputは不要

    SQLite公式も、WALはreader/writer concurrencyを高める一方、同一host制約や追加管理を持ち、writerは同時に1つだけと説明しています。さらに2026年には、複数connectionで同時write/checkpointした場合の稀なWAL bugが3.51.3等で修正されています。デフォルトrollback journalの方が、この用途では単純です。(SQLite)

    推奨設定

    journal_mode:
      default rollback journal
    
    busy timeout:
      0.25〜1秒
    
    lock時:
      warning/advisory + static fallback
    
    transaction:
      1 actual executionにつき短いINSERT 1回
    
    DB failure:
      command result自体は変更しない
    

    Pythonの sqlite3.connect(timeout=...) は、lock時に OperationalError を出すまでの待機時間を設定できます。既定5秒はこのworkflowには長いため、短く明示する方がよいです。([Python documentation]6)

    保存場所

    repo外のper-repository stateを推奨します。

    $XDG_STATE_HOME/
      loop-protocol/
        vc-runtime-history/
          <sha256(realpath(git-common-dir))>.sqlite3
    

    XDG_STATE_HOME がなければ ~/.local/state を使います。

    これにより、

    • git statusを汚さない
    • worktree間で共有できる
    • clone間では混ざらない
    • Allowed Paths guardの対象外であるruntime stateとして扱える

    という利点があります。

    最小schema

    CREATE TABLE samples (
        sample_id TEXT PRIMARY KEY,
        command_group_key TEXT NOT NULL,
        environment_fingerprint TEXT NOT NULL,
        observed_at_utc TEXT NOT NULL,
        status TEXT NOT NULL CHECK (
            status IN ('success', 'failed', 'timed_out', 'cancelled')
        ),
        duration_ms INTEGER,
        applied_timeout_ms INTEGER NOT NULL,
        command_hash TEXT NOT NULL,
        writer_version TEXT NOT NULL
    );
    
    CREATE INDEX samples_lookup
    ON samples (
        command_group_key,
        environment_fingerprint,
        observed_at_utc
    );

    provenance_jsonを何でも入る箱として最初から作るより、必要なfieldだけ固定した方が破損・driftを防げます。

    Snapshot

    {
      "schema": "vc_command_runtime_snapshot/v1",
      "as_of_utc": "2026-08-29T00:00:00Z",
      "estimator_version": "nearest_rank_v1",
      "groups": [
        {
          "command_group_key": "...",
          "environment_fingerprint": "...",
          "eligible_success_count": 8,
          "timeout_count": 1,
          "observed_p50_ms": 266100,
          "observed_p95_ms": 274500,
          "timeout_backoff_floor_seconds": 300
        }
      ]
    }

    estimator_input_digest はDB file bytes、mtime、SQLite page layoutではなく、この canonical evidence object をhashしてください。


    Issue #2254 の推奨スコープ差し替え

    Revised Goal

    ローカルの反復VC実行について、実測成功durationとtimeout lower-boundから、既存static timeoutを自動的に引き上げるadvisory・raise-only estimatorを実装する。可変storeはrootでimmutable snapshot化し、全consumerが同一snapshotから同一canonical planを生成する。historyが利用不能な場合はworkflowを止めず既存static policyへ劣化する。

    Revised In Scope

    - local per-repository SQLite history
    - immutable history snapshot
    - snapshot digestのconsumer伝播
    - command grouping identity
    - environment compatibility fingerprint
    - nearest_rank_v1
    - minimum samples / TTL / bounded window
    - success duration sampling
    - timeout lower-bound + bounded backoff
    - one row per actual subprocess launch
    - DB locked/corrupt/stale時のnon-blocking static fallback
    - scaled runtime integration tests
    

    Revised Out of Scope

    - GitHub Actions runをまたぐhistory永続化
    - ci_runtime_baseline_v1のschema変更
    - GitHub cache/artifact collector
    - timeoutの自動引き下げ
    - STATIC_PER_COMMAND_TIMEOUT_POLICYの削除
    - HMAC、署名、秘密鍵管理
    - 20-run CI calibration
    - third-party statistics dependency
    

    必須Allowed Paths追加

    .claude/skills/issue-contract-review/scripts/vc_runtime_history.py
    .claude/skills/issue-contract-review/scripts/contract_readiness_check.py
    .claude/skills/issue-contract-review/scripts/run_contract_review_once.py
    .claude/skills/issue-refinement-loop/scripts/run_root_review_pipeline.py
    .claude/skills/issue-contract-review/tests/test_run_contract_review_once_wrapper_wiring.py
    .claude/skills/issue-contract-review/scripts/tests/test_command_timeout_budget_history_estimate.py
    .claude/skills/issue-contract-review/scripts/tests/test_command_timeout_history_store.py
    

    巨大な baseline_vc_preflight.py にstore、schema、migration、percentile、snapshot処理をすべて詰め込まず、vc_runtime_history.py へ分離すべきです。


    改訂版Acceptance Criteria

    1. Snapshot determinism
      同一Issue body+同一history snapshotから全4 consumerが同一 plan_digest を生成し、snapshot生成後にDB更新またはTTL境界通過があっても現在のplanが変わらない。

    2. Identity separation
      command_group_key、environment_fingerprint、execution_id が別概念として実装され、timeout変更でhistory groupが変わらない。

    3. Estimator contract
      nearest_rank_v1、minimum 5、TTL 30日、最新50件、1.5倍margin、integer roundingがコード・docs・testで固定される。

    4. Raise-only precedence
      explicit_override > max(static_base, history, timeout_backoff) が検証され、historyがstatic timeoutを引き下げない。

    5. Censoring
      timeoutが lower-bound/backoffとして次回budgetを引き上げ、cancelledとnon-zero failureが成功percentileを汚染しない。

    6. One launch, one sample
      同一executionを複数ACが参照してもsampleは1件だけ保存される。

    7. Atomic local persistence
      2プロセス並行INSERT後も全sampleが保存され、DB schemaが有効である。

    8. Non-blocking degradation
      missing、locked、corrupt、unknown schema、invalid row、fingerprint mismatch、staleのすべてでstatic sourceへ戻り、history障害だけではreviewをblockしない。

    9. Production wiring
      実commandを1回起動し、sample保存後の次invocationでproduction compute_canonical_vc_plan() がhistoryを利用するintegration testがある。

    10. Scope boundary
      ci_runtime_baseline_v1 はprovenance慣習のみ参照し、schema/storeは再利用しない理由と、CI cross-run persistenceがOut of ScopeであることをdocsとPR本文に記載する。


    最終評価

    このIssueを全面的に捨てる必要はありません。ただし、現在の「P50/P95 calibration基盤、CI baseline再利用、tampering防止、atomic store」を一括で実装すると、個人趣味開発としては基盤コストが高く、既存workflowを止める新しい故障点を増やします。

    最も有用な形は次です。

    verdict: REQUEST_CHANGES
    implementation_ready: false
    recommended_scope: local_advisory_raise_only
    required_before_implementation:
      - immutable_history_snapshot
      - timeout_censoring_backoff
      - explicit_raise_only_precedence
      - local_only_storage_decision
      - consumer_snapshot_wiring
      - non_blocking_degradation
      - scaled_runtime_integration

    推奨は #2254 を「local adaptive timeout cache」に狭めて全面改訂することです。
    その改訂を行わないなら、現在のtrusted static policyを維持して not planned にする方が、現行契約のまま複雑なhistory基盤を実装するより品質・有用性ともに上です。

  11. squne121 commented on Aug 28, 2026

    @squne121
    OwnerAuthor

    issue-refinement-loop 終了報告(Issue #2254)

    結果: approved

    anchor comment(OWNER, https://github.com/squne121/loop-protocol/issues/2254#issuecomment-5456836854)の REQUEST_CHANGES を反映し、3 iteration で本文を全面改訂した。

    • iteration 1: codebase-investigator による調査 + issue-reviewer レビュー → VERDICT: needs-fix(P0×4: mutable history と plan_digest 決定性の衝突 / timeout censoring / static_policy と history の優先順位未定義 / local-CI スコープ未確定。P1×5も検出)
    • rewrite 1: issue-editor が本文を全面改訂(immutable snapshot 方式・timeout right-censored lower-bound・raise-only precedence・execution key 分離・nearest_rank_v1 percentile契約・AC8簡略化・重複カウント防止を反映)
    • iteration 2: 再レビュー → VERDICT: needs-fix(残 blocker 1件: AC9 の VC が既存17テストファイルへの -k フィルタで pytest exit 5 hard-block になっていた)
    • rewrite 2: AC9 の VC を未作成の専用テストファイル参照に修正(pytest exit 4 = expected baseline fail に是正、control-plane が独立実行で確認済み)
    • iteration 3: 再レビュー → VERDICT: APPROVE(blocking issue 0件、non-blocking advisory 1件のみ)

    Final Gate: CONTRACT_REVIEW_RESULT_V1.status: go(execute mode, all_checks_pass, readiness_status: go, vc_preflight_status: pass)

    LOOP_HANDOFF_RESULT_V1:
      status: impl_ready
      routing_action: run_impl_review_loop
      contract_review:
        status: go
        gate_result: fresh_go
        latest_comment_url: null
        generated_at: "2026-08-29T00:00:00Z"
        body_sha256: "sha256:600f659433053cda08e603d2a48917eaf86e0b0362a09e10d9846d9bd6028667"
      metadata:
        title_prefix_ready: true
  12. squne121 commented on Aug 28, 2026

    @squne121
    OwnerAuthor

    root-owned entry router audit

    route: invoke_impl_review_loop
    reason: fresh_review_go_live_equality

  13. squne121 commented on Aug 28, 2026

    @squne121
    OwnerAuthor

    root-owned entry router audit

    route: invoke_impl_review_loop
    reason: fresh_review_go_live_equality

  14. squne121 commented on Aug 28, 2026

    @squne121
    OwnerAuthor

    implement-issue: 実装完了 (2026-08-28T20:40:00Z)

    Verification Commands 結果(全 AC PASS)

    AC VC 結果
    AC1 pytest ... -k snapshot_determinism PASS (3件)
    AC2 pytest ... -k identity_separation PASS (5件)
    AC3 pytest ... -k nearest_rank PASS (6件)
    AC4 pytest ... -k raise_only_precedence PASS (5件)
    AC5 pytest ... -k timeout_censoring_backoff PASS (3件)
    AC6 pytest ... -k one_launch_one_sample PASS (3件)
    AC7 pytest ... -k atomic_concurrent_write PASS (2件)
    AC8 pytest ... -k non_blocking_degradation PASS (7件)
    AC9 pytest test_history_snapshot_production_wiring.py -v PASS (2件、runtime-verification: true)
    AC10 rg -n "ci_runtime_baseline_v1" vc-preflight.md PASS

    回帰確認: 既存 test_command_timeout_budget.py(15件)+ 新規回帰4件 = 19件 PASS。
    .claude/skills/issue-contract-review/scripts/tests/ 全体 421 passed, 1 skipped(無回帰)。
    .claude/skills/issue-contract-review/tests/ 全体 549 passed(無回帰)。
    run_root_review_pipeline.py 関連の issue-refinement-loop/tests 97 passed(無回帰)。
    ruff check: 変更ファイル全件 PASS。

    • 後続: PR レビュー(pr-review-judge)→ マージ → post-merge-cleanup
  15. self-assigned this
    on Aug 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

agent/implementerenhancementfollow-upphase/implementationtriage-required

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions