From 186fc35396789d52df5fb8c6d5aa13ad915f8ff5 Mon Sep 17 00:00:00 2001 From: Zeng Chuang Date: Wed, 25 Nov 2026 16:21:59 +0800 Subject: [PATCH 1/4] Add pytest coverage for the Codex Qwen-Image user journey Exercise the natural-language entry point, recompute round decisions and independent results, and verify the delivered source against the measured candidate. Keep historical replay and the real Codex/A2 run opt-in. Agent-assisted-by: Codex (implementation and verification) Signed-off-by: zengchuang --- docs/contributing.md | 4 + docs/e2e-qwen-image-codex.md | 209 +++++++++ e2e/__init__.py | 1 + e2e/conftest.py | 39 ++ e2e/qwen_image/__init__.py | 1 + e2e/qwen_image/audit.py | 556 ++++++++++++++++++++++ e2e/qwen_image/driver.py | 115 +++++ e2e/qwen_image/request.txt | 1 + e2e/qwen_image/retest.py | 144 ++++++ e2e/qwen_image/test_archived_journey.py | 176 +++++++ e2e/qwen_image/test_user_journey.py | 62 +++ tests/campaigns/test_user_e2e_audit.py | 598 ++++++++++++++++++++++++ tests/fixtures/user_e2e/codex_host.py | 15 + tests/fixtures/user_e2e/measure.py | 38 ++ 14 files changed, 1959 insertions(+) create mode 100644 docs/e2e-qwen-image-codex.md create mode 100644 e2e/__init__.py create mode 100644 e2e/conftest.py create mode 100644 e2e/qwen_image/__init__.py create mode 100644 e2e/qwen_image/audit.py create mode 100644 e2e/qwen_image/driver.py create mode 100644 e2e/qwen_image/request.txt create mode 100644 e2e/qwen_image/retest.py create mode 100644 e2e/qwen_image/test_archived_journey.py create mode 100644 e2e/qwen_image/test_user_journey.py create mode 100644 tests/campaigns/test_user_e2e_audit.py create mode 100644 tests/fixtures/user_e2e/codex_host.py create mode 100644 tests/fixtures/user_e2e/measure.py diff --git a/docs/contributing.md b/docs/contributing.md index 624fc0687..d7687f5be 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -28,6 +28,10 @@ Synthetic benchmark scripts belong in `tests/fixtures/`; historical validator snapshots in `tests/fixtures/legacy/` remain byte-for-byte frozen. Current runnable examples are the three Qwen scripts under `examples/`. +For the [Codex user-journey E2E case](e2e-qwen-image-codex.md), select a live +Codex/A2 session or replay retained artifacts with the documented pytest options. +Its CPU controls run in the default test suite. + Git treats recorded bundles under `evidence/` and `tests/fixtures/legacy/` as exact bytes (`-text`), so checkout and add do not normalize their line endings. The evidence README and reusable `_template/` remain ordinary LF text. This diff --git a/docs/e2e-qwen-image-codex.md b/docs/e2e-qwen-image-codex.md new file mode 100644 index 000000000..5244b7e8c --- /dev/null +++ b/docs/e2e-qwen-image-codex.md @@ -0,0 +1,209 @@ +# Codex 用户优化 Qwen-Image 的 pytest 用例 + +设计与验收范围:[Issue #479](https://github.com/InferMatrixLab/InferRSI/issues/479)。 +这是普通用户体验用例,不是 `benchmarks` 题包。测试入口在 +[`e2e/qwen_image/test_user_journey.py`](../e2e/qwen_image/test_user_journey.py), +不在默认 `pytest` 的 `tests/` 范围内,不增加 CI lane 或自动预约 NPU。 + +## 历史证据回放 + +在 InferRSI 仓库根目录运行: + +```bash +python -m pytest -v e2e/qwen_image/test_archived_journey.py \ + --e2e-archived-evidence \ + --e2e-archived-retest +``` + +第一个目录含 `plan/actor-plan.json` 和 `results/actor/`,第二个目录含 +`sealed-source.json`、`independent-result.json` 和原始 PNG。回放只读取文件。 +三个测试分别重算逐轮取舍与会话 final、独立复测的顺序/图像/计时、实际补丁与受测快照身份。 +归档的格式调整即使保持 Python AST 相同,文件字节发生变化也会触发身份断言。 +pytest 会展示具体文件和两份摘要。默认测试发现不会启动真实 Agent。 + +## 正式试跑的计时 A/A + +将两臂均使用固定基线的测量放在协议冻结前完成,使用正式比较相同的工作负载、 +预热次数、交叉顺序和配对数。准备记录的 `timing_policy` 引用冻结协议中的 JSON。 +观察记录的 `timing_aa` 引用按执行顺序排列的 `[{step, result}]`。 +`result` 是带相对路径和 SHA-256 的原始回执,含实际加载的源码摘要 +`loaded_source_sha256`、起止时间、完整请求耗时及 PNG。回执与用例中的质量 A/A 分开。 + +当前支持的估计方法 `maximum_absolute_paired_change_pct` 取各配对组中 +`100 × abs(B − A) / A` 的最大值,A、B 各取该组六次请求的中位数。 +在冻结文件中记录 `estimator`、原始记录摘要 `aa_sha256`、实测噪声 +`observed_noise_pct` 和 `adoption_threshold_pct`。采用门槛由本次执行计划决定, +须覆盖该噪声,并与 Harness 配置一致。将 `adoption_comparator` 设为 +`current_best` 表示相对当前累计最佳也要达到采用门槛。若实际计划选用其他估计方法, +此检查返回 INCONCLUSIVE。缺少原始记录时同样保留 INCONCLUSIVE。 + +## 用户输入 + +交付补丁时由观察者保留 `submission` 回执,含 `candidate_id`、`attempt`、 +`candidate_sha256` 和原始补丁字节的 `patch_sha256`。将回执以路径和摘要加入 +`observer.json` 的 `submission`。独立复测在应用补丁前读取原始回执; +另一份能得到相同源码的合法补丁也会在计时前被拒绝。 + +准备好固定版本的 vLLM-Omni Codex 项目、InferRSI 插件和 A2 使用 skill 后, +唯一发送给 Codex 的用户输入是 [`request.txt`](../e2e/qwen_image/request.txt): + +> 请用 InferRSI 优化当前 vLLM-Omni 项目的 Qwen-Image-2.1-Turbo,在 Ascend A2 单卡上生成 1280×704 图片,保持出图质量,把单张生图耗时降到尽可能低。请多轮尝试、复测最优方案,并交付补丁和结果。 + +测试器不会给 Codex 提供 TASK.md、协议文件、候选实现、优化建议或重试提示。 +Agent 自行准备并冻结内部协议,使用普通 `campaign start/round/final` 流程。 +固定基线使用 #479 中规定的首次 Turbo 支持 PR 合入后的提交,作为运行参数传入, +不写入共享测试默认值。质量/采样/收益门槛以该次搜索前冻结的协议为准。 + +## 执行 + +安装 `python -m pip install -e '.[dev,image]'`。操作者先在独立、干净的项目目录 +检出 ``,配置实际使用的 Codex 模型、插件和 A2 skill,验证同一用户 +和执行环境能非交互登录、独占健康单卡、读取已核验文件字节的模型缓存。 +连接信息和凭据留在现有 skill/环境,不传入测试配置。 + +当前自动启动适配器是 **Codex CLI**;显式指定模型,保存客户端版本、请求、 +逐事件原始输出及接收时刻、最终回复和墙钟耗时。它使用现有权限设置, +不添加绕过批准或隔离的参数,不自动继续失败会话。 +CLI 的结果不能用作 Codex Desktop 的宿主兼容性通过证明;Desktop 的原生会话 +可以由看护者导出证据,再使用下文的只读复核入口。 + +```bash +python -m pytest e2e/qwen_image/test_user_journey.py --run-agent-e2e \ + --e2e-project '' \ + --e2e-baseline-revision '' \ + --e2e-model '' \ + --e2e-timeout-seconds '' \ + --e2e-artifacts '' \ + --e2e-campaign-parent '' \ + --e2e-observer '/observer.json' +``` + +这是会实际使用模型和机器的显式运行。看护者在运行中持续保留选择依据、 +人工介入和环境回执,在结束后完成 `observer.json`。这些是**观察输出**, +不会传给 Agent。测试器只接收一个与本次项目及开始时间匹配的新 campaign; +出现多个尝试时要求先整理版本/尝试索引,避免挑选有利数据。 + +会话结束之后还需要独立复测**实际交付的补丁**。在已通过环境准备的执行宿主上, +使用 campaign 原始 InferRSI runtime 运行: + +```bash +python -m e2e.qwen_image.retest \ + --project '' --baseline-revision '' \ + --campaign '' --patch '' \ + --submission '' \ + --output '/independent' \ + --timeout-seconds '' +``` + +该操作创建新的独立 Git 副本,从固定基线应用补丁,验证与已保存轮次/尝试的 +完整源码身份一致,写 `seal.json` **之后**才调用现有 Harness 执行器。 +不改变 Agent 项目的 HEAD、文件或旧实验记录。换行或权限差异不会被静默归一化。 +如果基线最终胜出,session final 仍测基线;独立入口则测质量通过且测量完整的 +最快 Agent 候选,同分取较早轮次。没有有效候选时保留缺口。 + +冻结命令必须适用于当前执行宿主。SSH、容器挂载、模型路径和设备分配继续由 +原有 A2 skill/冻结命令负责;本用例不实现另一套远程调度器。 +当 pytest 本身就在合格执行宿主时,可以为 live 命令增加 +`--e2e-retest-locally --e2e-patch ''`。 +超时只终止本次本地客户端;远端资源是否清理必须由看护者核实,未知不能写已清理。 + +保留原始结果后,可重复运行只读验收而不重新调用 Codex/NPU: + +```bash +python -m pytest e2e/qwen_image/test_user_journey.py \ + --e2e-campaign '' \ + --e2e-observer '/observer.json' \ + --e2e-artifacts '' +``` + +## 检查什么 + +| 输出 | 检查 | +| --- | --- | +| 每轮选择 | 方案事件先于首次编辑和测量;起点是上一轮最佳;有备选、所选措施、理由、预期、风险、引用和反馈 | +| 选择合理性 | 独立审阅者针对候选源码身份给出依据、差异引用及预期是否得到支持;缺失不能自动 PASS | +| 每轮优选 | 用 Harness 对原始结果重新判定质量、完整性、中位数和冻结门槛,再重算采用/拒绝、累计最佳;保留慢轮及失败轮 | +| 有效实验 | 不把相同源码/声明配置重复提交当新优化;检查真实 AB/BA 顺序,不能仅核对每侧样本集合 | +| 图片及原始时间 | 六组冻结 prompt,seed 42–47,1280×704;逐张读取 PNG 的 RGBA 字节与哈希,重算请求时间中位数 | +| 比较前提 | 搜索前跨独立进程的基线 A/A 像素相同;工作负载、环境身份、实际 scheduler 网格一致,不能只看请求的 steps 参数 | +| 最终结果 | session final 和独立实际补丁复测分别输出 B、F、B−F、百分比收益、正确性和性能结论 | +| 使用体验 | 是否需要看护者代操作,第一次卡住的步骤、介入时间/原因;普通用户回答或批准与代操作分开 | + +源码、声明配置和运行所需的相对文件都必须在 campaign 的 include 范围内; +外部依赖/模型/设备仍需环境核验。单凭布尔质量结果、Agent 自述或宿主正常退出 +不足以证明完整用例通过。该用例限定 warmed offline `Omni.generate` 到解码图片, +不能扩展成在线服务或 SLO 收益。 + +## 看护记录的输出契约 + +`observer.json` 位于私有观察目录。文件引用均为 +`{"path":"relative/path", "sha256":""}`,相对于这个目录; +不接受目录外路径或符号链接。它是看护过程中收集的证据索引,不是用户题包。 +[`tests/campaigns/test_user_e2e_audit.py`](../tests/campaigns/test_user_e2e_audit.py) 中的完整合成示例 +展示文件之间如何关联;示例时间、图像和身份仅为 CPU 负面控制。 + +| 字段 | 内容 | +| --- | --- | +| `preparation` | 准备回执 JSON 引用,字段见下文 | +| `round_choices` | 按 `candidate_id` 索引的三个宿主事件引用 `plan_event/first_edit_event/measurement_event` 和独立 `review` 引用 | +| `baseline_repeat` | `results` 为至少两次独立进程的基线 JSON 引用;对应 `fresh_process_ids/source_sha256`;以及 `search_started_at/effective_scheduler/environment_identity/workload_sha256` | +| `independent_directory` | 独立入口输出目录相对位置,包含 seal、实际补丁、重建源码、原始执行记录及 receipt | +| `interventions` | 全部介入,明确 `kind`(`assistance/answer/approval`)、`stage/at_seconds/reason/action`;没有介入时为 `[]`,缺失表示未知 | +| `final_reply` | 实际最终回复的文件引用 | + +准备回执包含:`input_version/baseline_revision/plan_digest/protocol_frozen_at`; +`runspec` 的 `repository/revision/backend/device_class/device_count/model`; +`codex` 的实际 `client/version/model/configuration_sha256`; +`inferrsi.version/runtime_digest`;`a2_skill.name/sha256`; +`quality_cases` 引用 Agent 已冻结的六个 `{prompt,seed}`; +`workload` 引用冻结工作负载 JSON,包含 `width/height/dtype/batch_size/concurrency/` +`tensor_parallel_size/guidance_scale/num_inference_steps/timing_scope/requests`。 +本例为 1280×704、bfloat16、batch/concurrency/TP/CFG 均为 1、原生 8 步, +`timing_scope` 为 `Omni.generate_to_decoded_image`,`requests` 与质量输入一致。 +`expected_scheduler` 保存事前约定的实际 `num_steps/timesteps/sigmas`,与基线 +跨进程复测及所有轮次对照;不能用仅记录请求 steps 的值替代运行网格。 +`checks` 中的 `noninteractive_login/healthy_exclusive_device/model_bytes_verified/` +`baseline_repeat_before_search/owned_resources_cleaned`。未知字段保持未知,不能补造。 +这些环境回执依赖可归属的看护/执行系统;CPU 复核不能重新证明远端硬件事实。 + +三个事件导出保留原始宿主事件 `raw`、一致的 `host_session_id` 和单调 `sequence`, +不要用文件 mtime 替代时序。 +方案事件的 `choice` 包含 `starting_best_sha256/alternatives/chosen_measure/reason/` +`expected_effect/risk/sources/feedback_or_initial_analysis`。`review` 包含 +`independent/reviewer/basis/diff_refs/candidate_sha256/verdict/expectation`; +`diff_refs` 为实际文件引用;`expectation` 为 `supported/refuted/inconclusive`。 +作者自己切换角色不构成独立审阅。 + +质量/测量 JSON 继续满足 Harness 的冻结字段,并保留 `requests`,每个请求有 +`seed/latency_ms/file/pixel_sha256`,组内 `median_ms`;以及实际 +`effective_scheduler/environment_identity/workload_sha256`。 +基线重复、逐轮、会话 final 和补丁独立复测的每个执行进程都要在结果中记录 +`loaded_source_sha256`。从实际加载的源码定位纳入冻结清单的文件,用 Harness 的 +`candidates.identity` 口径计算该组源码摘要。核查器按步骤比对所属组的基线或候选 +快照摘要。缺少进程摘要时记为 INCONCLUSIVE,摘要不一致时记为 FAIL,并列出步骤。 + +A/A JSON 另保留 `process.id/started_at/finished_at`。这些补充字段由 Agent 或 +观察系统的实际记录提供;旧记录缺少时报告证据不全,不补写历史事实。 + +## 判定及开发检查 + +实时运行会逐字节比对观察者留存的最终回复与本次 Codex 输出的 `final-reply.txt`。 +只读回放核对留存文件的摘要与非空文本。验收人还须从该回复打开逐轮表、会话 final +回执、独立复测回执与补丁,并核对候选身份、基线和最终耗时、差值及百分比、 +质量通过数与介入记录。pytest 报告列出回复摘要,供验收人定位原文。 + +`pytest-report.json` 保留 `PASS/FAIL/INCONCLUSIVE`、逐轮表格、两次最终比较及 +介入情况。pytest 没有 INCONCLUSIVE 状态,因此证据缺失会让验收断言失败, +同时 JSON 中仍保留 INCONCLUSIVE,不能将它当质量失败或静默通过。 +`test_completion_required_no_observer_assistance` 单独检查无代操作完成; +协助完成不改写质量/性能结果。无加速也不会凭空判使用流程失败,性能结论另列。 +未显式选择 live 或 replay 时,两条昂贵用例跳过。 + +```bash +pytest tests/campaigns/test_user_e2e_audit.py +ruff check e2e tests/campaigns/test_user_e2e_audit.py tests/fixtures/user_e2e +``` + +这些 CPU 控制会启动真实 Harness 子进程,使用合成代码、PNG 和时间,覆盖优选链、 +两份回执、换错合法补丁、交换 AB 顺序、事后补方案、缺审阅、环境缺口和人工介入。 +它们通过只说明测试器行为得到检查,不说明本机完成了 Codex/A2 生图验收。 diff --git a/e2e/__init__.py b/e2e/__init__.py new file mode 100644 index 000000000..1d6bbb769 --- /dev/null +++ b/e2e/__init__.py @@ -0,0 +1 @@ +"""Explicit, operator-run acceptance tests; excluded from the default testpaths.""" diff --git a/e2e/conftest.py b/e2e/conftest.py new file mode 100644 index 000000000..b793a866a --- /dev/null +++ b/e2e/conftest.py @@ -0,0 +1,39 @@ +from pathlib import Path + +import pytest + + +def pytest_addoption(parser): + group = parser.getgroup("inferrsi-user-e2e") + group.addoption("--e2e-archived-evidence", help="Read a historical actor evidence export") + group.addoption("--e2e-archived-retest", help="Read the corresponding raw independent attempt") + group.addoption("--run-agent-e2e", action="store_true", + help="Launch a real, billable Codex run") + for name in ("project", "baseline-revision", "artifacts", "campaign-parent", "campaign", + "observer", "model", "patch"): + group.addoption("--e2e-" + name, default=None) + group.addoption("--e2e-codex", default="codex") + group.addoption("--e2e-timeout-seconds", type=float, default=None) + group.addoption("--e2e-retest-locally", action="store_true", + help="Execute the frozen protocol on this already-qualified NPU host") + + +@pytest.fixture(scope="session") +def e2e_options(pytestconfig): + def required(name): + value = pytestconfig.getoption("e2e_" + name.replace("-", "_")) + if value is None: + pytest.fail("Explicit --e2e-" + name + " is required", pytrace=False) + return value + + if not pytestconfig.getoption("run_agent_e2e"): + campaign = pytestconfig.getoption("e2e_campaign") + if campaign is None: + pytest.skip("Explicit live opt-in or --e2e-campaign replay is required") + return {"campaign": Path(campaign), "observer": Path(required("observer")), "live": False, + "artifacts": pytestconfig.getoption("e2e_artifacts")} + return {"live": True, **{name.replace("-", "_"): required(name) for name in ( + "project", "baseline-revision", "artifacts", "campaign-parent", "observer", "model", + "timeout-seconds")}, "executable": pytestconfig.getoption("e2e_codex"), + "retest": pytestconfig.getoption("e2e_retest_locally"), + "patch": pytestconfig.getoption("e2e_patch")} diff --git a/e2e/qwen_image/__init__.py b/e2e/qwen_image/__init__.py new file mode 100644 index 000000000..9c81929ac --- /dev/null +++ b/e2e/qwen_image/__init__.py @@ -0,0 +1 @@ +"""Ordinary Codex user journey from acceptance issue #479.""" diff --git a/e2e/qwen_image/audit.py b/e2e/qwen_image/audit.py new file mode 100644 index 000000000..734466def --- /dev/null +++ b/e2e/qwen_image/audit.py @@ -0,0 +1,556 @@ +"""Read-only checks of real managed campaigns, not an optimization engine. + +Harness owns execution, assessment and selection. This case recomputes those +facts and checks the additional user-journey evidence from issue #479. Observer +receipts are outputs of supervision, never extra instructions sent to Codex. +""" + +import hashlib +import json +import math +from pathlib import Path +from statistics import median + +from inferrsi.harness import candidates, project +from inferrsi.harness.artifact_primitives import digest, sha256 +from inferrsi.harness.optimization import read_records + + +class EvidenceViolation(ValueError): + """Complete retained facts contradict an identity or order requirement.""" + + +def read(path): + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def inside(root, name): + path = root / name + if Path(name).is_absolute() or not path.resolve().is_relative_to(root.resolve()): + raise ValueError("Evidence reference escapes its root") + if any(p.is_symlink() for p in (path, *path.parents) if p.is_relative_to(root)): + raise ValueError("Evidence reference traverses a symbolic link") + return path + + +class Report: + def __init__(self): + self.findings = [] + self.rounds = [] + self.results = {} + + def add(self, code, verdict="INCONCLUSIVE", **details): + self.findings.append({"code": code, "verdict": verdict, **details}) + + def document(self): + verdict = "PASS" + if self.findings: + verdict = ("FAIL" if any(f["verdict"] == "FAIL" for f in self.findings) + else "INCONCLUSIVE") + return {"workflow_verdict": verdict, "findings": self.findings, + "rounds": self.rounds, **self.results} + + +def reference(root, ref): + path = inside(root, ref["path"]) + if sha256(path) != ref["sha256"]: + raise EvidenceViolation("Evidence reference hash mismatch") + return path + + +def check_timing_aa(observer_root, observer, preparation, plan, report): + """Recompute the declared noise estimator from two arms running the baseline.""" + try: + policy_path = reference(observer_root, preparation["timing_policy"]) + if sha256(policy_path) not in plan["frozen_files"].values(): + raise EvidenceViolation("Timing policy was not frozen") + policy = read(policy_path) + if policy.get("adoption_comparator") != "current_best": + report.add("timing_aa_adoption_comparator_unqualified") + return + trace_path = reference(observer_root, observer["timing_aa"]) + if policy["aa_sha256"] != sha256(trace_path): + raise EvidenceViolation("Timing trace differs from the frozen record") + if policy["estimator"] != "maximum_absolute_paired_change_pct": + report.add("timing_aa_estimator_not_supported") + return + settings = plan["evaluation_settings"] + rows = read(trace_path) + steps = [step for step in project.steps(settings) if step["phase"] != "quality"] + if [row["step"] for row in rows] != [step["id"] for step in steps]: + raise EvidenceViolation("Missing or reordered timing A/A steps") + arms = {"baseline": [], "candidate": []} + environment = observer["baseline_repeat"]["environment_identity"] + previous_end = None + for row, step in zip(rows, steps, strict=True): + path = reference(observer_root, row["result"]) + raw = read(path) + if (raw["loaded_source_sha256"] != plan["baseline_sha256"] + or raw["workload_sha256"] != preparation["workload"]["sha256"] + or raw["effective_scheduler"] != preparation["expected_scheduler"] + or raw["environment_identity"] != environment): + report.add("timing_aa_environment_or_source_unqualified") + return + start, end = raw["process"]["started_at"], raw["process"]["finished_at"] + if not (math.isfinite(start) and math.isfinite(end) + and start <= end <= preparation["protocol_frozen_at"] + and (previous_end is None or previous_end <= start)): + raise EvidenceViolation("Timing A/A was not completed in order before freeze") + previous_end = end + image_requests(path.parent, raw) + if step["phase"] == "measurement": + arms[step["side"]].append(raw["median_ms"]) + pairs = zip(arms["baseline"], arms["candidate"], strict=True) + noise = max(100 * abs(b - a) / a for a, b in pairs) + gate = policy["adoption_threshold_pct"] + if (type(gate) not in (float, int) or not math.isfinite(gate) + or not math.isclose(noise, policy["observed_noise_pct"], abs_tol=1e-9) + or gate != settings["min_improvement_pct"] or gate < noise): + raise EvidenceViolation("Frozen rule disagrees with actual A/A measurements") + report.results["timing_aa"] = {"paired_groups": len(arms["baseline"]), + "observed_noise_pct": noise, "adoption_threshold_pct": gate} + except EvidenceViolation: + report.add("timing_aa_frozen_rule_contradicted", "FAIL") + except (OSError, ImportError, ValueError, TypeError, KeyError): + report.add("timing_aa_evidence_unavailable") + + +def check_preparation(observer_root, observer, plan, state, report): + try: + preparation = read(reference(observer_root, observer["preparation"])) + check_timing_aa(observer_root, observer, preparation, plan, report) + runspec = preparation["runspec"] + if (runspec["repository"] != "vllm-project/vllm-omni" + or runspec["backend"] != "ascend" or runspec["device_class"] != "A2" + or runspec["device_count"] != 1 + or runspec["model"] != "Qwen-Image-2.1-Turbo" + or runspec["revision"] != preparation["baseline_revision"]): + report.add("prepared_environment_does_not_match_case") + if (len(preparation["baseline_revision"]) != 40 + or not preparation["input_version"] + or preparation["plan_digest"] != digest(plan)): + report.add("preparation_does_not_bind_frozen_plan") + for key in ("client", "version", "model", "configuration_sha256"): + if not preparation["codex"].get(key): + report.add("codex_environment_not_pinned", field=key) + for section, keys in (("inferrsi", ("version", "runtime_digest")), + ("a2_skill", ("name", "sha256"))): + if any(not preparation[section].get(key) for key in keys): + report.add("prepared_tool_identity_missing", tool=section) + if preparation["inferrsi"]["runtime_digest"] != digest(plan["runtime_identity"]): + report.add("prepared_inferrsi_runtime_mismatch") + for key in ("noninteractive_login", "healthy_exclusive_device", "model_bytes_verified", + "baseline_repeat_before_search", "owned_resources_cleaned"): + if preparation["checks"].get(key) is not True: + report.add("preparation_or_cleanup_unqualified", check=key) + if not preparation["protocol_frozen_at"] <= state["rounds"][0]["started_at"]: + report.add("protocol_not_frozen_before_search", "FAIL") + # Case identities and prompts are in the Agent's frozen protocol, rather + # than a hidden replacement task supplied by this test. + cases_path = reference(observer_root, preparation["quality_cases"]) + cases = read(cases_path) + if (sorted(c["seed"] for c in cases) != list(range(42, 48)) + or any(not c.get("prompt") for c in cases)): + report.add("six_frozen_prompt_seed_cases_missing") + if sha256(cases_path) not in plan["frozen_files"].values(): + report.add("quality_cases_not_frozen_before_search", "FAIL") + workload_path = reference(observer_root, preparation["workload"]) + workload = read(workload_path) + required = {"width": 1280, "height": 704, "dtype": "bfloat16", "batch_size": 1, + "concurrency": 1, "tensor_parallel_size": 1, "guidance_scale": 1, + "num_inference_steps": 8, "timing_scope": "Omni.generate_to_decoded_image"} + if any(workload.get(key) != value for key, value in required.items()): + report.add("baseline_workload_not_the_intended_turbo_case") + if workload.get("requests") != cases: + report.add("workload_requests_do_not_match_quality_cases") + if (sha256(workload_path) not in plan["frozen_files"].values() + or observer["baseline_repeat"]["workload_sha256"] != sha256(workload_path)): + report.add("workload_identity_not_bound_to_frozen_inputs") + scheduler = preparation["expected_scheduler"] + if (scheduler != observer["baseline_repeat"]["effective_scheduler"] + or scheduler.get("num_steps") != 8 or len(scheduler.get("timesteps", [])) != 8 + or not scheduler.get("sigmas")): + report.add("baseline_did_not_run_intended_scheduler") + report.results["input_version"] = preparation["input_version"] + report.results["baseline_revision"] = preparation["baseline_revision"] + except EvidenceViolation: + report.add("preparation_evidence_hash_mismatch", "FAIL") + except (OSError, ValueError, KeyError, TypeError, IndexError): + report.add("preparation_evidence_unavailable") + + +def recompute(directory, settings, execution, identities=None): + """Use the existing assessor, with an explicit cross-arm ordering check.""" + expected = project.steps(settings) + actual = execution.get("steps", []) + if [s.get("id") for s in actual] != [s["id"] for s in expected[:len(actual)]]: + raise EvidenceViolation("Cross-arm execution order differs from the frozen protocol") + checks = execution.get("source_checks", []) + for step, check in zip(actual, checks): + if check.get("step") != step["id"]: + raise EvidenceViolation("Source check is bound to a different execution step") + if identities and check.get("expected") and check.get("actual"): + if check["expected"] != identities or check["actual"] != identities: + raise EvidenceViolation("Loaded source differs from retained candidate identity") + return project.assess(directory, settings, execution) + + +def select_patch_round(rounds): + """Even if baseline wins, independently test an actual, quality-valid patch. + + Stable min retains the first attempt on a tie. Eligibility for an improvement + claim is deliberately separate from suitability for this independent check. + """ + valid = [r for r in rounds if r["assessment"]["status"] == "completed" + and r["assessment"].get("quality_passed") is True] + if not valid: + raise ValueError("No complete quality-valid Agent candidate to retest") + return min(valid, key=lambda r: r["assessment"]["score"]) + + +def audit_selection(plan, state, root, report): + settings = plan["evaluation_settings"] + best = {"sha256": plan["baseline_sha256"], "score": None, "kind": "baseline"} + seen = {best["sha256"]} + recalculated = [] + for record in state["rounds"]: + directory = inside(root, record["path"]) + execution = read(directory / "execution/execution.json") + assessment = recompute(directory, settings, execution, { + "baseline": plan["baseline_sha256"], "candidate": record["candidate_sha256"]}) + if assessment != record["assessment"]: + report.add("assessment_disagrees_with_raw_evidence", "FAIL", + candidate=record["candidate_id"]) + candidate = record["candidate_sha256"] + if candidate in seen: + report.add("unchanged_or_repeated_candidate", "FAIL", + candidate=record["candidate_id"]) + seen.add(candidate) + if best["score"] is None and assessment["status"] == "completed": + best["score"] = assessment["baseline_score"] + previous = dict(best) + score = assessment.get("score") + increment = ((previous["score"] - score) / previous["score"] * 100 + if score is not None and previous["score"] is not None else None) + adopted = (assessment["status"] == "completed" + and assessment.get("eligible") is True and increment is not None + and increment > 0 and increment >= settings["min_improvement_pct"]) + if adopted: + best = {"sha256": candidate, "score": assessment["score"], "kind": "candidate"} + if any(record["best_after"].get(key) != value for key, value in best.items()): + report.add("wrong_adopt_reject_decision", "FAIL", candidate=record["candidate_id"]) + if assessment["status"] == "infrastructure_failure": + report.add("round_evidence_incomplete", candidate=record["candidate_id"]) + report.rounds.append({ + "candidate": record["candidate_id"], "attempt": record["path"], + "source_sha256": candidate, "starting_best_sha256": previous["sha256"], + "decision": "adopt" if adopted else "keep_previous_best", + "baseline_ms": assessment.get("baseline_score"), "candidate_ms": score, + "total_improvement_pct": assessment.get("improvement_pct"), + "incremental_improvement_pct": increment, + "quality_passed": assessment.get("quality_passed"), + }) + recalculated.append({**record, "assessment": assessment}) + if any(state["best"].get(key) != value for key, value in best.items()): + report.add("final_best_chain_mismatch", "FAIL") + final = state.get("final") + if final is None: + report.add("missing_session_final") + else: + if final["candidate_sha256"] != best["sha256"]: + report.add("session_final_retested_wrong_source", "FAIL") + directory = inside(root, final["path"]) + assessment = recompute(directory, settings, read(directory / "execution/execution.json"), { + "baseline": plan["baseline_sha256"], "candidate": final["candidate_sha256"]}) + if assessment != final["assessment"]: + report.add("session_final_assessment_mismatch", "FAIL") + if assessment["status"] != "completed": + report.add("session_final_incomplete") + report.results["session_final"] = metrics(assessment) + return recalculated + + +def metrics(assessment): + before, after = assessment.get("baseline_score"), assessment.get("score") + return {"baseline_ms": before, "candidate_ms": after, + "delta_ms": before - after if before and after else None, + "improvement_pct": assessment.get("improvement_pct"), + "performance_verdict": assessment["verdict"], + "quality_passed": assessment.get("quality_passed")} + + +def check_choices(observer_root, observer, rounds, report): + """Ordering is mechanical; applicability requires attributable independent review.""" + choices = observer.get("round_choices", {}) + for record, row in zip(rounds, report.rounds): + choice = choices.get(record["candidate_id"]) + if not choice: + report.add("missing_pre_edit_choice", candidate=record["candidate_id"]) + continue + try: + # The observer exports three host events, each with an ordered sequence + # and original bytes. File mtimes and retrospective prose do not count. + events = [read(reference(observer_root, choice[key])) + for key in ("plan_event", "first_edit_event", "measurement_event")] + if (any(not event.get("raw") for event in events) + or len({event.get("host_session_id") for event in events}) != 1 + or not events[0].get("host_session_id")): + report.add("missing_original_host_choice_events") + if not (events[0]["sequence"] < events[1]["sequence"] < events[2]["sequence"]): + report.add("choice_recorded_after_edit_or_measurement", "FAIL") + declaration = events[0]["choice"] + if declaration["starting_best_sha256"] != row["starting_best_sha256"]: + report.add("round_started_from_wrong_best", "FAIL") + for key in ("alternatives", "chosen_measure", "reason", "expected_effect", + "risk", "sources", "feedback_or_initial_analysis"): + if not declaration.get(key): + report.add("incomplete_pre_edit_choice", field=key) + review = read(reference(observer_root, choice["review"])) + for ref in review.get("diff_refs", []): + reference(observer_root, ref) + if (review.get("independent") is not True or not review.get("reviewer") + or not review.get("basis") or not review.get("diff_refs") + or review.get("candidate_sha256") != record["candidate_sha256"]): + report.add("missing_independent_choice_review") + elif review.get("verdict") == "FAIL": + report.add("choice_or_patch_not_supported_by_review", "FAIL") + elif review.get("verdict") != "PASS": + report.add("choice_rationale_unresolved") + if review.get("expectation") not in ("supported", "refuted", "inconclusive"): + report.add("optimization_expectation_not_reviewed") + row["chosen_measure"] = declaration.get("chosen_measure") + row["expectation_review"] = review.get("expectation", "unknown") + except EvidenceViolation: + report.add("choice_evidence_hash_mismatch", "FAIL") + except (OSError, ValueError, KeyError, TypeError): + report.add("choice_evidence_unavailable", candidate=record["candidate_id"]) + + +def image_requests(directory, document): + """Hash decoded RGBA pixels and recompute the metric from original request times.""" + from PIL import Image + + requests = document["requests"] + if sorted(r["seed"] for r in requests) != list(range(42, 48)): + raise ValueError("Expected the six frozen seed cases, exactly once each") + pixels, times = {}, [] + for request in requests: + value = request["latency_ms"] + if type(value) not in (int, float) or not math.isfinite(value) or value <= 0: + raise ValueError("Invalid original request latency") + with Image.open(inside(directory, request["file"])) as image: + if image.size != (1280, 704): + raise ValueError("Wrong generated image dimensions") + digest = hashlib.sha256(image.convert("RGBA").tobytes()).hexdigest() + if digest != request["pixel_sha256"]: + raise EvidenceViolation("PNG bytes disagree with recorded decoded pixels") + pixels[request["seed"]] = digest + times.append(value) + if median(times) != document["median_ms"]: + raise EvidenceViolation("Metric disagrees with raw request times") + return pixels + + +def check_loaded_source(document, expected, report, attempt, step): + """Compare what the executing worker loaded with the frozen arm identity.""" + actual = document.get("loaded_source_sha256") + if not actual: + report.add("loaded_source_identity_missing", attempt=attempt, step=step) + elif actual != expected: + report.add("wrong_source_loaded", "FAIL", attempt=attempt, step=step, + expected=expected, actual=actual) + + +def check_outputs(root, plan, state, observer_root, observer, report): + """No generic similarity threshold; the case freezes exact RGBA equality.""" + try: + repeat = observer["baseline_repeat"] + references = [reference(observer_root, ref) for ref in repeat["results"]] + if len(references) < 2 or len(set(repeat["fresh_process_ids"])) != len(references): + report.add("baseline_repeat_not_across_fresh_processes") + return + baseline_pixels = [image_requests(path.parent, read(path)) for path in references] + if any(pixels != baseline_pixels[0] for pixels in baseline_pixels[1:]): + report.add("baseline_pixel_reference_unqualified") + return + expected_grid = repeat["effective_scheduler"] + expected_environment = repeat["environment_identity"] + expected_workload = repeat["workload_sha256"] + if (len(set(repeat["source_sha256"])) != 1 + or len(repeat["source_sha256"]) != len(references)): + report.add("baseline_repeat_source_not_verified") + return + if repeat["source_sha256"][0] != plan["baseline_sha256"]: + report.add("baseline_repeat_wrong_source", "FAIL") + for index, path in enumerate(references): + document = read(path) + check_loaded_source(document, plan["baseline_sha256"], report, "baseline-repeat", index) + if (document.get("effective_scheduler") != expected_grid + or document.get("environment_identity") != expected_environment + or document.get("workload_sha256") != expected_workload): + report.add("baseline_repeat_protocol_mismatch") + return + if (max(read(path)["process"]["finished_at"] for path in references) + >= repeat["search_started_at"]): + report.add("baseline_repeat_not_before_search") + return + if [read(path)["process"]["id"] for path in references] != repeat["fresh_process_ids"]: + report.add("baseline_repeat_process_receipt_mismatch") + return + if state["rounds"] and repeat["search_started_at"] != state["rounds"][0]["started_at"]: + report.add("baseline_repeat_search_boundary_mismatch") + return + if not expected_grid or not expected_environment or not expected_workload: + report.add("missing_effective_environment_or_scheduler") + return + for record in [*state["rounds"], *([state["final"]] if state.get("final") else [])]: + directory = inside(root, record["path"]) + execution = read(directory / "execution/execution.json") + candidate_bad = False + for step in execution["steps"]: + path = inside(directory, "execution/" + step["id"] + "/result.json") + document = read(path) + side = step["id"].rsplit("-", 1)[-1] + expected_sha = (plan["baseline_sha256"] if side == "baseline" + else record["candidate_sha256"]) + check_loaded_source(document, expected_sha, report, record["path"], step["id"]) + if (document.get("status") == "candidate_failure" + or (step["id"] == "quality-candidate" and project._value( + document, plan["evaluation_settings"]["quality_key"]) is False)): + continue + if document.get("effective_scheduler") != expected_grid: + report.add("effective_scheduler_changed", "FAIL" if side == "candidate" + and "effective_scheduler" in document else "INCONCLUSIVE") + if (document.get("environment_identity") != expected_environment + or document.get("workload_sha256") != expected_workload): + report.add("environment_or_workload_not_comparable") + pixels = image_requests(path.parent, document) + if pixels != baseline_pixels[0]: + if side == "baseline": + report.add("baseline_pixel_reference_unqualified") + else: + candidate_bad = True + if candidate_bad and record["assessment"].get("quality_passed") is True: + report.add("incorrect_candidate_was_accepted_as_quality_valid", "FAIL") + except ImportError: + report.add("image_dependency_unavailable") + except EvidenceViolation: + report.add("raw_quality_or_timing_evidence_contradicted", "FAIL") + except (OSError, ValueError, KeyError, TypeError): + report.add("raw_quality_or_timing_evidence_unavailable") + + +def check_independent(root, observer, selected, plan, report): + try: + directory = inside(root, observer["independent_directory"]) + seal = read(directory / "seal.json") + submission = read(reference(root, observer["submission"])) + fields = ("candidate_id", "attempt", "candidate_sha256", "patch_sha256") + if any(submission[key] != seal[key] for key in fields): + report.add("independent_retest_differs_from_original_submission", "FAIL") + return + if (seal["candidate_id"] != selected["candidate_id"] + or seal["attempt"] != selected["path"] + or seal["candidate_sha256"] != selected["candidate_sha256"] + or seal["baseline_sha256"] != plan["baseline_sha256"] + or seal["plan_digest"] != digest(plan)): + report.add("independent_selection_binding_mismatch", "FAIL") + return + if (report.results.get("baseline_revision") is not None + and seal["baseline_revision"] != report.results["baseline_revision"]): + report.add("independent_git_baseline_revision_mismatch", "FAIL") + return + if (sha256(directory / "candidate.patch") != seal["patch_sha256"] + or candidates.identity(directory / "attempt/candidate") + != seal["candidate_sha256"] + or candidates.identity(directory / "frozen/baseline") + != seal["baseline_sha256"]): + report.add("independent_sealed_source_changed", "FAIL") + return + for name, expected in plan["frozen_files"].items(): + if sha256(inside(directory / "frozen", name)) != expected: + report.add("independent_protocol_or_baseline_drift", "FAIL") + return + receipt = read(directory / "receipt.json") + if (receipt["seal_sha256"] != sha256(directory / "seal.json") + or not seal["sealed_at"] < receipt["started_at"]): + report.add("independent_seal_not_before_measurement", "FAIL") + execution = read(directory / "attempt/execution/execution.json") + assessment = recompute(directory / "attempt", plan["evaluation_settings"], execution, { + "baseline": seal["baseline_sha256"], "candidate": seal["candidate_sha256"]}) + if assessment != receipt["assessment"]: + report.add("independent_assessment_mismatch", "FAIL") + if assessment["status"] != "completed": + report.add("independent_retest_incomplete") + report.results["independent_patch_retest"] = metrics(assessment) + # Recheck the independent PNGs/grid too, against the same qualified A/A reference. + attempt = {"path": "attempt", "assessment": assessment, + "candidate_sha256": seal["candidate_sha256"]} + check_outputs(directory, plan, {"rounds": [], "final": attempt}, root, observer, report) + except EvidenceViolation: + report.add("independent_execution_identity_or_order_violation", "FAIL") + except (OSError, ValueError, KeyError, TypeError): + report.add("independent_retest_unavailable") + + +def check_final_reply(root, observer, report, host_reply=None): + try: + reply = reference(root, observer["final_reply"]).read_bytes() + if host_reply is not None and reply != Path(host_reply).read_bytes(): + report.add("observer_reply_differs_from_host_output", "FAIL") + elif not reply.decode("utf-8-sig").strip(): + report.add("empty_final_reply", "FAIL") + else: + report.results["final_reply_sha256"] = hashlib.sha256(reply).hexdigest() + except EvidenceViolation: + report.add("final_reply_evidence_hash_mismatch", "FAIL") + except (OSError, ValueError, KeyError, TypeError): + report.add("final_reply_evidence_unavailable") + + +def audit(root, observer_path, *, host_reply=None): + report = Report() + observer_path = Path(observer_path) + try: + observer = read(observer_path) + plan, state, _ = read_records(Path(root)) + if (plan["task_source"] != "project" + or plan["evaluation_settings"]["direction"] != "minimize" + or plan["evaluation_settings"]["metric_unit"] != "ms"): + report.add("wrong_case_or_metric", "FAIL") + return report.document() + if len(state["rounds"]) < 2: + if not state["rounds"] and state.get("state") == "completed": + report.add("completed_without_candidate", "FAIL") + report.add("multiple_optimization_rounds_not_demonstrated") + rounds = audit_selection(plan, state, Path(root), report) + check_preparation(observer_path.parent, observer, plan, state, report) + check_choices(observer_path.parent, observer, rounds, report) + check_outputs(Path(root), plan, state, observer_path.parent, observer, report) + try: + selected = select_patch_round(rounds) + check_independent(observer_path.parent, observer, selected, plan, report) + except ValueError: + report.add("no_valid_agent_patch_to_retest") + interventions = observer.get("interventions") + if interventions is None: + report.add("user_intervention_record_missing") + else: + for event in interventions: + if (event.get("kind") not in ("assistance", "answer", "approval") + or any(key not in event for key in ( + "stage", "at_seconds", "reason", "action"))): + report.add("incomplete_intervention_record") + assisted = [event for event in interventions if event["kind"] == "assistance"] + if assisted: + report.add("observer_intervention_required", "FAIL") + report.results["completion_mode"] = "assisted" if assisted else "unassisted" + report.results["first_blocked_step"] = assisted[0]["stage"] if assisted else None + report.results["interventions"] = interventions + check_final_reply(observer_path.parent, observer, report, host_reply) + report.results["scope"] = "offline Omni.generate to decoded image; no service/SLO claim" + except EvidenceViolation: + report.add("execution_identity_or_order_violation", "FAIL") + except (OSError, ValueError, KeyError, TypeError) as error: + report.add("campaign_or_observer_evidence_unavailable", error_type=type(error).__name__) + return report.document() diff --git a/e2e/qwen_image/driver.py b/e2e/qwen_image/driver.py new file mode 100644 index 000000000..12feca8e2 --- /dev/null +++ b/e2e/qwen_image/driver.py @@ -0,0 +1,115 @@ +"""Opt-in Codex CLI host adapter. Sends exactly request.txt as the sole user turn.""" + +import json +import queue +import subprocess +import threading +import time +from pathlib import Path + +from .retest import git, write + + +def launch(project, baseline_revision, output, *, executable, model, timeout): + project, output = Path(project).resolve(), Path(output).resolve() + head = git(project, "rev-parse", "HEAD").decode().strip() + if head != baseline_revision: + raise ValueError("Prepared project is not at the issue's pinned baseline") + if git(project, "status", "--porcelain", "--untracked-files=all").strip(): + raise ValueError("Prepare a clean, separate Codex project before this test") + if output.exists() or output.is_relative_to(project): + raise ValueError("Use a new private output directory outside the project") + if timeout <= 0: + raise ValueError("An explicit positive wall-clock budget is required") + output.mkdir(parents=True) + prompt = Path(__file__).with_name("request.txt").read_text(encoding="utf-8").strip() + (output / "request.txt").write_text(prompt + "\n", encoding="utf-8") + command = [str(executable)] if isinstance(executable, (str, Path)) else list(executable) + version = subprocess.run([*command, "--version"], check=True, + capture_output=True, text=True).stdout.strip() + argv = [*command, "exec", "--json", "--cd", str(project), "--model", model, + "--output-last-message", str(output / "final-reply.txt"), "-"] + started = time.time() + write(output / "host.json", { + "client": "Codex CLI", "version": version, "requested_model": model, + "effective_model": "unknown unless exported by host", + "baseline_revision": head, "started_at": started, "state": "running", + }) + events = queue.Queue() + # Credentials/configuration are inherited by Codex, never inspected or dumped. + # No bypass flags, added optimization hints, resume prompt or automatic retry. + with (output / "stderr.log").open("w", encoding="utf-8") as stderr: + child = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=stderr, text=True, encoding="utf-8", errors="replace") + + def consume(): + for line in child.stdout: + events.put((time.time(), line)) + events.put(None) + + reader = threading.Thread(target=consume, daemon=True) + reader.start() + child.stdin.write(prompt) + child.stdin.close() + timed_out = False + sequence = 0 + with (output / "events.jsonl").open("w", encoding="utf-8") as log: + while True: + remaining = started + timeout - time.time() + if remaining <= 0: + timed_out = True + child.terminate() + break + try: + item = events.get(timeout=min(remaining, 1)) + except queue.Empty: + continue + if item is None: + break + at, line = item + sequence += 1 + log.write(json.dumps({"sequence": sequence, "received_at": at, + "elapsed_seconds": at - started, "raw": line}, + ensure_ascii=False) + "\n") + log.flush() + try: + returncode = child.wait(timeout=10) + except subprocess.TimeoutExpired: + child.kill() + returncode = child.wait() + receipt = {"client": "Codex CLI", "version": version, "requested_model": model, + "baseline_revision": head, "started_at": started, "finished_at": time.time(), + "elapsed_seconds": time.time() - started, "returncode": returncode, + "state": "timed_out" if timed_out else "exited", + "remote_cleanup": "unknown; observer must verify owned remote resources"} + exported = [] + for line in (output / "events.jsonl").read_text(encoding="utf-8").splitlines(): + try: + exported.append(json.loads(json.loads(line)["raw"])) + except (ValueError, TypeError): + continue + sessions = [event["thread_id"] for event in exported if event.get("type") == "thread.started"] + receipt["native_session_ids"] = sessions + receipt["native_turn_completed"] = ( + len(sessions) == 1 and any(e.get("type") == "turn.completed" for e in exported) + and not any(e.get("type") in ("turn.failed", "error") for e in exported)) + write(output / "host.json", receipt) + return receipt + + +def discover(parent, project, started): + matches = [] + for path in Path(parent).glob("**/campaign.json"): + try: + campaign = json.loads(path.read_text(encoding="utf-8")) + plan = json.loads(path.with_name("plan.json").read_text(encoding="utf-8")) + state = json.loads(path.with_name("state.json").read_text(encoding="utf-8")) + if (campaign.get("managed_optimization") is True and plan["task_source"] == "project" + and Path(plan["working_candidate"]).resolve() == Path(project).resolve() + and state["started_at"] >= started): + matches.append(path.parent) + except (OSError, ValueError, KeyError): + continue + if len(matches) != 1: + raise ValueError("Expected one new campaign for this project; index all attempts") + return matches[0] diff --git a/e2e/qwen_image/request.txt b/e2e/qwen_image/request.txt new file mode 100644 index 000000000..b42d7d78c --- /dev/null +++ b/e2e/qwen_image/request.txt @@ -0,0 +1 @@ +请用 InferRSI 优化当前 vLLM-Omni 项目的 Qwen-Image-2.1-Turbo,在 Ascend A2 单卡上生成 1280×704 图片,保持出图质量,把单张生图耗时降到尽可能低。请多轮尝试、复测最优方案,并交付补丁和结果。 diff --git a/e2e/qwen_image/retest.py b/e2e/qwen_image/retest.py new file mode 100644 index 000000000..4baec08cf --- /dev/null +++ b/e2e/qwen_image/retest.py @@ -0,0 +1,144 @@ +"""Seal the actual delivered patch, then reuse Harness for independent execution. + +Run on the qualified execution host with the campaign's original InferRSI +runtime. Connection setup belongs to that host's skill/environment, not here. +""" + +import argparse +import hashlib +import json +import shutil +import subprocess +import time +from pathlib import Path + +from inferrsi.harness import candidates, project +from inferrsi.harness.artifact_primitives import digest, sha256 +from inferrsi.harness.optimization import read_records +from inferrsi.harness.optimization_session import _project_execute, _runtime_identity + +from .audit import EvidenceViolation, Report, audit_selection, read, select_patch_round + + +def write(path, document): + path.write_text(json.dumps(document, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + + +def git(repo, *args): + # Arrays only; neither task data nor patch bytes are shell commands. + return subprocess.run(["git", "-C", str(repo), *args], check=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout + + +def seal(project_repo, baseline_revision, campaign, patch, output, *, submission): + """No measurement starts until clean-Git reconstruction matches the selected attempt.""" + project_repo, campaign, patch, output = map(Path, (project_repo, campaign, patch, output)) + plan, state, _ = read_records(campaign) + report = Report() + rounds = audit_selection(plan, state, campaign, report) + if report.findings: + raise ValueError("Campaign round/final checks must pass before independent replay") + selected = select_patch_round(rounds) + patch_bytes = patch.read_bytes() + submitted = read(submission) + expected = {"candidate_id": selected["candidate_id"], "attempt": selected["path"], + "candidate_sha256": selected["candidate_sha256"], + "patch_sha256": hashlib.sha256(patch_bytes).hexdigest()} + if any(submitted[key] != value for key, value in expected.items()): + raise EvidenceViolation("Patch or selection differs from original submission") + revision = git(project_repo, "rev-parse", "--verify", baseline_revision + "^{commit}") + revision = revision.decode().strip() + if revision != baseline_revision: + raise ValueError("A full pinned baseline commit is required") + if output.exists(): + raise ValueError("Independent output must be new; preserve previous attempts") + output.mkdir(parents=True) + write(output / "status.json", {"stage": "reconstruction", "verdict": "INCONCLUSIVE"}) + # A separate clone avoids moving the Agent's HEAD or touching its working tree. + git(project_repo, "clone", "--no-checkout", "--shared", str(project_repo.resolve()), + str(output.resolve() / "reconstructed")) + reconstructed = output / "reconstructed" + git(reconstructed, "config", "core.autocrlf", "false") + git(reconstructed, "checkout", "--detach", revision) + includes = plan["candidate_includes"] + baseline = output / "frozen/baseline" + baseline.parent.mkdir() + actual_baseline = candidates.retain(reconstructed, baseline, includes) + if actual_baseline != plan["baseline_sha256"]: + raise ValueError("Frozen baseline differs from the pinned clean Git checkout") + if not patch_bytes.strip(): + raise ValueError("An actual nonempty Agent patch is required") + (output / "candidate.patch").write_bytes(patch_bytes) + try: + git(reconstructed, "apply", "--check", str((output / "candidate.patch").resolve())) + git(reconstructed, "apply", str((output / "candidate.patch").resolve())) + except subprocess.CalledProcessError as error: + raise EvidenceViolation("Delivered patch does not apply to the pinned baseline") from error + # Reject changes outside the Agent's declared inputs, including new files. + changed = git(reconstructed, "diff", "--name-only", "-z", "HEAD").split(b"\0") + added = git(reconstructed, "ls-files", "--others", "--exclude-standard", "-z").split(b"\0") + declared = candidates.members(reconstructed, includes) + allowed = set(declared) | set(candidates.members(baseline)) + if any(name.decode("utf-8") not in allowed for name in [*changed, *added] if name): + raise EvidenceViolation("Delivered patch changes files outside declared candidate inputs") + attempt = output / "attempt" + attempt.mkdir() + actual_candidate = candidates.retain(reconstructed, attempt / "candidate", includes) + if actual_candidate != selected["candidate_sha256"]: + raise EvidenceViolation( + "Delivered patch does not reconstruct the selected Agent round/attempt") + shutil.copytree(campaign / "frozen/protocol", output / "frozen/protocol") + (output / "frozen/TASK.md").write_bytes((campaign / "frozen/TASK.md").read_bytes()) + for name, expected in plan["frozen_files"].items(): + if sha256(output / "frozen" / name) != expected: + raise ValueError("Frozen files changed during independent preparation") + seal_record = { + "baseline_revision": revision, "baseline_sha256": actual_baseline, + "candidate_id": selected["candidate_id"], "attempt": selected["path"], + "candidate_sha256": actual_candidate, "patch_sha256": sha256(output / "candidate.patch"), + "plan_digest": digest(plan), "sealed_at": time.time(), + } + write(output / "seal.json", seal_record) + return plan, seal_record + + +def execute(output, plan, timeout): + if timeout <= 0: + raise ValueError("An explicit positive independent budget is required") + if (output / "attempt/execution").exists() or (output / "receipt.json").exists(): + raise ValueError("Keep previous execution evidence; use a new independent attempt") + sealed = read(output / "seal.json") + if (sealed["plan_digest"] != digest(plan) + or sealed["patch_sha256"] != sha256(output / "candidate.patch") + or sealed["candidate_sha256"] != candidates.identity(output / "attempt/candidate") + or sealed["baseline_sha256"] != candidates.identity(output / "frozen/baseline")): + raise EvidenceViolation("Sealed independent inputs changed before timing") + for name, expected in plan["frozen_files"].items(): + if sha256(output / "frozen" / name) != expected: + raise ValueError("Frozen protocol changed before independent timing") + if plan["runtime_identity"] != _runtime_identity(): + raise ValueError("Use the campaign's frozen InferRSI runtime for independent execution") + started = time.time() + write(output / "status.json", {"stage": "measurement", "verdict": "INCONCLUSIVE"}) + execution = _project_execute(output, output / "attempt", plan, started + timeout) + assessment = project.assess(output / "attempt", plan["evaluation_settings"], execution) + receipt = {"seal_sha256": sha256(output / "seal.json"), "started_at": started, + "finished_at": time.time(), "assessment": assessment} + write(output / "receipt.json", receipt) + write(output / "status.json", {"stage": "finished", "verdict": assessment["verdict"]}) + return receipt + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("project", "baseline-revision", "campaign", "patch", "submission", "output"): + parser.add_argument("--" + name, required=True) + parser.add_argument("--timeout-seconds", type=float, required=True) + args = parser.parse_args() + plan, _ = seal(args.project, args.baseline_revision, args.campaign, args.patch, args.output, + submission=args.submission) + execute(Path(args.output), plan, args.timeout_seconds) + + +if __name__ == "__main__": + main() diff --git a/e2e/qwen_image/test_archived_journey.py b/e2e/qwen_image/test_archived_journey.py new file mode 100644 index 000000000..33e7f0401 --- /dev/null +++ b/e2e/qwen_image/test_archived_journey.py @@ -0,0 +1,176 @@ +"""Read-only replay of the historical observer export. Never invokes its executables.""" + +import re +from pathlib import Path +from statistics import median + +import pytest + +from inferrsi.harness import project +from inferrsi.harness.artifact_primitives import sha256 + +from .audit import image_requests, inside, read + + +@pytest.fixture(scope="module") +def archive(pytestconfig): + location = pytestconfig.getoption("e2e_archived_evidence") + if location is None: + pytest.skip("Select a retained #479 actor evidence directory") + return Path(location) + + +@pytest.fixture(scope="module") +def replay(pytestconfig): + location = pytestconfig.getoption("e2e_archived_retest") + if location is None: + pytest.skip("Select a retained #479 independent attempt") + return Path(location) + + +def sample_groups(parent, steps, workload_sha): + """Recompute each recorded median and compare every decoded image by seed.""" + samples = {"baseline": [], "candidate": []} + reference_pixels = None + count = 0 + for step in steps: + directory = parent / step + result = read(directory / "result.json") + assert result["workload_sha256"] == workload_sha, step + pixels = image_requests(directory, result) + if reference_pixels is None: + reference_pixels = pixels + assert pixels == reference_pixels, f"RGBA comparison differs for {step}" + if step.startswith("measurement-"): + samples[step.split("-")[-1]].append(result["median_ms"]) + count += len(pixels) + return samples, count, reference_pixels + + +def test_archived_rounds_and_session_final(archive): + plan = read(archive / "plan/actor-plan.json") + state = read(archive / "results/actor-state.json") + settings = plan["evaluation_settings"] + assert settings["direction"] == "minimize" + expected = [step["id"] for step in project.steps(settings)] + workload = plan["frozen_files"]["protocol/workload.json"] + best = plan["baseline_sha256"] + best_score = None + seen = {best} + assert len(state["rounds"]) >= 2 + reference_pixels = None + for index, record in enumerate([*state["rounds"], state["final"]], start=1): + final = index > len(state["rounds"]) + folder = "actor-final" if final else f"round-{index:02d}" + execution = record["execution"] + assert [step["id"] for step in execution["steps"]] == expected, folder + assert all(step["returncode"] == 0 for step in execution["steps"]), folder + identities = { + "baseline": plan["baseline_sha256"], + "candidate": record["candidate_sha256"], + } + assert [check["step"] for check in execution["source_checks"]] == expected + for check in execution["source_checks"]: + assert check["verified"] and check["actual"] == check["expected"] == identities + samples, _, pixels = sample_groups( + archive / "results/actor" / folder, expected, workload + ) + if reference_pixels is None: + reference_pixels = pixels + assert pixels == reference_pixels, folder + baseline, candidate = (median(samples[arm]) for arm in ("baseline", "candidate")) + assessment = record["assessment"] + assert assessment["quality_passed"] is True + assert assessment["metrics"]["samples"] == samples + assert (assessment["baseline_score"], assessment["score"]) == (baseline, candidate) + if final: + assert record["candidate_sha256"] == best == state["best"]["sha256"] + continue + assert record["candidate_sha256"] not in seen + seen.add(record["candidate_sha256"]) + if best_score is None: + best_score = baseline + gain = (1 - candidate / baseline) * 100 + if candidate < best_score and gain >= settings["min_improvement_pct"]: + best, best_score = record["candidate_sha256"], candidate + assert (record["best_after"]["sha256"], record["best_after"]["score"]) == ( + best, + best_score, + ) + + +def test_archived_independent_measurements(replay): + freeze = read(replay / "evaluator-freeze.json") + seal = read(replay / "sealed-source.json") + summary = read(replay / "independent-result.json") + assert ( + freeze["baseline_revision"] == summary["baseline_revision"] == seal["baseline_revision"] + ) + assert summary["candidate_id"] == seal["candidate_id"] + assert summary["source_sha256"] == seal["source_sha256"] + assert sha256(replay / "candidate.patch") == seal["patch_sha256"] + assert freeze["validator_sha256"] == summary["validator_sha256"] == seal["validator_sha256"] + for name in ("benchmark.py", "model-manifest.json", "workload.json"): + assert sha256(replay / "protocol" / name) == freeze["validator_sha256"][name] + order = re.search(r"\b(?:AB|BA)(?:/(?:AB|BA))*\b", freeze["statistics"]) + assert order and "median of group medians" in freeze["statistics"] + expected = ["quality-baseline", "quality-candidate"] + for index, pair in enumerate(order.group().split("/"), start=1): + arms = {"A": "baseline", "B": "candidate"} + expected.extend(f"measurement-{index:03d}-{arms[arm]}" for arm in pair) + assert [r["step"] for r in summary["execution"]] == expected + assert [c["step"] for c in summary["source_checks"]] == expected + for receipt, check in zip(summary["execution"], summary["source_checks"], strict=True): + directory = replay / "results" / receipt["step"] + assert receipt == read(directory / "receipt.json") + assert receipt["returncode"] == 0 and receipt["result_sha256"] == sha256( + directory / "result.json" + ) + assert check["verified"] and check["after_execution_verified"] + assert {arm: check[arm] for arm in ("baseline", "candidate")} == seal["source_sha256"] + samples, count, pixels = sample_groups( + replay / "results", expected, freeze["validator_sha256"]["workload.json"] + ) + assert summary["samples"] == samples + baseline, candidate = median(samples["baseline"]), median(samples["candidate"]) + assert summary["baseline_ms"] == baseline and summary["candidate_ms"] == candidate + assert summary["latency_reduction_ms"] == pytest.approx(baseline - candidate) + assert summary["latency_reduction_pct"] == pytest.approx(100 * (1 - candidate / baseline)) + assert summary["raw_request_timings"] == summary["decoded_pngs_verified"] == count + assert summary["quality_pairs_passed"] == len(pixels) + + +def test_archived_patch_matches_selected_snapshot(archive, replay): + """Evaluate the current exact-source requirement against the old evidence.""" + state = read(archive / "results/actor-state.json") + seal = read(replay / "sealed-source.json") + chosen = next(r for r in state["rounds"] if r["candidate_id"] == seal["candidate_id"]) + assert seal["candidate_attempt"] == chosen["path"] + "/candidate" + assert ( + seal["measured_candidate_sha256"] + == chosen["candidate_sha256"] + == state["final"]["candidate_sha256"] + ) + assert ( + sha256(archive / "patch/qwen21-a2.patch") + == sha256(replay / "candidate.patch") + == seal["patch_sha256"] + ) + for mapping in seal["delivery_format_mapping"]: + measured_result = read( + archive / "results/actor/actor-final/measurement-001-candidate/result.json" + ) + digest_fields = { + "autoencoder_kl_qwenimage21.py": "vae_sha256", + "qwen_image_21_transformer.py": "transformer_sha256", + "pipeline_qwen_image_21.py": "pipeline_sha256", + } + measured = measured_result[digest_fields[Path(mapping["file"]).name]] + rebuilt = sha256(inside(replay / "candidate", mapping["file"])) + assert (measured, rebuilt) == (mapping["measured_sha256"], mapping["delivery_sha256"]) + assert rebuilt == measured, ( + f"Reconstructed {Path(mapping['file']).name} differs from the measured VAE" + ) + assert seal["matches_actor_snapshot_bytes"] is True, ( + "The historical reconstruction receipt records a byte mismatch with the Agent snapshot." + ) diff --git a/e2e/qwen_image/test_user_journey.py b/e2e/qwen_image/test_user_journey.py new file mode 100644 index 000000000..9657d6d75 --- /dev/null +++ b/e2e/qwen_image/test_user_journey.py @@ -0,0 +1,62 @@ +"""Explicit acceptance entry: live Agent run or read-only evidence replay.""" + +from pathlib import Path +from subprocess import CalledProcessError + +import pytest + +from e2e.qwen_image.audit import EvidenceViolation, audit, read, reference +from e2e.qwen_image.driver import discover, launch +from e2e.qwen_image.retest import execute, seal, write + + +@pytest.fixture(scope="module") +def observed(e2e_options): + options = e2e_options + if not options["live"]: + report = audit(options["campaign"], options["observer"]) + if options["artifacts"]: + output = Path(options["artifacts"]) + output.mkdir(parents=True, exist_ok=False) + write(output / "pytest-report.json", report) + return report + output = Path(options["artifacts"]) + host = launch(options["project"], options["baseline_revision"], output, + executable=options["executable"], model=options["model"], + timeout=options["timeout_seconds"]) + if (host["returncode"] != 0 or host["state"] != "exited" + or not host["native_turn_completed"]): + report = {"workflow_verdict": "INCONCLUSIVE", "findings": [{ + "code": "host_did_not_complete", "verdict": "INCONCLUSIVE"}], "host": host} + write(output / "pytest-report.json", report) + return report + try: + campaign = discover(options["campaign_parent"], options["project"], host["started_at"]) + if options["retest"]: + if not options["patch"]: + raise ValueError("An actual --e2e-patch is required before independent timing") + observer = Path(options["observer"]) + submission = reference(observer.parent, read(observer)["submission"]) + plan, _ = seal(options["project"], options["baseline_revision"], campaign, + options["patch"], output / "independent", submission=submission) + execute(output / "independent", plan, options["timeout_seconds"]) + report = audit(campaign, options["observer"], host_reply=output / "final-reply.txt") + except EvidenceViolation: + report = {"workflow_verdict": "FAIL", "findings": [{ + "code": "independent_patch_identity_violation", "verdict": "FAIL"}]} + except (OSError, ValueError, KeyError, CalledProcessError) as error: + report = {"workflow_verdict": "INCONCLUSIVE", "findings": [{ + "code": "collection_or_independent_retest_incomplete", "verdict": "INCONCLUSIVE", + "error_type": type(error).__name__}]} + write(output / "pytest-report.json", report) + return report + + +def test_ordinary_user_optimization(observed): + # pytest has no INCONCLUSIVE status. Keep it in the JSON receipt and fail the + # acceptance assertion, rather than silently reporting missing NPU evidence green. + assert observed["workflow_verdict"] == "PASS", observed + + +def test_completion_required_no_observer_assistance(observed): + assert observed.get("completion_mode") == "unassisted", observed diff --git a/tests/campaigns/test_user_e2e_audit.py b/tests/campaigns/test_user_e2e_audit.py new file mode 100644 index 000000000..f55aa0a49 --- /dev/null +++ b/tests/campaigns/test_user_e2e_audit.py @@ -0,0 +1,598 @@ +"""CPU negative controls for #479; synthetic times/images, never A2 qualification.""" + +import copy +import hashlib +import io +import json +import shutil +import subprocess +import sys +from contextlib import redirect_stdout +from pathlib import Path + +import pytest + +from e2e.qwen_image.audit import ( + Report, + audit, + audit_selection, + check_choices, + check_final_reply, + check_independent, + check_outputs, + check_timing_aa, + image_requests, + read, + recompute, + select_patch_round, +) +from e2e.qwen_image.driver import discover, launch +from e2e.qwen_image.retest import execute, git, seal, write +from inferrsi.apps.cli import main +from inferrsi.harness.artifact_primitives import digest, sha256 +from inferrsi.harness.optimization import read_records + +REPOSITORY_ROOT = Path(__file__).resolve().parents[2] +FIXTURES = REPOSITORY_ROOT / "tests/fixtures/user_e2e" + + +def invoke(argv): + with redirect_stdout(io.StringIO()) as output: + assert main(argv) == 0, output.getvalue() + return json.loads(output.getvalue()) + + +def ref(root, path): + return {"path": path.relative_to(root).as_posix(), "sha256": sha256(path)} + + +@pytest.fixture(scope="module") +def campaign(tmp_path_factory): + Image = pytest.importorskip("PIL.Image") + root = tmp_path_factory.mktemp("synthetic-user-e2e") + repo, protocol, campaign = (root / name for name in ("repo", "protocol", "campaign")) + repo.mkdir() + protocol.mkdir() + (repo / "engine.py").write_bytes(b"LATENCY = 100\n") + git(repo, "init") + git(repo, "add", "engine.py") + git(repo, "-c", "user.name=Synthetic Control", "-c", "user.email=control@example.invalid", + "commit", "-m", "Synthetic baseline") + baseline = git(repo, "rev-parse", "HEAD").decode().strip() + cases = [{"seed": seed, "prompt": f"Synthetic seed {seed}"} for seed in range(42, 48)] + write(protocol / "cases.json", cases) + write(protocol / "workload.json", { + "width": 1280, "height": 704, "dtype": "bfloat16", "batch_size": 1, + "concurrency": 1, "tensor_parallel_size": 1, "guidance_scale": 1, + "num_inference_steps": 8, "timing_scope": "Omni.generate_to_decoded_image", + "requests": cases, + }) + scheduler = {"num_steps": 8, "timesteps": list(range(8)), "sigmas": [1, 0]} + for case in cases: + Image.new("RGBA", (1280, 704), (case["seed"], 0, 0, 255)).save( + protocol / f"seed-{case['seed']}.png") + # A real child process is started for every quality/measurement step. It + # copies fixed synthetic images; no model, Codex or accelerator is involved. + (protocol / "measure.py").write_bytes( + (FIXTURES / "measure.py").read_bytes()) + instructions = root / "request.md" + instructions.write_text("Synthetic software control; no performance claim.", encoding="utf-8") + command = '"{python}" "{protocol}/measure.py" "{candidate}" "{result}"' + timing_rows = [] + for group, arms in enumerate((("baseline", "candidate"), ("candidate", "baseline")), start=1): + for arm in arms: + step = f"measurement-{group:03d}-{arm}" + directory = root / f"aa-{step}" + directory.mkdir() + result = directory / "result.json" + subprocess.run([sys.executable, str(protocol / "measure.py"), str(repo), str(result)], + check=True) + timing_rows.append({"step": step, "result": ref(root, result)}) + trace = root / "timing-aa.json" + write(trace, timing_rows) + write(protocol / "timing-policy.json", { + "estimator": "maximum_absolute_paired_change_pct", "observed_noise_pct": 0, + "adoption_threshold_pct": 1, "adoption_comparator": "current_best", + "aa_sha256": sha256(trace), + }) + invoke(["campaign", "start", "--directory", str(campaign), "--repo", str(repo), + "--include", "engine.py", "--protocol", str(protocol), + "--instructions", str(instructions), "--measure-command", command, + "--quality-command", command, "--metric-key", "median_ms", "--metric-unit", "ms", + "--direction", "minimize", "--quality-key", "correct", "--scope", "synthetic-only", + "--repetitions", "2", "--warmups", "0", "--min-improvement-pct", "1", + "--rounds", "3", "--round-mode", "exact", "--max-minutes", "5", + "--evaluation-timeout-seconds", "30"]) + repeat_paths = [] + for index in range(2): + directory = root / f"baseline-repeat-{index}" + directory.mkdir() + result = directory / "result.json" + subprocess.run([sys.executable, str(campaign / "frozen/protocol/measure.py"), + str(campaign / "frozen/baseline"), str(result)], check=True) + repeat_paths.append(result) + invoke(["campaign", "diagnose", "--directory", str(campaign), + "--bottleneck", "Synthetic measured request latency", + "--evidence", str(repeat_paths[0])]) + for value in (90, 110, 80): + (repo / "engine.py").write_bytes(f"LATENCY = {value}\n".encode()) + invoke(["campaign", "round", "--directory", str(campaign), "--candidate", str(repo), + "--hypothesis", "Synthetic declared source change"]) + invoke(["campaign", "final", "--directory", str(campaign)]) + patch = root / "delivered.patch" + patch.write_bytes(git(repo, "diff", "--binary", "HEAD")) + _, state, _ = read_records(campaign) + selected = select_patch_round(state["rounds"]) + submission = root / "submission.json" + write(submission, {"candidate_id": selected["candidate_id"], "attempt": selected["path"], + "candidate_sha256": selected["candidate_sha256"], + "patch_sha256": sha256(patch)}) + plan, _ = seal(repo, baseline, campaign, patch, root / "independent", submission=submission) + execute(root / "independent", plan, 60) + plan, state, _ = read_records(campaign) + choices = {} + current_best = plan["baseline_sha256"] + for index, record in enumerate(state["rounds"]): + event_root = root / record["candidate_id"] + event_root.mkdir() + choice = {} + for offset, key in enumerate(("plan_event", "first_edit_event", "measurement_event")): + event = {"sequence": index * 3 + offset, "raw": "synthetic host event", + "host_session_id": "synthetic-session"} + if offset == 0: + event["choice"] = { + "starting_best_sha256": current_best, + "alternatives": ["synthetic A", "synthetic B"], + "chosen_measure": "synthetic A", "reason": "Synthetic control rationale", + "expected_effect": "reduce synthetic metric", "risk": "synthetic risk", + "sources": ["synthetic source"], + "feedback_or_initial_analysis": "Synthetic previous observation", + } + path = event_root / (key + ".json") + write(path, event) + choice[key] = ref(root, path) + review = event_root / "review.json" + diff = event_root / "candidate-source.txt" + diff.write_bytes((campaign / record["path"] / "candidate/engine.py").read_bytes()) + write(review, {"independent": True, "reviewer": "synthetic-control-reviewer", + "basis": "Synthetic applicability evidence", + "diff_refs": [ref(root, diff)], "verdict": "PASS", + "candidate_sha256": record["candidate_sha256"], + "expectation": "supported"}) + choice["review"] = ref(root, review) + choices[record["candidate_id"]] = choice + current_best = record["best_after"]["sha256"] + preparation = root / "preparation.json" + write(preparation, { + "input_version": "synthetic-v1", "baseline_revision": baseline, + "plan_digest": digest(plan), "protocol_frozen_at": state["started_at"], + "runspec": {"repository": "vllm-project/vllm-omni", "revision": baseline, + "backend": "ascend", "device_class": "A2", "device_count": 1, + "model": "Qwen-Image-2.1-Turbo"}, + "codex": {"client": "synthetic", "version": "synthetic", "model": "synthetic", + "configuration_sha256": "synthetic"}, + "inferrsi": {"version": "synthetic", "runtime_digest": digest(plan["runtime_identity"])}, + "a2_skill": {"name": "synthetic", "sha256": "synthetic"}, + "checks": dict.fromkeys(("noninteractive_login", "healthy_exclusive_device", + "model_bytes_verified", "baseline_repeat_before_search", + "owned_resources_cleaned"), True), + "quality_cases": ref(root, campaign / "frozen/protocol/cases.json"), + "timing_policy": ref(root, campaign / "frozen/protocol/timing-policy.json"), + "workload": ref(root, campaign / "frozen/protocol/workload.json"), + "expected_scheduler": scheduler, + }) + reply = root / "reply.txt" + reply.write_text( + f"Selected {selected['candidate_id']}. Baseline 100 ms, final 80 ms, " + "a 20 ms (20%) reduction. Quality 6/6. See independent/receipt.json " + "and independent/candidate.patch. These are synthetic measurements.", + encoding="utf-8") + observer = { + "round_choices": choices, "preparation": ref(root, preparation), + "timing_aa": ref(root, trace), + "submission": ref(root, submission), + "final_reply": ref(root, reply), "interventions": [], + "independent_directory": "independent", "baseline_repeat": { + "results": [ref(root, path) for path in repeat_paths], + "fresh_process_ids": [read(path)["process"]["id"] for path in repeat_paths], + "search_started_at": state["rounds"][0]["started_at"], + "source_sha256": [plan["baseline_sha256"]] * 2, + "effective_scheduler": scheduler, + "environment_identity": "synthetic-not-a-device", + "workload_sha256": sha256(protocol / "workload.json"), + }, + } + write(root / "observer.json", observer) + return root, repo, campaign, plan, state, observer, baseline, patch + + +def codes(report): + return {item["code"] for item in report.findings} + + +@pytest.mark.parametrize("change,expected", [ + ("missing", "INCONCLUSIVE"), ("different_trace", "FAIL"), ("lower_gate", "FAIL"), +]) +def test_timing_aa_must_match_the_frozen_raw_measurements(campaign, change, expected): + root, _, _, plan, _, observer, *_ = campaign + observer = copy.deepcopy(observer) + plan = copy.deepcopy(plan) + preparation = read(root / observer["preparation"]["path"]) + if change == "missing": + del observer["timing_aa"] + elif change == "different_trace": + observer["timing_aa"] = observer["preparation"] + else: + plan["evaluation_settings"]["min_improvement_pct"] = 0 + report = Report() + check_timing_aa(root, observer, preparation, plan, report) + assert report.document()["workflow_verdict"] == expected + + +def test_complete_synthetic_journey_recomputes_choices_and_two_receipts(campaign): + root, _, path, *_ = campaign + report = audit(path, root / "observer.json") + assert report["workflow_verdict"] == "PASS", report + assert [row["decision"] for row in report["rounds"]] == [ + "adopt", "keep_previous_best", "adopt"] + assert report["rounds"][1]["incremental_improvement_pct"] < 0 + assert report["rounds"][2]["starting_best_sha256"] == report["rounds"][0]["source_sha256"] + for receipt in ("session_final", "independent_patch_retest"): + assert report[receipt]["baseline_ms"] == 100 + assert report[receipt]["candidate_ms"] == 80 + assert report[receipt]["delta_ms"] == 20 + + +def test_cross_arm_swap_is_rejected_even_with_identical_arm_multisets(campaign): + _, _, root, plan, state, *_ = campaign + directory = root / state["rounds"][0]["path"] + execution = read(directory / "execution/execution.json") + execution["steps"][2:4] = reversed(execution["steps"][2:4]) + with pytest.raises(ValueError, match="Cross-arm"): + recompute(directory, plan["evaluation_settings"], execution) + + +def test_slower_candidate_must_not_replace_best(campaign): + _, _, root, plan, state, *_ = campaign + altered = copy.deepcopy(state) + altered["rounds"][1]["best_after"] = { + "sha256": altered["rounds"][1]["candidate_sha256"], "score": 110, "kind": "candidate"} + report = Report() + audit_selection(plan, altered, root, report) + assert "wrong_adopt_reject_decision" in codes(report) + + +def test_change_inside_noise_must_not_replace_the_previous_best(campaign, monkeypatch): + _, _, root, plan, state, *_ = campaign + altered = copy.deepcopy(state) + record = altered["rounds"][-1] + record["assessment"]["score"] = 89.5 # Below baseline 100, within 1% of best 90. + record["best_after"]["score"] = 89.5 + original = recompute + + def replay(directory, *args): + if directory == root / record["path"]: + return record["assessment"] + return original(directory, *args) + + monkeypatch.setattr("e2e.qwen_image.audit.recompute", replay) + report = Report() + audit_selection(plan, altered, root, report) + assert report.rounds[-1]["decision"] == "keep_previous_best" + assert "wrong_adopt_reject_decision" in codes(report) + + +def test_baseline_winner_still_selects_real_patch_and_earliest_tie(): + rounds = [{"candidate_id": name, "assessment": { + "status": "completed", "quality_passed": True, "score": score, "eligible": False}} + for name, score in (("first", 110), ("second", 110), ("third", 120))] + assert select_patch_round(rounds)["candidate_id"] == "first" + + +def test_wrong_legal_patch_rejected_before_any_measurement(campaign): + root, repo, path, _, _, _, baseline, _ = campaign + wrong = root / "different.patch" + original = (repo / "engine.py").read_bytes() + try: + (repo / "engine.py").write_bytes(b"LATENCY = 85\n") + wrong.write_bytes(git(repo, "diff", "HEAD")) + finally: + (repo / "engine.py").write_bytes(original) + output = root / "wrong-independent" + with pytest.raises(ValueError, match="original submission"): + seal(repo, baseline, path, wrong, output, submission=root / "submission.json") + assert not (output / "seal.json").exists() + assert not (output / "attempt/execution").exists() + + +def test_different_patch_with_identical_source_is_rejected(campaign, tmp_path): + root, repo, path, _, _, _, baseline, original = campaign + clone = tmp_path / "baseline" + git(repo, "clone", "--quiet", "--config", "core.autocrlf=false", str(repo), str(clone)) + equivalent = tmp_path / "equivalent.patch" + equivalent.write_bytes(b"Equivalent change with a distinct header\n\n" + original.read_bytes()) + git(clone, "apply", str(equivalent)) + assert (clone / "engine.py").read_bytes() == (repo / "engine.py").read_bytes() + output = tmp_path / "independent" + with pytest.raises(ValueError, match="original submission"): + seal(repo, baseline, path, equivalent, output, submission=root / "submission.json") + assert not output.exists() + + +def test_sealed_source_drift_is_rejected_before_timing(campaign): + root, repo, path, _, _, _, baseline, patch = campaign + output = root / "changed-after-seal" + plan, _ = seal(repo, baseline, path, patch, output, submission=root / "submission.json") + (output / "attempt/candidate/engine.py").write_bytes(b"LATENCY = 1\n") + with pytest.raises(ValueError, match="changed before timing"): + execute(output, plan, 30) + assert not (output / "attempt/execution").exists() + + +def test_posthoc_choice_is_rejected(campaign): + root, _, _, _, state, observer, *_ = campaign + observer = copy.deepcopy(observer) + choice = observer["round_choices"][state["rounds"][0]["candidate_id"]] + choice["plan_event"], choice["first_edit_event"] = ( + choice["first_edit_event"], choice["plan_event"]) + report = Report() + report.rounds = [{"starting_best_sha256": "synthetic"}] * len(state["rounds"]) + check_choices(root, observer, state["rounds"], report) + assert "choice_recorded_after_edit_or_measurement" in codes(report) + + +def test_missing_choice_review_never_becomes_automatic_pass(campaign): + root, _, _, _, state, observer, *_ = campaign + observer = copy.deepcopy(observer) + del observer["round_choices"][state["rounds"][0]["candidate_id"]]["review"] + report = Report() + report.rounds = [{"starting_best_sha256": "synthetic"}] * len(state["rounds"]) + check_choices(root, observer, state["rounds"], report) + assert "choice_evidence_unavailable" in codes(report) + + +@pytest.mark.parametrize("change,expected", [ + ("fresh_process_ids", "baseline_repeat_not_across_fresh_processes"), + ("source_sha256", "baseline_repeat_wrong_source"), + ("effective_scheduler", "baseline_repeat_protocol_mismatch"), +]) +def test_unqualified_baseline_stays_inconclusive(campaign, change, expected): + root, _, path, plan, state, observer, *_ = campaign + observer = copy.deepcopy(observer) + observer["baseline_repeat"][change] = { + "fresh_process_ids": ["same", "same"], "source_sha256": ["wrong", "wrong"], + "effective_scheduler": {"synthetic_grid": [99]}, + }[change] + report = Report() + check_outputs(path, plan, state, root, observer, report) + assert expected in codes(report) + assert report.document()["workflow_verdict"] == ("FAIL" if change == "source_sha256" + else "INCONCLUSIVE") + + +def test_independent_receipt_cannot_be_bound_to_a_different_attempt(campaign): + root, _, _, plan, state, observer, *_ = campaign + selected = {**select_patch_round(state["rounds"]), "path": "wrong-attempt"} + report = Report() + check_independent(root, observer, selected, plan, report) + assert "independent_selection_binding_mismatch" in codes(report) + + +def test_assistance_is_separate_from_correct_results(campaign): + root, _, path, _, _, observer, *_ = campaign + observer = copy.deepcopy(observer) + observer["interventions"] = [{"kind": "assistance", "stage": "baseline", + "at_seconds": 12, "reason": "synthetic connection repair", + "action": "synthetic repair"}] + receipt = root / "assisted-observer.json" + write(receipt, observer) + report = audit(path, receipt) + assert report["workflow_verdict"] == "FAIL" + assert report["completion_mode"] == "assisted" + assert report["independent_patch_retest"]["quality_passed"] is True + assert report["first_blocked_step"] == "baseline" + + +def test_live_driver_refuses_dirty_project_before_launch(campaign): + root, repo, _, _, _, _, baseline, _ = campaign + with pytest.raises(ValueError, match="clean"): + launch(repo, baseline, root / "never-launched", executable="not-a-command", + model="synthetic", timeout=10) + assert not (root / "never-launched").exists() + + +def test_driver_sends_only_the_natural_request_to_one_new_session(campaign, tmp_path): + _, repo, _, _, _, _, baseline, _ = campaign + clean = tmp_path / "clean-project" + git(repo, "clone", "--no-checkout", str(repo), str(clean)) + git(clean, "checkout", "--detach", baseline) + output = tmp_path / "host-output" + fake_host = FIXTURES / "codex_host.py" + receipt = launch(clean, baseline, output, executable=[sys.executable, str(fake_host)], + model="synthetic-model", timeout=15) + expected = REPOSITORY_ROOT / "e2e/qwen_image/request.txt" + assert (output / "final-reply.txt").read_text(encoding="utf-8") == ( + expected.read_text(encoding="utf-8").strip()) + assert receipt["native_session_ids"] == ["synthetic-session"] + assert receipt["native_turn_completed"] is True + assert receipt["elapsed_seconds"] > 0 + assert (output / "events.jsonl").is_file() + + +def test_discovery_excludes_old_or_other_project_campaigns(campaign): + root, repo, path, _, state, *_ = campaign + assert discover(root, repo, state["started_at"] - 1) == path + with pytest.raises(ValueError, match="one new campaign"): + discover(root, repo, state["started_at"] + 1) + + +@pytest.mark.parametrize("archive,host,expected", [ + (b"candidate A\n", b"candidate A\n", None), + (b"candidate A\n", b"candidate A\r\n", "observer_reply_differs_from_host_output"), + (b"candidate A", b"candidate B", "observer_reply_differs_from_host_output"), + (b"\xef\xbb\xbf \r\n", None, "empty_final_reply"), +]) +def test_final_reply_preserves_the_host_bytes(tmp_path, archive, host, expected): + reply = tmp_path / "observer-reply.txt" + reply.write_bytes(archive) + host_reply = None + if host is not None: + host_reply = tmp_path / "final-reply.txt" + host_reply.write_bytes(host) + report = Report() + check_final_reply(tmp_path, {"final_reply": ref(tmp_path, reply)}, report, host_reply) + if expected: + assert report.findings == [{"code": expected, "verdict": "FAIL"}] + else: + assert not report.findings + assert report.results["final_reply_sha256"] == sha256(host_reply) + + +def test_missing_host_reply_is_inconclusive_even_with_observer_copy(tmp_path): + reply = tmp_path / "observer-reply.txt" + reply.write_bytes(b"Retained copy") + report = Report() + check_final_reply(tmp_path, {"final_reply": ref(tmp_path, reply)}, report, + tmp_path / "missing-host-output.txt") + assert report.findings == [ + {"code": "final_reply_evidence_unavailable", "verdict": "INCONCLUSIVE"}] + + +def test_missing_evidence_is_not_a_passing_skip(tmp_path): + report = audit(tmp_path, tmp_path / "missing-observer.json") + assert report["workflow_verdict"] == "INCONCLUSIVE" + + +@pytest.mark.parametrize("field,expected,verdict", [ + ("effective_scheduler", "effective_scheduler_changed", "FAIL"), + ("environment_identity", "environment_or_workload_not_comparable", "INCONCLUSIVE"), + ("median_ms", "raw_quality_or_timing_evidence_contradicted", "FAIL"), +]) +def test_raw_candidate_changes_are_not_hidden_by_summary( + campaign, tmp_path, field, expected, verdict): + root, _, path, plan, state, observer, *_ = campaign + record = state["rounds"][0] + step = "measurement-001-candidate" + directory = tmp_path / "attempt/execution" / step + shutil.copytree(path / record["path"] / "execution" / step, directory) + result = read(directory / "result.json") + result[field] = {"effective_scheduler": {"num_steps": 1}, + "environment_identity": "different-synthetic-environment", + "median_ms": 1}[field] + write(directory / "result.json", result) + write(directory.parent / "execution.json", {"steps": [{"id": step}]}) + fake_state = {"rounds": [], "final": {**record, "path": "attempt"}} + report = Report() + check_outputs(tmp_path, plan, fake_state, root, observer, report) + assert expected in codes(report) + assert report.document()["workflow_verdict"] == verdict + + +@pytest.mark.parametrize("attempt,step,missing", [ + ("round", "quality-baseline", False), + ("final", "measurement-001-candidate", True), + ("independent", "measurement-001-candidate", False), +]) +def test_worker_must_load_the_source_of_its_arm(campaign, monkeypatch, attempt, step, missing): + root, _, path, _, state, *_ = campaign + directory = {"round": path / state["rounds"][0]["path"], + "final": path / state["final"]["path"], + "independent": root / "independent/attempt"}[attempt] + target = directory / "execution" / step / "result.json" + + def worker_result(filename): + result = read(filename) + if filename == target: + if missing: + del result["loaded_source_sha256"] + else: + result["loaded_source_sha256"] = "0" * 64 + return result + + monkeypatch.setattr("e2e.qwen_image.audit.read", worker_result) + report = audit(path, root / "observer.json") + assert report["workflow_verdict"] == ("INCONCLUSIVE" if missing else "FAIL") + code = "loaded_source_identity_missing" if missing else "wrong_source_loaded" + assert any(row["code"] == code and row["step"] == step for row in report["findings"]) + + +def test_verified_flag_cannot_hide_a_different_loaded_source(campaign): + _, _, root, plan, state, *_ = campaign + record = state["rounds"][0] + directory = root / record["path"] + execution = read(directory / "execution/execution.json") + expected = {"baseline": plan["baseline_sha256"], "candidate": record["candidate_sha256"]} + execution["source_checks"][0]["expected"]["candidate"] = "different-source" + execution["source_checks"][0]["actual"]["candidate"] = "different-source" + execution["source_checks"][0]["verified"] = True + with pytest.raises(ValueError, match="Loaded source"): + recompute(directory, plan["evaluation_settings"], execution, expected) + + +def test_repeated_source_is_not_another_optimization_round(campaign): + _, _, root, plan, state, *_ = campaign + altered = copy.deepcopy(state) + first = altered["rounds"][0] + altered["rounds"] = [first, copy.deepcopy(first)] + altered["best"] = first["best_after"] + altered["final"] = None + report = Report() + audit_selection(plan, altered, root, report) + assert "unchanged_or_repeated_candidate" in codes(report) + + +def test_rejected_quality_cannot_be_adopted_as_best(campaign, tmp_path): + _, _, root, plan, state, *_ = campaign + record = copy.deepcopy(state["rounds"][0]) + directory = tmp_path / "attempt" + shutil.copytree(root / record["path"], directory) + result_path = directory / "execution/quality-candidate/result.json" + result = read(result_path) + result["correct"] = False + write(result_path, result) + execution = read(directory / "execution/execution.json") + execution["steps"] = execution["steps"][:2] + execution["source_checks"] = execution["source_checks"][:2] + write(directory / "execution/execution.json", execution) + record["path"] = "attempt" + record["assessment"] = recompute(directory, plan["evaluation_settings"], execution) + assert record["assessment"]["status"] == "candidate_failure" + altered = {**state, "rounds": [record], "best": record["best_after"], "final": None} + report = Report() + audit_selection(plan, altered, tmp_path, report) + assert "wrong_adopt_reject_decision" in codes(report) + + +def test_unstable_baseline_pixels_are_inconclusive_not_candidate_failure(campaign): + from PIL import Image + + root, _, path, plan, state, observer, *_ = campaign + observer = copy.deepcopy(observer) + old_path = root / observer["baseline_repeat"]["results"][1]["path"] + directory = root / "unstable-baseline-repeat" + shutil.copytree(old_path.parent, directory) + result = read(directory / "result.json") + Image.new("RGBA", (1280, 704), (0, 0, 0, 255)).save(directory / "seed-42.png") + with Image.open(directory / "seed-42.png") as image: + result["requests"][0]["pixel_sha256"] = hashlib.sha256(image.tobytes()).hexdigest() + write(directory / "result.json", result) + image_requests(directory, result) # Internally consistent, but a different baseline image. + observer["baseline_repeat"]["results"][1] = ref(root, directory / "result.json") + report = Report() + check_outputs(path, plan, state, root, observer, report) + assert "baseline_pixel_reference_unqualified" in codes(report) + assert report.document()["workflow_verdict"] == "INCONCLUSIVE" + + +@pytest.mark.parametrize("complete", [True, False]) +def test_pytest_replay_entry_writes_verdict_and_never_hides_gaps(campaign, tmp_path, complete): + root, _, path, *_ = campaign + observer = root / "observer.json" if complete else tmp_path / "unavailable.json" + output = tmp_path / "report" + result = subprocess.run([ + sys.executable, "-m", "pytest", "e2e/qwen_image", "--e2e-campaign", str(path), + "--e2e-observer", str(observer), "--e2e-artifacts", str(output), + ], cwd=REPOSITORY_ROOT, capture_output=True, text=True, encoding="utf-8") + assert result.returncode == (0 if complete else 1), result.stdout + result.stderr + assert read(output / "pytest-report.json")["workflow_verdict"] == ( + "PASS" if complete else "INCONCLUSIVE") diff --git a/tests/fixtures/user_e2e/codex_host.py b/tests/fixtures/user_e2e/codex_host.py new file mode 100644 index 000000000..48b371b54 --- /dev/null +++ b/tests/fixtures/user_e2e/codex_host.py @@ -0,0 +1,15 @@ +"""Synthetic CLI host exercising exact prompt delivery, not an actual Agent.""" + +import json +import sys +from pathlib import Path + +if sys.argv[1:] == ["--version"]: + print("synthetic-codex-control") +else: + prompt = sys.stdin.buffer.read().decode("utf-8") + reply = Path(sys.argv[sys.argv.index("--output-last-message") + 1]) + reply.write_text(prompt, encoding="utf-8") + for event in ({"type": "thread.started", "thread_id": "synthetic-session"}, + {"type": "turn.completed"}): + print(json.dumps(event), flush=True) diff --git a/tests/fixtures/user_e2e/measure.py b/tests/fixtures/user_e2e/measure.py new file mode 100644 index 000000000..6929ac4d3 --- /dev/null +++ b/tests/fixtures/user_e2e/measure.py @@ -0,0 +1,38 @@ +"""Synthetic CPU control, not a Qwen benchmark or hardware evidence.""" + +import hashlib +import json +import os +import runpy +import shutil +import sys +import time +from pathlib import Path + +from PIL import Image + +from inferrsi.harness import candidates + +started = time.time() +source, output = map(Path, sys.argv[1:3]) +engine = runpy.run_path(str(source / "engine.py")) +loaded_file = Path(engine["__file__"]) +loaded_sha = candidates.identity(loaded_file.parent, [loaded_file.name]) +metric = engine["LATENCY"] +requests = [] +for seed in range(42, 48): + path = output.parent / f"seed-{seed}.png" + shutil.copyfile(Path(__file__).with_name(path.name), path) + with Image.open(path) as image: + pixels = hashlib.sha256(image.convert("RGBA").tobytes()).hexdigest() + requests.append({"seed": seed, "latency_ms": metric, "file": path.name, + "pixel_sha256": pixels}) +output.write_text(json.dumps({ + "loaded_source_sha256": loaded_sha, + "median_ms": metric, "correct": True, "requests": requests, + "effective_scheduler": {"num_steps": 8, "timesteps": list(range(8)), "sigmas": [1, 0]}, + "process": {"id": str(os.getpid()), "finished_at": time.time(), "started_at": started}, + "environment_identity": "synthetic-not-a-device", + "workload_sha256": hashlib.sha256(Path(__file__).with_name("workload.json").read_bytes()) + .hexdigest(), +}), encoding="utf-8") From 3bcaaaf1a18879f8d2c7ed28f13de3e6d950ef94 Mon Sep 17 00:00:00 2001 From: Zeng Chuang Date: Wed, 25 Nov 2026 16:25:03 +0800 Subject: [PATCH 2/4] Allow for six worker startups in the synthetic CPU fixture Agent-assisted-by: Codex (implementation and verification) Signed-off-by: zengchuang --- tests/campaigns/test_user_e2e_audit.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/campaigns/test_user_e2e_audit.py b/tests/campaigns/test_user_e2e_audit.py index f55aa0a49..2ca57d2c0 100644 --- a/tests/campaigns/test_user_e2e_audit.py +++ b/tests/campaigns/test_user_e2e_audit.py @@ -34,6 +34,8 @@ REPOSITORY_ROOT = Path(__file__).resolve().parents[2] FIXTURES = REPOSITORY_ROOT / "tests/fixtures/user_e2e" +# Each synthetic evaluation starts six Python workers and decodes their images. +FIXTURE_EVALUATION_SECONDS = 120 def invoke(argv): @@ -101,8 +103,8 @@ def campaign(tmp_path_factory): "--quality-command", command, "--metric-key", "median_ms", "--metric-unit", "ms", "--direction", "minimize", "--quality-key", "correct", "--scope", "synthetic-only", "--repetitions", "2", "--warmups", "0", "--min-improvement-pct", "1", - "--rounds", "3", "--round-mode", "exact", "--max-minutes", "5", - "--evaluation-timeout-seconds", "30"]) + "--rounds", "3", "--round-mode", "exact", "--max-minutes", "12", + "--evaluation-timeout-seconds", str(FIXTURE_EVALUATION_SECONDS)]) repeat_paths = [] for index in range(2): directory = root / f"baseline-repeat-{index}" @@ -128,7 +130,7 @@ def campaign(tmp_path_factory): "candidate_sha256": selected["candidate_sha256"], "patch_sha256": sha256(patch)}) plan, _ = seal(repo, baseline, campaign, patch, root / "independent", submission=submission) - execute(root / "independent", plan, 60) + execute(root / "independent", plan, FIXTURE_EVALUATION_SECONDS) plan, state, _ = read_records(campaign) choices = {} current_best = plan["baseline_sha256"] From ef13eb2a77cf341fee2423a37201a0a0f0785f81 Mon Sep 17 00:00:00 2001 From: Zeng Chuang Date: Wed, 25 Nov 2026 16:51:56 +0800 Subject: [PATCH 3/4] Run one unattended Codex optimization and measure the delivered patch on A2 Agent-assisted-by: Codex (implementation and verification) Signed-off-by: zengchuang --- docs/contributing.md | 5 +- docs/e2e-qwen-image-codex.md | 217 +-------- e2e/__init__.py | 1 - e2e/conftest.py | 39 -- e2e/qwen_image/__init__.py | 1 - e2e/qwen_image/audit.py | 556 ---------------------- e2e/qwen_image/driver.py | 115 ----- e2e/qwen_image/measure.py | 99 ++++ e2e/qwen_image/retest.py | 144 ------ e2e/qwen_image/test_archived_journey.py | 176 ------- e2e/qwen_image/test_user_journey.py | 255 +++++++--- e2e/qwen_image/workload.json | 18 + tests/campaigns/test_user_e2e_audit.py | 600 ------------------------ tests/fixtures/user_e2e/codex_host.py | 15 - tests/fixtures/user_e2e/measure.py | 38 -- 15 files changed, 340 insertions(+), 1939 deletions(-) delete mode 100644 e2e/__init__.py delete mode 100644 e2e/conftest.py delete mode 100644 e2e/qwen_image/__init__.py delete mode 100644 e2e/qwen_image/audit.py delete mode 100644 e2e/qwen_image/driver.py create mode 100644 e2e/qwen_image/measure.py delete mode 100644 e2e/qwen_image/retest.py delete mode 100644 e2e/qwen_image/test_archived_journey.py create mode 100644 e2e/qwen_image/workload.json delete mode 100644 tests/campaigns/test_user_e2e_audit.py delete mode 100644 tests/fixtures/user_e2e/codex_host.py delete mode 100644 tests/fixtures/user_e2e/measure.py diff --git a/docs/contributing.md b/docs/contributing.md index d7687f5be..cb604be69 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -28,9 +28,8 @@ Synthetic benchmark scripts belong in `tests/fixtures/`; historical validator snapshots in `tests/fixtures/legacy/` remain byte-for-byte frozen. Current runnable examples are the three Qwen scripts under `examples/`. -For the [Codex user-journey E2E case](e2e-qwen-image-codex.md), select a live -Codex/A2 session or replay retained artifacts with the documented pytest options. -Its CPU controls run in the default test suite. +Run the [Codex Qwen-Image E2E case](e2e-qwen-image-codex.md) on a prepared +Ascend A2 host to optimize the model and independently measure the delivered patch. Git treats recorded bundles under `evidence/` and `tests/fixtures/legacy/` as exact bytes (`-text`), so checkout and add do not normalize their line endings. diff --git a/docs/e2e-qwen-image-codex.md b/docs/e2e-qwen-image-codex.md index 5244b7e8c..8774590a5 100644 --- a/docs/e2e-qwen-image-codex.md +++ b/docs/e2e-qwen-image-codex.md @@ -1,209 +1,36 @@ -# Codex 用户优化 Qwen-Image 的 pytest 用例 +# 在 Ascend A2 上运行 Codex 图像优化 E2E -设计与验收范围:[Issue #479](https://github.com/InferMatrixLab/InferRSI/issues/479)。 -这是普通用户体验用例,不是 `benchmarks` 题包。测试入口在 -[`e2e/qwen_image/test_user_journey.py`](../e2e/qwen_image/test_user_journey.py), -不在默认 `pytest` 的 `tests/` 范围内,不增加 CI lane 或自动预约 NPU。 +本目录只有一个 pytest 用例。它在同一台 Ascend A2 机器上启动 Codex,等待优化结束,从固定基线应用最终补丁,然后独立测量单张图像的耗时与质量。[任务与基线版本](https://github.com/InferMatrixLab/InferRSI/issues/479) -## 历史证据回放 +## 运行 -在 InferRSI 仓库根目录运行: +在预配置的 Linux A2 环境中运行。该环境需要已登录的 Codex CLI、可用的 InferRSI、该基线所需的 vLLM-Omni 昇腾依赖和本地只读模型权重。给进程分配一张空闲的 Ascend 910B,使其仅能看到这张卡。环境变量可由机器的作业配置一次性设置。 ```bash -python -m pytest -v e2e/qwen_image/test_archived_journey.py \ - --e2e-archived-evidence \ - --e2e-archived-retest +export QWEN_E2E_REPO='<本地-vllm-omni-Git-仓库>' +export QWEN_E2E_REVISION='' +export QWEN_E2E_CHECKPOINT='<本地-Qwen-Image-2.1-Turbo-权重目录>' +export QWEN_E2E_RESULTS='<本次作业可写的私有结果父目录>' +python -m pytest -qs e2e/qwen_image/test_user_journey.py ``` -第一个目录含 `plan/actor-plan.json` 和 `results/actor/`,第二个目录含 -`sealed-source.json`、`independent-result.json` 和原始 PNG。回放只读取文件。 -三个测试分别重算逐轮取舍与会话 final、独立复测的顺序/图像/计时、实际补丁与受测快照身份。 -归档的格式调整即使保持 Python AST 相同,文件字节发生变化也会触发身份断言。 -pytest 会展示具体文件和两份摘要。默认测试发现不会启动真实 Agent。 +前三个变量是必需项。省略 `QWEN_E2E_RESULTS` 时使用 pytest 临时目录。每次运行都会新建结果子目录。Codex 使用机器上已配置的模型,也可以通过 `QWEN_E2E_CODEX_MODEL` 指定。默认每次 Codex 调用或测量进程的超时为 7200 秒,可用 `QWEN_E2E_TIMEOUT_SECONDS` 调整。运行期间无人工问答、审批或手工提交补丁。 -## 正式试跑的计时 A/A +## 输入与执行 -将两臂均使用固定基线的测量放在协议冻结前完成,使用正式比较相同的工作负载、 -预热次数、交叉顺序和配对数。准备记录的 `timing_policy` 引用冻结协议中的 JSON。 -观察记录的 `timing_aa` 引用按执行顺序排列的 `[{step, result}]`。 -`result` 是带相对路径和 SHA-256 的原始回执,含实际加载的源码摘要 -`loaded_source_sha256`、起止时间、完整请求耗时及 PNG。回执与用例中的质量 A/A 分开。 +- 用户请求见 [request.txt](../e2e/qwen_image/request.txt)。用例附上本机模型、冻结测量程序和新建 campaign 的位置,要求 Codex 将选中的实现留在工作副本的 `vllm_omni/` 中。实际投递内容保存在结果目录的 `request.txt`。 +- [workload.json](../e2e/qwen_image/workload.json) 固定两个预热请求和六个测量请求(种子 42–47)。两侧均使用 1280×704、BF16、原生八步、CFG=1、单卡、单请求单图。计时从调用 `Omni.generate` 开始,到取得已解码的 RGBA 图像为止。模型加载、预热和 PNG 落盘分别处理。 +- 用例先在两个全新进程中复测基线,核对六张原图,记录两组中位耗时的相对差值作为本次噪声参考。此时将运行条件写入 `frozen.json`。若 Issue 另有最低降幅,开跑前用 `QWEN_E2E_MIN_GAIN_PCT` 指定百分数。 +- Codex 退出后,用例读取同一次运行中的最终回复和 InferRSI campaign,核对至少两轮优化、完成状态和最终选中源码。随后从工作副本提取补丁,在第二个干净 Git 副本中应用,核对 `vllm_omni/` 的 Git 树。之后以 AB、BA、AB 的顺序交替测基线(A)与补丁(B),每组每侧启动一个新的推理进程。每个进程保存六个原始耗时与六张 PNG。 -当前支持的估计方法 `maximum_absolute_paired_change_pct` 取各配对组中 -`100 × abs(B − A) / A` 的最大值,A、B 各取该组六次请求的中位数。 -在冻结文件中记录 `estimator`、原始记录摘要 `aa_sha256`、实测噪声 -`observed_noise_pct` 和 `adoption_threshold_pct`。采用门槛由本次执行计划决定, -须覆盖该噪声,并与 Harness 配置一致。将 `adoption_comparator` 设为 -`current_best` 表示相对当前累计最佳也要达到采用门槛。若实际计划选用其他估计方法, -此检查返回 INCONCLUSIVE。缺少原始记录时同样保留 INCONCLUSIVE。 +## 校验优化指标 -## 用户输入 +`baseline_ms` 和 `candidate_ms` 分别为各自三个组中位数的中位数。用例输出节省的毫秒数、降幅 `100 × (baseline_ms − candidate_ms) / baseline_ms` 和加速比 `baseline_ms / candidate_ms`,逐种子比对所有候选图像的 RGBA 字节。 -交付补丁时由观察者保留 `submission` 回执,含 `candidate_id`、`attempt`、 -`candidate_sha256` 和原始补丁字节的 `patch_sha256`。将回执以路径和摘要加入 -`observer.json` 的 `submission`。独立复测在应用补丁前读取原始回执; -另一份能得到相同源码的合法补丁也会在计时前被拒绝。 - -准备好固定版本的 vLLM-Omni Codex 项目、InferRSI 插件和 A2 使用 skill 后, -唯一发送给 Codex 的用户输入是 [`request.txt`](../e2e/qwen_image/request.txt): - -> 请用 InferRSI 优化当前 vLLM-Omni 项目的 Qwen-Image-2.1-Turbo,在 Ascend A2 单卡上生成 1280×704 图片,保持出图质量,把单张生图耗时降到尽可能低。请多轮尝试、复测最优方案,并交付补丁和结果。 - -测试器不会给 Codex 提供 TASK.md、协议文件、候选实现、优化建议或重试提示。 -Agent 自行准备并冻结内部协议,使用普通 `campaign start/round/final` 流程。 -固定基线使用 #479 中规定的首次 Turbo 支持 PR 合入后的提交,作为运行参数传入, -不写入共享测试默认值。质量/采样/收益门槛以该次搜索前冻结的协议为准。 - -## 执行 - -安装 `python -m pip install -e '.[dev,image]'`。操作者先在独立、干净的项目目录 -检出 ``,配置实际使用的 Codex 模型、插件和 A2 skill,验证同一用户 -和执行环境能非交互登录、独占健康单卡、读取已核验文件字节的模型缓存。 -连接信息和凭据留在现有 skill/环境,不传入测试配置。 - -当前自动启动适配器是 **Codex CLI**;显式指定模型,保存客户端版本、请求、 -逐事件原始输出及接收时刻、最终回复和墙钟耗时。它使用现有权限设置, -不添加绕过批准或隔离的参数,不自动继续失败会话。 -CLI 的结果不能用作 Codex Desktop 的宿主兼容性通过证明;Desktop 的原生会话 -可以由看护者导出证据,再使用下文的只读复核入口。 - -```bash -python -m pytest e2e/qwen_image/test_user_journey.py --run-agent-e2e \ - --e2e-project '' \ - --e2e-baseline-revision '' \ - --e2e-model '' \ - --e2e-timeout-seconds '' \ - --e2e-artifacts '' \ - --e2e-campaign-parent '' \ - --e2e-observer '/observer.json' -``` - -这是会实际使用模型和机器的显式运行。看护者在运行中持续保留选择依据、 -人工介入和环境回执,在结束后完成 `observer.json`。这些是**观察输出**, -不会传给 Agent。测试器只接收一个与本次项目及开始时间匹配的新 campaign; -出现多个尝试时要求先整理版本/尝试索引,避免挑选有利数据。 - -会话结束之后还需要独立复测**实际交付的补丁**。在已通过环境准备的执行宿主上, -使用 campaign 原始 InferRSI runtime 运行: - -```bash -python -m e2e.qwen_image.retest \ - --project '' --baseline-revision '' \ - --campaign '' --patch '' \ - --submission '' \ - --output '/independent' \ - --timeout-seconds '' -``` - -该操作创建新的独立 Git 副本,从固定基线应用补丁,验证与已保存轮次/尝试的 -完整源码身份一致,写 `seal.json` **之后**才调用现有 Harness 执行器。 -不改变 Agent 项目的 HEAD、文件或旧实验记录。换行或权限差异不会被静默归一化。 -如果基线最终胜出,session final 仍测基线;独立入口则测质量通过且测量完整的 -最快 Agent 候选,同分取较早轮次。没有有效候选时保留缺口。 - -冻结命令必须适用于当前执行宿主。SSH、容器挂载、模型路径和设备分配继续由 -原有 A2 skill/冻结命令负责;本用例不实现另一套远程调度器。 -当 pytest 本身就在合格执行宿主时,可以为 live 命令增加 -`--e2e-retest-locally --e2e-patch ''`。 -超时只终止本次本地客户端;远端资源是否清理必须由看护者核实,未知不能写已清理。 - -保留原始结果后,可重复运行只读验收而不重新调用 Codex/NPU: - -```bash -python -m pytest e2e/qwen_image/test_user_journey.py \ - --e2e-campaign '' \ - --e2e-observer '/observer.json' \ - --e2e-artifacts '' -``` - -## 检查什么 - -| 输出 | 检查 | +| 结果 | 条件 | | --- | --- | -| 每轮选择 | 方案事件先于首次编辑和测量;起点是上一轮最佳;有备选、所选措施、理由、预期、风险、引用和反馈 | -| 选择合理性 | 独立审阅者针对候选源码身份给出依据、差异引用及预期是否得到支持;缺失不能自动 PASS | -| 每轮优选 | 用 Harness 对原始结果重新判定质量、完整性、中位数和冻结门槛,再重算采用/拒绝、累计最佳;保留慢轮及失败轮 | -| 有效实验 | 不把相同源码/声明配置重复提交当新优化;检查真实 AB/BA 顺序,不能仅核对每侧样本集合 | -| 图片及原始时间 | 六组冻结 prompt,seed 42–47,1280×704;逐张读取 PNG 的 RGBA 字节与哈希,重算请求时间中位数 | -| 比较前提 | 搜索前跨独立进程的基线 A/A 像素相同;工作负载、环境身份、实际 scheduler 网格一致,不能只看请求的 steps 参数 | -| 最终结果 | session final 和独立实际补丁复测分别输出 B、F、B−F、百分比收益、正确性和性能结论 | -| 使用体验 | 是否需要看护者代操作,第一次卡住的步骤、介入时间/原因;普通用户回答或批准与代操作分开 | - -源码、声明配置和运行所需的相对文件都必须在 campaign 的 include 范围内; -外部依赖/模型/设备仍需环境核验。单凭布尔质量结果、Agent 自述或宿主正常退出 -不足以证明完整用例通过。该用例限定 warmed offline `Omni.generate` 到解码图片, -不能扩展成在线服务或 SLO 收益。 - -## 看护记录的输出契约 - -`observer.json` 位于私有观察目录。文件引用均为 -`{"path":"relative/path", "sha256":""}`,相对于这个目录; -不接受目录外路径或符号链接。它是看护过程中收集的证据索引,不是用户题包。 -[`tests/campaigns/test_user_e2e_audit.py`](../tests/campaigns/test_user_e2e_audit.py) 中的完整合成示例 -展示文件之间如何关联;示例时间、图像和身份仅为 CPU 负面控制。 - -| 字段 | 内容 | -| --- | --- | -| `preparation` | 准备回执 JSON 引用,字段见下文 | -| `round_choices` | 按 `candidate_id` 索引的三个宿主事件引用 `plan_event/first_edit_event/measurement_event` 和独立 `review` 引用 | -| `baseline_repeat` | `results` 为至少两次独立进程的基线 JSON 引用;对应 `fresh_process_ids/source_sha256`;以及 `search_started_at/effective_scheduler/environment_identity/workload_sha256` | -| `independent_directory` | 独立入口输出目录相对位置,包含 seal、实际补丁、重建源码、原始执行记录及 receipt | -| `interventions` | 全部介入,明确 `kind`(`assistance/answer/approval`)、`stage/at_seconds/reason/action`;没有介入时为 `[]`,缺失表示未知 | -| `final_reply` | 实际最终回复的文件引用 | - -准备回执包含:`input_version/baseline_revision/plan_digest/protocol_frozen_at`; -`runspec` 的 `repository/revision/backend/device_class/device_count/model`; -`codex` 的实际 `client/version/model/configuration_sha256`; -`inferrsi.version/runtime_digest`;`a2_skill.name/sha256`; -`quality_cases` 引用 Agent 已冻结的六个 `{prompt,seed}`; -`workload` 引用冻结工作负载 JSON,包含 `width/height/dtype/batch_size/concurrency/` -`tensor_parallel_size/guidance_scale/num_inference_steps/timing_scope/requests`。 -本例为 1280×704、bfloat16、batch/concurrency/TP/CFG 均为 1、原生 8 步, -`timing_scope` 为 `Omni.generate_to_decoded_image`,`requests` 与质量输入一致。 -`expected_scheduler` 保存事前约定的实际 `num_steps/timesteps/sigmas`,与基线 -跨进程复测及所有轮次对照;不能用仅记录请求 steps 的值替代运行网格。 -`checks` 中的 `noninteractive_login/healthy_exclusive_device/model_bytes_verified/` -`baseline_repeat_before_search/owned_resources_cleaned`。未知字段保持未知,不能补造。 -这些环境回执依赖可归属的看护/执行系统;CPU 复核不能重新证明远端硬件事实。 - -三个事件导出保留原始宿主事件 `raw`、一致的 `host_session_id` 和单调 `sequence`, -不要用文件 mtime 替代时序。 -方案事件的 `choice` 包含 `starting_best_sha256/alternatives/chosen_measure/reason/` -`expected_effect/risk/sources/feedback_or_initial_analysis`。`review` 包含 -`independent/reviewer/basis/diff_refs/candidate_sha256/verdict/expectation`; -`diff_refs` 为实际文件引用;`expectation` 为 `supported/refuted/inconclusive`。 -作者自己切换角色不构成独立审阅。 - -质量/测量 JSON 继续满足 Harness 的冻结字段,并保留 `requests`,每个请求有 -`seed/latency_ms/file/pixel_sha256`,组内 `median_ms`;以及实际 -`effective_scheduler/environment_identity/workload_sha256`。 -基线重复、逐轮、会话 final 和补丁独立复测的每个执行进程都要在结果中记录 -`loaded_source_sha256`。从实际加载的源码定位纳入冻结清单的文件,用 Harness 的 -`candidates.identity` 口径计算该组源码摘要。核查器按步骤比对所属组的基线或候选 -快照摘要。缺少进程摘要时记为 INCONCLUSIVE,摘要不一致时记为 FAIL,并列出步骤。 - -A/A JSON 另保留 `process.id/started_at/finished_at`。这些补充字段由 Agent 或 -观察系统的实际记录提供;旧记录缺少时报告证据不全,不补写历史事实。 - -## 判定及开发检查 - -实时运行会逐字节比对观察者留存的最终回复与本次 Codex 输出的 `final-reply.txt`。 -只读回放核对留存文件的摘要与非空文本。验收人还须从该回复打开逐轮表、会话 final -回执、独立复测回执与补丁,并核对候选身份、基线和最终耗时、差值及百分比、 -质量通过数与介入记录。pytest 报告列出回复摘要,供验收人定位原文。 - -`pytest-report.json` 保留 `PASS/FAIL/INCONCLUSIVE`、逐轮表格、两次最终比较及 -介入情况。pytest 没有 INCONCLUSIVE 状态,因此证据缺失会让验收断言失败, -同时 JSON 中仍保留 INCONCLUSIVE,不能将它当质量失败或静默通过。 -`test_completion_required_no_observer_assistance` 单独检查无代操作完成; -协助完成不改写质量/性能结果。无加速也不会凭空判使用流程失败,性能结论另列。 -未显式选择 live 或 replay 时,两条昂贵用例跳过。 - -```bash -pytest tests/campaigns/test_user_e2e_audit.py -ruff check e2e tests/campaigns/test_user_e2e_audit.py tests/fixtures/user_e2e -``` +| `PASS` | 六组图像全部一致;耗时降幅为正、达到预设最低降幅,且超过测前基线 A/A 差值。 | +| `FAIL` | 已完成优化却没有交付源码改动、补丁与选中源码不符、候选图像变化,或实测未达到正向收益及设定的最低降幅。 | +| `INCONCLUSIVE` | 基线不稳定、环境或执行证据不完整,或正向收益仍处于 A/A 波动范围。pytest 返回非零。 | -这些 CPU 控制会启动真实 Harness 子进程,使用合成代码、PNG 和时间,覆盖优选链、 -两份回执、换错合法补丁、交换 AB 顺序、事后补方案、缺审阅、环境缺口和人工介入。 -它们通过只说明测试器行为得到检查,不说明本机完成了 Codex/A2 生图验收。 +最终结果见 `result.json`。同目录保留 Codex 会话日志、回复、`candidate.patch`、各组原始耗时和 PNG,可从这些文件复核结果。运行目录可能含私有机器路径和会话内容。 diff --git a/e2e/__init__.py b/e2e/__init__.py deleted file mode 100644 index 1d6bbb769..000000000 --- a/e2e/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Explicit, operator-run acceptance tests; excluded from the default testpaths.""" diff --git a/e2e/conftest.py b/e2e/conftest.py deleted file mode 100644 index b793a866a..000000000 --- a/e2e/conftest.py +++ /dev/null @@ -1,39 +0,0 @@ -from pathlib import Path - -import pytest - - -def pytest_addoption(parser): - group = parser.getgroup("inferrsi-user-e2e") - group.addoption("--e2e-archived-evidence", help="Read a historical actor evidence export") - group.addoption("--e2e-archived-retest", help="Read the corresponding raw independent attempt") - group.addoption("--run-agent-e2e", action="store_true", - help="Launch a real, billable Codex run") - for name in ("project", "baseline-revision", "artifacts", "campaign-parent", "campaign", - "observer", "model", "patch"): - group.addoption("--e2e-" + name, default=None) - group.addoption("--e2e-codex", default="codex") - group.addoption("--e2e-timeout-seconds", type=float, default=None) - group.addoption("--e2e-retest-locally", action="store_true", - help="Execute the frozen protocol on this already-qualified NPU host") - - -@pytest.fixture(scope="session") -def e2e_options(pytestconfig): - def required(name): - value = pytestconfig.getoption("e2e_" + name.replace("-", "_")) - if value is None: - pytest.fail("Explicit --e2e-" + name + " is required", pytrace=False) - return value - - if not pytestconfig.getoption("run_agent_e2e"): - campaign = pytestconfig.getoption("e2e_campaign") - if campaign is None: - pytest.skip("Explicit live opt-in or --e2e-campaign replay is required") - return {"campaign": Path(campaign), "observer": Path(required("observer")), "live": False, - "artifacts": pytestconfig.getoption("e2e_artifacts")} - return {"live": True, **{name.replace("-", "_"): required(name) for name in ( - "project", "baseline-revision", "artifacts", "campaign-parent", "observer", "model", - "timeout-seconds")}, "executable": pytestconfig.getoption("e2e_codex"), - "retest": pytestconfig.getoption("e2e_retest_locally"), - "patch": pytestconfig.getoption("e2e_patch")} diff --git a/e2e/qwen_image/__init__.py b/e2e/qwen_image/__init__.py deleted file mode 100644 index 9c81929ac..000000000 --- a/e2e/qwen_image/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Ordinary Codex user journey from acceptance issue #479.""" diff --git a/e2e/qwen_image/audit.py b/e2e/qwen_image/audit.py deleted file mode 100644 index 734466def..000000000 --- a/e2e/qwen_image/audit.py +++ /dev/null @@ -1,556 +0,0 @@ -"""Read-only checks of real managed campaigns, not an optimization engine. - -Harness owns execution, assessment and selection. This case recomputes those -facts and checks the additional user-journey evidence from issue #479. Observer -receipts are outputs of supervision, never extra instructions sent to Codex. -""" - -import hashlib -import json -import math -from pathlib import Path -from statistics import median - -from inferrsi.harness import candidates, project -from inferrsi.harness.artifact_primitives import digest, sha256 -from inferrsi.harness.optimization import read_records - - -class EvidenceViolation(ValueError): - """Complete retained facts contradict an identity or order requirement.""" - - -def read(path): - return json.loads(Path(path).read_text(encoding="utf-8")) - - -def inside(root, name): - path = root / name - if Path(name).is_absolute() or not path.resolve().is_relative_to(root.resolve()): - raise ValueError("Evidence reference escapes its root") - if any(p.is_symlink() for p in (path, *path.parents) if p.is_relative_to(root)): - raise ValueError("Evidence reference traverses a symbolic link") - return path - - -class Report: - def __init__(self): - self.findings = [] - self.rounds = [] - self.results = {} - - def add(self, code, verdict="INCONCLUSIVE", **details): - self.findings.append({"code": code, "verdict": verdict, **details}) - - def document(self): - verdict = "PASS" - if self.findings: - verdict = ("FAIL" if any(f["verdict"] == "FAIL" for f in self.findings) - else "INCONCLUSIVE") - return {"workflow_verdict": verdict, "findings": self.findings, - "rounds": self.rounds, **self.results} - - -def reference(root, ref): - path = inside(root, ref["path"]) - if sha256(path) != ref["sha256"]: - raise EvidenceViolation("Evidence reference hash mismatch") - return path - - -def check_timing_aa(observer_root, observer, preparation, plan, report): - """Recompute the declared noise estimator from two arms running the baseline.""" - try: - policy_path = reference(observer_root, preparation["timing_policy"]) - if sha256(policy_path) not in plan["frozen_files"].values(): - raise EvidenceViolation("Timing policy was not frozen") - policy = read(policy_path) - if policy.get("adoption_comparator") != "current_best": - report.add("timing_aa_adoption_comparator_unqualified") - return - trace_path = reference(observer_root, observer["timing_aa"]) - if policy["aa_sha256"] != sha256(trace_path): - raise EvidenceViolation("Timing trace differs from the frozen record") - if policy["estimator"] != "maximum_absolute_paired_change_pct": - report.add("timing_aa_estimator_not_supported") - return - settings = plan["evaluation_settings"] - rows = read(trace_path) - steps = [step for step in project.steps(settings) if step["phase"] != "quality"] - if [row["step"] for row in rows] != [step["id"] for step in steps]: - raise EvidenceViolation("Missing or reordered timing A/A steps") - arms = {"baseline": [], "candidate": []} - environment = observer["baseline_repeat"]["environment_identity"] - previous_end = None - for row, step in zip(rows, steps, strict=True): - path = reference(observer_root, row["result"]) - raw = read(path) - if (raw["loaded_source_sha256"] != plan["baseline_sha256"] - or raw["workload_sha256"] != preparation["workload"]["sha256"] - or raw["effective_scheduler"] != preparation["expected_scheduler"] - or raw["environment_identity"] != environment): - report.add("timing_aa_environment_or_source_unqualified") - return - start, end = raw["process"]["started_at"], raw["process"]["finished_at"] - if not (math.isfinite(start) and math.isfinite(end) - and start <= end <= preparation["protocol_frozen_at"] - and (previous_end is None or previous_end <= start)): - raise EvidenceViolation("Timing A/A was not completed in order before freeze") - previous_end = end - image_requests(path.parent, raw) - if step["phase"] == "measurement": - arms[step["side"]].append(raw["median_ms"]) - pairs = zip(arms["baseline"], arms["candidate"], strict=True) - noise = max(100 * abs(b - a) / a for a, b in pairs) - gate = policy["adoption_threshold_pct"] - if (type(gate) not in (float, int) or not math.isfinite(gate) - or not math.isclose(noise, policy["observed_noise_pct"], abs_tol=1e-9) - or gate != settings["min_improvement_pct"] or gate < noise): - raise EvidenceViolation("Frozen rule disagrees with actual A/A measurements") - report.results["timing_aa"] = {"paired_groups": len(arms["baseline"]), - "observed_noise_pct": noise, "adoption_threshold_pct": gate} - except EvidenceViolation: - report.add("timing_aa_frozen_rule_contradicted", "FAIL") - except (OSError, ImportError, ValueError, TypeError, KeyError): - report.add("timing_aa_evidence_unavailable") - - -def check_preparation(observer_root, observer, plan, state, report): - try: - preparation = read(reference(observer_root, observer["preparation"])) - check_timing_aa(observer_root, observer, preparation, plan, report) - runspec = preparation["runspec"] - if (runspec["repository"] != "vllm-project/vllm-omni" - or runspec["backend"] != "ascend" or runspec["device_class"] != "A2" - or runspec["device_count"] != 1 - or runspec["model"] != "Qwen-Image-2.1-Turbo" - or runspec["revision"] != preparation["baseline_revision"]): - report.add("prepared_environment_does_not_match_case") - if (len(preparation["baseline_revision"]) != 40 - or not preparation["input_version"] - or preparation["plan_digest"] != digest(plan)): - report.add("preparation_does_not_bind_frozen_plan") - for key in ("client", "version", "model", "configuration_sha256"): - if not preparation["codex"].get(key): - report.add("codex_environment_not_pinned", field=key) - for section, keys in (("inferrsi", ("version", "runtime_digest")), - ("a2_skill", ("name", "sha256"))): - if any(not preparation[section].get(key) for key in keys): - report.add("prepared_tool_identity_missing", tool=section) - if preparation["inferrsi"]["runtime_digest"] != digest(plan["runtime_identity"]): - report.add("prepared_inferrsi_runtime_mismatch") - for key in ("noninteractive_login", "healthy_exclusive_device", "model_bytes_verified", - "baseline_repeat_before_search", "owned_resources_cleaned"): - if preparation["checks"].get(key) is not True: - report.add("preparation_or_cleanup_unqualified", check=key) - if not preparation["protocol_frozen_at"] <= state["rounds"][0]["started_at"]: - report.add("protocol_not_frozen_before_search", "FAIL") - # Case identities and prompts are in the Agent's frozen protocol, rather - # than a hidden replacement task supplied by this test. - cases_path = reference(observer_root, preparation["quality_cases"]) - cases = read(cases_path) - if (sorted(c["seed"] for c in cases) != list(range(42, 48)) - or any(not c.get("prompt") for c in cases)): - report.add("six_frozen_prompt_seed_cases_missing") - if sha256(cases_path) not in plan["frozen_files"].values(): - report.add("quality_cases_not_frozen_before_search", "FAIL") - workload_path = reference(observer_root, preparation["workload"]) - workload = read(workload_path) - required = {"width": 1280, "height": 704, "dtype": "bfloat16", "batch_size": 1, - "concurrency": 1, "tensor_parallel_size": 1, "guidance_scale": 1, - "num_inference_steps": 8, "timing_scope": "Omni.generate_to_decoded_image"} - if any(workload.get(key) != value for key, value in required.items()): - report.add("baseline_workload_not_the_intended_turbo_case") - if workload.get("requests") != cases: - report.add("workload_requests_do_not_match_quality_cases") - if (sha256(workload_path) not in plan["frozen_files"].values() - or observer["baseline_repeat"]["workload_sha256"] != sha256(workload_path)): - report.add("workload_identity_not_bound_to_frozen_inputs") - scheduler = preparation["expected_scheduler"] - if (scheduler != observer["baseline_repeat"]["effective_scheduler"] - or scheduler.get("num_steps") != 8 or len(scheduler.get("timesteps", [])) != 8 - or not scheduler.get("sigmas")): - report.add("baseline_did_not_run_intended_scheduler") - report.results["input_version"] = preparation["input_version"] - report.results["baseline_revision"] = preparation["baseline_revision"] - except EvidenceViolation: - report.add("preparation_evidence_hash_mismatch", "FAIL") - except (OSError, ValueError, KeyError, TypeError, IndexError): - report.add("preparation_evidence_unavailable") - - -def recompute(directory, settings, execution, identities=None): - """Use the existing assessor, with an explicit cross-arm ordering check.""" - expected = project.steps(settings) - actual = execution.get("steps", []) - if [s.get("id") for s in actual] != [s["id"] for s in expected[:len(actual)]]: - raise EvidenceViolation("Cross-arm execution order differs from the frozen protocol") - checks = execution.get("source_checks", []) - for step, check in zip(actual, checks): - if check.get("step") != step["id"]: - raise EvidenceViolation("Source check is bound to a different execution step") - if identities and check.get("expected") and check.get("actual"): - if check["expected"] != identities or check["actual"] != identities: - raise EvidenceViolation("Loaded source differs from retained candidate identity") - return project.assess(directory, settings, execution) - - -def select_patch_round(rounds): - """Even if baseline wins, independently test an actual, quality-valid patch. - - Stable min retains the first attempt on a tie. Eligibility for an improvement - claim is deliberately separate from suitability for this independent check. - """ - valid = [r for r in rounds if r["assessment"]["status"] == "completed" - and r["assessment"].get("quality_passed") is True] - if not valid: - raise ValueError("No complete quality-valid Agent candidate to retest") - return min(valid, key=lambda r: r["assessment"]["score"]) - - -def audit_selection(plan, state, root, report): - settings = plan["evaluation_settings"] - best = {"sha256": plan["baseline_sha256"], "score": None, "kind": "baseline"} - seen = {best["sha256"]} - recalculated = [] - for record in state["rounds"]: - directory = inside(root, record["path"]) - execution = read(directory / "execution/execution.json") - assessment = recompute(directory, settings, execution, { - "baseline": plan["baseline_sha256"], "candidate": record["candidate_sha256"]}) - if assessment != record["assessment"]: - report.add("assessment_disagrees_with_raw_evidence", "FAIL", - candidate=record["candidate_id"]) - candidate = record["candidate_sha256"] - if candidate in seen: - report.add("unchanged_or_repeated_candidate", "FAIL", - candidate=record["candidate_id"]) - seen.add(candidate) - if best["score"] is None and assessment["status"] == "completed": - best["score"] = assessment["baseline_score"] - previous = dict(best) - score = assessment.get("score") - increment = ((previous["score"] - score) / previous["score"] * 100 - if score is not None and previous["score"] is not None else None) - adopted = (assessment["status"] == "completed" - and assessment.get("eligible") is True and increment is not None - and increment > 0 and increment >= settings["min_improvement_pct"]) - if adopted: - best = {"sha256": candidate, "score": assessment["score"], "kind": "candidate"} - if any(record["best_after"].get(key) != value for key, value in best.items()): - report.add("wrong_adopt_reject_decision", "FAIL", candidate=record["candidate_id"]) - if assessment["status"] == "infrastructure_failure": - report.add("round_evidence_incomplete", candidate=record["candidate_id"]) - report.rounds.append({ - "candidate": record["candidate_id"], "attempt": record["path"], - "source_sha256": candidate, "starting_best_sha256": previous["sha256"], - "decision": "adopt" if adopted else "keep_previous_best", - "baseline_ms": assessment.get("baseline_score"), "candidate_ms": score, - "total_improvement_pct": assessment.get("improvement_pct"), - "incremental_improvement_pct": increment, - "quality_passed": assessment.get("quality_passed"), - }) - recalculated.append({**record, "assessment": assessment}) - if any(state["best"].get(key) != value for key, value in best.items()): - report.add("final_best_chain_mismatch", "FAIL") - final = state.get("final") - if final is None: - report.add("missing_session_final") - else: - if final["candidate_sha256"] != best["sha256"]: - report.add("session_final_retested_wrong_source", "FAIL") - directory = inside(root, final["path"]) - assessment = recompute(directory, settings, read(directory / "execution/execution.json"), { - "baseline": plan["baseline_sha256"], "candidate": final["candidate_sha256"]}) - if assessment != final["assessment"]: - report.add("session_final_assessment_mismatch", "FAIL") - if assessment["status"] != "completed": - report.add("session_final_incomplete") - report.results["session_final"] = metrics(assessment) - return recalculated - - -def metrics(assessment): - before, after = assessment.get("baseline_score"), assessment.get("score") - return {"baseline_ms": before, "candidate_ms": after, - "delta_ms": before - after if before and after else None, - "improvement_pct": assessment.get("improvement_pct"), - "performance_verdict": assessment["verdict"], - "quality_passed": assessment.get("quality_passed")} - - -def check_choices(observer_root, observer, rounds, report): - """Ordering is mechanical; applicability requires attributable independent review.""" - choices = observer.get("round_choices", {}) - for record, row in zip(rounds, report.rounds): - choice = choices.get(record["candidate_id"]) - if not choice: - report.add("missing_pre_edit_choice", candidate=record["candidate_id"]) - continue - try: - # The observer exports three host events, each with an ordered sequence - # and original bytes. File mtimes and retrospective prose do not count. - events = [read(reference(observer_root, choice[key])) - for key in ("plan_event", "first_edit_event", "measurement_event")] - if (any(not event.get("raw") for event in events) - or len({event.get("host_session_id") for event in events}) != 1 - or not events[0].get("host_session_id")): - report.add("missing_original_host_choice_events") - if not (events[0]["sequence"] < events[1]["sequence"] < events[2]["sequence"]): - report.add("choice_recorded_after_edit_or_measurement", "FAIL") - declaration = events[0]["choice"] - if declaration["starting_best_sha256"] != row["starting_best_sha256"]: - report.add("round_started_from_wrong_best", "FAIL") - for key in ("alternatives", "chosen_measure", "reason", "expected_effect", - "risk", "sources", "feedback_or_initial_analysis"): - if not declaration.get(key): - report.add("incomplete_pre_edit_choice", field=key) - review = read(reference(observer_root, choice["review"])) - for ref in review.get("diff_refs", []): - reference(observer_root, ref) - if (review.get("independent") is not True or not review.get("reviewer") - or not review.get("basis") or not review.get("diff_refs") - or review.get("candidate_sha256") != record["candidate_sha256"]): - report.add("missing_independent_choice_review") - elif review.get("verdict") == "FAIL": - report.add("choice_or_patch_not_supported_by_review", "FAIL") - elif review.get("verdict") != "PASS": - report.add("choice_rationale_unresolved") - if review.get("expectation") not in ("supported", "refuted", "inconclusive"): - report.add("optimization_expectation_not_reviewed") - row["chosen_measure"] = declaration.get("chosen_measure") - row["expectation_review"] = review.get("expectation", "unknown") - except EvidenceViolation: - report.add("choice_evidence_hash_mismatch", "FAIL") - except (OSError, ValueError, KeyError, TypeError): - report.add("choice_evidence_unavailable", candidate=record["candidate_id"]) - - -def image_requests(directory, document): - """Hash decoded RGBA pixels and recompute the metric from original request times.""" - from PIL import Image - - requests = document["requests"] - if sorted(r["seed"] for r in requests) != list(range(42, 48)): - raise ValueError("Expected the six frozen seed cases, exactly once each") - pixels, times = {}, [] - for request in requests: - value = request["latency_ms"] - if type(value) not in (int, float) or not math.isfinite(value) or value <= 0: - raise ValueError("Invalid original request latency") - with Image.open(inside(directory, request["file"])) as image: - if image.size != (1280, 704): - raise ValueError("Wrong generated image dimensions") - digest = hashlib.sha256(image.convert("RGBA").tobytes()).hexdigest() - if digest != request["pixel_sha256"]: - raise EvidenceViolation("PNG bytes disagree with recorded decoded pixels") - pixels[request["seed"]] = digest - times.append(value) - if median(times) != document["median_ms"]: - raise EvidenceViolation("Metric disagrees with raw request times") - return pixels - - -def check_loaded_source(document, expected, report, attempt, step): - """Compare what the executing worker loaded with the frozen arm identity.""" - actual = document.get("loaded_source_sha256") - if not actual: - report.add("loaded_source_identity_missing", attempt=attempt, step=step) - elif actual != expected: - report.add("wrong_source_loaded", "FAIL", attempt=attempt, step=step, - expected=expected, actual=actual) - - -def check_outputs(root, plan, state, observer_root, observer, report): - """No generic similarity threshold; the case freezes exact RGBA equality.""" - try: - repeat = observer["baseline_repeat"] - references = [reference(observer_root, ref) for ref in repeat["results"]] - if len(references) < 2 or len(set(repeat["fresh_process_ids"])) != len(references): - report.add("baseline_repeat_not_across_fresh_processes") - return - baseline_pixels = [image_requests(path.parent, read(path)) for path in references] - if any(pixels != baseline_pixels[0] for pixels in baseline_pixels[1:]): - report.add("baseline_pixel_reference_unqualified") - return - expected_grid = repeat["effective_scheduler"] - expected_environment = repeat["environment_identity"] - expected_workload = repeat["workload_sha256"] - if (len(set(repeat["source_sha256"])) != 1 - or len(repeat["source_sha256"]) != len(references)): - report.add("baseline_repeat_source_not_verified") - return - if repeat["source_sha256"][0] != plan["baseline_sha256"]: - report.add("baseline_repeat_wrong_source", "FAIL") - for index, path in enumerate(references): - document = read(path) - check_loaded_source(document, plan["baseline_sha256"], report, "baseline-repeat", index) - if (document.get("effective_scheduler") != expected_grid - or document.get("environment_identity") != expected_environment - or document.get("workload_sha256") != expected_workload): - report.add("baseline_repeat_protocol_mismatch") - return - if (max(read(path)["process"]["finished_at"] for path in references) - >= repeat["search_started_at"]): - report.add("baseline_repeat_not_before_search") - return - if [read(path)["process"]["id"] for path in references] != repeat["fresh_process_ids"]: - report.add("baseline_repeat_process_receipt_mismatch") - return - if state["rounds"] and repeat["search_started_at"] != state["rounds"][0]["started_at"]: - report.add("baseline_repeat_search_boundary_mismatch") - return - if not expected_grid or not expected_environment or not expected_workload: - report.add("missing_effective_environment_or_scheduler") - return - for record in [*state["rounds"], *([state["final"]] if state.get("final") else [])]: - directory = inside(root, record["path"]) - execution = read(directory / "execution/execution.json") - candidate_bad = False - for step in execution["steps"]: - path = inside(directory, "execution/" + step["id"] + "/result.json") - document = read(path) - side = step["id"].rsplit("-", 1)[-1] - expected_sha = (plan["baseline_sha256"] if side == "baseline" - else record["candidate_sha256"]) - check_loaded_source(document, expected_sha, report, record["path"], step["id"]) - if (document.get("status") == "candidate_failure" - or (step["id"] == "quality-candidate" and project._value( - document, plan["evaluation_settings"]["quality_key"]) is False)): - continue - if document.get("effective_scheduler") != expected_grid: - report.add("effective_scheduler_changed", "FAIL" if side == "candidate" - and "effective_scheduler" in document else "INCONCLUSIVE") - if (document.get("environment_identity") != expected_environment - or document.get("workload_sha256") != expected_workload): - report.add("environment_or_workload_not_comparable") - pixels = image_requests(path.parent, document) - if pixels != baseline_pixels[0]: - if side == "baseline": - report.add("baseline_pixel_reference_unqualified") - else: - candidate_bad = True - if candidate_bad and record["assessment"].get("quality_passed") is True: - report.add("incorrect_candidate_was_accepted_as_quality_valid", "FAIL") - except ImportError: - report.add("image_dependency_unavailable") - except EvidenceViolation: - report.add("raw_quality_or_timing_evidence_contradicted", "FAIL") - except (OSError, ValueError, KeyError, TypeError): - report.add("raw_quality_or_timing_evidence_unavailable") - - -def check_independent(root, observer, selected, plan, report): - try: - directory = inside(root, observer["independent_directory"]) - seal = read(directory / "seal.json") - submission = read(reference(root, observer["submission"])) - fields = ("candidate_id", "attempt", "candidate_sha256", "patch_sha256") - if any(submission[key] != seal[key] for key in fields): - report.add("independent_retest_differs_from_original_submission", "FAIL") - return - if (seal["candidate_id"] != selected["candidate_id"] - or seal["attempt"] != selected["path"] - or seal["candidate_sha256"] != selected["candidate_sha256"] - or seal["baseline_sha256"] != plan["baseline_sha256"] - or seal["plan_digest"] != digest(plan)): - report.add("independent_selection_binding_mismatch", "FAIL") - return - if (report.results.get("baseline_revision") is not None - and seal["baseline_revision"] != report.results["baseline_revision"]): - report.add("independent_git_baseline_revision_mismatch", "FAIL") - return - if (sha256(directory / "candidate.patch") != seal["patch_sha256"] - or candidates.identity(directory / "attempt/candidate") - != seal["candidate_sha256"] - or candidates.identity(directory / "frozen/baseline") - != seal["baseline_sha256"]): - report.add("independent_sealed_source_changed", "FAIL") - return - for name, expected in plan["frozen_files"].items(): - if sha256(inside(directory / "frozen", name)) != expected: - report.add("independent_protocol_or_baseline_drift", "FAIL") - return - receipt = read(directory / "receipt.json") - if (receipt["seal_sha256"] != sha256(directory / "seal.json") - or not seal["sealed_at"] < receipt["started_at"]): - report.add("independent_seal_not_before_measurement", "FAIL") - execution = read(directory / "attempt/execution/execution.json") - assessment = recompute(directory / "attempt", plan["evaluation_settings"], execution, { - "baseline": seal["baseline_sha256"], "candidate": seal["candidate_sha256"]}) - if assessment != receipt["assessment"]: - report.add("independent_assessment_mismatch", "FAIL") - if assessment["status"] != "completed": - report.add("independent_retest_incomplete") - report.results["independent_patch_retest"] = metrics(assessment) - # Recheck the independent PNGs/grid too, against the same qualified A/A reference. - attempt = {"path": "attempt", "assessment": assessment, - "candidate_sha256": seal["candidate_sha256"]} - check_outputs(directory, plan, {"rounds": [], "final": attempt}, root, observer, report) - except EvidenceViolation: - report.add("independent_execution_identity_or_order_violation", "FAIL") - except (OSError, ValueError, KeyError, TypeError): - report.add("independent_retest_unavailable") - - -def check_final_reply(root, observer, report, host_reply=None): - try: - reply = reference(root, observer["final_reply"]).read_bytes() - if host_reply is not None and reply != Path(host_reply).read_bytes(): - report.add("observer_reply_differs_from_host_output", "FAIL") - elif not reply.decode("utf-8-sig").strip(): - report.add("empty_final_reply", "FAIL") - else: - report.results["final_reply_sha256"] = hashlib.sha256(reply).hexdigest() - except EvidenceViolation: - report.add("final_reply_evidence_hash_mismatch", "FAIL") - except (OSError, ValueError, KeyError, TypeError): - report.add("final_reply_evidence_unavailable") - - -def audit(root, observer_path, *, host_reply=None): - report = Report() - observer_path = Path(observer_path) - try: - observer = read(observer_path) - plan, state, _ = read_records(Path(root)) - if (plan["task_source"] != "project" - or plan["evaluation_settings"]["direction"] != "minimize" - or plan["evaluation_settings"]["metric_unit"] != "ms"): - report.add("wrong_case_or_metric", "FAIL") - return report.document() - if len(state["rounds"]) < 2: - if not state["rounds"] and state.get("state") == "completed": - report.add("completed_without_candidate", "FAIL") - report.add("multiple_optimization_rounds_not_demonstrated") - rounds = audit_selection(plan, state, Path(root), report) - check_preparation(observer_path.parent, observer, plan, state, report) - check_choices(observer_path.parent, observer, rounds, report) - check_outputs(Path(root), plan, state, observer_path.parent, observer, report) - try: - selected = select_patch_round(rounds) - check_independent(observer_path.parent, observer, selected, plan, report) - except ValueError: - report.add("no_valid_agent_patch_to_retest") - interventions = observer.get("interventions") - if interventions is None: - report.add("user_intervention_record_missing") - else: - for event in interventions: - if (event.get("kind") not in ("assistance", "answer", "approval") - or any(key not in event for key in ( - "stage", "at_seconds", "reason", "action"))): - report.add("incomplete_intervention_record") - assisted = [event for event in interventions if event["kind"] == "assistance"] - if assisted: - report.add("observer_intervention_required", "FAIL") - report.results["completion_mode"] = "assisted" if assisted else "unassisted" - report.results["first_blocked_step"] = assisted[0]["stage"] if assisted else None - report.results["interventions"] = interventions - check_final_reply(observer_path.parent, observer, report, host_reply) - report.results["scope"] = "offline Omni.generate to decoded image; no service/SLO claim" - except EvidenceViolation: - report.add("execution_identity_or_order_violation", "FAIL") - except (OSError, ValueError, KeyError, TypeError) as error: - report.add("campaign_or_observer_evidence_unavailable", error_type=type(error).__name__) - return report.document() diff --git a/e2e/qwen_image/driver.py b/e2e/qwen_image/driver.py deleted file mode 100644 index 12feca8e2..000000000 --- a/e2e/qwen_image/driver.py +++ /dev/null @@ -1,115 +0,0 @@ -"""Opt-in Codex CLI host adapter. Sends exactly request.txt as the sole user turn.""" - -import json -import queue -import subprocess -import threading -import time -from pathlib import Path - -from .retest import git, write - - -def launch(project, baseline_revision, output, *, executable, model, timeout): - project, output = Path(project).resolve(), Path(output).resolve() - head = git(project, "rev-parse", "HEAD").decode().strip() - if head != baseline_revision: - raise ValueError("Prepared project is not at the issue's pinned baseline") - if git(project, "status", "--porcelain", "--untracked-files=all").strip(): - raise ValueError("Prepare a clean, separate Codex project before this test") - if output.exists() or output.is_relative_to(project): - raise ValueError("Use a new private output directory outside the project") - if timeout <= 0: - raise ValueError("An explicit positive wall-clock budget is required") - output.mkdir(parents=True) - prompt = Path(__file__).with_name("request.txt").read_text(encoding="utf-8").strip() - (output / "request.txt").write_text(prompt + "\n", encoding="utf-8") - command = [str(executable)] if isinstance(executable, (str, Path)) else list(executable) - version = subprocess.run([*command, "--version"], check=True, - capture_output=True, text=True).stdout.strip() - argv = [*command, "exec", "--json", "--cd", str(project), "--model", model, - "--output-last-message", str(output / "final-reply.txt"), "-"] - started = time.time() - write(output / "host.json", { - "client": "Codex CLI", "version": version, "requested_model": model, - "effective_model": "unknown unless exported by host", - "baseline_revision": head, "started_at": started, "state": "running", - }) - events = queue.Queue() - # Credentials/configuration are inherited by Codex, never inspected or dumped. - # No bypass flags, added optimization hints, resume prompt or automatic retry. - with (output / "stderr.log").open("w", encoding="utf-8") as stderr: - child = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, - stderr=stderr, text=True, encoding="utf-8", errors="replace") - - def consume(): - for line in child.stdout: - events.put((time.time(), line)) - events.put(None) - - reader = threading.Thread(target=consume, daemon=True) - reader.start() - child.stdin.write(prompt) - child.stdin.close() - timed_out = False - sequence = 0 - with (output / "events.jsonl").open("w", encoding="utf-8") as log: - while True: - remaining = started + timeout - time.time() - if remaining <= 0: - timed_out = True - child.terminate() - break - try: - item = events.get(timeout=min(remaining, 1)) - except queue.Empty: - continue - if item is None: - break - at, line = item - sequence += 1 - log.write(json.dumps({"sequence": sequence, "received_at": at, - "elapsed_seconds": at - started, "raw": line}, - ensure_ascii=False) + "\n") - log.flush() - try: - returncode = child.wait(timeout=10) - except subprocess.TimeoutExpired: - child.kill() - returncode = child.wait() - receipt = {"client": "Codex CLI", "version": version, "requested_model": model, - "baseline_revision": head, "started_at": started, "finished_at": time.time(), - "elapsed_seconds": time.time() - started, "returncode": returncode, - "state": "timed_out" if timed_out else "exited", - "remote_cleanup": "unknown; observer must verify owned remote resources"} - exported = [] - for line in (output / "events.jsonl").read_text(encoding="utf-8").splitlines(): - try: - exported.append(json.loads(json.loads(line)["raw"])) - except (ValueError, TypeError): - continue - sessions = [event["thread_id"] for event in exported if event.get("type") == "thread.started"] - receipt["native_session_ids"] = sessions - receipt["native_turn_completed"] = ( - len(sessions) == 1 and any(e.get("type") == "turn.completed" for e in exported) - and not any(e.get("type") in ("turn.failed", "error") for e in exported)) - write(output / "host.json", receipt) - return receipt - - -def discover(parent, project, started): - matches = [] - for path in Path(parent).glob("**/campaign.json"): - try: - campaign = json.loads(path.read_text(encoding="utf-8")) - plan = json.loads(path.with_name("plan.json").read_text(encoding="utf-8")) - state = json.loads(path.with_name("state.json").read_text(encoding="utf-8")) - if (campaign.get("managed_optimization") is True and plan["task_source"] == "project" - and Path(plan["working_candidate"]).resolve() == Path(project).resolve() - and state["started_at"] >= started): - matches.append(path.parent) - except (OSError, ValueError, KeyError): - continue - if len(matches) != 1: - raise ValueError("Expected one new campaign for this project; index all attempts") - return matches[0] diff --git a/e2e/qwen_image/measure.py b/e2e/qwen_image/measure.py new file mode 100644 index 000000000..85252f7ec --- /dev/null +++ b/e2e/qwen_image/measure.py @@ -0,0 +1,99 @@ +"""Measure one checkout on one Ascend A2 NPU in a fresh Python process.""" + +import argparse +import hashlib +import json +import os +import sys +import time +from pathlib import Path +from statistics import median + + +def measure(source, checkpoint, output): + workload_bytes = Path(__file__).with_name("workload.json").read_bytes() + workload = json.loads(workload_bytes) + model_bytes = (checkpoint / "model_index.json").read_bytes() + model = json.loads(model_bytes) + sigmas = workload["sample_sigmas"] + if (model.get("_class_name") != "QwenImage21Pipeline" + or len(sigmas) != 8 or model.get("sample_sigmas") != sigmas): + raise ValueError("The checkpoint must contain the frozen native Turbo sampling grid") + + # Spawned engine processes must resolve the same checkout as this process. + sys.path.insert(0, str(source)) + old_path = os.environ.get("PYTHONPATH") + os.environ["PYTHONPATH"] = str(source) + (os.pathsep + old_path if old_path else "") + os.environ["HF_HUB_OFFLINE"] = "1" + import torch + import vllm_omni + from vllm_omni.diffusion.utils.image_output import extract_images_from_outputs + from vllm_omni.entrypoints.omni import Omni + from vllm_omni.inputs.data import OmniDiffusionSamplingParams + from vllm_omni.platforms import current_omni_platform + + for module in (vllm_omni, sys.modules[Omni.__module__], + sys.modules[extract_images_from_outputs.__module__]): + if not Path(module.__file__).resolve().is_relative_to(source / "vllm_omni"): + raise RuntimeError("The measurement process imported a different vLLM-Omni checkout") + if current_omni_platform.device_type != "npu" or torch.npu.device_count() != 1: + raise RuntimeError("Expose exactly one Ascend A2 NPU to the measurement process") + device = current_omni_platform.get_device_name(0) + if "910B" not in device.upper(): + raise RuntimeError(f"Expected an Ascend A2 (910B) NPU, detected {device}") + + output.mkdir(parents=True, exist_ok=True) + if (output / "result.json").exists() or any(output.glob("seed-*.png")): + raise FileExistsError("Use a fresh output directory for every measurement") + warmup_ms, latencies_ms = [], [] + engine = Omni( + model=str(checkpoint), dtype="bfloat16", tensor_parallel_size=1, enforce_eager=True, + ) + try: + for group in ("warmups", "requests"): + for case in workload[group]: + params = OmniDiffusionSamplingParams( + width=workload["width"], height=workload["height"], seed=case["seed"], + true_cfg_scale=1.0, num_outputs_per_prompt=1, + sigmas=list(sigmas), + ) + prompt = {"prompt": case["prompt"], "modalities": ["image"]} + start = time.perf_counter_ns() + outputs = engine.generate(prompt, sampling_params_list=[params], use_tqdm=False) + images = extract_images_from_outputs(outputs) + if len(images) != 1: + raise ValueError("Expected exactly one decoded image") + image = images[0] + image.load() + elapsed = (time.perf_counter_ns() - start) / 1e6 + if image.size != (workload["width"], workload["height"]) or image.mode != "RGBA": + raise ValueError( + f"Unexpected image for seed {case['seed']}: {image.size}, {image.mode}" + ) + if group == "warmups": + warmup_ms.append(elapsed) + else: + latencies_ms.append(elapsed) + image.save(output / f"seed-{case['seed']}.png") + finally: + engine.close() + result = { + "device": device, "workload_sha256": hashlib.sha256(workload_bytes).hexdigest(), + "model_index_sha256": hashlib.sha256(model_bytes).hexdigest(), "sample_sigmas": sigmas, + "seeds": [case["seed"] for case in workload["requests"]], + "warmup_ms": warmup_ms, "latencies_ms": latencies_ms, "median_ms": median(latencies_ms), + } + (output / "result.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + for name in ("source", "checkpoint", "output"): + parser.add_argument(name, type=Path) + args = parser.parse_args() + measure(args.source.resolve(), args.checkpoint.resolve(), args.output.resolve()) + # The pinned Ascend runtime can abort during interpreter teardown after engine.close(). + # Only use this exit once all work, engine cleanup and file writes have succeeded. + sys.stdout.flush() + sys.stderr.flush() + os._exit(0) diff --git a/e2e/qwen_image/retest.py b/e2e/qwen_image/retest.py deleted file mode 100644 index 4baec08cf..000000000 --- a/e2e/qwen_image/retest.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Seal the actual delivered patch, then reuse Harness for independent execution. - -Run on the qualified execution host with the campaign's original InferRSI -runtime. Connection setup belongs to that host's skill/environment, not here. -""" - -import argparse -import hashlib -import json -import shutil -import subprocess -import time -from pathlib import Path - -from inferrsi.harness import candidates, project -from inferrsi.harness.artifact_primitives import digest, sha256 -from inferrsi.harness.optimization import read_records -from inferrsi.harness.optimization_session import _project_execute, _runtime_identity - -from .audit import EvidenceViolation, Report, audit_selection, read, select_patch_round - - -def write(path, document): - path.write_text(json.dumps(document, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - - -def git(repo, *args): - # Arrays only; neither task data nor patch bytes are shell commands. - return subprocess.run(["git", "-C", str(repo), *args], check=True, - stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout - - -def seal(project_repo, baseline_revision, campaign, patch, output, *, submission): - """No measurement starts until clean-Git reconstruction matches the selected attempt.""" - project_repo, campaign, patch, output = map(Path, (project_repo, campaign, patch, output)) - plan, state, _ = read_records(campaign) - report = Report() - rounds = audit_selection(plan, state, campaign, report) - if report.findings: - raise ValueError("Campaign round/final checks must pass before independent replay") - selected = select_patch_round(rounds) - patch_bytes = patch.read_bytes() - submitted = read(submission) - expected = {"candidate_id": selected["candidate_id"], "attempt": selected["path"], - "candidate_sha256": selected["candidate_sha256"], - "patch_sha256": hashlib.sha256(patch_bytes).hexdigest()} - if any(submitted[key] != value for key, value in expected.items()): - raise EvidenceViolation("Patch or selection differs from original submission") - revision = git(project_repo, "rev-parse", "--verify", baseline_revision + "^{commit}") - revision = revision.decode().strip() - if revision != baseline_revision: - raise ValueError("A full pinned baseline commit is required") - if output.exists(): - raise ValueError("Independent output must be new; preserve previous attempts") - output.mkdir(parents=True) - write(output / "status.json", {"stage": "reconstruction", "verdict": "INCONCLUSIVE"}) - # A separate clone avoids moving the Agent's HEAD or touching its working tree. - git(project_repo, "clone", "--no-checkout", "--shared", str(project_repo.resolve()), - str(output.resolve() / "reconstructed")) - reconstructed = output / "reconstructed" - git(reconstructed, "config", "core.autocrlf", "false") - git(reconstructed, "checkout", "--detach", revision) - includes = plan["candidate_includes"] - baseline = output / "frozen/baseline" - baseline.parent.mkdir() - actual_baseline = candidates.retain(reconstructed, baseline, includes) - if actual_baseline != plan["baseline_sha256"]: - raise ValueError("Frozen baseline differs from the pinned clean Git checkout") - if not patch_bytes.strip(): - raise ValueError("An actual nonempty Agent patch is required") - (output / "candidate.patch").write_bytes(patch_bytes) - try: - git(reconstructed, "apply", "--check", str((output / "candidate.patch").resolve())) - git(reconstructed, "apply", str((output / "candidate.patch").resolve())) - except subprocess.CalledProcessError as error: - raise EvidenceViolation("Delivered patch does not apply to the pinned baseline") from error - # Reject changes outside the Agent's declared inputs, including new files. - changed = git(reconstructed, "diff", "--name-only", "-z", "HEAD").split(b"\0") - added = git(reconstructed, "ls-files", "--others", "--exclude-standard", "-z").split(b"\0") - declared = candidates.members(reconstructed, includes) - allowed = set(declared) | set(candidates.members(baseline)) - if any(name.decode("utf-8") not in allowed for name in [*changed, *added] if name): - raise EvidenceViolation("Delivered patch changes files outside declared candidate inputs") - attempt = output / "attempt" - attempt.mkdir() - actual_candidate = candidates.retain(reconstructed, attempt / "candidate", includes) - if actual_candidate != selected["candidate_sha256"]: - raise EvidenceViolation( - "Delivered patch does not reconstruct the selected Agent round/attempt") - shutil.copytree(campaign / "frozen/protocol", output / "frozen/protocol") - (output / "frozen/TASK.md").write_bytes((campaign / "frozen/TASK.md").read_bytes()) - for name, expected in plan["frozen_files"].items(): - if sha256(output / "frozen" / name) != expected: - raise ValueError("Frozen files changed during independent preparation") - seal_record = { - "baseline_revision": revision, "baseline_sha256": actual_baseline, - "candidate_id": selected["candidate_id"], "attempt": selected["path"], - "candidate_sha256": actual_candidate, "patch_sha256": sha256(output / "candidate.patch"), - "plan_digest": digest(plan), "sealed_at": time.time(), - } - write(output / "seal.json", seal_record) - return plan, seal_record - - -def execute(output, plan, timeout): - if timeout <= 0: - raise ValueError("An explicit positive independent budget is required") - if (output / "attempt/execution").exists() or (output / "receipt.json").exists(): - raise ValueError("Keep previous execution evidence; use a new independent attempt") - sealed = read(output / "seal.json") - if (sealed["plan_digest"] != digest(plan) - or sealed["patch_sha256"] != sha256(output / "candidate.patch") - or sealed["candidate_sha256"] != candidates.identity(output / "attempt/candidate") - or sealed["baseline_sha256"] != candidates.identity(output / "frozen/baseline")): - raise EvidenceViolation("Sealed independent inputs changed before timing") - for name, expected in plan["frozen_files"].items(): - if sha256(output / "frozen" / name) != expected: - raise ValueError("Frozen protocol changed before independent timing") - if plan["runtime_identity"] != _runtime_identity(): - raise ValueError("Use the campaign's frozen InferRSI runtime for independent execution") - started = time.time() - write(output / "status.json", {"stage": "measurement", "verdict": "INCONCLUSIVE"}) - execution = _project_execute(output, output / "attempt", plan, started + timeout) - assessment = project.assess(output / "attempt", plan["evaluation_settings"], execution) - receipt = {"seal_sha256": sha256(output / "seal.json"), "started_at": started, - "finished_at": time.time(), "assessment": assessment} - write(output / "receipt.json", receipt) - write(output / "status.json", {"stage": "finished", "verdict": assessment["verdict"]}) - return receipt - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - for name in ("project", "baseline-revision", "campaign", "patch", "submission", "output"): - parser.add_argument("--" + name, required=True) - parser.add_argument("--timeout-seconds", type=float, required=True) - args = parser.parse_args() - plan, _ = seal(args.project, args.baseline_revision, args.campaign, args.patch, args.output, - submission=args.submission) - execute(Path(args.output), plan, args.timeout_seconds) - - -if __name__ == "__main__": - main() diff --git a/e2e/qwen_image/test_archived_journey.py b/e2e/qwen_image/test_archived_journey.py deleted file mode 100644 index 33e7f0401..000000000 --- a/e2e/qwen_image/test_archived_journey.py +++ /dev/null @@ -1,176 +0,0 @@ -"""Read-only replay of the historical observer export. Never invokes its executables.""" - -import re -from pathlib import Path -from statistics import median - -import pytest - -from inferrsi.harness import project -from inferrsi.harness.artifact_primitives import sha256 - -from .audit import image_requests, inside, read - - -@pytest.fixture(scope="module") -def archive(pytestconfig): - location = pytestconfig.getoption("e2e_archived_evidence") - if location is None: - pytest.skip("Select a retained #479 actor evidence directory") - return Path(location) - - -@pytest.fixture(scope="module") -def replay(pytestconfig): - location = pytestconfig.getoption("e2e_archived_retest") - if location is None: - pytest.skip("Select a retained #479 independent attempt") - return Path(location) - - -def sample_groups(parent, steps, workload_sha): - """Recompute each recorded median and compare every decoded image by seed.""" - samples = {"baseline": [], "candidate": []} - reference_pixels = None - count = 0 - for step in steps: - directory = parent / step - result = read(directory / "result.json") - assert result["workload_sha256"] == workload_sha, step - pixels = image_requests(directory, result) - if reference_pixels is None: - reference_pixels = pixels - assert pixels == reference_pixels, f"RGBA comparison differs for {step}" - if step.startswith("measurement-"): - samples[step.split("-")[-1]].append(result["median_ms"]) - count += len(pixels) - return samples, count, reference_pixels - - -def test_archived_rounds_and_session_final(archive): - plan = read(archive / "plan/actor-plan.json") - state = read(archive / "results/actor-state.json") - settings = plan["evaluation_settings"] - assert settings["direction"] == "minimize" - expected = [step["id"] for step in project.steps(settings)] - workload = plan["frozen_files"]["protocol/workload.json"] - best = plan["baseline_sha256"] - best_score = None - seen = {best} - assert len(state["rounds"]) >= 2 - reference_pixels = None - for index, record in enumerate([*state["rounds"], state["final"]], start=1): - final = index > len(state["rounds"]) - folder = "actor-final" if final else f"round-{index:02d}" - execution = record["execution"] - assert [step["id"] for step in execution["steps"]] == expected, folder - assert all(step["returncode"] == 0 for step in execution["steps"]), folder - identities = { - "baseline": plan["baseline_sha256"], - "candidate": record["candidate_sha256"], - } - assert [check["step"] for check in execution["source_checks"]] == expected - for check in execution["source_checks"]: - assert check["verified"] and check["actual"] == check["expected"] == identities - samples, _, pixels = sample_groups( - archive / "results/actor" / folder, expected, workload - ) - if reference_pixels is None: - reference_pixels = pixels - assert pixels == reference_pixels, folder - baseline, candidate = (median(samples[arm]) for arm in ("baseline", "candidate")) - assessment = record["assessment"] - assert assessment["quality_passed"] is True - assert assessment["metrics"]["samples"] == samples - assert (assessment["baseline_score"], assessment["score"]) == (baseline, candidate) - if final: - assert record["candidate_sha256"] == best == state["best"]["sha256"] - continue - assert record["candidate_sha256"] not in seen - seen.add(record["candidate_sha256"]) - if best_score is None: - best_score = baseline - gain = (1 - candidate / baseline) * 100 - if candidate < best_score and gain >= settings["min_improvement_pct"]: - best, best_score = record["candidate_sha256"], candidate - assert (record["best_after"]["sha256"], record["best_after"]["score"]) == ( - best, - best_score, - ) - - -def test_archived_independent_measurements(replay): - freeze = read(replay / "evaluator-freeze.json") - seal = read(replay / "sealed-source.json") - summary = read(replay / "independent-result.json") - assert ( - freeze["baseline_revision"] == summary["baseline_revision"] == seal["baseline_revision"] - ) - assert summary["candidate_id"] == seal["candidate_id"] - assert summary["source_sha256"] == seal["source_sha256"] - assert sha256(replay / "candidate.patch") == seal["patch_sha256"] - assert freeze["validator_sha256"] == summary["validator_sha256"] == seal["validator_sha256"] - for name in ("benchmark.py", "model-manifest.json", "workload.json"): - assert sha256(replay / "protocol" / name) == freeze["validator_sha256"][name] - order = re.search(r"\b(?:AB|BA)(?:/(?:AB|BA))*\b", freeze["statistics"]) - assert order and "median of group medians" in freeze["statistics"] - expected = ["quality-baseline", "quality-candidate"] - for index, pair in enumerate(order.group().split("/"), start=1): - arms = {"A": "baseline", "B": "candidate"} - expected.extend(f"measurement-{index:03d}-{arms[arm]}" for arm in pair) - assert [r["step"] for r in summary["execution"]] == expected - assert [c["step"] for c in summary["source_checks"]] == expected - for receipt, check in zip(summary["execution"], summary["source_checks"], strict=True): - directory = replay / "results" / receipt["step"] - assert receipt == read(directory / "receipt.json") - assert receipt["returncode"] == 0 and receipt["result_sha256"] == sha256( - directory / "result.json" - ) - assert check["verified"] and check["after_execution_verified"] - assert {arm: check[arm] for arm in ("baseline", "candidate")} == seal["source_sha256"] - samples, count, pixels = sample_groups( - replay / "results", expected, freeze["validator_sha256"]["workload.json"] - ) - assert summary["samples"] == samples - baseline, candidate = median(samples["baseline"]), median(samples["candidate"]) - assert summary["baseline_ms"] == baseline and summary["candidate_ms"] == candidate - assert summary["latency_reduction_ms"] == pytest.approx(baseline - candidate) - assert summary["latency_reduction_pct"] == pytest.approx(100 * (1 - candidate / baseline)) - assert summary["raw_request_timings"] == summary["decoded_pngs_verified"] == count - assert summary["quality_pairs_passed"] == len(pixels) - - -def test_archived_patch_matches_selected_snapshot(archive, replay): - """Evaluate the current exact-source requirement against the old evidence.""" - state = read(archive / "results/actor-state.json") - seal = read(replay / "sealed-source.json") - chosen = next(r for r in state["rounds"] if r["candidate_id"] == seal["candidate_id"]) - assert seal["candidate_attempt"] == chosen["path"] + "/candidate" - assert ( - seal["measured_candidate_sha256"] - == chosen["candidate_sha256"] - == state["final"]["candidate_sha256"] - ) - assert ( - sha256(archive / "patch/qwen21-a2.patch") - == sha256(replay / "candidate.patch") - == seal["patch_sha256"] - ) - for mapping in seal["delivery_format_mapping"]: - measured_result = read( - archive / "results/actor/actor-final/measurement-001-candidate/result.json" - ) - digest_fields = { - "autoencoder_kl_qwenimage21.py": "vae_sha256", - "qwen_image_21_transformer.py": "transformer_sha256", - "pipeline_qwen_image_21.py": "pipeline_sha256", - } - measured = measured_result[digest_fields[Path(mapping["file"]).name]] - rebuilt = sha256(inside(replay / "candidate", mapping["file"])) - assert (measured, rebuilt) == (mapping["measured_sha256"], mapping["delivery_sha256"]) - assert rebuilt == measured, ( - f"Reconstructed {Path(mapping['file']).name} differs from the measured VAE" - ) - assert seal["matches_actor_snapshot_bytes"] is True, ( - "The historical reconstruction receipt records a byte mismatch with the Agent snapshot." - ) diff --git a/e2e/qwen_image/test_user_journey.py b/e2e/qwen_image/test_user_journey.py index 9657d6d75..9344b7cc3 100644 --- a/e2e/qwen_image/test_user_journey.py +++ b/e2e/qwen_image/test_user_journey.py @@ -1,62 +1,205 @@ -"""Explicit acceptance entry: live Agent run or read-only evidence replay.""" +"""One opt-in, unattended Codex optimization and independent Ascend A2 measurement.""" +import hashlib +import json +import math +import os +import signal +import subprocess +import sys +import tempfile from pathlib import Path -from subprocess import CalledProcessError +from statistics import median import pytest -from e2e.qwen_image.audit import EvidenceViolation, audit, read, reference -from e2e.qwen_image.driver import discover, launch -from e2e.qwen_image.retest import execute, seal, write - - -@pytest.fixture(scope="module") -def observed(e2e_options): - options = e2e_options - if not options["live"]: - report = audit(options["campaign"], options["observer"]) - if options["artifacts"]: - output = Path(options["artifacts"]) - output.mkdir(parents=True, exist_ok=False) - write(output / "pytest-report.json", report) - return report - output = Path(options["artifacts"]) - host = launch(options["project"], options["baseline_revision"], output, - executable=options["executable"], model=options["model"], - timeout=options["timeout_seconds"]) - if (host["returncode"] != 0 or host["state"] != "exited" - or not host["native_turn_completed"]): - report = {"workflow_verdict": "INCONCLUSIVE", "findings": [{ - "code": "host_did_not_complete", "verdict": "INCONCLUSIVE"}], "host": host} - write(output / "pytest-report.json", report) - return report +CASE = Path(__file__).resolve().parent + + +def git(repo, *args): + return subprocess.run( + ["git", "-C", str(repo), *args], check=True, stdout=subprocess.PIPE, + stdin=subprocess.DEVNULL, + ).stdout + + +def checkout(repo, revision, destination): + subprocess.run(["git", "clone", "--quiet", "--no-local", "--no-checkout", + str(repo), str(destination)], check=True, stdin=subprocess.DEVNULL) + git(destination, "checkout", "--quiet", "--detach", revision) + if git(destination, "rev-parse", "HEAD").decode().strip() != revision: + raise ValueError("Use the full baseline commit from the acceptance issue") + + +def write_json(path, data): + path.write_text(json.dumps(data, indent=2, allow_nan=False) + "\n", encoding="utf-8") + + +def run_logged(argv, cwd, logfile, timeout, prompt=None): + # On the A2 host, stop this run's local process group if its deadline expires. + with logfile.open("wb") as log, subprocess.Popen( + argv, cwd=cwd, start_new_session=True, stdout=log, stderr=subprocess.STDOUT, + stdin=subprocess.DEVNULL if prompt is None else subprocess.PIPE, + ) as child: + try: + child.communicate(input=prompt, timeout=timeout) + except subprocess.TimeoutExpired: + os.killpg(child.pid, signal.SIGKILL) + child.wait() + raise + if child.returncode: + raise RuntimeError(f"{Path(argv[0]).name} exited {child.returncode}; see " + f"{logfile.name}") + + +def optimize(project, checkpoint, output, timeout): + from inferrsi.harness.candidates import identity + + agent_runs = output / "agent-runs" + agent_runs.mkdir() + campaign = agent_runs / "campaign" + prompt = (CASE / "request.txt").read_text(encoding="utf-8").strip() + prompt += ( + f"\n本机模型目录:{checkpoint}。冻结的测量程序:{CASE / 'measure.py'}," + "依次传入源码目录、模型目录、新输出目录。请自主使用本机 InferRSI 的 " + f"campaign start、round、final 完成多轮优化,campaign 目录使用 {campaign}。" + "将最终选中的生产代码留在当前项目的 vllm_omni/ 下,供独立复测。" + ) + (output / "request.txt").write_text(prompt + "\n", encoding="utf-8") + command = ["codex", "--ask-for-approval", "never", "exec", "--sandbox", "workspace-write", + "--add-dir", str(agent_runs), + "--json", "--output-last-message", str(output / "final-reply.txt")] + if model := os.environ.get("QWEN_E2E_CODEX_MODEL"): + command += ["--model", model] + run_logged([*command, "-"], project, output / "codex.jsonl", timeout, prompt.encode("utf-8")) + # The campaign and final reply must both belong to this fresh invocation. + plan = json.loads((campaign / "plan.json").read_bytes()) + state = json.loads((campaign / "state.json").read_bytes()) + if (not (output / "final-reply.txt").read_text(encoding="utf-8").strip() + or plan["task_source"] != "project" or Path(plan["working_candidate"]) != project + or state["state"] != "completed" or len(state["rounds"]) < 2 + or identity(project, plan["candidate_includes"]) != state["final"]["candidate_sha256"]): + raise ValueError("The Codex run did not deliver the final source of this project campaign") + + +def measure(source, checkpoint, output, timeout): + output.mkdir() + run_logged([sys.executable, str(CASE / "measure.py"), str(source), str(checkpoint), + str(output)], source, output / "worker.log", timeout) + + +def sample(source, checkpoint, output, timeout, workload): + from PIL import Image + + measure(source, checkpoint, output, timeout) + receipt = json.loads((output / "result.json").read_bytes()) + times = receipt["latencies_ms"] + seeds = [row["seed"] for row in workload["requests"]] + if (receipt["seeds"] != seeds or len(times) != len(seeds) + or len(receipt["warmup_ms"]) != len(workload["warmups"]) + or any(not math.isfinite(t) or t <= 0 for t in [*times, *receipt["warmup_ms"]])): + raise ValueError("Missing or invalid raw timing samples") + pixels = {} + for seed in seeds: + with Image.open(output / f"seed-{seed}.png") as image: + if image.mode != "RGBA" or image.size != (workload["width"], workload["height"]): + raise ValueError("Unexpected decoded image format") + pixels[seed] = hashlib.sha256(image.tobytes()).hexdigest() + identity = {k: receipt[k] for k in ("device", "sample_sigmas", "workload_sha256", + "model_index_sha256")} + return median(times), pixels, identity + + +def verify_source(repo, expected_tree): + if (git(repo, "write-tree").decode().strip() != expected_tree + or git(repo, "diff", "--name-only", "--", "vllm_omni") + or git(repo, "ls-files", "--others", "--exclude-standard", "--", "vllm_omni")): + raise ValueError("The measured source changed after checkout or patch reconstruction") + + +def test_codex_optimizes_qwen_image_on_a2(tmp_path): + parent = Path(os.environ.get("QWEN_E2E_RESULTS", tmp_path)).resolve() + parent.mkdir(parents=True, exist_ok=True) + output = Path(tempfile.mkdtemp(prefix="qwen-a2-", dir=parent)) + print(f"E2E results: {output}", flush=True) + report = {"verdict": "INCONCLUSIVE", "stage": "preflight"} try: - campaign = discover(options["campaign_parent"], options["project"], host["started_at"]) - if options["retest"]: - if not options["patch"]: - raise ValueError("An actual --e2e-patch is required before independent timing") - observer = Path(options["observer"]) - submission = reference(observer.parent, read(observer)["submission"]) - plan, _ = seal(options["project"], options["baseline_revision"], campaign, - options["patch"], output / "independent", submission=submission) - execute(output / "independent", plan, options["timeout_seconds"]) - report = audit(campaign, options["observer"], host_reply=output / "final-reply.txt") - except EvidenceViolation: - report = {"workflow_verdict": "FAIL", "findings": [{ - "code": "independent_patch_identity_violation", "verdict": "FAIL"}]} - except (OSError, ValueError, KeyError, CalledProcessError) as error: - report = {"workflow_verdict": "INCONCLUSIVE", "findings": [{ - "code": "collection_or_independent_retest_incomplete", "verdict": "INCONCLUSIVE", - "error_type": type(error).__name__}]} - write(output / "pytest-report.json", report) - return report - - -def test_ordinary_user_optimization(observed): - # pytest has no INCONCLUSIVE status. Keep it in the JSON receipt and fail the - # acceptance assertion, rather than silently reporting missing NPU evidence green. - assert observed["workflow_verdict"] == "PASS", observed - - -def test_completion_required_no_observer_assistance(observed): - assert observed.get("completion_mode") == "unassisted", observed + repo = Path(os.environ["QWEN_E2E_REPO"]).resolve(strict=True) + checkpoint = Path(os.environ["QWEN_E2E_CHECKPOINT"]).resolve(strict=True) + revision = os.environ["QWEN_E2E_REVISION"] + timeout = int(os.environ.get("QWEN_E2E_TIMEOUT_SECONDS", "7200")) + minimum = float(os.environ.get("QWEN_E2E_MIN_GAIN_PCT", "0")) + if timeout <= 0 or not math.isfinite(minimum) or minimum < 0: + raise ValueError("Invalid timeout or minimum latency reduction") + workload = json.loads((CASE / "workload.json").read_bytes()) + baseline, project, candidate = (output / n for n in ("baseline", "optimize", "candidate")) + for tree in (baseline, project): + checkout(repo, revision, tree) + baseline_tree = git(baseline, "write-tree").decode().strip() + first, reference, identity = sample(baseline, checkpoint, output / "preflight-a", + timeout, workload) + second, pixels, other = sample(baseline, checkpoint, output / "preflight-b", + timeout, workload) + if (pixels != reference or identity != other + or identity["sample_sigmas"] != workload["sample_sigmas"] + or identity["workload_sha256"] != hashlib.sha256( + (CASE / "workload.json").read_bytes()).hexdigest()): + raise ValueError("Baseline A/A pixels or environment changed before optimization") + noise = 100 * abs(second - first) / first + report.update(baseline_revision=revision, environment=identity, aa_ms=[first, second], + noise_pct=noise, min_gain_pct=minimum) + write_json(output / "frozen.json", report) + report["stage"] = "codex" + optimize(project, checkpoint, output, timeout) + + report["stage"] = "reconstruct" + git(project, "add", "-A", "--", "vllm_omni") + patch = git(project, "diff", "--cached", "--binary", "--full-index", revision, + "--", "vllm_omni") + if not patch: + report.update(verdict="FAIL", error="Codex finished without delivering a source change") + pytest.fail(report["error"]) + patchfile = output / "candidate.patch" + patchfile.write_bytes(patch) + checkout(repo, revision, candidate) + git(candidate, "apply", "--index", "--binary", str(patchfile)) + selected = git(project, "write-tree").decode().strip() + rebuilt = git(candidate, "write-tree").decode().strip() + if git(project, "rev-parse", selected + ":vllm_omni") != git( + candidate, "rev-parse", rebuilt + ":vllm_omni"): + report.update(verdict="FAIL", error="Patch does not reconstruct the selected source") + pytest.fail(report["error"]) + report.update(candidate_tree=rebuilt, patch_sha256=hashlib.sha256(patch).hexdigest()) + + report["stage"] = "independent_retest" + scores = {"baseline": [], "candidate": []} + failed_seeds = set() + for i, pair in enumerate(("AB", "BA", "AB"), 1): + for arm in pair: + name, tree = ("baseline", baseline) if arm == "A" else ("candidate", candidate) + expected_tree = baseline_tree if arm == "A" else rebuilt + verify_source(tree, expected_tree) + value, actual, runtime = sample(tree, checkpoint, output / f"{i:02}-{name}", + timeout, workload) + verify_source(tree, expected_tree) + if runtime != identity or (name == "baseline" and actual != reference): + raise ValueError("Independent baseline or measurement environment changed") + failed_seeds.update(seed for seed in reference if actual[seed] != reference[seed]) + scores[name].append(value) + before, after = (median(scores[name]) for name in ("baseline", "candidate")) + gain = 100 * (before - after) / before + report.update(stage="finished", group_medians_ms=scores, baseline_ms=before, + candidate_ms=after, reduction_ms=before - after, reduction_pct=gain, + speedup=before / after, quality_passed=len(reference) - len(failed_seeds), + quality_total=len(reference), failed_seeds=sorted(failed_seeds)) + if failed_seeds or gain <= 0 or gain < minimum: + report["verdict"] = "FAIL" + elif gain > noise: + report["verdict"] = "PASS" + assert report["verdict"] == "PASS", report + except Exception as error: + report["error"] = str(error) + raise + finally: + write_json(output / "result.json", report) + print(json.dumps(report, ensure_ascii=False), flush=True) diff --git a/e2e/qwen_image/workload.json b/e2e/qwen_image/workload.json new file mode 100644 index 000000000..3146a7ea8 --- /dev/null +++ b/e2e/qwen_image/workload.json @@ -0,0 +1,18 @@ +{ + "model": "Qwen/Qwen-Image-2.1-Turbo", + "width": 1280, + "height": 704, + "sample_sigmas": [1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568], + "warmups": [ + {"seed": 30, "prompt": "A white lighthouse at the end of a rocky pier at dawn."}, + {"seed": 31, "prompt": "Three oranges in a blue bowl on a white kitchen counter."} + ], + "requests": [ + {"seed": 42, "prompt": "A red ceramic teapot on a wooden table, soft side lighting."}, + {"seed": 43, "prompt": "A snowy mountain village at dusk, warm lights in the windows."}, + {"seed": 44, "prompt": "A watercolor of a kingfisher above a stream lined with reeds."}, + {"seed": 45, "prompt": "A minimal yellow poster with the large title FRESH LEMONS and a lemon illustration."}, + {"seed": 46, "prompt": "A candid portrait of an elderly gardener in a greenhouse, natural morning light."}, + {"seed": 47, "prompt": "一只戴着红色围巾的小狐狸站在雪地里,远处是安静的松林。"} + ] +} diff --git a/tests/campaigns/test_user_e2e_audit.py b/tests/campaigns/test_user_e2e_audit.py deleted file mode 100644 index 2ca57d2c0..000000000 --- a/tests/campaigns/test_user_e2e_audit.py +++ /dev/null @@ -1,600 +0,0 @@ -"""CPU negative controls for #479; synthetic times/images, never A2 qualification.""" - -import copy -import hashlib -import io -import json -import shutil -import subprocess -import sys -from contextlib import redirect_stdout -from pathlib import Path - -import pytest - -from e2e.qwen_image.audit import ( - Report, - audit, - audit_selection, - check_choices, - check_final_reply, - check_independent, - check_outputs, - check_timing_aa, - image_requests, - read, - recompute, - select_patch_round, -) -from e2e.qwen_image.driver import discover, launch -from e2e.qwen_image.retest import execute, git, seal, write -from inferrsi.apps.cli import main -from inferrsi.harness.artifact_primitives import digest, sha256 -from inferrsi.harness.optimization import read_records - -REPOSITORY_ROOT = Path(__file__).resolve().parents[2] -FIXTURES = REPOSITORY_ROOT / "tests/fixtures/user_e2e" -# Each synthetic evaluation starts six Python workers and decodes their images. -FIXTURE_EVALUATION_SECONDS = 120 - - -def invoke(argv): - with redirect_stdout(io.StringIO()) as output: - assert main(argv) == 0, output.getvalue() - return json.loads(output.getvalue()) - - -def ref(root, path): - return {"path": path.relative_to(root).as_posix(), "sha256": sha256(path)} - - -@pytest.fixture(scope="module") -def campaign(tmp_path_factory): - Image = pytest.importorskip("PIL.Image") - root = tmp_path_factory.mktemp("synthetic-user-e2e") - repo, protocol, campaign = (root / name for name in ("repo", "protocol", "campaign")) - repo.mkdir() - protocol.mkdir() - (repo / "engine.py").write_bytes(b"LATENCY = 100\n") - git(repo, "init") - git(repo, "add", "engine.py") - git(repo, "-c", "user.name=Synthetic Control", "-c", "user.email=control@example.invalid", - "commit", "-m", "Synthetic baseline") - baseline = git(repo, "rev-parse", "HEAD").decode().strip() - cases = [{"seed": seed, "prompt": f"Synthetic seed {seed}"} for seed in range(42, 48)] - write(protocol / "cases.json", cases) - write(protocol / "workload.json", { - "width": 1280, "height": 704, "dtype": "bfloat16", "batch_size": 1, - "concurrency": 1, "tensor_parallel_size": 1, "guidance_scale": 1, - "num_inference_steps": 8, "timing_scope": "Omni.generate_to_decoded_image", - "requests": cases, - }) - scheduler = {"num_steps": 8, "timesteps": list(range(8)), "sigmas": [1, 0]} - for case in cases: - Image.new("RGBA", (1280, 704), (case["seed"], 0, 0, 255)).save( - protocol / f"seed-{case['seed']}.png") - # A real child process is started for every quality/measurement step. It - # copies fixed synthetic images; no model, Codex or accelerator is involved. - (protocol / "measure.py").write_bytes( - (FIXTURES / "measure.py").read_bytes()) - instructions = root / "request.md" - instructions.write_text("Synthetic software control; no performance claim.", encoding="utf-8") - command = '"{python}" "{protocol}/measure.py" "{candidate}" "{result}"' - timing_rows = [] - for group, arms in enumerate((("baseline", "candidate"), ("candidate", "baseline")), start=1): - for arm in arms: - step = f"measurement-{group:03d}-{arm}" - directory = root / f"aa-{step}" - directory.mkdir() - result = directory / "result.json" - subprocess.run([sys.executable, str(protocol / "measure.py"), str(repo), str(result)], - check=True) - timing_rows.append({"step": step, "result": ref(root, result)}) - trace = root / "timing-aa.json" - write(trace, timing_rows) - write(protocol / "timing-policy.json", { - "estimator": "maximum_absolute_paired_change_pct", "observed_noise_pct": 0, - "adoption_threshold_pct": 1, "adoption_comparator": "current_best", - "aa_sha256": sha256(trace), - }) - invoke(["campaign", "start", "--directory", str(campaign), "--repo", str(repo), - "--include", "engine.py", "--protocol", str(protocol), - "--instructions", str(instructions), "--measure-command", command, - "--quality-command", command, "--metric-key", "median_ms", "--metric-unit", "ms", - "--direction", "minimize", "--quality-key", "correct", "--scope", "synthetic-only", - "--repetitions", "2", "--warmups", "0", "--min-improvement-pct", "1", - "--rounds", "3", "--round-mode", "exact", "--max-minutes", "12", - "--evaluation-timeout-seconds", str(FIXTURE_EVALUATION_SECONDS)]) - repeat_paths = [] - for index in range(2): - directory = root / f"baseline-repeat-{index}" - directory.mkdir() - result = directory / "result.json" - subprocess.run([sys.executable, str(campaign / "frozen/protocol/measure.py"), - str(campaign / "frozen/baseline"), str(result)], check=True) - repeat_paths.append(result) - invoke(["campaign", "diagnose", "--directory", str(campaign), - "--bottleneck", "Synthetic measured request latency", - "--evidence", str(repeat_paths[0])]) - for value in (90, 110, 80): - (repo / "engine.py").write_bytes(f"LATENCY = {value}\n".encode()) - invoke(["campaign", "round", "--directory", str(campaign), "--candidate", str(repo), - "--hypothesis", "Synthetic declared source change"]) - invoke(["campaign", "final", "--directory", str(campaign)]) - patch = root / "delivered.patch" - patch.write_bytes(git(repo, "diff", "--binary", "HEAD")) - _, state, _ = read_records(campaign) - selected = select_patch_round(state["rounds"]) - submission = root / "submission.json" - write(submission, {"candidate_id": selected["candidate_id"], "attempt": selected["path"], - "candidate_sha256": selected["candidate_sha256"], - "patch_sha256": sha256(patch)}) - plan, _ = seal(repo, baseline, campaign, patch, root / "independent", submission=submission) - execute(root / "independent", plan, FIXTURE_EVALUATION_SECONDS) - plan, state, _ = read_records(campaign) - choices = {} - current_best = plan["baseline_sha256"] - for index, record in enumerate(state["rounds"]): - event_root = root / record["candidate_id"] - event_root.mkdir() - choice = {} - for offset, key in enumerate(("plan_event", "first_edit_event", "measurement_event")): - event = {"sequence": index * 3 + offset, "raw": "synthetic host event", - "host_session_id": "synthetic-session"} - if offset == 0: - event["choice"] = { - "starting_best_sha256": current_best, - "alternatives": ["synthetic A", "synthetic B"], - "chosen_measure": "synthetic A", "reason": "Synthetic control rationale", - "expected_effect": "reduce synthetic metric", "risk": "synthetic risk", - "sources": ["synthetic source"], - "feedback_or_initial_analysis": "Synthetic previous observation", - } - path = event_root / (key + ".json") - write(path, event) - choice[key] = ref(root, path) - review = event_root / "review.json" - diff = event_root / "candidate-source.txt" - diff.write_bytes((campaign / record["path"] / "candidate/engine.py").read_bytes()) - write(review, {"independent": True, "reviewer": "synthetic-control-reviewer", - "basis": "Synthetic applicability evidence", - "diff_refs": [ref(root, diff)], "verdict": "PASS", - "candidate_sha256": record["candidate_sha256"], - "expectation": "supported"}) - choice["review"] = ref(root, review) - choices[record["candidate_id"]] = choice - current_best = record["best_after"]["sha256"] - preparation = root / "preparation.json" - write(preparation, { - "input_version": "synthetic-v1", "baseline_revision": baseline, - "plan_digest": digest(plan), "protocol_frozen_at": state["started_at"], - "runspec": {"repository": "vllm-project/vllm-omni", "revision": baseline, - "backend": "ascend", "device_class": "A2", "device_count": 1, - "model": "Qwen-Image-2.1-Turbo"}, - "codex": {"client": "synthetic", "version": "synthetic", "model": "synthetic", - "configuration_sha256": "synthetic"}, - "inferrsi": {"version": "synthetic", "runtime_digest": digest(plan["runtime_identity"])}, - "a2_skill": {"name": "synthetic", "sha256": "synthetic"}, - "checks": dict.fromkeys(("noninteractive_login", "healthy_exclusive_device", - "model_bytes_verified", "baseline_repeat_before_search", - "owned_resources_cleaned"), True), - "quality_cases": ref(root, campaign / "frozen/protocol/cases.json"), - "timing_policy": ref(root, campaign / "frozen/protocol/timing-policy.json"), - "workload": ref(root, campaign / "frozen/protocol/workload.json"), - "expected_scheduler": scheduler, - }) - reply = root / "reply.txt" - reply.write_text( - f"Selected {selected['candidate_id']}. Baseline 100 ms, final 80 ms, " - "a 20 ms (20%) reduction. Quality 6/6. See independent/receipt.json " - "and independent/candidate.patch. These are synthetic measurements.", - encoding="utf-8") - observer = { - "round_choices": choices, "preparation": ref(root, preparation), - "timing_aa": ref(root, trace), - "submission": ref(root, submission), - "final_reply": ref(root, reply), "interventions": [], - "independent_directory": "independent", "baseline_repeat": { - "results": [ref(root, path) for path in repeat_paths], - "fresh_process_ids": [read(path)["process"]["id"] for path in repeat_paths], - "search_started_at": state["rounds"][0]["started_at"], - "source_sha256": [plan["baseline_sha256"]] * 2, - "effective_scheduler": scheduler, - "environment_identity": "synthetic-not-a-device", - "workload_sha256": sha256(protocol / "workload.json"), - }, - } - write(root / "observer.json", observer) - return root, repo, campaign, plan, state, observer, baseline, patch - - -def codes(report): - return {item["code"] for item in report.findings} - - -@pytest.mark.parametrize("change,expected", [ - ("missing", "INCONCLUSIVE"), ("different_trace", "FAIL"), ("lower_gate", "FAIL"), -]) -def test_timing_aa_must_match_the_frozen_raw_measurements(campaign, change, expected): - root, _, _, plan, _, observer, *_ = campaign - observer = copy.deepcopy(observer) - plan = copy.deepcopy(plan) - preparation = read(root / observer["preparation"]["path"]) - if change == "missing": - del observer["timing_aa"] - elif change == "different_trace": - observer["timing_aa"] = observer["preparation"] - else: - plan["evaluation_settings"]["min_improvement_pct"] = 0 - report = Report() - check_timing_aa(root, observer, preparation, plan, report) - assert report.document()["workflow_verdict"] == expected - - -def test_complete_synthetic_journey_recomputes_choices_and_two_receipts(campaign): - root, _, path, *_ = campaign - report = audit(path, root / "observer.json") - assert report["workflow_verdict"] == "PASS", report - assert [row["decision"] for row in report["rounds"]] == [ - "adopt", "keep_previous_best", "adopt"] - assert report["rounds"][1]["incremental_improvement_pct"] < 0 - assert report["rounds"][2]["starting_best_sha256"] == report["rounds"][0]["source_sha256"] - for receipt in ("session_final", "independent_patch_retest"): - assert report[receipt]["baseline_ms"] == 100 - assert report[receipt]["candidate_ms"] == 80 - assert report[receipt]["delta_ms"] == 20 - - -def test_cross_arm_swap_is_rejected_even_with_identical_arm_multisets(campaign): - _, _, root, plan, state, *_ = campaign - directory = root / state["rounds"][0]["path"] - execution = read(directory / "execution/execution.json") - execution["steps"][2:4] = reversed(execution["steps"][2:4]) - with pytest.raises(ValueError, match="Cross-arm"): - recompute(directory, plan["evaluation_settings"], execution) - - -def test_slower_candidate_must_not_replace_best(campaign): - _, _, root, plan, state, *_ = campaign - altered = copy.deepcopy(state) - altered["rounds"][1]["best_after"] = { - "sha256": altered["rounds"][1]["candidate_sha256"], "score": 110, "kind": "candidate"} - report = Report() - audit_selection(plan, altered, root, report) - assert "wrong_adopt_reject_decision" in codes(report) - - -def test_change_inside_noise_must_not_replace_the_previous_best(campaign, monkeypatch): - _, _, root, plan, state, *_ = campaign - altered = copy.deepcopy(state) - record = altered["rounds"][-1] - record["assessment"]["score"] = 89.5 # Below baseline 100, within 1% of best 90. - record["best_after"]["score"] = 89.5 - original = recompute - - def replay(directory, *args): - if directory == root / record["path"]: - return record["assessment"] - return original(directory, *args) - - monkeypatch.setattr("e2e.qwen_image.audit.recompute", replay) - report = Report() - audit_selection(plan, altered, root, report) - assert report.rounds[-1]["decision"] == "keep_previous_best" - assert "wrong_adopt_reject_decision" in codes(report) - - -def test_baseline_winner_still_selects_real_patch_and_earliest_tie(): - rounds = [{"candidate_id": name, "assessment": { - "status": "completed", "quality_passed": True, "score": score, "eligible": False}} - for name, score in (("first", 110), ("second", 110), ("third", 120))] - assert select_patch_round(rounds)["candidate_id"] == "first" - - -def test_wrong_legal_patch_rejected_before_any_measurement(campaign): - root, repo, path, _, _, _, baseline, _ = campaign - wrong = root / "different.patch" - original = (repo / "engine.py").read_bytes() - try: - (repo / "engine.py").write_bytes(b"LATENCY = 85\n") - wrong.write_bytes(git(repo, "diff", "HEAD")) - finally: - (repo / "engine.py").write_bytes(original) - output = root / "wrong-independent" - with pytest.raises(ValueError, match="original submission"): - seal(repo, baseline, path, wrong, output, submission=root / "submission.json") - assert not (output / "seal.json").exists() - assert not (output / "attempt/execution").exists() - - -def test_different_patch_with_identical_source_is_rejected(campaign, tmp_path): - root, repo, path, _, _, _, baseline, original = campaign - clone = tmp_path / "baseline" - git(repo, "clone", "--quiet", "--config", "core.autocrlf=false", str(repo), str(clone)) - equivalent = tmp_path / "equivalent.patch" - equivalent.write_bytes(b"Equivalent change with a distinct header\n\n" + original.read_bytes()) - git(clone, "apply", str(equivalent)) - assert (clone / "engine.py").read_bytes() == (repo / "engine.py").read_bytes() - output = tmp_path / "independent" - with pytest.raises(ValueError, match="original submission"): - seal(repo, baseline, path, equivalent, output, submission=root / "submission.json") - assert not output.exists() - - -def test_sealed_source_drift_is_rejected_before_timing(campaign): - root, repo, path, _, _, _, baseline, patch = campaign - output = root / "changed-after-seal" - plan, _ = seal(repo, baseline, path, patch, output, submission=root / "submission.json") - (output / "attempt/candidate/engine.py").write_bytes(b"LATENCY = 1\n") - with pytest.raises(ValueError, match="changed before timing"): - execute(output, plan, 30) - assert not (output / "attempt/execution").exists() - - -def test_posthoc_choice_is_rejected(campaign): - root, _, _, _, state, observer, *_ = campaign - observer = copy.deepcopy(observer) - choice = observer["round_choices"][state["rounds"][0]["candidate_id"]] - choice["plan_event"], choice["first_edit_event"] = ( - choice["first_edit_event"], choice["plan_event"]) - report = Report() - report.rounds = [{"starting_best_sha256": "synthetic"}] * len(state["rounds"]) - check_choices(root, observer, state["rounds"], report) - assert "choice_recorded_after_edit_or_measurement" in codes(report) - - -def test_missing_choice_review_never_becomes_automatic_pass(campaign): - root, _, _, _, state, observer, *_ = campaign - observer = copy.deepcopy(observer) - del observer["round_choices"][state["rounds"][0]["candidate_id"]]["review"] - report = Report() - report.rounds = [{"starting_best_sha256": "synthetic"}] * len(state["rounds"]) - check_choices(root, observer, state["rounds"], report) - assert "choice_evidence_unavailable" in codes(report) - - -@pytest.mark.parametrize("change,expected", [ - ("fresh_process_ids", "baseline_repeat_not_across_fresh_processes"), - ("source_sha256", "baseline_repeat_wrong_source"), - ("effective_scheduler", "baseline_repeat_protocol_mismatch"), -]) -def test_unqualified_baseline_stays_inconclusive(campaign, change, expected): - root, _, path, plan, state, observer, *_ = campaign - observer = copy.deepcopy(observer) - observer["baseline_repeat"][change] = { - "fresh_process_ids": ["same", "same"], "source_sha256": ["wrong", "wrong"], - "effective_scheduler": {"synthetic_grid": [99]}, - }[change] - report = Report() - check_outputs(path, plan, state, root, observer, report) - assert expected in codes(report) - assert report.document()["workflow_verdict"] == ("FAIL" if change == "source_sha256" - else "INCONCLUSIVE") - - -def test_independent_receipt_cannot_be_bound_to_a_different_attempt(campaign): - root, _, _, plan, state, observer, *_ = campaign - selected = {**select_patch_round(state["rounds"]), "path": "wrong-attempt"} - report = Report() - check_independent(root, observer, selected, plan, report) - assert "independent_selection_binding_mismatch" in codes(report) - - -def test_assistance_is_separate_from_correct_results(campaign): - root, _, path, _, _, observer, *_ = campaign - observer = copy.deepcopy(observer) - observer["interventions"] = [{"kind": "assistance", "stage": "baseline", - "at_seconds": 12, "reason": "synthetic connection repair", - "action": "synthetic repair"}] - receipt = root / "assisted-observer.json" - write(receipt, observer) - report = audit(path, receipt) - assert report["workflow_verdict"] == "FAIL" - assert report["completion_mode"] == "assisted" - assert report["independent_patch_retest"]["quality_passed"] is True - assert report["first_blocked_step"] == "baseline" - - -def test_live_driver_refuses_dirty_project_before_launch(campaign): - root, repo, _, _, _, _, baseline, _ = campaign - with pytest.raises(ValueError, match="clean"): - launch(repo, baseline, root / "never-launched", executable="not-a-command", - model="synthetic", timeout=10) - assert not (root / "never-launched").exists() - - -def test_driver_sends_only_the_natural_request_to_one_new_session(campaign, tmp_path): - _, repo, _, _, _, _, baseline, _ = campaign - clean = tmp_path / "clean-project" - git(repo, "clone", "--no-checkout", str(repo), str(clean)) - git(clean, "checkout", "--detach", baseline) - output = tmp_path / "host-output" - fake_host = FIXTURES / "codex_host.py" - receipt = launch(clean, baseline, output, executable=[sys.executable, str(fake_host)], - model="synthetic-model", timeout=15) - expected = REPOSITORY_ROOT / "e2e/qwen_image/request.txt" - assert (output / "final-reply.txt").read_text(encoding="utf-8") == ( - expected.read_text(encoding="utf-8").strip()) - assert receipt["native_session_ids"] == ["synthetic-session"] - assert receipt["native_turn_completed"] is True - assert receipt["elapsed_seconds"] > 0 - assert (output / "events.jsonl").is_file() - - -def test_discovery_excludes_old_or_other_project_campaigns(campaign): - root, repo, path, _, state, *_ = campaign - assert discover(root, repo, state["started_at"] - 1) == path - with pytest.raises(ValueError, match="one new campaign"): - discover(root, repo, state["started_at"] + 1) - - -@pytest.mark.parametrize("archive,host,expected", [ - (b"candidate A\n", b"candidate A\n", None), - (b"candidate A\n", b"candidate A\r\n", "observer_reply_differs_from_host_output"), - (b"candidate A", b"candidate B", "observer_reply_differs_from_host_output"), - (b"\xef\xbb\xbf \r\n", None, "empty_final_reply"), -]) -def test_final_reply_preserves_the_host_bytes(tmp_path, archive, host, expected): - reply = tmp_path / "observer-reply.txt" - reply.write_bytes(archive) - host_reply = None - if host is not None: - host_reply = tmp_path / "final-reply.txt" - host_reply.write_bytes(host) - report = Report() - check_final_reply(tmp_path, {"final_reply": ref(tmp_path, reply)}, report, host_reply) - if expected: - assert report.findings == [{"code": expected, "verdict": "FAIL"}] - else: - assert not report.findings - assert report.results["final_reply_sha256"] == sha256(host_reply) - - -def test_missing_host_reply_is_inconclusive_even_with_observer_copy(tmp_path): - reply = tmp_path / "observer-reply.txt" - reply.write_bytes(b"Retained copy") - report = Report() - check_final_reply(tmp_path, {"final_reply": ref(tmp_path, reply)}, report, - tmp_path / "missing-host-output.txt") - assert report.findings == [ - {"code": "final_reply_evidence_unavailable", "verdict": "INCONCLUSIVE"}] - - -def test_missing_evidence_is_not_a_passing_skip(tmp_path): - report = audit(tmp_path, tmp_path / "missing-observer.json") - assert report["workflow_verdict"] == "INCONCLUSIVE" - - -@pytest.mark.parametrize("field,expected,verdict", [ - ("effective_scheduler", "effective_scheduler_changed", "FAIL"), - ("environment_identity", "environment_or_workload_not_comparable", "INCONCLUSIVE"), - ("median_ms", "raw_quality_or_timing_evidence_contradicted", "FAIL"), -]) -def test_raw_candidate_changes_are_not_hidden_by_summary( - campaign, tmp_path, field, expected, verdict): - root, _, path, plan, state, observer, *_ = campaign - record = state["rounds"][0] - step = "measurement-001-candidate" - directory = tmp_path / "attempt/execution" / step - shutil.copytree(path / record["path"] / "execution" / step, directory) - result = read(directory / "result.json") - result[field] = {"effective_scheduler": {"num_steps": 1}, - "environment_identity": "different-synthetic-environment", - "median_ms": 1}[field] - write(directory / "result.json", result) - write(directory.parent / "execution.json", {"steps": [{"id": step}]}) - fake_state = {"rounds": [], "final": {**record, "path": "attempt"}} - report = Report() - check_outputs(tmp_path, plan, fake_state, root, observer, report) - assert expected in codes(report) - assert report.document()["workflow_verdict"] == verdict - - -@pytest.mark.parametrize("attempt,step,missing", [ - ("round", "quality-baseline", False), - ("final", "measurement-001-candidate", True), - ("independent", "measurement-001-candidate", False), -]) -def test_worker_must_load_the_source_of_its_arm(campaign, monkeypatch, attempt, step, missing): - root, _, path, _, state, *_ = campaign - directory = {"round": path / state["rounds"][0]["path"], - "final": path / state["final"]["path"], - "independent": root / "independent/attempt"}[attempt] - target = directory / "execution" / step / "result.json" - - def worker_result(filename): - result = read(filename) - if filename == target: - if missing: - del result["loaded_source_sha256"] - else: - result["loaded_source_sha256"] = "0" * 64 - return result - - monkeypatch.setattr("e2e.qwen_image.audit.read", worker_result) - report = audit(path, root / "observer.json") - assert report["workflow_verdict"] == ("INCONCLUSIVE" if missing else "FAIL") - code = "loaded_source_identity_missing" if missing else "wrong_source_loaded" - assert any(row["code"] == code and row["step"] == step for row in report["findings"]) - - -def test_verified_flag_cannot_hide_a_different_loaded_source(campaign): - _, _, root, plan, state, *_ = campaign - record = state["rounds"][0] - directory = root / record["path"] - execution = read(directory / "execution/execution.json") - expected = {"baseline": plan["baseline_sha256"], "candidate": record["candidate_sha256"]} - execution["source_checks"][0]["expected"]["candidate"] = "different-source" - execution["source_checks"][0]["actual"]["candidate"] = "different-source" - execution["source_checks"][0]["verified"] = True - with pytest.raises(ValueError, match="Loaded source"): - recompute(directory, plan["evaluation_settings"], execution, expected) - - -def test_repeated_source_is_not_another_optimization_round(campaign): - _, _, root, plan, state, *_ = campaign - altered = copy.deepcopy(state) - first = altered["rounds"][0] - altered["rounds"] = [first, copy.deepcopy(first)] - altered["best"] = first["best_after"] - altered["final"] = None - report = Report() - audit_selection(plan, altered, root, report) - assert "unchanged_or_repeated_candidate" in codes(report) - - -def test_rejected_quality_cannot_be_adopted_as_best(campaign, tmp_path): - _, _, root, plan, state, *_ = campaign - record = copy.deepcopy(state["rounds"][0]) - directory = tmp_path / "attempt" - shutil.copytree(root / record["path"], directory) - result_path = directory / "execution/quality-candidate/result.json" - result = read(result_path) - result["correct"] = False - write(result_path, result) - execution = read(directory / "execution/execution.json") - execution["steps"] = execution["steps"][:2] - execution["source_checks"] = execution["source_checks"][:2] - write(directory / "execution/execution.json", execution) - record["path"] = "attempt" - record["assessment"] = recompute(directory, plan["evaluation_settings"], execution) - assert record["assessment"]["status"] == "candidate_failure" - altered = {**state, "rounds": [record], "best": record["best_after"], "final": None} - report = Report() - audit_selection(plan, altered, tmp_path, report) - assert "wrong_adopt_reject_decision" in codes(report) - - -def test_unstable_baseline_pixels_are_inconclusive_not_candidate_failure(campaign): - from PIL import Image - - root, _, path, plan, state, observer, *_ = campaign - observer = copy.deepcopy(observer) - old_path = root / observer["baseline_repeat"]["results"][1]["path"] - directory = root / "unstable-baseline-repeat" - shutil.copytree(old_path.parent, directory) - result = read(directory / "result.json") - Image.new("RGBA", (1280, 704), (0, 0, 0, 255)).save(directory / "seed-42.png") - with Image.open(directory / "seed-42.png") as image: - result["requests"][0]["pixel_sha256"] = hashlib.sha256(image.tobytes()).hexdigest() - write(directory / "result.json", result) - image_requests(directory, result) # Internally consistent, but a different baseline image. - observer["baseline_repeat"]["results"][1] = ref(root, directory / "result.json") - report = Report() - check_outputs(path, plan, state, root, observer, report) - assert "baseline_pixel_reference_unqualified" in codes(report) - assert report.document()["workflow_verdict"] == "INCONCLUSIVE" - - -@pytest.mark.parametrize("complete", [True, False]) -def test_pytest_replay_entry_writes_verdict_and_never_hides_gaps(campaign, tmp_path, complete): - root, _, path, *_ = campaign - observer = root / "observer.json" if complete else tmp_path / "unavailable.json" - output = tmp_path / "report" - result = subprocess.run([ - sys.executable, "-m", "pytest", "e2e/qwen_image", "--e2e-campaign", str(path), - "--e2e-observer", str(observer), "--e2e-artifacts", str(output), - ], cwd=REPOSITORY_ROOT, capture_output=True, text=True, encoding="utf-8") - assert result.returncode == (0 if complete else 1), result.stdout + result.stderr - assert read(output / "pytest-report.json")["workflow_verdict"] == ( - "PASS" if complete else "INCONCLUSIVE") diff --git a/tests/fixtures/user_e2e/codex_host.py b/tests/fixtures/user_e2e/codex_host.py deleted file mode 100644 index 48b371b54..000000000 --- a/tests/fixtures/user_e2e/codex_host.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Synthetic CLI host exercising exact prompt delivery, not an actual Agent.""" - -import json -import sys -from pathlib import Path - -if sys.argv[1:] == ["--version"]: - print("synthetic-codex-control") -else: - prompt = sys.stdin.buffer.read().decode("utf-8") - reply = Path(sys.argv[sys.argv.index("--output-last-message") + 1]) - reply.write_text(prompt, encoding="utf-8") - for event in ({"type": "thread.started", "thread_id": "synthetic-session"}, - {"type": "turn.completed"}): - print(json.dumps(event), flush=True) diff --git a/tests/fixtures/user_e2e/measure.py b/tests/fixtures/user_e2e/measure.py deleted file mode 100644 index 6929ac4d3..000000000 --- a/tests/fixtures/user_e2e/measure.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Synthetic CPU control, not a Qwen benchmark or hardware evidence.""" - -import hashlib -import json -import os -import runpy -import shutil -import sys -import time -from pathlib import Path - -from PIL import Image - -from inferrsi.harness import candidates - -started = time.time() -source, output = map(Path, sys.argv[1:3]) -engine = runpy.run_path(str(source / "engine.py")) -loaded_file = Path(engine["__file__"]) -loaded_sha = candidates.identity(loaded_file.parent, [loaded_file.name]) -metric = engine["LATENCY"] -requests = [] -for seed in range(42, 48): - path = output.parent / f"seed-{seed}.png" - shutil.copyfile(Path(__file__).with_name(path.name), path) - with Image.open(path) as image: - pixels = hashlib.sha256(image.convert("RGBA").tobytes()).hexdigest() - requests.append({"seed": seed, "latency_ms": metric, "file": path.name, - "pixel_sha256": pixels}) -output.write_text(json.dumps({ - "loaded_source_sha256": loaded_sha, - "median_ms": metric, "correct": True, "requests": requests, - "effective_scheduler": {"num_steps": 8, "timesteps": list(range(8)), "sigmas": [1, 0]}, - "process": {"id": str(os.getpid()), "finished_at": time.time(), "started_at": started}, - "environment_identity": "synthetic-not-a-device", - "workload_sha256": hashlib.sha256(Path(__file__).with_name("workload.json").read_bytes()) - .hexdigest(), -}), encoding="utf-8") From a7a8c6fffb31228285a2ac6249b7100e14537efc Mon Sep 17 00:00:00 2001 From: zengchuang Date: Wed, 25 Nov 2026 22:59:22 +0800 Subject: [PATCH 4/4] Require three optimization rounds in the Ascend E2E case Freeze the exact round budget in the user journey and verify it against the completed campaign before independent retest. Agent-assisted-by: Codex (implementation and verification) Signed-off-by: zengchuang --- docs/e2e-qwen-image-codex.md | 2 +- e2e/qwen_image/request.txt | 2 +- e2e/qwen_image/test_user_journey.py | 20 ++++++++++++++++---- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/docs/e2e-qwen-image-codex.md b/docs/e2e-qwen-image-codex.md index 8774590a5..e476aac0c 100644 --- a/docs/e2e-qwen-image-codex.md +++ b/docs/e2e-qwen-image-codex.md @@ -21,7 +21,7 @@ python -m pytest -qs e2e/qwen_image/test_user_journey.py - 用户请求见 [request.txt](../e2e/qwen_image/request.txt)。用例附上本机模型、冻结测量程序和新建 campaign 的位置,要求 Codex 将选中的实现留在工作副本的 `vllm_omni/` 中。实际投递内容保存在结果目录的 `request.txt`。 - [workload.json](../e2e/qwen_image/workload.json) 固定两个预热请求和六个测量请求(种子 42–47)。两侧均使用 1280×704、BF16、原生八步、CFG=1、单卡、单请求单图。计时从调用 `Omni.generate` 开始,到取得已解码的 RGBA 图像为止。模型加载、预热和 PNG 落盘分别处理。 - 用例先在两个全新进程中复测基线,核对六张原图,记录两组中位耗时的相对差值作为本次噪声参考。此时将运行条件写入 `frozen.json`。若 Issue 另有最低降幅,开跑前用 `QWEN_E2E_MIN_GAIN_PCT` 指定百分数。 -- Codex 退出后,用例读取同一次运行中的最终回复和 InferRSI campaign,核对至少两轮优化、完成状态和最终选中源码。随后从工作副本提取补丁,在第二个干净 Git 副本中应用,核对 `vllm_omni/` 的 Git 树。之后以 AB、BA、AB 的顺序交替测基线(A)与补丁(B),每组每侧启动一个新的推理进程。每个进程保存六个原始耗时与六张 PNG。 +- Codex 退出后,用例读取同一次运行中的最终回复和 InferRSI campaign,核对计划和实际执行都恰好是三轮优化,并检查完成状态和最终选中源码。随后从工作副本提取补丁,在第二个干净 Git 副本中应用,核对 `vllm_omni/` 的 Git 树。之后以 AB、BA、AB 的顺序交替测基线(A)与补丁(B),每组每侧启动一个新的推理进程。每个进程保存六个原始耗时与六张 PNG。 ## 校验优化指标 diff --git a/e2e/qwen_image/request.txt b/e2e/qwen_image/request.txt index b42d7d78c..72ba5fa7d 100644 --- a/e2e/qwen_image/request.txt +++ b/e2e/qwen_image/request.txt @@ -1 +1 @@ -请用 InferRSI 优化当前 vLLM-Omni 项目的 Qwen-Image-2.1-Turbo,在 Ascend A2 单卡上生成 1280×704 图片,保持出图质量,把单张生图耗时降到尽可能低。请多轮尝试、复测最优方案,并交付补丁和结果。 +请用 InferRSI 优化当前 vLLM-Omni 项目的 Qwen-Image-2.1-Turbo,在 Ascend A2 单卡上生成 1280×704 图片,保持出图质量,把单张生图耗时降到尽可能低。请完成 3 轮优化迭代,再复测这 3 轮中表现最好的方案,并交付补丁、优化前后的单张生图耗时和降幅。 diff --git a/e2e/qwen_image/test_user_journey.py b/e2e/qwen_image/test_user_journey.py index 9344b7cc3..914dd65f4 100644 --- a/e2e/qwen_image/test_user_journey.py +++ b/e2e/qwen_image/test_user_journey.py @@ -14,6 +14,7 @@ import pytest CASE = Path(__file__).resolve().parent +OPTIMIZATION_ROUNDS = 3 def git(repo, *args): @@ -62,7 +63,8 @@ def optimize(project, checkpoint, output, timeout): prompt += ( f"\n本机模型目录:{checkpoint}。冻结的测量程序:{CASE / 'measure.py'}," "依次传入源码目录、模型目录、新输出目录。请自主使用本机 InferRSI 的 " - f"campaign start、round、final 完成多轮优化,campaign 目录使用 {campaign}。" + f"campaign start(--rounds {OPTIMIZATION_ROUNDS} --round-mode exact)、round、final " + f"完成三轮优化,campaign 目录使用 {campaign}。" "将最终选中的生产代码留在当前项目的 vllm_omni/ 下,供独立复测。" ) (output / "request.txt").write_text(prompt + "\n", encoding="utf-8") @@ -75,11 +77,20 @@ def optimize(project, checkpoint, output, timeout): # The campaign and final reply must both belong to this fresh invocation. plan = json.loads((campaign / "plan.json").read_bytes()) state = json.loads((campaign / "state.json").read_bytes()) + completed_rounds = len(state["rounds"]) + if (plan["round_mode"] != "exact" or plan["round_limit"] != OPTIMIZATION_ROUNDS + or completed_rounds != OPTIMIZATION_ROUNDS): + raise ValueError( + f"Expected exactly {OPTIMIZATION_ROUNDS} planned and completed optimization rounds; " + f"found round_mode={plan['round_mode']!r}, round_limit={plan['round_limit']}, " + f"completed_rounds={completed_rounds}" + ) if (not (output / "final-reply.txt").read_text(encoding="utf-8").strip() or plan["task_source"] != "project" or Path(plan["working_candidate"]) != project - or state["state"] != "completed" or len(state["rounds"]) < 2 + or state["state"] != "completed" or identity(project, plan["candidate_includes"]) != state["final"]["candidate_sha256"]): raise ValueError("The Codex run did not deliver the final source of this project campaign") + return completed_rounds def measure(source, checkpoint, output, timeout): @@ -122,7 +133,8 @@ def test_codex_optimizes_qwen_image_on_a2(tmp_path): parent.mkdir(parents=True, exist_ok=True) output = Path(tempfile.mkdtemp(prefix="qwen-a2-", dir=parent)) print(f"E2E results: {output}", flush=True) - report = {"verdict": "INCONCLUSIVE", "stage": "preflight"} + report = {"verdict": "INCONCLUSIVE", "stage": "preflight", + "required_optimization_rounds": OPTIMIZATION_ROUNDS} try: repo = Path(os.environ["QWEN_E2E_REPO"]).resolve(strict=True) checkpoint = Path(os.environ["QWEN_E2E_CHECKPOINT"]).resolve(strict=True) @@ -150,7 +162,7 @@ def test_codex_optimizes_qwen_image_on_a2(tmp_path): noise_pct=noise, min_gain_pct=minimum) write_json(output / "frozen.json", report) report["stage"] = "codex" - optimize(project, checkpoint, output, timeout) + report["completed_optimization_rounds"] = optimize(project, checkpoint, output, timeout) report["stage"] = "reconstruct" git(project, "add", "-A", "--", "vllm_omni")