From 149e09dae0ad72663419925479c170bebd46c34d Mon Sep 17 00:00:00 2001 From: amy-why-3459 <221522807+amy-why-3459@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:51:26 +0800 Subject: [PATCH 1/3] Require calibrated performance goals before freezing project campaigns Agent-assisted-by: Codex (Harness implementation, workflow integration and tests) Signed-off-by: amy-why-3459 <221522807+amy-why-3459@users.noreply.github.com> --- .../ISSUE_TEMPLATE/campaign-acceptance.yml | 4 +- AGENTS.md | 1 + docs/contributing.md | 5 + .../optimization-workflow-unification.md | 43 +++++- docs/guides/service-reuse-campaigns.md | 16 +- plugins/inferrsi/skills/inferrsi/SKILL.md | 7 + .../inferrsi/skills/inferrsi/SKILL.md | 7 + src/inferrsi/apps/cli/arguments.py | 5 + src/inferrsi/harness/optimization.py | 12 ++ src/inferrsi/harness/optimization_session.py | 29 +++- src/inferrsi/harness/project_objectives.py | 146 ++++++++++++++++++ src/inferrsi/harness/project_service.py | 32 ++-- .../test_engineering_benchmark_plugins.py | 2 + tests/apps/test_project_explanation.py | 7 +- tests/apps/test_project_optimization.py | 110 +++++++++++-- tests/apps/test_project_service_reuse.py | 23 +++ tests/fixtures/service_reuse.py | 21 +++ tests/fixtures/target_review.py | 43 ++++++ tests/harness/test_project_objectives.py | 41 +++++ 19 files changed, 513 insertions(+), 41 deletions(-) create mode 100644 src/inferrsi/harness/project_objectives.py create mode 100644 tests/fixtures/target_review.py diff --git a/.github/ISSUE_TEMPLATE/campaign-acceptance.yml b/.github/ISSUE_TEMPLATE/campaign-acceptance.yml index 8b9c70844..7d6dd6d5e 100644 --- a/.github/ISSUE_TEMPLATE/campaign-acceptance.yml +++ b/.github/ISSUE_TEMPLATE/campaign-acceptance.yml @@ -62,12 +62,12 @@ body: id: criteria_source attributes: label: Acceptance criteria source and derivation - description: Use user criteria when supplied; otherwise use performance-ceiling-analysis. Preserve partial requirements and identify derived fields and missing evidence. + description: Preserve supplied criteria. Review both supplied and derived performance goals against workload-matched baseline noise and attainable headroom using performance-ceiling-analysis. value: | Source: User request or accepted plan: Derived fields: - Analysis: + Target feasibility: Evidence gaps and next measurements: Freeze authority: validations: diff --git a/AGENTS.md b/AGENTS.md index f184c2637..f5ed63ad1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,6 +68,7 @@ Parameterized or manual acceptance runs are issue-scoped; they are not the defau ## RSI contract - **Resolve acceptance criteria** — preserve user-supplied criteria; when absent, use [performance-ceiling-analysis](src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/references/acceptance-criteria.md) to derive evidence-backed campaign targets. Retain partial requirements and derive only missing fields; unresolved evidence stays explicit. +- **Check performance target feasibility** — review supplied and derived gains against repeated baseline measurements and calibrated attainable performance for the same workload. New project campaigns require the [target review](docs/guides/optimization-workflow-unification.md#performance-target-review) before freezing. Preserve the requested goal and report missing evidence or an unsupported target. - **Freeze gates before search** — checklist and `validator/` locked in `plan/` before Phase 3 candidate experiments ([validation levels](docs/contributing.md#validation-levels)). - **One plane per campaign step** — change only the declared SIAS plane of the target system per step: `harness` | `model` | `infra`. These planes are not InferRSI packages. - **Emit RunSpec snapshots** — record repo × revision × backend × device × model × scenario (`contracts/runspec.py`, campaign `plan/`). diff --git a/docs/contributing.md b/docs/contributing.md index 044660495..f052d8bf6 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -133,6 +133,11 @@ Record any hardware, external service or historical run that was not verified. ## Acceptance checklist +Assess the feasibility of every new project performance target, including a value +supplied by the requester. Record the actual target, its origin, comparable baseline noise and +the attainable gain supported by calibration before freezing. See the +[mandatory project target review](guides/optimization-workflow-unification.md#performance-target-review). + Use user-provided acceptance criteria, including those in a referenced accepted plan. When none are supplied, use [performance-ceiling-analysis](../src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/references/acceptance-criteria.md) diff --git a/docs/guides/optimization-workflow-unification.md b/docs/guides/optimization-workflow-unification.md index 09d2465f9..483053367 100644 --- a/docs/guides/optimization-workflow-unification.md +++ b/docs/guides/optimization-workflow-unification.md @@ -173,16 +173,57 @@ Harness 没有常驻 Agent 驱动。Agent 逐次调用这些操作,代码在 ```bash inferrsi campaign start --directory \ --repo --include --include \ - --protocol --instructions \ + --protocol --instructions --target-review \ --measure-command '"{python}" "{protocol}/measure.py" --project "{candidate}" --result "{result}"' \ --quality-command '"{python}" "{protocol}/quality.py" --project "{candidate}" --reference "{baseline}" --result "{result}"' \ --metric-key --metric-unit --direction \ + --device-scope \ --quality-key --scope \ --min-improvement-pct --warmups --repetitions \ --rounds --round-mode up_to --max-minutes \ --evaluation-timeout-seconds --knowledge on ``` +#### Performance target review + +每个新项目在冻结前都要检查目标是否合理,包括用户明确给出的数值和准备实验时推导的数值。先按同一硬件、模型、请求、计时边界与质量约束运行基线多次,再根据同条件实测或经实测校准的关键路径估算,给出保守可达的端到端指标值。只测了单算子提速时,还要量出它在端到端关键路径上的占比。原始测量、假设和目标选择依据应可在引用的记录中复核。 + +目标声明与校准记录使用两个 JSON 文件。以下数值仅用于演示。命令行的目标、指标、单位、方向与声明必须一致。`review.json` 区分用户指定的门槛(`user`)和有依据的推导(`derived`)。 + +```json +{ + "calibration": "calibration.json", + "objectives": { + "latency": {"source": "derived", "target": 3, "target_reference": "Synthetic plan, latency section"} + } +} +``` + +`calibration.json` 由基线测量和可达性分析产生。路径相对于 `review.json`。以下示例的 `baseline_snapshot` 需要替换为测量时实际源码的标识。可用 `inferrsi.harness.candidates.identity(Path(repo), includes)` 获取,`includes` 与 `--include` 相同。`scope` 与 `device_scope` 分别对应 `--scope` 和 `--device-scope`。 + +```json +{ + "context": { + "baseline_snapshot": "", + "scope": "single-image latency after warmup", "device_scope": "two synthetic accelerators" + }, + "objectives": { + "latency": { + "metric": "latency", "unit": "s/image", "direction": "minimize", + "threshold_type": "relative_percent", "method": "calibrated_projection", + "baseline_samples": [50, 50.25, 50.5], "attainable_value": 47, + "calibration_evidence": "Synthetic trace T1 and matched component replay C1: removing 3.25 s of exposed work leaves 47 s at the median." + } + } +} +``` + +校准方法可选 `workload_measurement`(相同负载下的已知可达结果)或 `calibrated_projection`(用同负载实测校准的保守推算)。给出记录位置和假设。已达到的收益可以支持目标;更高的目标只说明当前证据不足以支持它。程序校验声明、来源匹配及算术,校准材料本身的真实性由实验记录和评审核实。 + +样本和可达值使用指标原单位。评估器根据指标方向,将基线最大值与最小值之差换算为观测波动,将基线中位数到可达值的变化换算为可达收益,两者与目标使用同一种改变量单位。观测波动用于准备实验,不提供置信区间。 + +缺少校准数据、目标高于可达收益、或正的观测波动大于等于目标时,启动失败且不会创建实验目录。零门槛只适用于观测波动为零且有正收益空间的情况。找不到合适目标时保留用户的原始要求,补齐证据或重新协商。通过时,启动输出和冻结计划保留 `target_review` 及每项目标的判断。实际收益和质量仍由 round 与独立 final 评估。 + `{candidate}` 在基线步骤指向留存基线,在候选步骤指向本轮快照;`{baseline}` 始终是基线。`{protocol}` 指向冻结协议,`{result}` 是本步骤输出文件。脚本需从这些路径读取项目和条件;已有 editable 安装、绝对导入或外部服务不会被自动改成候选版本。Agent 必须验证脚本确实测到指定版本。 项目适配器先检查基线和候选质量,再做 warmup 和交替顺序的基线/候选测量;每轮和 final 使用相同协议。每步骤启动新进程,因此跨进程 warmup 只能预热可持久缓存;设备/进程内 warmup 必须在测量脚本内完成并说明。性能取声明指标的中位数,当前没有通用服务生命周期管理器或统计显著性判定。 diff --git a/docs/guides/service-reuse-campaigns.md b/docs/guides/service-reuse-campaigns.md index 0848b32ff..eb134ceee 100644 --- a/docs/guides/service-reuse-campaigns.md +++ b/docs/guides/service-reuse-campaigns.md @@ -117,7 +117,7 @@ supply `--evaluation-config ` and omit the AB/BA single-metric, quality-command and sampling flags. Mixing both parameter sets is an error. ```text -inferrsi campaign start --evaluation-mode service_reuse --evaluation-config ... +inferrsi campaign start --evaluation-mode service_reuse --evaluation-config --target-review ... inferrsi campaign baseline --session inferrsi campaign diagnose --session --bottleneck --evidence inferrsi campaign knowledge --session --query --context-bytes @@ -198,7 +198,19 @@ retry is inferred. `resume --reason ` records an advisory-pause or explici abandonment decision; it does not make an incomplete attempt pass or satisfy an exact-round policy. -If conditions change, use `refresh-references --conditions --reason `. +A new service campaign requires the [performance target review](optimization-workflow-unification.md#performance-target-review). +Use `context.conditions` for the complete effective conditions and `context.baseline_revision` +for the baseline Git commit. Key each gain objective by its ID in both files and include +its scenario, aggregate, metric key, unit, direction and threshold type in calibration. +The target declaration carries its exact gain threshold. +Baseline samples and the attainable value use the metric's units and domain. The review +uses the configured mean or median and the same relative-percent, absolute or percentage-point +change as the evaluator. It records every decision. At least one gain objective must be +supported, matching the service's any-gain rule. All runtime regression guards still apply. + +If conditions change, supply a new review with +`refresh-references --conditions --target-review --reason `. +An explicit retry reuses the failed attempt's review. This requires room for a new candidate round; when the round budget is exhausted, the command rejects the refresh before changing conditions or starting a service. It measures the original baseline and comparison parent under the new conditions diff --git a/plugins/inferrsi/skills/inferrsi/SKILL.md b/plugins/inferrsi/skills/inferrsi/SKILL.md index d039ebeff..f8a0c3bd9 100644 --- a/plugins/inferrsi/skills/inferrsi/SKILL.md +++ b/plugins/inferrsi/skills/inferrsi/SKILL.md @@ -325,6 +325,13 @@ Reuse the user's benchmark and quality scripts, workload, accepted revisions, gates and budget. If they are missing, help prepare them and name the remaining inputs. Do not turn CLI defaults into accepted campaign criteria. +Before freezing any project performance goal, apply the performance-ceiling-analysis +procedure to evaluate the proposed target against comparable baseline variation +and calibrated end-to-end headroom. Preserve the source of each target. Pass the +calibration and rationale to `campaign start --target-review `; the Harness +computes the feasibility decision before freezing. Revisit unsupported goals or +collect missing evidence without silently relaxing a user requirement. + Use supplied acceptance criteria unchanged, including a referenced accepted plan. When none are supplied, read `inferrsi.common.skills.performance_ceiling_analysis` with `--material` through diff --git a/plugins/workswarm/inferrsi/skills/inferrsi/SKILL.md b/plugins/workswarm/inferrsi/skills/inferrsi/SKILL.md index 6ad0d78ab..95860355d 100644 --- a/plugins/workswarm/inferrsi/skills/inferrsi/SKILL.md +++ b/plugins/workswarm/inferrsi/skills/inferrsi/SKILL.md @@ -178,6 +178,13 @@ candidate within this workflow. ## Coordinate a comparison +Before freezing any project performance goal, apply the performance-ceiling-analysis +procedure to evaluate the proposed target against comparable baseline variation +and calibrated end-to-end headroom. Preserve the source of each target. Pass the +calibration and rationale to `campaign start --target-review `; the Harness +computes the feasibility decision before freezing. Revisit unsupported goals or +collect missing evidence without silently relaxing a user requirement. + Use supplied acceptance criteria unchanged, including a referenced accepted plan. When none are supplied, use the launcher to `read inferrsi.common.skills.performance_ceiling_analysis --material`, then load diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index a46b86171..f2a6b74f8 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -188,9 +188,12 @@ def _optimization_actions(stages, *, project=False): help="Project-relative input file/directory; repeat for dependencies") start.add_argument("--protocol", type=Path, required=True) start.add_argument("--instructions", type=Path, required=True) + start.add_argument("--target-review", type=Path, required=True, + help="JSON evidence for baseline noise and attainable gains") for name in ("measure-command", "quality-command", "metric-key", "metric-unit", "quality-key", "scope"): start.add_argument("--" + name) + start.add_argument("--device-scope", help="AB/BA calibration device model and topology") start.add_argument("--direction", choices=("minimize", "maximize")) start.add_argument("--min-improvement-pct", type=float) start.add_argument("--repetitions", type=int) @@ -269,6 +272,8 @@ def _optimization_actions(stages, *, project=False): ) if name == "refresh-references": stage.add_argument("--conditions", type=Path, required=True) + stage.add_argument("--target-review", type=Path, + help="Calibration for the new conditions") stage.add_argument("--reason", required=True) if name == "resume": stage.add_argument("--reason", required=True) diff --git a/src/inferrsi/harness/optimization.py b/src/inferrsi/harness/optimization.py index fbebf9d20..e86eac7e5 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/optimization.py @@ -1550,6 +1550,7 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non raise ValueError("Unknown service campaign action") initial, parent = state["initial_reference"], state["comparison_parent"] admission = None + refresh_review = None if kind == "baseline": if initial is not None: raise ValueError("Initial baseline is already measured") @@ -1591,6 +1592,11 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non raise ValueError("No changed conditions; reuse compatible retained references") if conditions["id"] == state["conditions"]["id"]: raise ValueError("Changed conditions require a new explicit ID") + if "target_review" in plan["evaluation_settings"]: + refresh_review = service.review_service_targets( + args.target_review, conditions, plan["baseline_revision"], + plan["evaluation_settings"]["objectives"], + ) state.update( conditions=conditions, reference_epoch=state["reference_epoch"] + 1, @@ -1600,6 +1606,10 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non state["stagnation"].update(consecutive=0, notified=False) elif conditions != old["conditions"]: raise ValueError("Reference retry must retain its declared conditions") + elif args.target_review: + raise ValueError("Reference retry reuses the retained target review") + else: + refresh_review = old.get("target_review") source, commit = root / plan["baseline_path"], plan["baseline_revision"] candidate_id, number = "reference-refresh", None else: @@ -1675,6 +1685,8 @@ 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 refresh_review is not None: + pending["target_review"] = refresh_review 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 111e592e1..f0a5700ae 100644 --- a/src/inferrsi/harness/optimization_session.py +++ b/src/inferrsi/harness/optimization_session.py @@ -122,6 +122,7 @@ def _runtime_identity(): "harness/usage.py", "harness/agent_sessions.py", "harness/task_protocol.py", "harness/protocol_child.py", "harness/candidates.py", "harness/project.py", "harness/measurement.py", + "harness/project_objectives.py", "harness/records/knowledge_capture.py", "apps/workflows/campaign.py", "knowledge/context_projection.py", "knowledge/knowledge_find.py", "knowledge/ranking_policy.py") @@ -177,6 +178,8 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None if args.evaluation_mode == "service_reuse": from inferrsi.harness.project_service import prepare as prepare_service + if args.device_scope is not None: + raise ValueError("Use service conditions for device scope in service reuse") if args.evaluation_config is None or any( getattr(args, key) is not None for key in names ): @@ -205,6 +208,7 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None **settings, } result = optimization.initialize(root, plan) + result["target_review"] = settings["evaluation_settings"]["target_review"] result["instructions"] = ( "Run campaign baseline before candidate search. Record the measured " "bottleneck with campaign diagnose before knowledge or rounds. " @@ -220,20 +224,39 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None "AB/BA requires its existing metric, quality, command and sampling options" ) from inferrsi.harness.project import prepare as prepare_project + from inferrsi.harness.project_objectives import review_targets repo = args.repo.resolve() if not repo.is_dir() or root.is_relative_to(repo): raise ValueError("Campaign output must be outside the editable project") - identity(repo, args.include) # Reject invalid inputs before preparation writes. + baseline_identity = identity(repo, args.include) specification = {key: getattr(args, key) for key in ( "metric_key", "metric_unit", "quality_key", "scope", "direction", "min_improvement_pct", "repetitions", "warmups", "decision", "require_explanation")} specification.update(measure_command=shlex.split(args.measure_command), quality_command=shlex.split(args.quality_command)) + objective = {"id": args.metric_key, "key": args.metric_key, "unit": args.metric_unit, + "direction": args.direction, "threshold_type": "relative_percent", + "gain_threshold": args.min_improvement_pct, "aggregate": "median"} + if not args.device_scope or not args.device_scope.strip(): + raise ValueError("--device-scope requires a device and topology description") + context = {"baseline_snapshot": baseline_identity, "scope": args.scope, + "device_scope": args.device_scope} + review = review_targets(args.target_review, context, [objective]) settings = prepare_project(root / "frozen", args.protocol.resolve(), args.instructions.resolve(), specification) - retain(repo, root / "frozen/baseline", args.include) + settings["target_review"] = review + try: + if retain(repo, root / "frozen/baseline", args.include) != baseline_identity: + raise ValueError("Reviewed baseline changed during campaign freeze") + except (OSError, ValueError): + # Only this start created frozen; a retry needs a fresh directory. + import shutil + + shutil.rmtree(root / "frozen") + root.rmdir() + raise settings["frozen_files"].update({p.relative_to(root / "frozen").as_posix(): sha256(p) for p in (root / "frozen/baseline").rglob("*") if p.is_file()}) candidate = {"task": "project:" + repo.name, "task_source": "project", @@ -272,6 +295,8 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None if report_metadata is not None: plan["report_metadata"] = report_metadata result = optimization.initialize(root, plan) + if args.project_task: + result["target_review"] = plan["target_review"] operation = "campaign" if args.project_task else "benchmarks session" result["instructions"] = ( f"Read the frozen TASK.md. Record the measured bottleneck with {operation} " diff --git a/src/inferrsi/harness/project_objectives.py b/src/inferrsi/harness/project_objectives.py new file mode 100644 index 000000000..42cacac29 --- /dev/null +++ b/src/inferrsi/harness/project_objectives.py @@ -0,0 +1,146 @@ +"""Check a project's proposed gain against its workload-specific calibration before freeze.""" + +import json +import math +from pathlib import Path +from statistics import mean, median + +from .records.evidence import bounded_record_bytes + + +def number(value): + try: + return type(value) in (int, float) and math.isfinite(value) + except OverflowError: + return False + + +def change(obj, candidate, reference): + sign = 1 if obj["direction"] == "maximize" else -1 + delta = sign * (candidate - reference) + if obj["threshold_type"] == "relative_percent": + if reference == 0: + if candidate != 0: + raise ValueError(f"Undefined relative change from zero: {obj['id']}") + return 0 + delta = 100 * delta / abs(reference) + if not number(delta): + raise ValueError("Nonfinite derived change") + return delta + + +def _assess(objective, goal, calibration): + name = objective["id"] + target = objective["gain_threshold"] + if not isinstance(goal, dict) or not number(goal.get("target")) or goal["target"] != target: + raise ValueError(f"Target review for {name} must preserve the proposed target {target}") + if goal.get("source") not in ("user", "derived"): + raise ValueError(f"Identify target source for {name} as user or derived") + if not isinstance(goal.get("target_reference"), str) or not goal["target_reference"].strip(): + raise ValueError(f"Target review for {name} requires target_reference") + + binding = { + "metric": objective["key"], + "unit": objective["unit"], + "direction": objective["direction"], + "threshold_type": objective["threshold_type"], + } + if "scenario" in objective: + binding.update(scenario=objective["scenario"], aggregate=objective["aggregate"]) + if not isinstance(calibration, dict) or any( + calibration.get(key) != expected for key, expected in binding.items() + ): + raise ValueError(f"Calibration for {name} is not comparable to the proposed metric") + if calibration.get("method") not in ("workload_measurement", "calibrated_projection"): + raise ValueError(f"Identify measurement or calibrated projection for {name}") + evidence = calibration.get("calibration_evidence") + if not isinstance(evidence, str) or not evidence.strip(): + raise ValueError(f"Supply calibration evidence and assumptions for {name}") + samples = calibration.get("baseline_samples") + attainable = calibration.get("attainable_value") + if not isinstance(samples, list) or len(samples) < 2 or not all(number(v) for v in samples): + raise ValueError(f"Insufficient evidence for {name}: supply repeated baseline samples") + if not number(attainable): + raise ValueError(f"Insufficient evidence for {name}: supply a calibrated attainable value") + for value in [*samples, attainable]: + if domain := objective.get("domain"): + if not domain["min"] <= value <= domain["max"]: + raise ValueError(f"Target calibration outside the declared domain for {name}") + elif value <= 0: # The ordinary AB/BA evaluator accepts only positive metric values. + raise ValueError(f"Target calibration for {name} requires positive metric values") + + baseline = (mean if objective["aggregate"] == "mean" else median)(samples) + if not number(baseline): + raise ValueError(f"Nonfinite baseline for {name}") + if objective["threshold_type"] == "relative_percent" and baseline == 0: + raise ValueError(f"Relative target for {name} needs a nonzero calibrated baseline") + # Use the observed baseline range in the evaluator's gain units. This is a + # conservative planning screen, not a statistical confidence interval. + noise = abs( + change(objective, max(samples), baseline) - change(objective, min(samples), baseline) + ) + headroom = change(objective, attainable, baseline) + if not number(noise): + raise ValueError(f"Nonfinite target calibration for {name}") + if headroom <= 0 or target > headroom: + verdict = "outside_attainable_range" + elif noise > 0 and target <= noise: + verdict = "indistinguishable_from_baseline" + else: + verdict = "supported" + return { + **binding, + "target": target, + "source": goal["source"], + "target_reference": goal["target_reference"], + "method": calibration["method"], + "calibration_evidence": evidence, + "attainable_value": attainable, + "baseline_samples": samples, + "baseline": baseline, + "observed_noise": noise, + "attainable_gain": headroom, + "decision": verdict, + } + + +def _read(root, relative): + raw, status = bounded_record_bytes(root, relative, 4 * 1024 * 1024) + if raw is None: + raise ValueError(f"Invalid target review input {relative!r}: {status}") + try: + data = json.loads(raw.decode("utf-8")) + except (ValueError, RecursionError) as exc: + raise ValueError(f"Invalid JSON in target review input {relative!r}") from exc + if not isinstance(data, dict): + raise ValueError(f"Target review input {relative!r} must be a JSON object") + return data + + +def review_targets(path: Path | None, context: dict, objectives: list[dict]) -> dict: + """Bind the requested goals to independently recorded calibration and compute feasibility.""" + if path is None: + raise ValueError("--target-review requires a calibration-backed goal review") + review = _read(path.parent, path.name) + calibration = _read(path.parent, review.get("calibration")) + if calibration.get("context") != context: + raise ValueError( + "Target calibration is not comparable: check baseline, workload and device" + ) + names = {obj["id"] for obj in objectives} + goals, samples = review.get("objectives"), calibration.get("objectives") + if any(not isinstance(rows, dict) or set(rows) != names for rows in (goals, samples)): + raise ValueError("Supply a goal and calibration for every declared gain objective") + decisions = { + obj["id"]: _assess(obj, goals[obj["id"]], samples[obj["id"]]) for obj in objectives + } + # Service selection accepts a gain on any enabled objective (and checks all + # regression guards). Report each assessment and use the same any-gain rule. + if not any(row["decision"] == "supported" for row in decisions.values()): + detail = ", ".join( + f"{name}: {row['decision']} ({row['source']} target {row['target']:g}, " + f"noise {row['observed_noise']:g}, attainable {row['attainable_gain']:g})" + for name, row in decisions.items() + ) + raise ValueError(f"Unsupported performance target: {detail}. Revisit goal or calibration.") + return {"context": context, "calibration": review["calibration"], "objectives": decisions} diff --git a/src/inferrsi/harness/project_service.py b/src/inferrsi/harness/project_service.py index c1bcde2d3..f99e19c30 100644 --- a/src/inferrsi/harness/project_service.py +++ b/src/inferrsi/harness/project_service.py @@ -16,6 +16,7 @@ from .atomic_json import atomic_write_json from .candidates import members, retain +from .project_objectives import change, number, review_targets INLINE_PROFILE_REASONS = ("fixed_checks_satisfied", "performance_gate_not_met") @@ -67,13 +68,6 @@ def read(path): return value -def number(value): - try: - return type(value) in (int, float) and math.isfinite(value) - except OverflowError: - return False - - def positive(value): return number(value) and value > 0 @@ -273,20 +267,6 @@ def aggregate(settings, documents, role): return {"values": aggregates, "samples": samples} -def change(obj, candidate, reference): - sign = 1 if obj["direction"] == "maximize" else -1 - delta = sign * (candidate - reference) - if obj["threshold_type"] == "relative_percent": - if reference == 0: - if candidate != 0: - raise ValueError(f"Undefined relative change from zero: {obj['id']}") - return 0 - delta = 100 * delta / abs(reference) - if not number(delta): - raise ValueError("Nonfinite derived change") - return delta - - def performance(settings, measured, parent, initial, *, screening=False): metrics, limits, gain, actual_gain = {}, True, False, False for obj in settings["objectives"]: @@ -419,6 +399,13 @@ def git(*args): target.chmod(mode) +def review_service_targets(path, conditions, revision, objectives): + context = {"conditions": conditions, "baseline_revision": revision} + review = review_targets(path, context, [obj for obj in objectives if obj["gain"]]) + no_fingerprints(review) + return review + + def prepare(root, args): from inferrsi import __version__ @@ -430,6 +417,9 @@ def prepare(root, args): if root.exists() or root.is_relative_to(source) or root.is_relative_to(protocol): raise ValueError("Use a new campaign directory outside project/protocol") commit = revision(source, args.include) + settings["target_review"] = review_service_targets( + args.target_review, settings["conditions"], commit, settings["objectives"] + ) members(protocol) if not args.instructions.is_file() or args.instructions.is_symlink(): raise ValueError("Regular task instructions required") diff --git a/tests/apps/test_engineering_benchmark_plugins.py b/tests/apps/test_engineering_benchmark_plugins.py index b1eadd835..2e8e22723 100644 --- a/tests/apps/test_engineering_benchmark_plugins.py +++ b/tests/apps/test_engineering_benchmark_plugins.py @@ -6,6 +6,7 @@ from tests.apps.test_codex_plugin import invoke from tests.apps.test_project_optimization import project as project from tests.fixtures.diagnosis import diagnosis_args +from tests.fixtures.target_review import project_review def test_isolated_benchmark_child_uses_its_bundled_runtime(distribution, tmp_path, monkeypatch): @@ -70,6 +71,7 @@ def test_isolated_plugin_runs_project_round_and_retained_final(distribution, tmp distribution, tmp_path, "campaign", "start", "--directory", str(root), "--repo", str(repo), "--include", "engine.py", "--include", "config.json", "--protocol", str(protocol), "--instructions", str(instructions), + "--target-review", project_review(root, repo), "--device-scope", "synthetic CPU", "--measure-command", '"{python}" "{protocol}/measure.py" "{candidate}" "{result}"', "--quality-command", '"{python}" "{protocol}/quality.py" "{candidate}" "{result}"', "--metric-key", "metric", "--metric-unit", "synthetic-units", "--direction", "maximize", diff --git a/tests/apps/test_project_explanation.py b/tests/apps/test_project_explanation.py index d3a46329c..70352d4ea 100644 --- a/tests/apps/test_project_explanation.py +++ b/tests/apps/test_project_explanation.py @@ -12,6 +12,7 @@ from inferrsi.harness.artifact_primitives import digest from inferrsi.harness.optimization import read_records from tests.fixtures.diagnosis import diagnosis_args +from tests.fixtures.target_review import project_review # Device-wide factor applied to every timed value of one measurement call, cycling per # call. It scales all regions together, as clocks or temperature would. @@ -56,10 +57,14 @@ def project(tmp_path): def start(project, capsys, *extra, repetitions=8): repo, protocol, instructions, root = project + direction = extra[extra.index("--direction") + 1] if "--direction" in extra else "minimize" code = main([ "campaign", "start", "--directory", str(root), "--repo", str(repo), "--include", "engine.py", "--include", "config.json", "--protocol", str(protocol), - "--instructions", str(instructions), "--measure-command", + "--instructions", str(instructions), + "--target-review", project_review(root, repo, "ms", direction), + "--device-scope", "synthetic CPU", + "--measure-command", '"{python}" "{protocol}/measure.py" "{candidate}" "{result}"', "--quality-command", '"{python}" "{protocol}/quality.py" "{candidate}" "{result}"', "--metric-key", "metric", "--metric-unit", "ms", "--direction", "minimize", diff --git a/tests/apps/test_project_optimization.py b/tests/apps/test_project_optimization.py index 64a999f3a..74a7ae789 100644 --- a/tests/apps/test_project_optimization.py +++ b/tests/apps/test_project_optimization.py @@ -12,6 +12,7 @@ from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard from inferrsi.harness.optimization import read_records from tests.fixtures.diagnosis import diagnosis_args +from tests.fixtures.target_review import project_review @pytest.fixture @@ -45,7 +46,9 @@ def start_arguments(project, *, direction="maximize", mode="up_to", extra=()): return [ "campaign", "start", "--directory", str(root), "--repo", str(repo), "--include", "engine.py", "--include", "config.json", "--protocol", str(protocol), - "--instructions", str(instructions), "--measure-command", + "--instructions", str(instructions), "--target-review", + project_review(root, repo, direction=direction), "--device-scope", "synthetic CPU", + "--measure-command", '"{python}" "{protocol}/measure.py" "{candidate}" "{result}"', "--quality-command", '"{python}" "{protocol}/quality.py" "{candidate}" "{result}"', "--metric-key", "metric", "--metric-unit", "synthetic-units", "--direction", direction, @@ -655,17 +658,14 @@ def test_assessment_reports_paired_statistics_without_changing_the_verdict( assert final["paired_statistics"]["gate_relation"] == "above_gate" -def test_unreachable_gate_keeps_the_original_fail_and_strict_json_records(project, capsys): - # A minimize gate of 100% has no finite speedup; the report must not block the FAIL. - start(project, capsys, direction="minimize", - extra=("--repetitions", "6", "--min-improvement-pct", "100")) - code, result = submit(project, capsys, 5) - assert code == 0 and result["best"]["kind"] == "baseline" - assessment = result["latest_observation"]["assessment"] - assert assessment["verdict"] == "FAIL" and assessment["eligible"] is False - paired = assessment["paired_statistics"] - assert paired["gate_speedup"] is None and paired["gate_relation"] == "gate_unreachable" - json.dumps(read_records(project[3])[1], allow_nan=False) +def test_unreachable_gate_is_rejected_before_creating_a_campaign(project, capsys): + root = project[3] + args = start_arguments(project, direction="minimize", extra=("--min-improvement-pct", "100")) + project_review(root, project[0], direction="minimize", target=100) + with pytest.raises(SystemExit): + main(args) + assert "outside_attainable_range" in capsys.readouterr().err + assert not root.exists() def test_records_without_paired_statistics_remain_readable(project, capsys, monkeypatch): @@ -688,3 +688,89 @@ def legacy_assess(*args, **kwargs): snapshot = dashboard_snapshot(project[3]) assert snapshot["data"]["candidates"][0]["verdict"] == "PASS" assert "Synthetic candidate" in render_dashboard(snapshot) + + +def test_target_review_is_required_and_missing_evidence_leaves_no_campaign(project, capsys): + root = project[3] + args = start_arguments(project) + idx = args.index("--target-review") + review = Path(args[idx + 1]) + with pytest.raises(SystemExit): + main(args[:idx] + args[idx + 2:]) + assert "--target-review" in capsys.readouterr().err + assert not root.exists() + + review.write_text(json.dumps({"objectives": {"metric": {"target": 1}}})) + with pytest.raises(SystemExit): + main(args) + assert "target review input" in capsys.readouterr().err + assert not root.exists() + + +@pytest.mark.parametrize("key", ["scope", "baseline_snapshot", "device_scope"]) +def test_start_rejects_mismatched_calibration_before_freeze(project, capsys, key): + args = start_arguments(project) + receipt = Path(args[args.index("--target-review") + 1]).with_suffix(".calibration.json") + data = json.loads(receipt.read_text()) + data["context"][key] = "different" + receipt.write_text(json.dumps(data)) + with pytest.raises(SystemExit): + main(args) + assert "not comparable" in capsys.readouterr().err + assert not project[3].exists() + + +@pytest.mark.parametrize("source", ["user", "derived"]) +def test_start_freezes_the_actual_goal_and_calibration(project, capsys, source): + args = start_arguments(project) + review = Path(args[args.index("--target-review") + 1]) + goals = json.loads(review.read_text()) + goals["objectives"]["metric"]["source"] = source + review.write_text(json.dumps(goals)) + assert main(args) == 0 + decision = json.loads(capsys.readouterr().out)["target_review"] + review.unlink() + review.with_suffix(".calibration.json").unlink() + plan, _, _ = read_records(project[3]) + assert plan["target_review"] == decision + assert decision["context"]["baseline_snapshot"] == plan["baseline_sha256"] + row = decision["objectives"]["metric"] + assert (row["source"], row["target"], row["decision"]) == (source, 1, "supported") + assert (row["baseline_samples"], row["observed_noise"], row["attainable_gain"]) == ( + [10, 10], 0, 100, + ) + + +def test_pre_review_project_plan_remains_readable(project, capsys): + from inferrsi.harness.artifact_primitives import digest + + start(project, capsys) + root = project[3] + plan_file = root / "plan.json" + plan = json.loads(plan_file.read_text()) + del plan["target_review"] + plan_file.write_text(json.dumps(plan)) + for name in ("campaign.json", "state.json"): + path = root / name + record = json.loads(path.read_text()) + record["plan_digest"] = digest(plan) + path.write_text(json.dumps(record)) + loaded, _, _ = read_records(root) + assert "target_review" not in loaded + + +def test_baseline_change_during_review_does_not_freeze_other_bytes(project, capsys, monkeypatch): + from inferrsi.harness import candidates + + args = start_arguments(project) + retain = candidates.retain + + def change_before_copy(repo, destination, includes): + (repo / "config.json").write_text('{"metric": 99}') + return retain(repo, destination, includes) + + monkeypatch.setattr(candidates, "retain", change_before_copy) + with pytest.raises(SystemExit): + main(args) + assert "Reviewed baseline changed" in capsys.readouterr().err + assert not project[3].exists() diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index e3839373d..900b41e62 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -1492,3 +1492,26 @@ def test_mechanism_declaration_is_refused_in_service_mode(campaign, tmp_path): campaign["capsys"].readouterr() state = json.loads((campaign["root"] / "state.json").read_text()) assert state["pending"] is None and not state.get("attempts", [])[1:] + + +def test_service_target_review_respects_any_gain_and_condition_binding(campaign): + args = campaign["start"] + path = Path(args[args.index("--target-review") + 1]).with_suffix(".calibration.json") + receipt = json.loads(path.read_text()) + receipt["objectives"]["a"]["attainable_value"] = 99 + path.write_text(json.dumps(receipt)) + decisions = call(campaign, "start")["target_review"]["objectives"] + assert decisions["a"]["decision"] == "outside_attainable_range" + assert decisions["b"]["decision"] == "supported" + call(campaign, "baseline") + root = campaign["root"] + before = (root / "state.json").read_bytes() + conditions = {**settings()["conditions"], "id": "new-machine", "topology": "other"} + changed = root.parent / "changed.json" + changed.write_text(json.dumps(conditions)) + with pytest.raises(SystemExit): + main(["campaign", "refresh-references", "--session", str(root), "--reason", "New host", + "--conditions", str(changed), "--target-review", + args[args.index("--target-review") + 1]]) + assert "not comparable" in campaign["capsys"].readouterr().err + assert (root / "state.json").read_bytes() == before diff --git a/tests/fixtures/service_reuse.py b/tests/fixtures/service_reuse.py index ae97d07ad..1a060bf5c 100644 --- a/tests/fixtures/service_reuse.py +++ b/tests/fixtures/service_reuse.py @@ -14,6 +14,7 @@ from inferrsi.harness.records import evidence, knowledge_capture from inferrsi.knowledge import knowledge_operations from tests.fixtures.diagnosis import diagnosis_args +from tests.fixtures.target_review import calibration, write_review @pytest.fixture(autouse=True) @@ -130,12 +131,25 @@ def settings(): } +def service_review(root, conditions, revision): + objectives = settings()["objectives"] + measurements = {obj["id"]: {**calibration(obj["unit"], obj["direction"]), + "metric": obj["key"], "baseline_samples": [100, 100], + "attainable_value": 90, "aggregate": obj["aggregate"], + "scenario": obj["scenario"]} for obj in objectives} + return write_review(root.with_suffix(".review.json"), + {"conditions": conditions, "baseline_revision": revision}, measurements, + {obj["id"]: obj["gain_threshold"] for obj in objectives}) + + @pytest.fixture def campaign(tmp_path, capsys): repo, protocol, root = (tmp_path / name for name in ("repo", "protocol", "campaign")) repo.mkdir() subprocess.run(["git", "-C", str(repo), "init", "-q"], check=True) commit(repo) + baseline_revision = subprocess.check_output(["git", "-C", repo, "rev-parse", "HEAD"], + text=True).strip() protocol.mkdir() shutil.copyfile( Path(__file__).with_name("service_reuse_protocol.py"), protocol / "protocol.py" @@ -161,6 +175,8 @@ def campaign(tmp_path, capsys): "service_reuse", "--evaluation-config", str(configuration), + "--target-review", + service_review(root, settings()["conditions"], baseline_revision), "--rounds", "8", "--max-minutes", @@ -174,6 +190,11 @@ def campaign(tmp_path, capsys): def call(campaign, action, *extra, expected=0): + if action == "refresh-references" and not {"--retry-of", "--target-review"}.intersection(extra): + conditions = json.loads(Path(extra[extra.index("--conditions") + 1]).read_text()) + root = campaign["root"] + revision = json.loads((root / "plan.json").read_text())["baseline_revision"] + extra = (*extra, "--target-review", service_review(root, conditions, revision)) args = ( campaign["start"] if action == "start" diff --git a/tests/fixtures/target_review.py b/tests/fixtures/target_review.py new file mode 100644 index 000000000..e4dfaa282 --- /dev/null +++ b/tests/fixtures/target_review.py @@ -0,0 +1,43 @@ +"""Preparation inputs for project campaign tests with synthetic metric values.""" + +import json + +from inferrsi.harness.candidates import identity + + +def calibration(unit, direction): + return { + "metric": "metric", + "direction": direction, + "unit": unit, + "threshold_type": "relative_percent", + "method": "workload_measurement", + "baseline_samples": [10, 10], + "attainable_value": 20 if direction == "maximize" else 5, + "calibration_evidence": "Both synthetic controls return fixed metric values.", + } + + +def write_review(path, context, measurements, targets): + receipt = path.with_suffix(".calibration.json") + receipt.write_text(json.dumps({"context": context, "objectives": measurements})) + goals = { + key: {"source": "derived", "target_reference": "Synthetic protocol", "target": value} + for key, value in targets.items() + } + path.write_text(json.dumps({"calibration": receipt.name, "objectives": goals})) + return str(path) + + +def project_review(root, repo, unit="synthetic-units", direction="maximize", target=1): + context = { + "scope": "synthetic-software-control", + "device_scope": "synthetic CPU", + "baseline_snapshot": identity(repo, ["engine.py", "config.json"]), + } + return write_review( + root.with_suffix(".review.json"), + context, + {"metric": calibration(unit, direction)}, + {"metric": target}, + ) diff --git a/tests/harness/test_project_objectives.py b/tests/harness/test_project_objectives.py index 1a2c7270f..69bcaa3b3 100644 --- a/tests/harness/test_project_objectives.py +++ b/tests/harness/test_project_objectives.py @@ -96,3 +96,44 @@ def test_metric_evidence_requires_finite_domain_valid_numbers(bad): } with pytest.raises(ValueError): aggregate(config, [doc], "candidate") + + +@pytest.mark.parametrize(("updates", "error"), [ + ({"baseline_samples": [100, 104]}, "indistinguishable_from_baseline"), + ({"baseline_samples": [100]}, "repeated baseline"), + ({"baseline_samples": [True, 100]}, "repeated baseline"), + ({"attainable_value": None}, "calibrated attainable value"), + ({"unit": "seconds"}, "not comparable"), + ({"calibration_evidence": " "}, "calibration evidence"), + ({"method": "theoretical_peak"}, "measurement or calibrated projection"), +]) +def test_unsupported_target_calibration(tmp_path, updates, error): + from inferrsi.harness.project_objectives import review_targets + from tests.fixtures.target_review import calibration, write_review + + ctx = {"scope": "test"} + obj = {**objective(kind="absolute"), "aggregate": "mean", "key": "metric"} + record = {**calibration("ms", "minimize"), "threshold_type": "absolute", + "baseline_samples": [100, 100], "attainable_value": 90, **updates} + path = tmp_path / "goal.json" + write_review(path, ctx, {"a": record}, {"a": 4}) + with pytest.raises(ValueError, match=error): + review_targets(path, ctx, [obj]) + + +def test_percentage_point_review_uses_native_units_and_the_service_aggregate(tmp_path): + from inferrsi.harness.project_objectives import review_targets + from tests.fixtures.target_review import calibration, write_review + + obj = {**objective("maximize", "percentage_point"), "key": "metric", "unit": "%", + "aggregate": "mean", "scenario": "a", "domain": {"min": 0, "max": 100}} + context = {"scope": "test"} + calibrated = {**calibration("%", "maximize"), "threshold_type": "percentage_point", + "aggregate": "mean", "scenario": "a", "baseline_samples": [90, 90, 93], + "attainable_value": 95} + path = tmp_path / "goals.json" + write_review(path, context, {"a": calibrated}, {"a": 4}) + row = review_targets(path, context, [obj])["objectives"]["a"] + assert (row["decision"], row["baseline"], row["observed_noise"], row["attainable_gain"]) == ( + "supported", 91, 3, 4, + ) From 4565133cec385d758bb5b7d8db8ca731699de0d2 Mon Sep 17 00:00:00 2001 From: amy-why-3459 <221522807+amy-why-3459@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:58:03 +0800 Subject: [PATCH 2/3] Recalibrate service controls after changing their baseline or conditions Agent-assisted-by: Codex (tests and verification) Signed-off-by: amy-why-3459 <221522807+amy-why-3459@users.noreply.github.com> --- tests/apps/test_project_service_reuse.py | 13 ++++++++++++- tests/fixtures/service_reuse.py | 17 ++++++++++++----- .../harness/test_service_profile_diagnostics.py | 3 ++- 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index 900b41e62..9bd26da56 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -13,7 +13,16 @@ from inferrsi.apps.cli import main from inferrsi.apps.cli.arguments import parser from inferrsi.harness import optimization, project_service -from tests.fixtures.service_reuse import begin, call, commit, diagnose, rejected, settings, submit +from tests.fixtures.service_reuse import ( + begin, + calibrate_start, + call, + commit, + diagnose, + rejected, + settings, + submit, +) from tests.fixtures.service_reuse import campaign as campaign from tests.fixtures.service_reuse import no_fingerprints as no_fingerprints @@ -307,6 +316,7 @@ def interrupted(command, *args, **kwargs): def test_incomplete_baseline_prevents_candidate_search(campaign): commit(campaign["repo"], missing_metric=True) + calibrate_start(campaign) call(campaign, "start") result = call(campaign, "baseline", expected=2) assert result["best"] is None and result["state"] == "blocked" @@ -948,6 +958,7 @@ def test_execution_preserves_tree_inputs_despite_export_attributes(campaign, att subprocess.run(["git", "-C", str(repo), "add", ".gitattributes", "inputs"], check=True) commit(repo) campaign["start"] += ["--include", "inputs"] + calibrate_start(campaign) baseline = begin(campaign)["latest_observation"] candidate = submit(campaign, version="accepted", a=90)["latest_observation"] final = call(campaign, "final", "--reason", "Verify exact committed inputs")["final"] diff --git a/tests/fixtures/service_reuse.py b/tests/fixtures/service_reuse.py index 1a060bf5c..d025a7697 100644 --- a/tests/fixtures/service_reuse.py +++ b/tests/fixtures/service_reuse.py @@ -142,14 +142,20 @@ def service_review(root, conditions, revision): {obj["id"]: obj["gain_threshold"] for obj in objectives}) +def calibrate_start(campaign): + revision = subprocess.check_output( + ["git", "-C", campaign["repo"], "rev-parse", "HEAD"], text=True + ).strip() + conditions = json.loads(campaign["config"].read_text())["conditions"] + return service_review(campaign["root"], conditions, revision) + + @pytest.fixture def campaign(tmp_path, capsys): repo, protocol, root = (tmp_path / name for name in ("repo", "protocol", "campaign")) repo.mkdir() subprocess.run(["git", "-C", str(repo), "init", "-q"], check=True) commit(repo) - baseline_revision = subprocess.check_output(["git", "-C", repo, "rev-parse", "HEAD"], - text=True).strip() protocol.mkdir() shutil.copyfile( Path(__file__).with_name("service_reuse_protocol.py"), protocol / "protocol.py" @@ -158,7 +164,8 @@ def campaign(tmp_path, capsys): instructions.write_text("Synthetic service control; no model claims.") configuration = tmp_path / "evaluation.json" configuration.write_text(json.dumps(settings())) - args = [ + campaign = {"repo": repo, "root": root, "config": configuration, "capsys": capsys} + campaign["start"] = [ "campaign", "start", "--session", @@ -176,7 +183,7 @@ def campaign(tmp_path, capsys): "--evaluation-config", str(configuration), "--target-review", - service_review(root, settings()["conditions"], baseline_revision), + calibrate_start(campaign), "--rounds", "8", "--max-minutes", @@ -186,7 +193,7 @@ def campaign(tmp_path, capsys): "--final-reserve-seconds", "30", ] - return {"repo": repo, "root": root, "start": args, "config": configuration, "capsys": capsys} + return campaign def call(campaign, action, *extra, expected=0): diff --git a/tests/harness/test_service_profile_diagnostics.py b/tests/harness/test_service_profile_diagnostics.py index 9ad3c6a00..311783322 100644 --- a/tests/harness/test_service_profile_diagnostics.py +++ b/tests/harness/test_service_profile_diagnostics.py @@ -5,7 +5,7 @@ import pytest from inferrsi.harness import project_service as service -from tests.fixtures.service_reuse import begin, call, submit +from tests.fixtures.service_reuse import begin, calibrate_start, call, submit from tests.fixtures.service_reuse import campaign as campaign # A valid protocol receipt below the JSON size limit but too large to copy twice. @@ -113,6 +113,7 @@ def test_large_effective_config_allows_inline_and_backfill_profiles(campaign): {f"engine.option_{i:04d}": i for i in range(1500)} ) campaign["config"].write_text(json.dumps(config)) + calibrate_start(campaign) begin(campaign) attempt = submit(campaign, a=90)["latest_observation"] inline = attempt["profiling"] From b82f04c6d3f478b8f0bafad85b26b73d4dabd024 Mon Sep 17 00:00:00 2001 From: amy-why-3459 <221522807+amy-why-3459@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:00:45 +0800 Subject: [PATCH 3/3] Compare complete service workload definitions with goal calibration Agent-assisted-by: Codex (implementation and regression coverage) Signed-off-by: amy-why-3459 <221522807+amy-why-3459@users.noreply.github.com> --- docs/guides/service-reuse-campaigns.md | 3 +- src/inferrsi/harness/optimization.py | 2 +- src/inferrsi/harness/project_objectives.py | 2 ++ src/inferrsi/harness/project_service.py | 10 +++--- tests/apps/test_project_optimization.py | 14 ++++++++ tests/apps/test_project_service_reuse.py | 11 +++++++ tests/fixtures/service_reuse.py | 38 ++++++++++++++-------- 7 files changed, 61 insertions(+), 19 deletions(-) diff --git a/docs/guides/service-reuse-campaigns.md b/docs/guides/service-reuse-campaigns.md index eb134ceee..7e7635350 100644 --- a/docs/guides/service-reuse-campaigns.md +++ b/docs/guides/service-reuse-campaigns.md @@ -200,7 +200,8 @@ exact-round policy. A new service campaign requires the [performance target review](optimization-workflow-unification.md#performance-target-review). Use `context.conditions` for the complete effective conditions and `context.baseline_revision` -for the baseline Git commit. Key each gain objective by its ID in both files and include +for the baseline Git commit. Copy the protocol’s full scenario list into `context.scenarios` so +a reused scenario ID cannot substitute another workload or request count. Key each gain objective by its ID in both files and include its scenario, aggregate, metric key, unit, direction and threshold type in calibration. The target declaration carries its exact gain threshold. Baseline samples and the attainable value use the metric's units and domain. The review diff --git a/src/inferrsi/harness/optimization.py b/src/inferrsi/harness/optimization.py index e86eac7e5..e3a36d975 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/optimization.py @@ -1595,7 +1595,7 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non if "target_review" in plan["evaluation_settings"]: refresh_review = service.review_service_targets( args.target_review, conditions, plan["baseline_revision"], - plan["evaluation_settings"]["objectives"], + plan["evaluation_settings"], ) state.update( conditions=conditions, diff --git a/src/inferrsi/harness/project_objectives.py b/src/inferrsi/harness/project_objectives.py index 42cacac29..79bab46c5 100644 --- a/src/inferrsi/harness/project_objectives.py +++ b/src/inferrsi/harness/project_objectives.py @@ -123,6 +123,8 @@ def review_targets(path: Path | None, context: dict, objectives: list[dict]) -> raise ValueError("--target-review requires a calibration-backed goal review") review = _read(path.parent, path.name) calibration = _read(path.parent, review.get("calibration")) + if path.samefile(path.parent / review["calibration"]): + raise ValueError("Supply the calibration in a separate file from the target declaration") if calibration.get("context") != context: raise ValueError( "Target calibration is not comparable: check baseline, workload and device" diff --git a/src/inferrsi/harness/project_service.py b/src/inferrsi/harness/project_service.py index f99e19c30..6157b21aa 100644 --- a/src/inferrsi/harness/project_service.py +++ b/src/inferrsi/harness/project_service.py @@ -399,9 +399,11 @@ def git(*args): target.chmod(mode) -def review_service_targets(path, conditions, revision, objectives): - context = {"conditions": conditions, "baseline_revision": revision} - review = review_targets(path, context, [obj for obj in objectives if obj["gain"]]) +def review_service_targets(path, conditions, revision, settings): + context = { + "conditions": conditions, "baseline_revision": revision, "scenarios": settings["scenarios"], + } + review = review_targets(path, context, [obj for obj in settings["objectives"] if obj["gain"]]) no_fingerprints(review) return review @@ -418,7 +420,7 @@ def prepare(root, args): raise ValueError("Use a new campaign directory outside project/protocol") commit = revision(source, args.include) settings["target_review"] = review_service_targets( - args.target_review, settings["conditions"], commit, settings["objectives"] + args.target_review, settings["conditions"], commit, settings ) members(protocol) if not args.instructions.is_file() or args.instructions.is_symlink(): diff --git a/tests/apps/test_project_optimization.py b/tests/apps/test_project_optimization.py index 74a7ae789..d43cc4a06 100644 --- a/tests/apps/test_project_optimization.py +++ b/tests/apps/test_project_optimization.py @@ -707,6 +707,20 @@ def test_target_review_is_required_and_missing_evidence_leaves_no_campaign(proje assert not root.exists() +def test_calibration_cannot_reference_the_goal_file_itself(project, capsys): + args = start_arguments(project) + review = Path(args[args.index("--target-review") + 1]) + goal = json.loads(review.read_text()) + record = json.loads((review.parent / goal["calibration"]).read_text()) + record["objectives"]["metric"].update(goal["objectives"]["metric"]) + record["calibration"] = review.name + review.write_text(json.dumps(record)) + with pytest.raises(SystemExit): + main(args) + assert "separate file" in capsys.readouterr().err + assert not project[3].exists() + + @pytest.mark.parametrize("key", ["scope", "baseline_snapshot", "device_scope"]) def test_start_rejects_mismatched_calibration_before_freeze(project, capsys, key): args = start_arguments(project) diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index 9bd26da56..0de7bd673 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -1505,6 +1505,17 @@ def test_mechanism_declaration_is_refused_in_service_mode(campaign, tmp_path): assert state["pending"] is None and not state.get("attempts", [])[1:] +@pytest.mark.parametrize(("field", "value"), [("workload", "other workload"), ("requests", 20)]) +def test_service_target_review_checks_workload_under_same_scenario_id(campaign, field, value): + settings = json.loads(campaign["config"].read_text()) + settings["scenarios"][0][field] = value + campaign["config"].write_text(json.dumps(settings)) + with pytest.raises(SystemExit): + main(campaign["start"]) + assert "not comparable" in campaign["capsys"].readouterr().err + assert not campaign["root"].exists() + + def test_service_target_review_respects_any_gain_and_condition_binding(campaign): args = campaign["start"] path = Path(args[args.index("--target-review") + 1]).with_suffix(".calibration.json") diff --git a/tests/fixtures/service_reuse.py b/tests/fixtures/service_reuse.py index d025a7697..5ac2b0744 100644 --- a/tests/fixtures/service_reuse.py +++ b/tests/fixtures/service_reuse.py @@ -131,23 +131,32 @@ def settings(): } -def service_review(root, conditions, revision): - objectives = settings()["objectives"] - measurements = {obj["id"]: {**calibration(obj["unit"], obj["direction"]), - "metric": obj["key"], "baseline_samples": [100, 100], - "attainable_value": 90, "aggregate": obj["aggregate"], - "scenario": obj["scenario"]} for obj in objectives} - return write_review(root.with_suffix(".review.json"), - {"conditions": conditions, "baseline_revision": revision}, measurements, - {obj["id"]: obj["gain_threshold"] for obj in objectives}) +def service_review(root, conditions, revision, config): + objectives = [obj for obj in config["objectives"] if obj["gain"]] + measurements = { + obj["id"]: { + **calibration(obj["unit"], obj["direction"]), + "metric": obj["key"], "baseline_samples": [100, 100], "attainable_value": 90, + "aggregate": obj["aggregate"], "scenario": obj["scenario"], + "threshold_type": obj["threshold_type"], + } + for obj in objectives + } + context = { + "conditions": conditions, "baseline_revision": revision, "scenarios": config["scenarios"], + } + return write_review( + root.with_suffix(".review.json"), context, measurements, + {obj["id"]: obj["gain_threshold"] for obj in objectives}, + ) def calibrate_start(campaign): revision = subprocess.check_output( ["git", "-C", campaign["repo"], "rev-parse", "HEAD"], text=True ).strip() - conditions = json.loads(campaign["config"].read_text())["conditions"] - return service_review(campaign["root"], conditions, revision) + config = json.loads(campaign["config"].read_text()) + return service_review(campaign["root"], config["conditions"], revision, config) @pytest.fixture @@ -200,8 +209,11 @@ def call(campaign, action, *extra, expected=0): if action == "refresh-references" and not {"--retry-of", "--target-review"}.intersection(extra): conditions = json.loads(Path(extra[extra.index("--conditions") + 1]).read_text()) root = campaign["root"] - revision = json.loads((root / "plan.json").read_text())["baseline_revision"] - extra = (*extra, "--target-review", service_review(root, conditions, revision)) + plan = json.loads((root / "plan.json").read_text()) + review = service_review( + root, conditions, plan["baseline_revision"], plan["evaluation_settings"] + ) + extra = (*extra, "--target-review", review) args = ( campaign["start"] if action == "start"