diff --git a/docs/guides/result-delivery.md b/docs/guides/result-delivery.md index 85cf5124a..2d13d3b50 100644 --- a/docs/guides/result-delivery.md +++ b/docs/guides/result-delivery.md @@ -148,7 +148,7 @@ remain null without accounting observations; elapsed wall time is insufficient. | Input | Authoritative facts | Deliberate gaps | | --- | --- | --- | | Native project / Benchmark | Plan, campaign, state, digest-bound observations/execution/evidence and retained code; labelled cached history if observations are lost | Cached history cannot verify delivery; summaries cannot substitute for final | -| Native service-reuse campaign | Plan version 3, state version 2, frozen protocol and retained final observation with labelled cached history if the observation is lost or conflicts | Delivery acceptance requires a separate digest-bound run and configuration | +| Native service-reuse campaign | Plan version 3, state version 2, frozen protocol and the retained final attempts | Delivery acceptance requires a separate digest-bound run and configuration | | Historical version 1 `summary.json` | Recorded final assessment and reported completion | No reconstructed rounds, independent final, binding or usage coverage | | Legacy run directory | `run.lock.json`, `status.json`, `evaluation.json`; paired single-experiment median | No invented iterative rounds/final or generalized L4 claim | | Apps `result.json` | Validated AppsResultV1, explicitly selected primary claim, fixed refs, all original claims | Operation success is not campaign completion; storage is not implicitly mounted/fetched | @@ -159,6 +159,11 @@ Arbitrary files named `result.json` or `summary.json` are not guessed into these contracts. Campaign-specific historical formats need explicit adapters; unsupported schemas fail instead of manufacturing facts. +Service-reuse bundles list each final in `final_attempts`, with its attempt ID, +candidate, revision, verdict and indexed assessment reference. The history marks +the current final. When an observation is missing or conflicts with state, that +row identifies its cached assessment and labels it unverified. + The no-fingerprint extension uses identical `best.binding` and `final.candidate_binding` objects in retained native records: diff --git a/docs/guides/service-reuse-campaigns.md b/docs/guides/service-reuse-campaigns.md index 0848b32ff..4bcbf1246 100644 --- a/docs/guides/service-reuse-campaigns.md +++ b/docs/guides/service-reuse-campaigns.md @@ -222,6 +222,35 @@ required warmup and measurement receipts for the selection and its reference runs under the applicable conditions, then collects performance and quality on its own service. +### Continue after an independent FAIL + +For an up-to-budget service-reuse campaign, add `--allow-final-continuation` +when starting the campaign to allow one explicit continuation. After a completed +independent FAIL with verified cleanup, `campaign status` reports +`can_continue: true` when the retained references are valid and a search round +and search time remain. If continuation is unavailable, read +`continuation_block_reason`. Use the failed final's `attempt_id` and submit a +committed candidate. + +```text +inferrsi campaign round --session --candidate \ + --hypothesis --continue-after-final \ + --continuation-reason +inferrsi campaign final --session --reason +``` + +The first continued round records the prior final and continuation reason in +the same locked admission that allocates the round. The original round cap, +deadline and final reserve apply. If admission is interrupted, use +`campaign recover` to settle the retained attempt under the usual cleanup +rules. An explicit retry of an inconclusive round uses its existing round slot. + +Status and the summary list each final attempt with its candidate, verdict and +observation path. The dashboard and result bundle identify the current final +alongside the history. The latest conclusive final is current. A later +INCONCLUSIVE or interrupted attempt leaves the preceding conclusive result +available with its own observation and previously published bundle. + ## Profiling a settled round Run `inferrsi campaign profile --session --round ` to diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index c6c241b2f..c241e6305 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -204,6 +204,10 @@ def _optimization_actions(stages, *, project=False): help="Adopt a candidate only when its declared mechanism is " "confirmed by measured breakdown/counters") 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", + ) else: start.add_argument("task") start.add_argument("--evaluation-args", required=True) @@ -253,6 +257,11 @@ def _optimization_actions(stages, *, project=False): help="Delivered path, path#item-ref, or CANNBot receipt; repeatable") stage.add_argument("--mechanism-file", type=Path, 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") + stage.add_argument("--continuation-reason", + help="Why search should continue after the failed final") if name == "final": stage.add_argument("--reason", help="Why the caller stopped an up-to-budget search") if name == "recover": diff --git a/src/inferrsi/apps/delivery/projection.py b/src/inferrsi/apps/delivery/projection.py index 95e32b2b8..9b6bf120b 100644 --- a/src/inferrsi/apps/delivery/projection.py +++ b/src/inferrsi/apps/delivery/projection.py @@ -198,6 +198,36 @@ def _binding(snapshot, selected, final, *, attempt_id, protocol_digest): ) +def _service_final_attempts(snapshot, result, state, state_ref): + history = [] + for index, attempt in enumerate(state["attempts"]): + if attempt.get("kind") != "final": + continue + observation, ref = snapshot.object(attempt["path"] + "/observation.json", "assessment") + retained = observation == attempt + if not retained: + gap(result, "CACHED_ASSESSMENT_UNVERIFIED", ref, + "The retained final is unavailable or differs from committed service state") + assessment_ref = ref if retained else state_ref + value = attempt.get("assessment") + verdict = value.get("verdict") if isinstance(value, dict) else None + history.append({ + "attempt_id": attempt["attempt_id"], + "candidate_id": attempt.get("candidate_id"), + "revision": attempt.get("revision"), + "verdict": verdict, + "assessment_ref": assessment_ref, + "assessment_provenance": { + "kind": "retained_observation" if retained else "cached_state", + "artifact_ref": assessment_ref, + "json_pointer": "/assessment" if retained else f"/attempts/{index}/assessment", + "verification": "verified" if retained else "unverified", + }, + "current": attempt == state.get("final"), + }) + return history + + def _service_reuse(snapshot, result, plan, state, campaign, *, plan_ref, state_ref): """Report the service controller's retained assessment without re-running it.""" settings = plan.get("evaluation_settings") @@ -211,6 +241,7 @@ def _service_reuse(snapshot, result, plan, state, campaign, *, plan_ref, state_r or state.get("protocol_id") != protocol_id or campaign.get("protocol_id") != protocol_id or campaign.get("ranking_policy") != plan.get("ranking_policy") or campaign.get("diagnosis_required", False) != plan.get("diagnosis_required", False) + or campaign.get("allow_final_continuation") != plan.get("allow_final_continuation") ): raise ValueError("Incompatible service campaign records") protocol, protocol_ref = snapshot.object("frozen/evaluation.json", "protocol", required=True) @@ -238,30 +269,22 @@ def _service_reuse(snapshot, result, plan, state, campaign, *, plan_ref, state_r if state.get("state") in ("completed", "blocked"): result["export"]["kind"] = "final" final = state.get("final") + result["final_attempts"] = _service_final_attempts(snapshot, result, state, state_ref) if final is None: gap(result, "FINAL_NOT_RUN", "final_acceptance", "Independent final evaluation is absent") return - if (not isinstance(final, dict) or final.get("kind") != "final" - or final not in state["attempts"]): + current = next((item for item in result["final_attempts"] if item["current"]), None) + if current is None: raise ValueError("Service final is missing from committed attempts") - observation, ref = snapshot.object(final["path"] + "/observation.json", "assessment") - retained = observation == final - if not retained: - gap(result, "CACHED_ASSESSMENT_UNVERIFIED", ref, - "The retained final is unavailable or differs from committed service state") - assessment_ref = ref if retained else state_ref - value = final.get("assessment") - assessment(result, value, assessment_ref, scope="independent_final") - provenance = { - "kind": "retained_observation" if retained else "cached_state", - "artifact_ref": assessment_ref, - "json_pointer": "/assessment" if retained else "/final/assessment", - "verification": "verified" if retained else "unverified", - } if result["acceptance"]["status"] == "assessed" else None + assessment(result, final.get("assessment"), current["assessment_ref"], + scope="independent_final") + provenance = (current["assessment_provenance"] + if result["acceptance"]["status"] == "assessed" else None) result["acceptance"]["assessment_provenance"] = provenance result["final"] = { - "attempt_id": final.get("attempt_id"), "revision": final.get("revision"), - "protocol_ref": protocol_ref, "assessment_ref": assessment_ref, + "attempt_id": current["attempt_id"], "revision": current["revision"], + "candidate_id": current["candidate_id"], + "protocol_ref": protocol_ref, "assessment_ref": current["assessment_ref"], "assessment_provenance": provenance, "binding": {"verified": False, "kind": None}, } @@ -269,6 +292,7 @@ def _service_reuse(snapshot, result, plan, state, campaign, *, plan_ref, state_r "Delivery acceptance requires a digest-bound run and configuration") if (state.get("state") == "completed" and state.get("pending") is None and result["acceptance"]["verdict"] in ("PASS", "FAIL")): + retained = provenance["verification"] == "verified" result["completion"] = { "status": "completed", "reason": "Service controller recorded a completed independent final" if retained else diff --git a/src/inferrsi/apps/delivery/render.py b/src/inferrsi/apps/delivery/render.py index 1c85fefd5..163d770c4 100644 --- a/src/inferrsi/apps/delivery/render.py +++ b/src/inferrsi/apps/delivery/render.py @@ -169,6 +169,17 @@ 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": + sections.insert(3, ( + "Independent final attempts", + ["Attempt", "Candidate", "Revision", "Verdict", "Assessment", "Current result"], + [ + [row["attempt_id"], row["candidate_id"], row["revision"], row["verdict"], + row["assessment_provenance"], "Yes" if row["current"] else ""] + for row in final_attempts + ], + )) return sections diff --git a/src/inferrsi/apps/delivery/schema.py b/src/inferrsi/apps/delivery/schema.py index d172c2fe7..ce2158ea3 100644 --- a/src/inferrsi/apps/delivery/schema.py +++ b/src/inferrsi/apps/delivery/schema.py @@ -141,10 +141,11 @@ def validate_result(value): for key in ("baseline", "selected_candidate", "final"): if value[key] is not None and not isinstance(value[key], dict): raise ValueError("Invalid optional delivery object") - for key in ("sources", "gaps", "metrics", "checks", "rounds"): - if value[key] is None and key not in ("sources", "gaps"): + for key in ("sources", "gaps", "metrics", "checks", "rounds", "final_attempts"): + rows = value.get(key) + if rows is None and key not in ("sources", "gaps"): continue - if not isinstance(value[key], list) or any(not isinstance(row, dict) for row in value[key]): + if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows): raise ValueError("Invalid delivery collection") if value["completion"].get("status") not in ("completed", "incomplete"): raise ValueError("Invalid workflow completion") diff --git a/src/inferrsi/apps/views/optimization_chart.py b/src/inferrsi/apps/views/optimization_chart.py index 25181bf54..d4a76837b 100644 --- a/src/inferrsi/apps/views/optimization_chart.py +++ b/src/inferrsi/apps/views/optimization_chart.py @@ -17,6 +17,9 @@ def render_service(summary): + str(len(summary["accepted_attempt_ids"])) + "

", ] + current_final = summary.get("current_final_attempt_id") + if current_final: + chunks.insert(2, "

Current final attempt: " + escape(current_final) + "

") for attempt in summary["attempts"]: execution = attempt["execution"] profiling = attempt.get("profiling") @@ -57,7 +60,13 @@ def render_service(summary): ) + "" ) - chunks.append("
    ") + chunks.append("") + if attempt["kind"] == "final": + chunks.append( + "

    Candidate " + escape(attempt["candidate_id"]) + + " ยท Evidence " + escape(attempt["path"] + "/observation.json") + "

    " + ) + chunks.append("
      ") for stage in execution.get("steps", []): chunks.append( "
    • " diff --git a/src/inferrsi/harness/optimization.py b/src/inferrsi/harness/optimization.py index 31c0a4557..00611e55d 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/optimization.py @@ -110,6 +110,7 @@ def _control(root): or state.get("protocol_id") != manifest["protocol_id"] or manifest.get("diagnosis_required", False) != plan.get("diagnosis_required", False) + or manifest.get("allow_final_continuation") != plan.get("allow_final_continuation") ) ): raise ValueError("Incompatible service campaign records") @@ -1001,6 +1002,7 @@ def _service_initialize(root, plan): "protocol_id": state["protocol_id"], "diagnosis_required": plan.get("diagnosis_required", False), **({"ranking_policy": plan["ranking_policy"]} if "ranking_policy" in plan else {}), + **({"allow_final_continuation": True} if plan.get("allow_final_continuation") else {}), }, ) atomic_write_json(root / "state.json", state) @@ -1098,6 +1100,52 @@ def _service_deadline(state): return state["deadline"] + sum(entry["elapsed_seconds"] for entry in entries) +def _service_continuation_block_reason(root, plan, state, reference_reason, *, budget_time): + from . import service_evidence + + if plan.get("allow_final_continuation") is not True or plan["round_mode"] != "up_to": + return "continuation_not_enabled" + if state["pending"] is not None: + return "unresolved_attempt_or_pause" + if any(attempt.get("continuation") for attempt in state["attempts"]): + return "continuation_already_used" + final = state["final"] + if ( + state["state"] != "completed" + or final is None + or final["kind"] != "final" + or final["assessment"]["verdict"] != "FAIL" + or final["execution"].get("status") != "completed" + or final not in state["attempts"] + ): + return "completed_failed_final_required" + if not _service_cleanup_confirmed(state, final): + return "failed_final_cleanup_unverified" + if reference_reason is not None: + return reference_reason + if plan.get("diagnosis_required") and not _diagnosis(state): + return "missing_bottleneck_diagnosis" + if len(state["rounds"]) >= plan["round_limit"]: + return "round_budget_exhausted" + if budget_time >= _service_deadline(state) - plan["final_reserve_seconds"]: + return "search_time_exhausted" + return service_evidence.settlement_reason(root, plan, state, final) + + +def _service_final_attempts(state): + return [ + { + "attempt_id": attempt["attempt_id"], + "candidate_id": attempt["candidate_id"], + "revision": attempt["revision"], + "verdict": attempt["assessment"]["verdict"], + "reason": attempt["assessment"]["reason"], + "observation": attempt["path"] + "/observation.json", + } + for attempt in state["attempts"] if attempt["kind"] == "final" + ] + + def _service_selected_evidence_reason(root, plan, state, *, starting_epoch=False): from . import service_evidence @@ -1113,7 +1161,7 @@ def _service_selected_evidence_reason(root, plan, state, *, starting_epoch=False ) -def _service_final_reason(root, plan, state, *, budget_time=None): +def _service_final_reference_reason(root, plan, state): if not _service_runtime_matches(plan): return "runtime_version_mismatch" if state["requires_current_conditions_acceptance"] or ( @@ -1125,9 +1173,12 @@ def _service_final_reason(root, plan, state, *, budget_time=None): ) ): return "missing_current_conditions_acceptance" - reason = _service_selected_evidence_reason(root, plan, state) - if reason: - return reason + return _service_selected_evidence_reason(root, plan, state) + + +def _service_final_reason(plan, state, reference_reason, *, budget_time=None): + if reference_reason is not None: + return reference_reason if state["pending"] is not None or state["state"] != "active": return "unresolved_attempt_or_pause" completed = sum(item["terminal"] for item in state["rounds"]) @@ -1141,9 +1192,16 @@ def _service_final_reason(root, plan, state, *, budget_time=None): def _service_status(root, plan, state): from . import service_observations - reason = _service_final_reason(root, plan, state) - remaining = max(0, _service_deadline(state) - time.time()) - if state["state"] == "completed" and not state["pending"]: + reference_reason = _service_final_reference_reason(root, plan, state) + now = time.time() + reason = _service_final_reason(plan, state, reference_reason, budget_time=now) + continuation_reason = _service_continuation_block_reason( + root, plan, state, reference_reason, budget_time=now, + ) + remaining = max(0, _service_deadline(state) - now) + if continuation_reason is None: + next_action = "continue_search_after_failed_final" + elif state["state"] == "completed" and not state["pending"]: next_action = "completed" elif reason == "runtime_version_mismatch": next_action = "use_recorded_runtime_version" @@ -1164,6 +1222,7 @@ def _service_status(root, plan, state): next_action = "independently_retest_selected_candidate_with_final" else: next_action = "edit_candidate_and_submit_round" + finals = _service_final_attempts(state) latest = [_service_round_view(root, attempt) for attempt in state["attempts"][-1:]] state = service_observations.selection_view(state, latest) return { @@ -1173,6 +1232,8 @@ def _service_status(root, plan, state): "next_action": next_action, "recorded_runtime_version": plan.get("runtime_version"), "can_finalize": reason is None, + "can_continue": continuation_reason is None, + "continuation_block_reason": continuation_reason, "final_block_reason": reason, "completed_rounds": sum(item["terminal"] for item in state["rounds"]), "allocated_rounds": len(state["rounds"]), @@ -1189,6 +1250,7 @@ def _service_status(root, plan, state): "accepted_attempt_ids": state["accepted_attempt_ids"], "stagnation": state["stagnation"], "final": state["final"], + "final_attempts": finals, "latest_observation": state["attempts"][-1] if state["attempts"] else None, "diagnosis": _diagnosis(state), "summary": str(root / "summary.json"), @@ -1202,7 +1264,10 @@ def _service_summary(root, plan, state, *, attempts=None, budget_time=None): attempts = [_service_round_view(root, attempt) for attempt in state["attempts"]] reason = ( None if state["state"] == "completed" - else _service_final_reason(root, plan, state, budget_time=budget_time) + else _service_final_reason( + plan, state, _service_final_reference_reason(root, plan, state), + budget_time=budget_time, + ) ) state = service_observations.selection_view(state, attempts) return { @@ -1216,6 +1281,8 @@ def _service_summary(root, plan, state, *, attempts=None, budget_time=None): "selected_candidate": state["best"], "selection": plan["selection"], "final_assessment": state["final"]["assessment"] if state["final"] else None, + "current_final_attempt_id": state["final"]["attempt_id"] if state["final"] else None, + "final_attempts": _service_final_attempts(state), "final_block_reason": reason, "optimization_speedup": None, "reference_epoch": state["reference_epoch"], @@ -1372,8 +1439,15 @@ def _service_settle(root, plan, state, pending, execution): if policy["action"] == "pause": state["state"] = "paused" elif kind == "final": - state["final"] = record - state["stop_reason"] = record["hypothesis"] + # A later inconclusive attempt stays in history without superseding a conclusive final. + previous = state["final"] + if ( + verdict != "INCONCLUSIVE" + or previous is None + or previous["assessment"]["verdict"] == "INCONCLUSIVE" + ): + state["final"] = record + state["stop_reason"] = record["hypothesis"] if verdict != "INCONCLUSIVE": state["state"] = "completed" elif not record.get("admission_failure"): @@ -1542,6 +1616,26 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non plan, state = _load(root, read_only=action == "status") ranking_policy = resolve_frozen_ranking(plan, ranking_policy_for, read_only=action == "status") + after_final = getattr(args, "continue_after_final", None) + continuation_reason = getattr(args, "continuation_reason", None) + continuation = None + if after_final is not None or continuation_reason is not None: + if ( + action != "round" or not after_final or not (continuation_reason or "").strip() + or any(getattr(args, name, None) is not None for name in ( + "retry_of", "repair_reason", "repair_protocol", "cleanup_receipt", + )) + ): + raise ValueError("Continuation requires a failed final ID and a separate reason") + reason = _service_continuation_block_reason( + root, plan, state, _service_final_reference_reason(root, plan, state), + budget_time=time.time(), + ) + if reason is not None: + raise ValueError(f"Cannot continue campaign ({reason})") + if after_final != state["final"]["attempt_id"]: + raise ValueError("Continuation must name the current failed final") + continuation = {"after_final": after_final, "reason": continuation_reason.strip()} if getattr(args, "cleanup_receipt", None) is not None: _service_cleanup_receipt(root, state, args.cleanup_receipt) if action == "status": @@ -1692,7 +1786,7 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non raise ValueError( "Investigate and explicitly retry or resume before launching more work" ) - if state["pending"] is not None or state["state"] == "completed": + if state["pending"] is not None or (state["state"] == "completed" and continuation is None): raise ValueError("Campaign completed or attempt unresolved") reserve = 0 if action == "final" else plan["final_reserve_seconds"] if time.time() >= _service_deadline(state) - reserve: @@ -1713,18 +1807,20 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non source, commit = root / plan["baseline_path"], plan["baseline_revision"] candidate_id, number = "baseline", None elif kind == "round": - if initial is None or parent is None: - raise ValueError("Complete baseline and compatible reference refresh first") - reason = _service_selected_evidence_reason( - root, plan, state, starting_epoch=state["requires_current_conditions_acceptance"] - ) - if reason: - raise ValueError(f"Cannot establish selected parent: {reason}") - if ( - initial["conditions"] != state["conditions"] - or parent["conditions"] != state["conditions"] - ): - raise ValueError("Refresh both incompatible performance references first") + if continuation is None: + if initial is None or parent is None: + raise ValueError("Complete baseline and compatible reference refresh first") + reason = _service_selected_evidence_reason( + root, plan, state, + starting_epoch=state["requires_current_conditions_acceptance"], + ) + if reason: + raise ValueError(f"Cannot establish selected parent: {reason}") + if ( + initial["conditions"] != state["conditions"] + or parent["conditions"] != state["conditions"] + ): + raise ValueError("Refresh both incompatible performance references first") diagnosis = _diagnosis_reference(plan, state) number = old["round_number"] if old else len(state["rounds"]) + 1 if number > plan["round_limit"] or not args.hypothesis.strip(): @@ -1762,7 +1858,9 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non else: if plan["round_mode"] == "up_to" and not (args.reason or "").strip(): raise ValueError("Record why search stopped") - admission = _service_final_reason(root, plan, state) + admission = _service_final_reason( + plan, state, _service_final_reference_reason(root, plan, state), + ) selected = state["best"] source = ( service.safe_path(root, selected["path"]) @@ -1832,6 +1930,9 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non pending.update(refresh_initial=initial, refresh_parent=parent) if kind == "round": pending.update(diagnosis) + if continuation is not None: + pending["continuation"] = continuation + state["state"] = "active" state["pending"] = pending atomic_write_json(root / "state.json", state) try: diff --git a/src/inferrsi/harness/optimization_session.py b/src/inferrsi/harness/optimization_session.py index 8a522793a..5cab96bf7 100644 --- a/src/inferrsi/harness/optimization_session.py +++ b/src/inferrsi/harness/optimization_session.py @@ -162,6 +162,11 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None if (external_knowledge and args.project_task and args.evaluation_mode == "service_reuse"): raise ValueError("External round knowledge requires a benchmark or AB/BA campaign") + allow_continuation = getattr(args, "allow_final_continuation", False) + if allow_continuation and ( + args.evaluation_mode != "service_reuse" or args.round_mode != "up_to" + ): + raise ValueError("Final continuation requires an up-to-budget service-reuse campaign") if args.project_task: names = ( "metric_key", @@ -203,6 +208,7 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None "evaluation_timeout_seconds": args.evaluation_timeout_seconds, "evaluation_prefix": evaluation_prefix, "python": args.python, + **({"allow_final_continuation": True} if allow_continuation else {}), **settings, } result = optimization.initialize(root, plan) @@ -330,6 +336,8 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None or getattr(args, "repair_reason", None) or getattr(args, "cleanup_receipt", None) or getattr(args, "repair_protocol", None) + or getattr(args, "continue_after_final", None) is not None + or getattr(args, "continuation_reason", None) is not None ): raise ValueError("Service lifecycle/retry operations require a service-reuse campaign") if plan["runtime_identity"] != _runtime_identity(): diff --git a/src/inferrsi/harness/service_evidence.py b/src/inferrsi/harness/service_evidence.py index 0e771584a..aa2233a0a 100644 --- a/src/inferrsi/harness/service_evidence.py +++ b/src/inferrsi/harness/service_evidence.py @@ -73,6 +73,18 @@ def receipt(stage): return doc precheck = service.read(service.safe_path(directory, "execution/precheck/result.json")) + if assessed["reason"] == "functional_check_rejected": + status = precheck.get("status") + rejected = status == "candidate_failure" or ( + status == "completed" and precheck.get("passed") is False + ) + retained = next( + (step.get("result") for step in execution["steps"] if step["id"] == "precheck"), + None, + ) + if not rejected or retained != precheck or assessed["verdict"] != "FAIL": + return "unverifiable_evaluation_evidence" + return None owner = service.read(service.safe_path(directory, "service/owner.json")) ready = receipt("ready") if ( @@ -214,13 +226,11 @@ def settlement_reason(root, plan, state, record): assessed = record["assessment"] if kind not in ("baseline", "round", "final") or assessed["verdict"] not in ("PASS", "FAIL"): return None - if assessed["reason"] == "functional_check_rejected": - if kind != "final": - return None - else: - reason = evaluation_reason(root, plan, record) - if reason: - return reason + if assessed["reason"] == "functional_check_rejected" and kind != "final": + return None + reason = evaluation_reason(root, plan, record) + if reason: + return reason if kind == "baseline": return None selected = state["best"] if kind == "final" else None diff --git a/tests/apps/test_optimization_session.py b/tests/apps/test_optimization_session.py index 28ad3d225..30557fdae 100644 --- a/tests/apps/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -593,6 +593,8 @@ def stop_after_assessor_spawn(root, attempt, plan, execution): def test_interrupted_final_requires_an_explicit_retry(session, capsys, monkeypatch): + from inferrsi.apps.delivery import read_bundle + for factor in (2, 3, 4): submit(session, factor, capsys) @@ -619,7 +621,14 @@ def stop(*args): assert view["can_finalize"] and view["next_action"].endswith("with_final") assert (session / "calls.log").read_text().splitlines() == ["2", "3", "4"] assert main([*command, "final", *target]) == 0 - assert json.loads(capsys.readouterr().out)["state"] == "completed" + view = json.loads(capsys.readouterr().out) + assert view["state"] == "completed" + assert view["delivery"]["status"] == "published", view["delivery"] + delivery = read_bundle(Path(view["delivery"]["output"])) + interrupted, = delivery["final_attempts"] + assert interrupted["status"] == "interrupted" + assert interrupted["recovery_ref"] == f"source:{attempt['recovery']['path']}" + assert delivery["completion"]["status"] == "completed" state = json.loads((session / "state.json").read_bytes()) assert state["final_attempts"] == [attempt] and state["final"]["path"] != attempt["path"] assert (session / "calls.log").read_text().splitlines() == ["2", "3", "4", "4"] diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index 1c99f94fe..d426601ee 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -4,6 +4,7 @@ import json import shutil import subprocess +import sys import time from pathlib import Path from types import SimpleNamespace @@ -122,6 +123,228 @@ def test_one_service_order_and_independent_final_ignores_workspace(campaign): assert report["acceptance"]["delivery_accepted"] is False +def _failed_final(campaign, *, opt_in=True, functional_failure=False): + if opt_in: + campaign["start"].append("--allow-final-continuation") + begin(campaign) + round_result = submit(campaign, version="first-selection", a=90, final_a=100, + final_functional_failure=functional_failure) + assert round_result["latest_observation"]["assessment"]["verdict"] == "PASS" + result = call(campaign, "final", "--reason", "Confirm the selected revision") + assert result["state"] == "completed" + assert result["final"]["assessment"]["verdict"] == "FAIL" + assert result["delivery"]["status"] == "published" + return result + + +def _continue_args(campaign, failed): + return [ + "campaign", "round", "--session", str(campaign["root"]), + "--candidate", str(campaign["repo"]), "--hypothesis", "Improve objective A", + "--continue-after-final", failed["attempt_id"], + "--continuation-reason", "Use the remaining search budget", + ] + + +@pytest.mark.parametrize("second_verdict", ["PASS", "INCONCLUSIVE"]) +def test_continue_after_failed_final_retains_each_final(campaign, second_verdict): + from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard + + first_result = _failed_final(campaign) + first = first_result["final"] + root = campaign["root"] + first_receipt = root / first["path"] / "observation.json" + original_bytes = first_receipt.read_bytes() + original_export = Path(first_result["delivery"]["output"]) + plan = (root / "plan.json").read_bytes() + deadline = project_service.read(root / "state.json")["deadline"] + assert first_result["can_continue"] is True + assert first_result["next_action"] == "continue_search_after_failed_final" + + commit(campaign["repo"], version="second-selection", a=80, + final_quality_missing=second_verdict == "INCONCLUSIVE") + args = _continue_args(campaign, first) + proc = subprocess.run( + [sys.executable, "-m", "inferrsi", *args], + cwd=Path(optimization.__file__).resolve().parents[2], + check=True, capture_output=True, text=True, timeout=30, + ) + resumed = json.loads(proc.stdout) + assert resumed["state"] == "active" + assert resumed["allocated_rounds"] == first_result["allocated_rounds"] + 1 + assert resumed["final"]["attempt_id"] == first["attempt_id"] + assert resumed["latest_observation"]["continuation"] == { + "after_final": first["attempt_id"], "reason": "Use the remaining search budget", + } + + result = call(campaign, "final", "--reason", "Confirm the new selection", + expected=0 if second_verdict == "PASS" else 2) + second = result["latest_observation"] + assert second["kind"] == "final" + assert second["assessment"]["verdict"] == second_verdict + selected = second if second_verdict == "PASS" else first + assert second["revision"] != first["revision"] + assert result["final"]["attempt_id"] == selected["attempt_id"] + assert result["can_continue"] is False + assert (root / "plan.json").read_bytes() == plan + assert project_service.read(root / "state.json")["deadline"] == deadline + assert first_receipt.read_bytes() == original_bytes + + status = call(campaign, "status", expected=0 if second_verdict == "PASS" else 2) + summary = project_service.read(root / "summary.json") + dashboard = dashboard_snapshot(root) + history = status["final_attempts"] + for document in (summary, dashboard["data"]["service_optimization"]): + assert document["final_attempts"] == history + assert document["current_final_attempt_id"] == selected["attempt_id"] + rendered = render_dashboard(dashboard) + assert [row["verdict"] for row in history] == ["FAIL", second_verdict] + for row in history: + assert row["observation"] in rendered and (root / row["observation"]).is_file() + + assert read_bundle(original_export)["acceptance"]["verdict"] == "FAIL" + assert result["delivery"]["status"] == "published" + output = Path(result["delivery"]["output"]) + delivery = read_bundle(output) + assert delivery["acceptance"]["verdict"] == selected["assessment"]["verdict"] + assert delivery["acceptance"]["delivery_accepted"] is False + assert delivery["final"]["attempt_id"] == selected["attempt_id"] + assert [row["verdict"] for row in delivery["final_attempts"]] == ["FAIL", second_verdict] + assert sum(row["current"] for row in delivery["final_attempts"]) == 1 + index = json.loads((output / "artifacts.json").read_text(encoding="utf-8")) + indexed = {entry["id"] for entry in index["artifacts"]} + for row in delivery["final_attempts"]: + assert row["assessment_ref"] in indexed + assert row["assessment_provenance"]["verification"] == "verified" + for report in ("report.md", "report.html"): + assert row["attempt_id"] in (output / report).read_text(encoding="utf-8") + + if second_verdict == "PASS": + try: + first_receipt.write_text("{}", encoding="utf-8") + _, projected, _ = project(root, export_id="service-history-mismatch") + finally: + first_receipt.write_bytes(original_bytes) + first_row, second_row = projected["final_attempts"] + assert first_row["verdict"] == "FAIL" + assert first_row["assessment_provenance"]["kind"] == "cached_state" + assert first_row["assessment_provenance"]["verification"] == "unverified" + assert second_row["assessment_provenance"]["verification"] == "verified" + assert projected["acceptance"]["verdict"] == "PASS" + + +@pytest.mark.parametrize("barrier", ["disabled", "rounds", "time", "identity", "reason"]) +def test_continuation_admission_preserves_state_on_refusal(campaign, monkeypatch, barrier): + if barrier == "rounds": + campaign["start"][campaign["start"].index("--rounds") + 1] = "1" + failed = _failed_final(campaign, opt_in=barrier != "disabled")["final"] + root = campaign["root"] + state = project_service.read(root / "state.json") + if barrier == "time": + reserve = project_service.read(root / "plan.json")["final_reserve_seconds"] + now = optimization._service_deadline(state) - reserve + monkeypatch.setattr(optimization, "time", SimpleNamespace(time=lambda: now)) + args = _continue_args(campaign, failed) + if barrier == "identity": + args[args.index("--continue-after-final") + 1] = "different-attempt" + if barrier == "reason": + args[-1] = " " + directories = list(root.glob("rounds/*/attempt-*")) + assert rejected(args) == 2 + assert project_service.read(root / "state.json") == state + assert list(root.glob("rounds/*/attempt-*")) == directories + status = call(campaign, "status") + assert status["can_continue"] is (barrier in ("identity", "reason")) + + +@pytest.mark.parametrize("evidence", ["selected", "final", "functional_final"]) +def test_continuation_status_and_admission_share_evidence_preflight(campaign, evidence): + functional_failure = evidence == "functional_final" + first_result = _failed_final(campaign, functional_failure=functional_failure) + first = first_result["final"] + assert first_result["can_continue"] is True + if functional_failure: + assert first["assessment"]["reason"] == "functional_check_rejected" + root = campaign["root"] + state_path = root / "state.json" + before = state_path.read_bytes() + attempt = ( + (root / first_result["best"]["path"]).parent if evidence == "selected" + else root / first["path"] + ) + stage = "precheck" if functional_failure else "measure-001" + receipt = attempt / "execution" / stage / "result.json" + original = receipt.read_bytes() + commit(campaign["repo"], version="continue-with-valid-reference", a=80) + args = _continue_args(campaign, first) + round_directories = sorted(root.glob("rounds/*/attempt-*")) + + receipt.unlink() + try: + status = call(campaign, "status") + assert status["can_continue"] is False + assert status["next_action"] == "completed" + reason = status["continuation_block_reason"] + assert reason == "unverifiable_evaluation_evidence" + assert rejected(args) == 2 + assert reason in campaign["capsys"].readouterr().err + assert state_path.read_bytes() == before + assert sorted(root.glob("rounds/*/attempt-*")) == round_directories + finally: + receipt.write_bytes(original) + + status = call(campaign, "status") + assert status["can_continue"] is True + assert status["continuation_block_reason"] is None + assert main(args) == 0 + resumed = json.loads(campaign["capsys"].readouterr().out) + assert resumed["state"] == "active" + assert resumed["allocated_rounds"] == first_result["allocated_rounds"] + 1 + + +def test_interrupted_continuation_admission_does_not_charge_twice(campaign, monkeypatch): + class Interrupted(BaseException): + pass + + def interrupted(*args): + raise Interrupted + + first_result = _failed_final(campaign) + first = first_result["final"] + root = campaign["root"] + commit(campaign["repo"], version="continue-once", a=80) + args = _continue_args(campaign, first) + with monkeypatch.context() as patch: + patch.setattr(optimization, "_service_execute", interrupted) + with pytest.raises(Interrupted): + main(args) + state = project_service.read(root / "state.json") + pending = state["pending"] + assert pending["round_number"] == 2 + assert pending["continuation"]["after_final"] == first["attempt_id"] + assert not (root / pending["path"] / "request.json").exists() + assert rejected(args) == 2 + assert project_service.read(root / "state.json") == state + assert read_bundle(Path(first_result["delivery"]["output"]))["acceptance"]["verdict"] == "FAIL" + + cleanup = root.parent / "cleanup.json" + cleanup.write_text(json.dumps({ + "attempt_id": pending["attempt_id"], "observed_at": time.time(), + "reason": "Controller stopped before service launch", "cleanup_complete": True, + "services": [], + })) + recovered = call(campaign, "recover", "--cleanup-receipt", cleanup, expected=2) + assert recovered["pending"] is None + assert recovered["allocated_rounds"] == 2 + assert recovered["latest_observation"]["attempt_id"] == pending["attempt_id"] + assert recovered["latest_observation"]["assessment"]["verdict"] == "INCONCLUSIVE" + assert recovered["final"]["attempt_id"] == first["attempt_id"] + settled = project_service.read(root / "state.json") + assert settled["deadline"] == state["deadline"] + assert rejected(args) == 2 + assert project_service.read(root / "state.json") == settled + + @pytest.mark.parametrize("failure", ["failed", "missing", "empty"]) def test_profile_failure_preserves_acceptance_and_final_selection(campaign, failure): begin(campaign) diff --git a/tests/fixtures/service_reuse_protocol.py b/tests/fixtures/service_reuse_protocol.py index 35dc4a1d5..4c3cf3ca0 100644 --- a/tests/fixtures/service_reuse_protocol.py +++ b/tests/fixtures/service_reuse_protocol.py @@ -50,12 +50,14 @@ def do_GET(self): loaded_revision=request["revision"], ) elif stage in ("measure", "warmup", "screening"): + final = attempt.parent.name == "final" body["scenarios"] = { name: { "workload": "synthetic-" + name, "requests": 2, "successes": 2, - "latency": config[name], + "latency": config.get("final_" + name, config[name]) + if final else config[name], "units": {name: "ms"}, } for name in ("a", "b") @@ -73,7 +75,9 @@ def do_GET(self): ) if config.get("quality_rejected"): body = {"status": "candidate_failure", "binding": request} - if config.get("quality_missing"): + if config.get("quality_missing") or ( + config.get("final_quality_missing") and attempt.parent.name == "final" + ): del body["quality"] elif stage == "profile": if config.get("profile_mode") == "failed": @@ -108,8 +112,11 @@ def do_GET(self): server.serve_forever() server.server_close() elif phase == "precheck": + functional_failure = config.get("functional_failure") or ( + config.get("final_functional_failure") and attempt.parent.name == "final" + ) write( - result_path, {"status": "completed", "passed": not config.get("functional_failure", False)} + result_path, {"status": "completed", "passed": not functional_failure} ) else: if phase == "screening" and config.get("screen_error"):