diff --git a/docs/guides/optimization-workflow-unification.md b/docs/guides/optimization-workflow-unification.md index 850341470..329847afa 100644 --- a/docs/guides/optimization-workflow-unification.md +++ b/docs/guides/optimization-workflow-unification.md @@ -224,6 +224,21 @@ Python 调用者从 `inferrsi.harness.analyzer` 导入 `diagnosis_draft`,从 `inferrsi.harness.indexer` 导入 `resolve_frozen_ranking`。此前后者位于 `inferrsi.harness.optimization`。[组件接口与会话时序](../../src/inferrsi/harness/README.md#managed-session-interfaces) +### 独立验收失败后继续搜索 + +普通 AB/BA 项目可在 `campaign start --round-mode up_to` 时加上 +`--allow-final-continuation`。独立 `final` 完成并得出 `FAIL` 后,`campaign status` +会报告 `can_continue` 和 `current_final_attempt_id`。若仍有轮次和搜索时间,可提交一次显式续跑。 + +```bash +inferrsi campaign round --directory --candidate \ + --hypothesis '' --continue-after-final \ + --continuation-reason '' +``` + +续跑沿用原冻结协议、截止时间、轮次上限和 `final` 预留。状态、摘要、看板和导出保留 +每次独立 `final` 的证据。最近一次确定判定仍是当前结果,直至得到新的确定判定。 + ### 用 profile 解释改进(可选) 端到端时间会随时钟、温度和共享负载整体漂移,单凭数值很难区分真实改进与波动。测量脚本可以在结果 JSON 中额外输出同一步骤的分区域耗时和工作量计数,单位由脚本自定并在各步骤保持一致: diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index e6c98c4c7..321992427 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -206,7 +206,7 @@ def _optimization_actions(stages, *, project=False): start.add_argument("--round-mode", choices=("exact", "up_to"), default="up_to") start.add_argument( "--allow-final-continuation", action="store_true", - help="Allow one explicit continuation after a failed up-to-budget service final", + help="Allow one explicit continuation after a failed up-to-budget project final", ) else: start.add_argument("task") @@ -259,7 +259,7 @@ def _optimization_actions(stages, *, project=False): help="JSON mechanism with expected region/counter directions") if project: stage.add_argument("--continue-after-final", metavar="ATTEMPT_ID", - help="Reopen a service campaign after this failed final") + help="Reopen a project campaign after this failed final") stage.add_argument("--continuation-reason", help="Why search should continue after the failed final") if name == "final": diff --git a/src/inferrsi/apps/delivery/projection.py b/src/inferrsi/apps/delivery/projection.py index b82c8125d..227ad60a0 100644 --- a/src/inferrsi/apps/delivery/projection.py +++ b/src/inferrsi/apps/delivery/projection.py @@ -349,7 +349,8 @@ def iterative(snapshot, result): gap(result, "FROZEN_INPUTS_CHANGED", "final_acceptance", "Frozen file set changed") for context in state.get("contexts", []): snapshot.file(context["path"], "knowledge", context.get("sha256")) - best = state.get("best") + final = state.get("final") + best = (final or {}).get("selected_at_final", state.get("best")) baseline = snapshot.candidate(plan["baseline_path"], plan.get("baseline_sha256")) result["baseline"] = {**baseline, "configuration": plan.get("evaluation_settings")} selected = None @@ -365,17 +366,21 @@ def iterative(snapshot, result): "configuration": plan.get("evaluation_settings"), } rounds = state.get("rounds", []) - final = state.get("final") + keep_history = plan.get("allow_final_continuation") is True + final_records = state.get("final_attempts", ()) if keep_history else ([final] if final else []) + if keep_history: + result["final_attempts"] = [] parsed = [] final_value = None final_refs = [] final_candidate = None - final_observation = None final_assessment_verified = False + latest_final_complete = False + latest_final_verified = False result["rounds"], result["metrics"], result["checks"] = [], [], [] - records = [*rounds, *([final] if final else [])] + records = [*rounds, *final_records] for index, record in enumerate(records): - is_final = index == len(rounds) + is_final = index >= len(rounds) phase = "final" if is_final else "search" directory = record["path"] observation, ref = snapshot.object( @@ -391,13 +396,13 @@ def iterative(snapshot, result): # this fallback is never current verification. historical = observation if observation is not None else record assessment_ref = ref if observation is not None else state_ref + pointer = f"/rounds/{index}" + if is_final: + pointer = f"/final_attempts/{index - len(rounds)}" if keep_history else "/final" provenance = { "kind": "retained_observation" if observation is not None else "cached_state", "artifact_ref": assessment_ref, - "json_pointer": ( - "" if observation is not None else "/final" if is_final else f"/rounds/{index}" - ) - + "/assessment", + "json_pointer": ("" if observation is not None else pointer) + "/assessment", "verification": "verified" if observation is not None else "unverified", } value = historical.get("assessment") @@ -448,6 +453,27 @@ def iterative(snapshot, result): )] for name, expected in (value or {}).get("evidence_files", {}).items(): evidence_refs.append(snapshot.file(directory + "/" + name, "measurement", expected)) + if is_final: + latest_final_verified = observation is not None and value is not None + latest_final_complete = ( + value is not None + and value["status"] in ("completed", "candidate_failure") + and execution.get("status") in ("completed", "failed") + ) + if is_final and keep_history: + verdict = (value or {}).get("verdict") + result["final_attempts"].append({ + "attempt_id": directory.rsplit("/", 1)[-1], + "candidate_id": record.get("candidate_id"), + "candidate_fingerprint": record.get("candidate_sha256"), + "verdict": verdict, + "assessment_ref": assessment_ref, + "assessment_provenance": provenance, + "evidence_refs": evidence_refs, + "current": record == final and verdict in ("PASS", "FAIL"), + }) + if record != final: + continue usage_source = (record.get("observations") or {}).get("usage_source") usage_record = observation or {} if usage_source: @@ -476,8 +502,8 @@ def iterative(snapshot, result): ) if is_final: final_value, final_refs = value, [ref, *evidence_refs] - final_candidate, final_observation = candidate, historical - final_assessment_verified = observation is not None and value is not None + final_candidate = candidate + final_assessment_verified = latest_final_verified result["final"] = { "attempt_id": directory.rsplit("/", 1)[-1], "fingerprint": record.get("candidate_sha256"), @@ -530,7 +556,7 @@ def iterative(snapshot, result): "best_score": best_after.get("score"), } ) - for record in state.get("final_attempts", []): + for record in state.get("final_attempts", ()) if not keep_history else (): directory = record["path"] recovery = record["recovery"] result.setdefault("final_attempts", []).append({ @@ -561,6 +587,7 @@ def iterative(snapshot, result): result["export"]["kind"] = "final" if terminal else "progress" result["execution"] = { "namespace": "inferrsi.harness.optimization", + **({"evaluation_mode": "abba"} if keep_history else {}), "state": state.get("state"), "budget": { "max_seconds": plan.get("max_seconds"), @@ -582,20 +609,14 @@ def iterative(snapshot, result): if plan["round_mode"] == "exact" else 0 < len(rounds) <= plan["round_limit"] and bool(state.get("stop_reason")) ) - finished = ( - rounds_complete - and final_value is not None - and final_value.get("status") in ("completed", "candidate_failure") - and (final_observation.get("execution") or {}).get("status") in ("completed", "failed") - and state.get("pending") is None - ) + finished = rounds_complete and latest_final_complete and state.get("pending") is None result["completion"] = { "status": "completed" if finished else "incomplete", "reason": "Required search and independent final assessment completed" if finished else "Required rounds or independent final assessment are incomplete", } - if finished and not final_assessment_verified: + if finished and not latest_final_verified: result["completion"]["reason"] = ( "Required search and independent final assessment completed according to " "cached state; unverified against the retained final observation" diff --git a/src/inferrsi/apps/delivery/render.py b/src/inferrsi/apps/delivery/render.py index 163d770c4..4905d6035 100644 --- a/src/inferrsi/apps/delivery/render.py +++ b/src/inferrsi/apps/delivery/render.py @@ -170,12 +170,15 @@ def _sections(result): sections.insert(0, ("Benchmark metrics", ["Metric", "Value", "Coverage / source"], benchmark_metric_rows(result["benchmark_metrics"]))) final_attempts = result.get("final_attempts") - if final_attempts and result["execution"].get("evaluation_mode") == "service_reuse": + mode = result["execution"].get("evaluation_mode") + if final_attempts and mode in ("abba", "service_reuse"): sections.insert(3, ( "Independent final attempts", - ["Attempt", "Candidate", "Revision", "Verdict", "Assessment", "Current result"], + ["Attempt", "Candidate", "Revision" if mode == "service_reuse" else "Fingerprint", + "Verdict", "Assessment", "Current result"], [ - [row["attempt_id"], row["candidate_id"], row["revision"], row["verdict"], + [row["attempt_id"], row["candidate_id"], + row.get("revision", row.get("candidate_fingerprint")), row["verdict"], row["assessment_provenance"], "Yes" if row["current"] else ""] for row in final_attempts ], diff --git a/src/inferrsi/apps/views/dashboard_data.py b/src/inferrsi/apps/views/dashboard_data.py index 8922b33eb..3e277ba31 100644 --- a/src/inferrsi/apps/views/dashboard_data.py +++ b/src/inferrsi/apps/views/dashboard_data.py @@ -802,9 +802,19 @@ def _managed_dashboard(root: Path, campaign: dict) -> dict: displayed_summary["final_reference"] = ( file_ref(root, root / state["final"]["path"] / "observation.json", "final_assessment") if state["final"] else None) - if attempts := state.get("final_attempts"): + if "final_attempts" in summary: + displayed_summary["current_final_attempt_id"] = summary["current_final_attempt_id"] + displayed_summary["final_attempts"] = [ + {"attempt_id": attempt["attempt_id"], "candidate_id": attempt["candidate_id"], + "verdict": attempt["verdict"], + "evidence": file_ref(root, root / attempt["observation"], "final_assessment")} + for attempt in summary["final_attempts"] + ] + interrupted = [record["recovery"] for record in state.get("final_attempts", ()) + if "recovery" in record] + if interrupted: displayed_summary["interrupted_finals"] = [ - file_ref(root, root / record["recovery"]["path"], "recovery") for record in attempts + file_ref(root, root / record["path"], "recovery") for record in interrupted ] if gate := state.get("cleanup_unconfirmed"): displayed_summary["cleanup_unconfirmed"] = file_ref(root, root / gate["path"], "recovery") diff --git a/src/inferrsi/apps/views/optimization_chart.py b/src/inferrsi/apps/views/optimization_chart.py index d4a76837b..55cbaaeb2 100644 --- a/src/inferrsi/apps/views/optimization_chart.py +++ b/src/inferrsi/apps/views/optimization_chart.py @@ -93,9 +93,19 @@ def render_result(summary: dict) -> str: fields.append(f'Final {summary["selection"]["metric"]}: {score:.6g}') if reference.get("state") == "present": fields.append(f'Evidence: {reference["path"]} (SHA-256 {reference["sha256"]})') + history = [] + for row in summary.get("final_attempts", ()): + value = f'{row["attempt_id"]} · {row["candidate_id"]} · {row["verdict"]}' + if row["attempt_id"] == summary["current_final_attempt_id"]: + value += " · Current result" + if row["evidence"].get("state") == "present": + value += f' · {row["evidence"]["path"]}' + history.append(f"
  • {escape(value)}
  • ") + attempts = ("

    Independent final attempts

      " + "".join(history) + "
    " + if history else "") return (f'

    Independent final: ' f'{escape(verdict)}

    ' - + "".join(f'

    {escape(field)}

    ' for field in fields) + '
    ') + + "".join(f'

    {escape(field)}

    ' for field in fields) + attempts + '') def render_curve(summary: dict) -> str: diff --git a/src/inferrsi/harness/manager/_session.py b/src/inferrsi/harness/manager/_session.py index 88cf6326f..7b1a8793e 100644 --- a/src/inferrsi/harness/manager/_session.py +++ b/src/inferrsi/harness/manager/_session.py @@ -63,10 +63,8 @@ def run_session( and request.evaluation_mode == "service_reuse"): raise ValueError("External round knowledge requires a benchmark or AB/BA campaign") allow_continuation = getattr(request, "allow_final_continuation", False) - if allow_continuation and ( - request.evaluation_mode != "service_reuse" or request.round_mode != "up_to" - ): - raise ValueError("Final continuation requires an up-to-budget service-reuse campaign") + if allow_continuation and request.round_mode != "up_to": + raise ValueError("Final continuation requires an up-to-budget project campaign") if project: names = ( "metric_key", @@ -175,6 +173,8 @@ def run_session( "evaluation_timeout_seconds": request.evaluation_timeout_seconds, "evaluation_prefix": evaluation_prefix, "python": request.python, "runtime_identity": session_runtime_identity(), **candidate, **settings} + if allow_continuation: + plan["allow_final_continuation"] = True if external_knowledge: plan["external_knowledge"] = external_knowledge plan["external_knowledge_project"] = external_project @@ -239,8 +239,6 @@ def run_session( or getattr(request, "repair_reason", None) or getattr(request, "cleanup_receipt", None) or getattr(request, "repair_protocol", None) - or getattr(request, "continue_after_final", None) is not None - or getattr(request, "continuation_reason", None) is not None ): raise ValueError("Service lifecycle/retry operations require a service-reuse campaign") if plan["runtime_identity"] != session_runtime_identity(): @@ -306,4 +304,6 @@ def run_session( selection_reason=getattr(request, "selection_reason", None), knowledge_refs=getattr(request, "knowledge_ref", None), mechanism=mechanism, + continue_after_final=getattr(request, "continue_after_final", None), + continuation_reason=getattr(request, "continuation_reason", None), ) diff --git a/src/inferrsi/harness/manager/_state.py b/src/inferrsi/harness/manager/_state.py index 119ffac01..3c2401b66 100644 --- a/src/inferrsi/harness/manager/_state.py +++ b/src/inferrsi/harness/manager/_state.py @@ -3,6 +3,7 @@ import hashlib import json import math +import shutil import time import uuid from dataclasses import dataclass @@ -136,8 +137,10 @@ def _load(root, *, read_only=False): _check_context_diagnosis(plan, diagnoses, context, retained) indexer.check_context_ranking(plan, retained) contexts[context["path"]] = context - for record in [*state["rounds"], *state.get("final_attempts", ()), - *([state["final"]] if state["final"] else [])]: + finals = list(state.get("final_attempts", ())) + if state["final"] is not None and state["final"] not in finals: + finals.append(state["final"]) + for record in [*state["rounds"], *finals]: directory = root / record["path"] raw = (directory / "observation.json").read_bytes() if hashlib.sha256(raw).hexdigest() != record["observation_sha256"]: @@ -145,7 +148,7 @@ def _load(root, *, read_only=False): observation = json.loads(raw) if any(observation.get(key) != record.get(key) for key in ("candidate_id", "hypothesis", "strategy", "alternatives", - "selection_reason")): + "selection_reason", "continuation", "selected_at_final")): raise ValueError("Round submission differs from the retained observation") if any(observation.get(key) != record.get(key) for key in ("knowledge_refs", "contexts")): raise ValueError("Round knowledge attribution differs from the retained observation") @@ -219,16 +222,18 @@ def status(root: Path) -> dict: plan["round_mode"] == "up_to" or len(state["rounds"]) == plan["round_limit"] ) if len(state["rounds"]) == plan["round_limit"] or ( - state.get("final_attempts") and final_eligible + final_eligible and any(record["assessment"]["status"] == "interrupted" + for record in state.get("final_attempts", ())) ): next_action = "independently_retest_selected_candidate_with_final" - remaining = state["deadline"] - time.time() - search_remaining = remaining - plan["final_reserve_seconds"] - if search_remaining <= 0 and state["final"] is None: + now = time.time() + remaining = state["deadline"] - now + search_remaining = state["deadline"] - plan["final_reserve_seconds"] - now + if search_remaining <= 0 and state["state"] == "active": next_action = ("independently_retest_selected_candidate_with_final" if final_eligible else "search_budget_exhausted_incomplete_session") - if remaining <= 0 and state["final"] is None: + if remaining <= 0 and state["state"] == "active": next_action = "deadline_exhausted_incomplete_session" if state["pending"] is not None: next_action = "recover_existing_attempt_without_relaunch" @@ -237,6 +242,15 @@ def status(root: Path) -> dict: gate = state.get("cleanup_unconfirmed") if gate is not None: next_action = "confirm_interrupted_process_cleanup" + project_continuation = {} + if plan.get("task_source") == "project": + block = _ordinary_continuation_block_reason(root, plan, state, search_remaining) + project_continuation = {"can_continue": block is None, "continuation_block_reason": block} + if block is None: + next_action = "continue_search_after_failed_final" + history = _ordinary_final_history(state) if plan.get("allow_final_continuation") else ( + {"final_attempts": state["final_attempts"]} if state.get("final_attempts") else {} + ) return { "session": str(root), "state": state["state"], "next_action": next_action, "completed_rounds": len(state["rounds"]), "round_limit": plan["round_limit"], @@ -250,7 +264,7 @@ def status(root: Path) -> dict: "best": state["best"], "pending": state["pending"], **({"cleanup_unconfirmed": gate, "recovery_command": "recover --confirm-domain-empty"} if gate is not None else {}), - **({"final_attempts": state["final_attempts"]} if state.get("final_attempts") else {}), + **project_continuation, **history, **({"external_knowledge": plan["external_knowledge"]} if "external_knowledge" in plan else {}), "latest_observation": state["rounds"][-1] if state["rounds"] else None, @@ -266,6 +280,56 @@ def _active(state, *, reserve=0): raise ValueError("Optimization deadline exhausted, final evaluation is incomplete") +def _ordinary_continuation_block_reason(root, plan, state, search_remaining): + if (plan.get("task_source") != "project" or plan.get("allow_final_continuation") is not True + or plan["round_mode"] != "up_to"): + return "continuation_not_enabled" + if state["pending"] is not None or state.get("cleanup_unconfirmed") is not None: + return "unresolved_attempt_or_pause" + if any(record.get("continuation") for record in state["rounds"]): + return "continuation_already_used" + final = state["final"] + if (state["state"] != "completed" or final is None or final["kind"] != "final" + or final["assessment"]["status"] != "completed" + or final["assessment"]["verdict"] != "FAIL"): + return "completed_failed_final_required" + if len(state["rounds"]) >= plan["round_limit"]: + return "round_budget_exhausted" + if search_remaining <= 0: + return "search_time_exhausted" + observation = root / final["path"] / "observation.json" + if json.loads(observation.read_bytes()) != { + key: value for key, value in final.items() if key != "observation_sha256" + }: + return "failed_final_observation_mismatch" + execution = final["execution"] + steps = {f"launch-{step['id']}": step for step in execution["steps"]} + launches = attempt_recovery.scan(root, final["path"], receipt_present=True) + if (not steps or {launch["stage"] for launch in launches} != steps.keys() + or any(launch["observation"] != "recorded_empty" + or launch["record"]["pid"] != steps[launch["stage"]].get("pid") + or launch["record"].get("argv_sha256") != digest(steps[launch["stage"]]["argv"]) + for launch in launches)): + return "failed_final_cleanup_unverified" + return None + + +def _ordinary_final_history(state): + final = state["final"] + current = (Path(final["path"]).name + if final and final["assessment"]["verdict"] in ("PASS", "FAIL") else None) + return { + "current_final_attempt_id": current, + "final_attempts": [ + {"attempt_id": Path(record["path"]).name, "candidate_id": record["candidate_id"], + "candidate_sha256": record["candidate_sha256"], + "verdict": record["assessment"]["verdict"], "reason": record["assessment"]["reason"], + "observation": record["path"] + "/observation.json"} + for record in state.get("final_attempts", ()) + ], + } + + def _diagnosis(state): records = state.get("diagnoses", []) if records and records[-1]["reference_epoch"] == state.get("reference_epoch"): @@ -569,15 +633,17 @@ def _summary(root, plan, state): return _service_summary(root, plan, state) rounds = state["rounds"] final = state["final"] + selected = final.get("selected_at_final", state["best"]) if final else state["best"] return { "schema_version": 1, "task": plan["task"], "condition": plan["condition"], "state": state["state"], "planned_rounds": plan["round_limit"], - "completed_rounds": len(rounds), "selected_candidate": state["best"], + "completed_rounds": len(rounds), "selected_candidate": selected, "final_assessment": final["assessment"] if final else None, + **(_ordinary_final_history(state) if plan.get("allow_final_continuation") else {}), "optimization_speedup": ( 1.0 if final and final["assessment"]["status"] == "completed" and final["assessment"].get("score") is not None - and state["best"]["kind"] == "baseline" + and selected["kind"] == "baseline" else (final["assessment"].get("speedup") if final["assessment"].get("speedup") is not None else (final["assessment"]["score"] if plan["selection"]["metric"] == "speedup" @@ -702,7 +768,11 @@ def _settle(root, plan, state, pending, execution, assess): record["best_after"] = dict(state["best"]) state["rounds"].append(record) else: - state["final"] = record + if plan.get("allow_final_continuation"): + state.setdefault("final_attempts", []).append(record) + if (not plan.get("allow_final_continuation") or state["final"] is None + or assessment["verdict"] in ("PASS", "FAIL")): + state["final"] = record state["state"] = "completed" if assessment["status"] == "completed" else "blocked" if assessment["status"] == "infrastructure_failure": state["state"] = "blocked" @@ -728,10 +798,27 @@ def _publish_attempt(root, plan, state, record): def evaluate_round(root: Path, *, candidate: Path | None, hypothesis: str, usage: Path | None, execute, assess, final=False, reason=None, strategy=None, knowledge_refs=None, alternatives=None, selection_reason=None, - mechanism: dict | None = None) -> dict: + mechanism: dict | None = None, continue_after_final: str | None = None, + continuation_reason: str | None = None) -> dict: with _locked(root): plan, state = _load(root) - _active(state, reserve=0 if final else plan["final_reserve_seconds"]) + reserve = 0 if final else plan["final_reserve_seconds"] + deadline = state["deadline"] - reserve + continuation = None + if continue_after_final is not None or continuation_reason is not None: + if (final or not isinstance(continue_after_final, str) or not continue_after_final + or not isinstance(continuation_reason, str) or not continuation_reason.strip()): + raise ValueError("Continuation requires a failed final ID and a separate reason") + block = _ordinary_continuation_block_reason(root, plan, state, deadline - time.time()) + if block is not None: + raise ValueError(f"Cannot continue campaign ({block})") + if continue_after_final != Path(state["final"]["path"]).name: + raise ValueError("Continuation must name the current failed final") + continuation = { + "after_final": continue_after_final, "reason": continuation_reason.strip(), + } + else: + _active(state, reserve=reserve) count = len(state["rounds"]) if final and (not count or (plan["round_mode"] == "exact" and count != plan["round_limit"])): @@ -791,11 +878,20 @@ def evaluate_round(root: Path, *, candidate: Path | None, hypothesis: str, pending["alternatives"] = list(alternatives) if selection_reason is not None: pending["selection_reason"] = selection_reason + if continuation is not None: + if pending["started_at"] >= deadline: + shutil.rmtree(directory) + raise ValueError("Cannot continue campaign (search_time_exhausted)") + pending["continuation"] = continuation + state["state"] = "active" + state.pop("settled_at", None) + state.pop("stop_reason", None) state["pending"] = pending if final: state["stop_reason"] = reason or "fixed_round_budget_completed" + if plan.get("allow_final_continuation"): + pending["selected_at_final"] = dict(state["best"]) durable_write_json(root / "state.json", state) - deadline = state["deadline"] - (0 if final else plan["final_reserve_seconds"]) try: execution = execute(root, directory, plan, deadline) except (Exception, SystemExit) as error: diff --git a/tests/apps/test_project_final_continuation.py b/tests/apps/test_project_final_continuation.py new file mode 100644 index 000000000..0c20f5275 --- /dev/null +++ b/tests/apps/test_project_final_continuation.py @@ -0,0 +1,312 @@ +"""CPU checks for explicit continuation of an ordinary project campaign.""" + +import errno +import hashlib +import json +import subprocess +import sys +import time +from html import unescape +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from inferrsi.apps import delivery +from inferrsi.apps.cli import main +from inferrsi.apps.views.dashboard import dashboard_snapshot +from inferrsi.harness import executor +from inferrsi.harness.manager import _state, read_session_records +from tests.apps.test_project_optimization import project as project +from tests.apps.test_project_optimization import start, start_arguments, submit + + +def _args(project, action, *extra): + return ["campaign", action, "--directory", str(project[3]), *extra] + + +def _call(project, capsys, action, *args, expected=0): + assert main(_args(project, action, *args)) == expected + return json.loads(capsys.readouterr().out) + + +def _failed_final(project, capsys, *, opt_in=True, rounds=3, inconclusive=False): + protocol = project[1] + (protocol / "measure.py").write_text( + "import json, sys\nfrom pathlib import Path\n" + "source, result = map(Path, sys.argv[1:])\n" + "metric = json.loads((source / 'config.json').read_text())['metric']\n" + "if 'final' in result.parts and metric == 20:\n metric = 10\n" + + ("if 'final' in result.parts and metric == 30:\n metric = None\n" + if inconclusive else "") + + "result.write_text(json.dumps({'metric': metric}))\n", + encoding="utf-8", + ) + extra = ("--rounds", str(rounds)) + (("--allow-final-continuation",) if opt_in else ()) + start(project, capsys, extra=extra) + code, first_round = submit(project, capsys, 20) + assert code == 0 and first_round["latest_observation"]["assessment"]["verdict"] == "PASS" + status = _call(project, capsys, "final", "--reason", "Independently check first selection") + first = read_session_records(project[3])[1]["final"] + assert status["state"] == "completed" and first["assessment"]["verdict"] == "FAIL" + assert first["assessment"]["reason"] == "performance_gate_not_met" + return status, first + + +def _continuation_args(project, first, *, attempt_id=None, reason="Try another candidate"): + return _args(project, "round", "--candidate", str(project[0]), "--hypothesis", "Try new input", + "--continue-after-final", attempt_id or Path(first["path"]).name, + "--continuation-reason", reason) + + +def _next_candidate(project): + (project[0] / "config.json").write_text('{"metric":30}', encoding="utf-8") + + +@pytest.mark.parametrize("second_verdict", ["PASS", "INCONCLUSIVE"]) +def test_continuation_retains_current_final_and_evidence(project, capsys, second_verdict): + root = project[3] + status, first = _failed_final(project, capsys, inconclusive=second_verdict == "INCONCLUSIVE") + assert status["can_continue"] and status["next_action"] == "continue_search_after_failed_final" + assert status["continuation_block_reason"] is None + first_id = status["current_final_attempt_id"] + plan_bytes = (root / "plan.json").read_bytes() + deadline = read_session_records(root)[1]["deadline"] + first_receipt = root / first["path"] / "observation.json" + first_bytes = first_receipt.read_bytes() + first_bundle = Path(status["delivery"]["output"]) + + _next_candidate(project) + proc = subprocess.run([sys.executable, "-m", "inferrsi", *_continuation_args(project, first)], + check=True, capture_output=True, text=True, timeout=30) + resumed = json.loads(proc.stdout) + assert resumed["state"] == "active" and resumed["completed_rounds"] == 2 + assert resumed["current_final_attempt_id"] == first_id + assert resumed["latest_observation"]["continuation"] == { + "after_final": first_id, "reason": "Try another candidate", + } + assert resumed["best"]["candidate_id"] != first["candidate_id"] + _, progress, _ = delivery.project(root, export_id="continued-progress") + assert progress["final"]["attempt_id"] == first_id + assert progress["selected_candidate"]["candidate_id"] == first["candidate_id"] + assert progress["final"]["binding"]["verified"] is True + + result = _call(project, capsys, "final", "--reason", "Independently check second selection", + expected=0 if second_verdict == "PASS" else 2) + _, state, summary = read_session_records(root) + history = result["final_attempts"] + assert [item["verdict"] for item in history] == ["FAIL", second_verdict] + assert [item["candidate_id"] for item in history] == [ + first["candidate_id"], resumed["best"]["candidate_id"], + ] + current = history[1 if second_verdict == "PASS" else 0] + assert result["current_final_attempt_id"] == current["attempt_id"] + assert result["continuation_block_reason"] == "continuation_already_used" + assert summary["final_attempts"] == history and summary["final_assessment"] == state["final"][ + "assessment" + ] + assert json.loads((root / "summary.json").read_bytes())["final_attempts"] == history + assert state["deadline"] == deadline and (root / "plan.json").read_bytes() == plan_bytes + assert first_receipt.read_bytes() == first_bytes + + dashboard = dashboard_snapshot(root) + view = dashboard["data"]["optimization_session"] + assert view["current_final_attempt_id"] == current["attempt_id"] + assert [item["attempt_id"] for item in view["final_attempts"]] == [ + item["attempt_id"] for item in history + ] + for item in history: + assert item["observation"] in dashboard["chart"] + assert delivery.read_bundle(first_bundle)["acceptance"]["verdict"] == "FAIL" + + bundle = Path(result["delivery"]["output"]) + published = delivery.read_bundle(bundle) + assert published["acceptance"]["verdict"] == current["verdict"] + assert published["completion"]["status"] == ( + "completed" if second_verdict == "PASS" else "incomplete" + ) + assert published["final"]["attempt_id"] == current["attempt_id"] + assert published["final"]["binding"]["verified"] is True + rows = published["final_attempts"] + assert [item["verdict"] for item in rows] == ["FAIL", second_verdict] + assert [item["attempt_id"] for item in rows if item["current"]] == [current["attempt_id"]] + index = {item["id"]: item for item in json.loads((bundle / "artifacts.json").read_bytes())[ + "artifacts" + ]} + original = index[rows[0]["assessment_ref"]] + assert original["location"] == history[0]["observation"] + assert original["sha256"] == hashlib.sha256(first_bytes).hexdigest() + for row in rows: + assert row["assessment_provenance"]["verification"] == "verified" + assert all(ref in index for ref in row["evidence_refs"]) + for report in ("report.md", "report.html"): + assert row["attempt_id"] in unescape((bundle / report).read_text(encoding="utf-8")) + + +@pytest.mark.parametrize(("barrier", "message"), [ + ("disabled", "continuation_not_enabled"), + ("rounds", "round_budget_exhausted"), + ("time", "search_time_exhausted"), + ("cleanup", "failed_final_cleanup_unverified"), + ("cleanup_other_attempt", "failed_final_cleanup_unverified"), + ("identity", "Continuation must name the current failed final"), + ("reason", "Continuation requires a failed final ID and a separate reason"), +]) +def test_continuation_refusal_spends_no_round(project, capsys, monkeypatch, barrier, message): + root = project[3] + _, first = _failed_final(project, capsys, opt_in=barrier != "disabled", + rounds=1 if barrier == "rounds" else 3) + plan, state, _ = read_session_records(root) + path = root / first["path"] / "execution/launch-quality-candidate.json" + if barrier == "cleanup": + path.unlink() + elif barrier == "cleanup_other_attempt": + other = root / state["rounds"][0]["path"] / "execution" / path.name + path.write_bytes(other.read_bytes()) + elif barrier == "time": + now = state["deadline"] - plan["final_reserve_seconds"] + monkeypatch.setattr(_state, "time", SimpleNamespace(time=lambda: now)) + args = _continuation_args(project, first, + attempt_id="absent" if barrier == "identity" else None, + reason=" " if barrier == "reason" else "Try another candidate") + _next_candidate(project) + state_path = root / "state.json" + original = state_path.read_bytes() + round_paths = sorted(root.glob("rounds/*/attempt-*")) + with pytest.raises(SystemExit) as refusal: + main(args) + assert refusal.value.code == 2 and message in capsys.readouterr().err + assert state_path.read_bytes() == original + assert sorted(root.glob("rounds/*/attempt-*")) == round_paths + status = _call(project, capsys, "status") + assert status["continuation_block_reason"] == ( + None if barrier in ("identity", "reason") else message + ) + + +def test_continuation_start_requires_up_to_project(project, capsys): + with pytest.raises(SystemExit) as refusal: + main(start_arguments(project, mode="exact", extra=("--allow-final-continuation",))) + assert refusal.value.code == 2 + assert "up-to-budget project" in capsys.readouterr().err + assert not project[3].exists() + + +def test_continuation_rechecks_budget_after_retention(project, capsys, monkeypatch): + root = project[3] + _, first = _failed_final(project, capsys) + _next_candidate(project) + plan, state, _ = read_session_records(root) + cutoff = state["deadline"] - plan["final_reserve_seconds"] + clock = cutoff - 1 + retain = _state.candidates.retain + + def retain_until_cutoff(*args, **kwargs): + nonlocal clock + fingerprint = retain(*args, **kwargs) + clock = cutoff + return fingerprint + + def reject_execution(*args): + pytest.fail("Candidate reached the executor after the search cutoff") + + monkeypatch.setattr(_state, "time", SimpleNamespace(time=lambda: clock)) + monkeypatch.setattr(_state.candidates, "retain", retain_until_cutoff) + monkeypatch.setattr(executor, "execute_ordinary", reject_execution) + control = (root / "state.json").read_bytes() + attempts = sorted(root.glob("rounds/*/attempt-*")) + with pytest.raises(SystemExit) as refusal: + main(_continuation_args(project, first)) + assert refusal.value.code == 2 and "search_time_exhausted" in capsys.readouterr().err + assert (root / "state.json").read_bytes() == control + assert sorted(root.glob("rounds/*/attempt-*")) == attempts + status = _call(project, capsys, "status") + assert status["continuation_block_reason"] == "search_time_exhausted" + assert status["current_final_attempt_id"] == Path(first["path"]).name + + +@pytest.mark.skipif(sys.platform != "linux", reason="requires a Linux controller process") +def test_interrupted_admission_excludes_second_process_and_replay(project, capsys, tmp_path): + root = project[3] + first_status, first = _failed_final(project, capsys) + _next_candidate(project) + args = _continuation_args(project, first) + marker = tmp_path / "admitted" + driver = """ +import sys, time +from pathlib import Path +from inferrsi.apps.cli import main +from inferrsi.harness import executor +def hold_before_launch(*args): + Path(sys.argv[1]).touch() + time.sleep(60) + raise AssertionError('test must stop the controller before launch') +executor.execute_ordinary = hold_before_launch +sys.exit(main(sys.argv[2:])) +""" + state_path = root / "state.json" + with subprocess.Popen([sys.executable, "-c", driver, str(marker), *args]) as controller: + try: + stop_at = time.monotonic() + 15 + while not marker.is_file() and controller.poll() is None and time.monotonic() < stop_at: + time.sleep(0.02) + assert marker.is_file() and controller.poll() is None + before = state_path.read_bytes() + contender = subprocess.run([sys.executable, "-m", "inferrsi", *args], + capture_output=True, text=True, timeout=15) + assert contender.returncode == 2 + assert f"[Errno {errno.EAGAIN}]" in contender.stderr + assert state_path.read_bytes() == before + finally: + controller.kill() + controller.wait(timeout=10) + + admitted = json.loads(before) + pending = admitted["pending"] + assert pending["continuation"]["after_final"] == first_status["current_final_attempt_id"] + assert len(admitted["rounds"]) == 1 + assert not (root / pending["path"] / "execution").exists() + with pytest.raises(SystemExit) as replay: + main(args) + assert replay.value.code == 2 and "unresolved_attempt_or_pause" in capsys.readouterr().err + assert state_path.read_bytes() == before + assert delivery.read_bundle(Path(first_status["delivery"]["output"]))["acceptance"][ + "verdict" + ] == "FAIL" + + _call(project, capsys, "recover", expected=2) + recovered = _call(project, capsys, "recover", "--confirm-domain-empty") + assert recovered["completed_rounds"] == 2 and recovered["pending"] is None + assert recovered["latest_observation"]["path"] == pending["path"] + assert recovered["current_final_attempt_id"] == first_status["current_final_attempt_id"] + assert recovered["continuation_block_reason"] == "continuation_already_used" + assert json.loads(state_path.read_bytes())["deadline"] == admitted["deadline"] + settled = state_path.read_bytes() + with pytest.raises(SystemExit) as replay: + main(args) + assert replay.value.code == 2 and "continuation_already_used" in capsys.readouterr().err + assert state_path.read_bytes() == settled + assert not (root / pending["path"] / "execution").exists() + + +def test_interrupted_second_final_keeps_previous_binding(project, capsys, monkeypatch): + root = project[3] + _, first = _failed_final(project, capsys) + _next_candidate(project) + assert main(_continuation_args(project, first)) == 0 + capsys.readouterr() + + def interrupt(*_): + raise KeyboardInterrupt + + with monkeypatch.context() as patch: + patch.setattr(executor, "execute_ordinary", interrupt) + with pytest.raises(KeyboardInterrupt): + main(_args(project, "final", "--reason", "Independently recheck the new selection")) + _call(project, capsys, "recover", expected=2) + _call(project, capsys, "recover", "--confirm-domain-empty") + _, result, _ = delivery.project(root, export_id="interrupted-final") + assert result["completion"]["status"] == "incomplete" + assert result["final"]["attempt_id"] == Path(first["path"]).name + assert result["final"]["binding"]["verified"] is True + assert [row["verdict"] for row in result["final_attempts"]] == ["FAIL", "INCONCLUSIVE"]