You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by gi...@apache.org on 2026/09/08 14:07:50 UTC
(seatunnel) branch gh-readonly-queue/dev/pr-12192-69150256a58f08cac091cd3e0c93f2a6ee3e1493 created (now 6a0f36278d)
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a change to branch gh-readonly-queue/dev/pr-12192-69150256a58f08cac091cd3e0c93f2a6ee3e1493
in repository https://gitbox.apache.org/repos/asf/seatunnel.git
at 6a0f36278d [Feature][CLI] Compare saved benchmark results across revisions (#12192)
This branch includes the following new commits:
new 6a0f36278d [Feature][CLI] Compare saved benchmark results across revisions (#12192)
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(seatunnel) 01/01: [Feature][CLI] Compare saved benchmark results across revisions (#12192)
Posted by gi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-12192-69150256a58f08cac091cd3e0c93f2a6ee3e1493
in repository https://gitbox.apache.org/repos/asf/seatunnel.git
commit 6a0f36278d31563d9a9c9243f899b1c522cf3a2d
Author: Goutam Adwant <86...@users.noreply.github.com>
AuthorDate: Tue Sep 8 14:07:24 2026 +0000
[Feature][CLI] Compare saved benchmark results across revisions (#12192)
Signed-off-by: Goutam Adwant <wo...@gmail.com>
---
docs/en/ai-cli/benchmark.md | 31 ++
docs/zh/ai-cli/benchmark.md | 28 ++
seatunnel-cli/benchmark/README.md | 54 +++
seatunnel-cli/benchmark/compare.py | 368 ++++++++++++++++
seatunnel-cli/benchmark/runner.py | 10 +
seatunnel-cli/tests/test_benchmark_comparison.py | 539 +++++++++++++++++++++++
6 files changed, 1030 insertions(+)
diff --git a/docs/en/ai-cli/benchmark.md b/docs/en/ai-cli/benchmark.md
index 24aee2441a..4c0c3e6d35 100644
--- a/docs/en/ai-cli/benchmark.md
+++ b/docs/en/ai-cli/benchmark.md
@@ -6,6 +6,37 @@ sidebar_position: 4
The AI CLI's accuracy is measured — not assumed — by a dedicated benchmark: 100 tasks in three complexity tiers, judged through layered verdict gates up to **real job execution** against Dockerized data sources, across 7 mainstream LLMs. This page summarizes the methodology, the results, and what they mean for choosing a model.
+## Comparing CLI Revisions
+
+Save baseline and candidate benchmark runs in separate directories, then compare
+their `results.json` files without making additional model calls:
+
+```bash
+cd seatunnel-cli
+python -m benchmark.compare benchmark/baseline/results.json benchmark/candidate/results.json \
+ --out benchmark/comparison.md
+```
+
+The Markdown report pairs model/task/trial identities and shows aggregate deltas
+alongside every first-attempt and repair-budget pass-to-fail/fail-to-pass transition.
+Matching recorded model configuration, requested gates, trial count, repair budget,
+CLI revision stamps, and task-definition fingerprints are required. Missing,
+incompatible, skipped, or incomplete results are visibly excluded from both
+denominators, not treated as improvements. Inspect exclusions before interpreting
+the paired subset as the full suite.
+
+New runs include `task_sha256`, covering the prompt, assertions, and execution
+probes. Older result files lack this evidence and are excluded; collect fresh runs
+with the fingerprint-enabled harness rather than backfilling hashes from current
+tasks. Existing single-run reports and inputs remain unchanged. The comparison
+refuses to overwrite an output file; omit `--out` to print to stdout. Exit code 0
+means a report was produced, not that an accuracy gate passed.
+
+This is an offline, descriptive comparison, not a statistical or CI acceptance
+gate. Keep provider environment variables, model serving state, validation code,
+connector metadata, engine version, and test data constant when isolating a CLI
+change. Task fingerprints alone do not establish that these other inputs match.
+
> Results below were measured in July 2026 against seatunnel-cli v0.1.0 (commit `59ada4ec0`) with models served by AWS Bedrock. Accuracy drifts as models and the CLI evolve; treat the numbers as a snapshot and re-run the benchmark for current values.
## Methodology
diff --git a/docs/zh/ai-cli/benchmark.md b/docs/zh/ai-cli/benchmark.md
index 58ad22c7e6..e2f14bd16c 100644
--- a/docs/zh/ai-cli/benchmark.md
+++ b/docs/zh/ai-cli/benchmark.md
@@ -6,6 +6,34 @@ sidebar_position: 4
AI CLI 的准确率靠实测而非假设:专门的基准测试包含 100 个任务、三档复杂度,判定门层层递进直至**真实作业执行**(连接 Docker 化的真实数据源),覆盖 7 个主流大模型。本页汇总方法论、测试结果与选型建议。
+## 比较 CLI 版本
+
+将基线和候选版本的基准测试分别保存到不同目录,然后比较其 `results.json`,
+无需再次调用模型:
+
+```bash
+cd seatunnel-cli
+python -m benchmark.compare benchmark/baseline/results.json benchmark/candidate/results.json \
+ --out benchmark/comparison.md
+```
+
+Markdown 报告按模型、任务和试验编号配对,同时展示总体变化,以及每个配对试验的
+首次交付配置和修复预算内的通过到失败、失败到通过等变化。
+比较要求已记录的模型配置、请求的判定门、试验次数、修复预算相同,且两侧都有
+CLI 提交标记和匹配的任务定义指纹。缺失、不兼容、跳过或不完整的结果会明确列出,
+并从两侧分母中同时排除,而不会被视为改进。将配对子集解释为完整任务集之前,
+应先检查所有排除项。
+
+新运行的结果包含 `task_sha256`,覆盖提示词、断言和执行验证条件。
+旧结果缺少这项证据,因此无法参与可信配对;应使用支持指纹的测试工具重新采集
+两侧结果,而不要根据当前任务文件回填哈希。原有单次运行报告和输入文件保持不变。
+比较命令拒绝覆盖已有输出文件;省略 `--out` 时输出到标准输出。
+退出码 0 仅表示报告已生成,不代表通过了准确率准入检查。
+
+这是离线描述性比较,不是统计显著性结论或 CI 准入门槛。若要隔离 CLI 变更的影响,
+应保持提供商环境变量、模型服务状态、验证代码、连接器元数据、引擎版本和测试数据
+一致。任务指纹相同并不能证明这些其他输入也相同。
+
> 以下数据于 2026 年 7 月实测,被测对象为 seatunnel-cli v0.1.0(commit `59ada4ec0`),模型由 AWS Bedrock 提供。模型与 CLI 都在演进,数字是时间快照——需要最新数据请重新运行基准测试。
## 方法论
diff --git a/seatunnel-cli/benchmark/README.md b/seatunnel-cli/benchmark/README.md
index 1873da1e1c..1743c3e40b 100644
--- a/seatunnel-cli/benchmark/README.md
+++ b/seatunnel-cli/benchmark/README.md
@@ -215,6 +215,60 @@ claude-sonnet-4 (bedrock) (28 tasks)
## Methodology notes
+### Compare saved results across revisions
+
+Keep each run in a separate output directory, then compare its saved JSON:
+
+```bash
+cd seatunnel-cli
+python -m benchmark.compare benchmark/baseline/results.json benchmark/candidate/results.json \
+ --out benchmark/comparison.md
+```
+
+This command uses only the Python standard library. It does not generate configs,
+call a model, start Docker, or rerun validation. Without `--out` it prints Markdown
+to stdout. An existing output file is never overwritten, including either input
+or an existing single-run report. Incompatible runs produce an explanatory report;
+exit code 0 means the report was produced, not that a regression gate passed.
+Unreadable/malformed input, ambiguous duplicate identities, or an output error
+produce exit code 2.
+
+The report shows per-model paired-trial rates for the first delivered config
+(`pass@1`) and success within the configured repair budget. Every matched task and
+trial also shows `pass→fail`, `fail→pass`, `pass→pass`, or `fail→fail`, so an overall
+gain cannot hide a regression. Trial indices identify independent samples, not
+matched random seeds; transitions are observations, not statistical significance.
+
+Compatibility is checked before reporting deltas:
+
+- Requested gates, trial count, and repair budget must match. Both runs need a
+ CLI revision stamp.
+- Model names identify rows; recorded provider settings must match and explicitly
+ include provider and model IDs. Different aliases are reported as missing models.
+- Task IDs must match and carry the same `task_sha256`. New runs record a SHA-256
+ of the complete task dictionary (including prompt, assertions, tier, and execution
+ probes), encoded as UTF-8 JSON with sorted keys, no whitespace separators, and
+ unescaped Unicode. This field is additive; existing summaries are unchanged.
+- Trial IDs must exactly cover the declared count. Missing tasks/models/trials,
+ initialization failures, skipped requested gates, and incomplete or contradictory
+ attempt records are excluded from both sides, with reasons. A real generation or
+ gate failure still counts as a failure; later gates short-circuited by that failure
+ do not make the trial incomplete.
+
+Results recorded before `task_sha256` was added cannot establish that their task
+definitions match. They remain readable by the existing single-run reporter, but
+the comparison excludes them. Collect new baseline and candidate runs with the
+fingerprint-enabled harness; do not backfill hashes from today's task files.
+
+Only the paired, complete subset contributes to both denominators. Inspect all
+exclusions before interpreting a delta as a full-suite change. The report compares
+recorded settings, not every runtime input: keep environment variables (including
+fast-model overrides), model serving state, gate implementations, connector metadata,
+engine version, and source/sink data constant when isolating a CLI change. A matching
+task hash does not prove these inputs match or attribute an improvement to CLI code.
+
+### Existing evaluation methodology
+
- **Determinism**: L2/L3 verdicts are exit-code/liveness based — no LLM judge.
- **Isolation**: each task gets a fresh Orchestrator; CLI state goes to a
temp `SEATUNNEL_CLI_DATA`; every model sees identical prompts and env.
diff --git a/seatunnel-cli/benchmark/compare.py b/seatunnel-cli/benchmark/compare.py
new file mode 100644
index 0000000000..3be9d0af38
--- /dev/null
+++ b/seatunnel-cli/benchmark/compare.py
@@ -0,0 +1,368 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Compare two saved benchmark results without running providers or gates."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+from pathlib import Path
+
+from benchmark.report import _cli_stamp
+
+
+def _index(items: list, key: str) -> dict:
+ if not isinstance(items, list):
+ raise ValueError(f"expected a list of {key} records")
+ indexed = {}
+ for item in items:
+ if (
+ not isinstance(item, dict)
+ or not isinstance(item.get(key), str)
+ or not item[key]
+ ):
+ raise ValueError(f"missing or invalid {key}")
+ if item[key] in indexed:
+ raise ValueError(f"duplicate {key}; comparison would be ambiguous")
+ indexed[item[key]] = item
+ return indexed
+
+
+def _run_issues(baseline: dict, candidate: dict) -> list[str]:
+ issues = []
+ for name, run in (("baseline", baseline), ("candidate", candidate)):
+ if not isinstance(run, dict):
+ raise ValueError(f"{name} results must be an object")
+ if (
+ not isinstance(run.get("cli"), dict)
+ or not isinstance(run["cli"].get("cli_commit"), str)
+ or not run["cli"]["cli_commit"]
+ ):
+ issues.append(f"{name}: CLI revision metadata missing")
+ levels = run.get("levels")
+ if levels not in (["l1"], ["l1", "l2"], ["l1", "l3"], ["l1", "l2", "l3"]):
+ issues.append(f"{name}: requested gate metadata missing or invalid")
+ for field, minimum in (("trials", 1), ("max_repairs", 0)):
+ value = run.get(field)
+ if type(value) is not int or value < minimum:
+ issues.append(f"{name}: {field} missing or invalid")
+ for field in ("levels", "trials", "max_repairs"):
+ if baseline.get(field) != candidate.get(field):
+ issues.append(f"{field} differs between runs")
+ return issues
+
+
+def _model_issue(before: dict, after: dict) -> str:
+ for name, model in (("baseline", before), ("candidate", after)):
+ if model.get("error"):
+ return f"{name} model did not run"
+ config = model.get("config")
+ if not isinstance(config, dict) or any(
+ not isinstance(config.get(key), str) or not config[key]
+ for key in ("provider", "model")
+ ):
+ return f"{name} explicit provider/model metadata missing"
+ # Names identify report rows, not provider settings. Never print config
+ # values: saved endpoints and provider errors can contain credentials.
+ configs = [
+ {key: value for key, value in model["config"].items() if key != "name"}
+ for model in (before, after)
+ ]
+ return "model configuration differs" if configs[0] != configs[1] else ""
+
+
+def _task_issue(before: dict, after: dict, trials: int) -> str:
+ for name, task in (("baseline", before), ("candidate", after)):
+ fingerprint = task.get("task_sha256")
+ if not isinstance(fingerprint, str) or not re.fullmatch(
+ "[0-9a-f]{64}", fingerprint
+ ):
+ return f"{name} task fingerprint missing or invalid; rerun to record task definitions"
+ records = task.get("trials")
+ if not isinstance(records, list) or any(
+ not isinstance(record, dict) or type(record.get("trial")) is not int
+ for record in records
+ ):
+ return f"{name} trial IDs missing or invalid"
+ ids = [record["trial"] for record in records]
+ if len(ids) != len(set(ids)):
+ return f"{name} duplicate trial IDs"
+ if len(ids) != trials or sorted(ids) != list(range(len(ids))):
+ return f"{name} trial IDs do not match declared trial count"
+ if before["task_sha256"] != after["task_sha256"]:
+ return "task definition differs"
+ return ""
+
+
+def _trial_outcome(trial: dict, levels: list[str], max_repairs: int) -> tuple:
+ """Return first/final success, or an exclusion reason for incomplete evidence.
+
+ A failed gate legitimately short-circuits later gates. A missing/skipped
+ gate without a preceding failure is not a measured failure or success.
+ """
+ if "first_pass_round" not in trial:
+ return None, None, "first_pass_round missing"
+ attempts = trial.get("attempts")
+ if not isinstance(attempts, list):
+ return None, None, "attempt records missing"
+ first_pass = None
+ if not attempts:
+ if trial.get("generation_error") and trial.get("first_pass_round") is None:
+ return False, False, ""
+ return None, None, "attempt records incomplete"
+ for number, attempt in enumerate(attempts):
+ if (
+ not isinstance(attempt, dict)
+ or type(attempt.get("round")) is not int
+ or attempt["round"] != number
+ or number > max_repairs
+ ):
+ return None, None, "attempt rounds invalid"
+ layers = attempt.get("layers")
+ # The runner records one explicit null-layer attempt when generation
+ # produces no config, including an empty config without an exception.
+ if (
+ "layers" in attempt
+ and layers is None
+ and number == 0
+ and len(attempts) == 1
+ ):
+ continue
+ if not isinstance(layers, dict):
+ return None, None, "gate results missing"
+ if (
+ "all_gates_executed" in layers
+ and type(layers["all_gates_executed"]) is not bool
+ ):
+ return None, None, "gate coverage flag invalid"
+ if layers.get("skipped_layers") or layers.get("all_gates_executed") is False:
+ return None, None, "requested gate skipped"
+ passed = True
+ for level in levels:
+ info = layers.get(level)
+ if not isinstance(info, dict) or type(info.get("passed")) is not bool:
+ return None, None, "requested gate result missing"
+ if info["passed"] is False:
+ passed = False
+ break
+ for flag in ("all_passed", "full_gate_passed"):
+ if flag in layers and (
+ type(layers[flag]) is not bool or layers[flag] != passed
+ ):
+ return None, None, f"{flag} contradicts gate results"
+ if passed:
+ first_pass = number
+ if number != len(attempts) - 1:
+ return None, None, "attempts continue after success"
+ recorded = trial.get("first_pass_round")
+ if (recorded is not None and type(recorded) is not int) or recorded != first_pass:
+ return None, None, "first_pass_round contradicts gate results"
+ return first_pass == 0, first_pass is not None, ""
+
+
+def compare_results(baseline: dict, candidate: dict) -> dict:
+ """Pair model/task/trial identities, excluding incompatible evidence.
+
+ Only the paired, complete trials contribute to both denominators. Input
+ dictionaries and existing single-run reports are never modified.
+ """
+ issues = _run_issues(baseline, candidate)
+ before_models = _index(baseline.get("models"), "name")
+ after_models = _index(candidate.get("models"), "name")
+ comparison = {
+ "baseline": (
+ baseline.get("cli") if isinstance(baseline.get("cli"), dict) else {}
+ ),
+ "candidate": (
+ candidate.get("cli") if isinstance(candidate.get("cli"), dict) else {}
+ ),
+ "max_repairs": baseline.get("max_repairs"),
+ "issues": issues,
+ "rows": [],
+ }
+ if issues:
+ return comparison
+ rows = comparison["rows"]
+
+ def excluded(model: str, task: str, reason: str) -> None:
+ rows.append(
+ {
+ "model": model,
+ "task": task,
+ "trial": None,
+ "first": None,
+ "repaired": None,
+ "reason": reason,
+ }
+ )
+
+ for name in sorted(before_models.keys() | after_models.keys()):
+ if name not in before_models or name not in after_models:
+ side = "baseline" if name not in before_models else "candidate"
+ excluded(name, "—", f"missing {side} model")
+ continue
+ before, after = before_models[name], after_models[name]
+ issue = _model_issue(before, after)
+ if issue:
+ excluded(name, "—", issue)
+ continue
+ before_tasks = _index(before.get("tasks"), "task_id")
+ after_tasks = _index(after.get("tasks"), "task_id")
+ for task_id in sorted(before_tasks.keys() | after_tasks.keys()):
+ if task_id not in before_tasks or task_id not in after_tasks:
+ side = "baseline" if task_id not in before_tasks else "candidate"
+ excluded(name, task_id, f"missing {side} task")
+ continue
+ before_task, after_task = before_tasks[task_id], after_tasks[task_id]
+ issue = _task_issue(before_task, after_task, baseline["trials"])
+ if issue:
+ excluded(name, task_id, issue)
+ continue
+ before_trials = {trial["trial"]: trial for trial in before_task["trials"]}
+ after_trials = {trial["trial"]: trial for trial in after_task["trials"]}
+ for index in sorted(before_trials):
+ outcomes = [
+ _trial_outcome(
+ records[index], baseline["levels"], baseline["max_repairs"]
+ )
+ for records in (before_trials, after_trials)
+ ]
+ reason = "; ".join(
+ f"{side}: {outcome[2]}"
+ for side, outcome in zip(("baseline", "candidate"), outcomes)
+ if outcome[2]
+ )
+ row = {
+ "model": name,
+ "task": task_id,
+ "trial": index,
+ "first": None,
+ "repaired": None,
+ "reason": reason,
+ }
+ if not reason:
+ for metric, position in (("first", 0), ("repaired", 1)):
+ row[metric] = "→".join(
+ "pass" if value[position] else "fail" for value in outcomes
+ )
+ rows.append(row)
+ return comparison
+
+
+def _cell(value) -> str:
+ text = (
+ str(value)
+ .replace("&", "&")
+ .replace("<", "<")
+ .replace(">", ">")
+ .replace("|", "|")
+ )
+ text = re.sub(r"[\x00-\x1f\x7f]", " ", text)
+ return re.sub(r"([\\`*\[\]_])", r"\\\1", text)
+
+
+def render_markdown(comparison: dict) -> str:
+ """Render a deterministic, descriptive report, not a CI acceptance gate."""
+ lines = [
+ "# SeaTunnel AI CLI Benchmark — Revision Comparison",
+ "",
+ f"Baseline: {_cell(_cli_stamp({'cli': comparison['baseline']}))}",
+ f"Candidate: {_cell(_cli_stamp({'cli': comparison['candidate']}))}",
+ "",
+ "Only paired trials with compatible recorded settings and complete verdicts are scored.",
+ "Missing or incompatible evidence is excluded from both denominators, not counted as a failure.",
+ "Model serving state, environment variables and engine/data state are not captured; "
+ "hold them constant when collecting runs. Trial numbers are independent samples, not shared random seeds.",
+ "",
+ ]
+ if comparison["issues"]:
+ lines += (
+ ["## Incompatible runs", ""]
+ + [f"- {_cell(issue)}" for issue in comparison["issues"]]
+ + [""]
+ )
+ comparable = [row for row in comparison["rows"] if not row["reason"]]
+ lines += ["## Paired-trial summary", ""]
+ if not comparable:
+ lines += ["No comparable trials. No accuracy delta is reported.", ""]
+ else:
+ lines += [
+ "| Model | Metric | Paired trials | Baseline | Candidate | Delta | Regressions | Improvements |",
+ "|---|---|---|---|---|---|---|---|",
+ ]
+ for name in sorted({row["model"] for row in comparable}):
+ model_rows = [row for row in comparable if row["model"] == name]
+ count = len(model_rows)
+ for metric, label in (
+ ("first", "pass@1"),
+ ("repaired", f"pass@≤{comparison['max_repairs']} repairs"),
+ ):
+ outcomes = [row[metric] for row in model_rows]
+ before = sum(value.startswith("pass") for value in outcomes) / count
+ after = sum(value.endswith("pass") for value in outcomes) / count
+ lines.append(
+ f"| {_cell(name)} | {label} | {count} | {before:.1%} | {after:.1%} | "
+ f"{(after - before) * 100:+.1f} pp | {outcomes.count('pass→fail')} | {outcomes.count('fail→pass')} |"
+ )
+ lines += [""]
+ lines += [
+ "## Task/trial transitions and exclusions",
+ "",
+ "Exclusions make this a partial comparison; do not treat the paired subset as the full suite.",
+ "",
+ "| Model | Task | Trial (zero-based) | pass@1 | Within repair budget | Exclusion |",
+ "|---|---|---|---|---|---|",
+ ]
+ for row in comparison["rows"]:
+ lines.append(
+ "| "
+ + " | ".join(
+ _cell(row[field]) if row[field] is not None else "—"
+ for field in ("model", "task", "trial", "first", "repaired", "reason")
+ )
+ + " |"
+ )
+ return "\n".join(lines) + "\n"
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("baseline", type=Path, help="Baseline results.json")
+ parser.add_argument("candidate", type=Path, help="Candidate results.json")
+ parser.add_argument(
+ "--out", type=Path, help="Create a new Markdown file; defaults to stdout"
+ )
+ args = parser.parse_args()
+ try:
+ runs = [
+ json.loads(path.read_text(encoding="utf-8"))
+ for path in (args.baseline, args.candidate)
+ ]
+ report = render_markdown(compare_results(*runs))
+ if args.out:
+ with args.out.open("x", encoding="utf-8") as output:
+ output.write(report)
+ else:
+ print(report, end="")
+ except (OSError, ValueError) as error:
+ parser.error(str(error))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/seatunnel-cli/benchmark/runner.py b/seatunnel-cli/benchmark/runner.py
index 8337ec0b4d..2775df8756 100644
--- a/seatunnel-cli/benchmark/runner.py
+++ b/seatunnel-cli/benchmark/runner.py
@@ -43,6 +43,7 @@ Usage:
from __future__ import annotations
import argparse
+import hashlib
import json
import os
import sys
@@ -322,6 +323,14 @@ def run_benchmark(models: list[dict], tasks: list[dict], levels: list[str],
out_dir.mkdir(parents=True, exist_ok=True)
configs_dir = out_dir / "configs"
configs_dir.mkdir(exist_ok=True)
+ # Freeze the complete task contract (prompt, assertions and execution
+ # probes) so revision reports never infer compatibility from IDs alone.
+ task_fingerprints = {
+ task["id"]: hashlib.sha256(json.dumps(
+ task, sort_keys=True, ensure_ascii=False, separators=(",", ":")
+ ).encode("utf-8")).hexdigest()
+ for task in tasks
+ }
all_results = {
"levels": levels,
@@ -357,6 +366,7 @@ def run_benchmark(models: list[dict], tasks: list[dict], levels: list[str],
"task_id": task["id"],
"tier": task["tier"],
"category": task.get("category", ""),
+ "task_sha256": task_fingerprints[task["id"]],
"trials": [],
}
for trial in range(trials):
diff --git a/seatunnel-cli/tests/test_benchmark_comparison.py b/seatunnel-cli/tests/test_benchmark_comparison.py
new file mode 100644
index 0000000000..ca5aadc3b2
--- /dev/null
+++ b/seatunnel-cli/tests/test_benchmark_comparison.py
@@ -0,0 +1,539 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Offline acceptance cases for comparing saved benchmark runs."""
+
+import copy
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).parent.parent))
+
+from benchmark.compare import compare_results, render_markdown # noqa: E402
+
+
+def trial(passed, index=0, first_pass=0):
+ attempts = []
+ for round_number in range(first_pass + 1):
+ success = passed and round_number == first_pass
+ attempts.append(
+ {
+ "round": round_number,
+ "seconds": 1.0,
+ "layers": {
+ "l1": {"passed": success},
+ "l2": None,
+ "l3": None,
+ "skipped_layers": [],
+ "all_gates_executed": True,
+ },
+ }
+ )
+ return {
+ "trial": index,
+ "attempts": attempts,
+ "first_pass_round": first_pass if passed else None,
+ }
+
+
+def results(outcomes):
+ return {
+ "cli": {"cli_version": "0.1.0", "cli_commit": "baseline"},
+ "levels": ["l1"],
+ "trials": 1,
+ "max_repairs": 3,
+ "models": [
+ {
+ "name": "model-a",
+ "config": {
+ "provider": "openai",
+ "model": "model-a",
+ "fast_model": "fast-a",
+ },
+ "tasks": [
+ {
+ "task_id": name,
+ "tier": 1,
+ "category": "smoke",
+ "task_sha256": "a" * 64,
+ "trials": [trial(passed)],
+ }
+ for name, passed in outcomes.items()
+ ],
+ }
+ ],
+ }
+
+
+def test_aggregate_gain_does_not_hide_task_regression(tmp_path):
+ from benchmark.report import _write_markdown
+
+ before = results({"lost": True, "gained-a": False, "gained-b": False})
+ after = results({"lost": False, "gained-a": True, "gained-b": True})
+ after["cli"]["cli_commit"] = "candidate"
+
+ # The existing single-run summary has aggregate rates, but no paired
+ # identities that reveal the lost task.
+ _write_markdown(before, tmp_path / "baseline.md")
+ _write_markdown(after, tmp_path / "candidate.md")
+ assert "lost" not in (tmp_path / "baseline.md").read_text()
+ assert "lost" not in (tmp_path / "candidate.md").read_text()
+
+ report = render_markdown(compare_results(before, after))
+
+ assert "33.3%" in report and "66.7%" in report and "+33.3 pp" in report
+ assert "pass→fail" in report and "fail→pass" in report
+ assert "lost" in report and "gained-a" in report and "gained-b" in report
+ assert "baseline" in report and "candidate" in report
+
+
+def test_identical_runs_are_unchanged_and_inputs_are_immutable():
+ before = results({"passed": True, "failed": False})
+ original = copy.deepcopy(before)
+ comparison = compare_results(before, before)
+ assert comparison["rows"][0]["first"] == "fail→fail"
+ assert comparison["rows"][1]["first"] == "pass→pass"
+ assert before == original
+ assert render_markdown(comparison) == render_markdown(
+ compare_results(before, before)
+ )
+
+
+@pytest.mark.parametrize(
+ "key,value",
+ [
+ ("levels", ["l1", "l2"]),
+ ("trials", 2),
+ ("max_repairs", 5),
+ ],
+)
+def test_incompatible_run_settings_are_not_scored(key, value):
+ before = results({"a": True})
+ after = copy.deepcopy(before)
+ after[key] = value
+ comparison = compare_results(before, after)
+ assert comparison["issues"]
+ assert not comparison["rows"]
+ assert "No comparable trials" in render_markdown(comparison)
+
+
+@pytest.mark.parametrize(
+ "change,reason",
+ [
+ (lambda task: task.pop("task_sha256"), "fingerprint"),
+ (lambda task: task.update(task_sha256="b" * 64), "definition"),
+ (lambda task: task.update(trials=[]), "trial IDs"),
+ (
+ lambda task: task["trials"].append(copy.deepcopy(task["trials"][0])),
+ "duplicate",
+ ),
+ ],
+)
+def test_incompatible_task_or_trial_metadata_is_excluded(change, reason):
+ before = results({"a": True})
+ after = copy.deepcopy(before)
+ change(after["models"][0]["tasks"][0])
+ rows = compare_results(before, after)["rows"]
+ assert len(rows) == 1 and reason in rows[0]["reason"]
+ assert rows[0]["first"] is None
+
+
+@pytest.mark.parametrize(
+ "layers",
+ [
+ {"l1": {"passed": True}, "l2": None},
+ {
+ "l1": {"passed": True},
+ "l2": {"passed": None},
+ "all_gates_executed": False,
+ "skipped_layers": ["l2"],
+ },
+ {
+ "l1": {"passed": True},
+ "l2": {"passed": True},
+ "all_gates_executed": False,
+ "skipped_layers": [],
+ },
+ ],
+)
+def test_absent_or_skipped_requested_gates_are_not_regressions(layers):
+ before = results({"a": True})
+ before["levels"] = ["l1", "l2"]
+ before["models"][0]["tasks"][0]["trials"][0]["attempts"][0]["layers"]["l2"] = {
+ "passed": True
+ }
+ after = copy.deepcopy(before)
+ after["models"][0]["tasks"][0]["trials"][0]["attempts"][0]["layers"] = layers
+ row = compare_results(before, after)["rows"][0]
+ assert row["first"] is None and "gate" in row["reason"]
+
+
+def test_missing_models_and_tasks_are_visible_not_failed():
+ before = results({"removed": True, "same": True})
+ after = results({"added": True, "same": True})
+ extra = copy.deepcopy(after["models"][0])
+ extra["name"] = "new-model"
+ after["models"].append(extra)
+ report = render_markdown(compare_results(before, after))
+ assert "missing baseline task" in report and "missing candidate task" in report
+ assert "missing baseline model" in report and "new-model" in report
+
+
+def test_model_config_change_is_excluded_without_printing_config():
+ before = results({"a": True})
+ after = copy.deepcopy(before)
+ after["models"][0]["config"]["base_url"] = "https://private.example/secret"
+ report = render_markdown(compare_results(before, after))
+ assert "model configuration differs" in report
+ assert "private.example" not in report and "secret" not in report
+
+
+def test_generation_failure_is_real_failure_but_empty_trial_is_incomplete():
+ before = results({"a": True, "b": True})
+ after = copy.deepcopy(before)
+ for task in after["models"][0]["tasks"]:
+ task["trials"][0].update(attempts=[], first_pass_round=None)
+ after["models"][0]["tasks"][0]["trials"][0]["generation_error"] = "provider failed"
+ rows = compare_results(before, after)["rows"]
+ assert rows[0]["first"] == "pass→fail"
+ assert rows[1]["first"] is None
+
+
+def test_repair_regression_is_separate_from_first_attempt():
+ before = results({"a": True})
+ after = copy.deepcopy(before)
+ after["models"][0]["tasks"][0]["trials"] = [trial(True, first_pass=2)]
+ row = compare_results(before, after)["rows"][0]
+ assert row["first"] == "pass→fail"
+ assert row["repaired"] == "pass→pass"
+
+
+def test_cli_is_offline_and_does_not_overwrite_inputs_or_reports(tmp_path):
+ before = tmp_path / "before.json"
+ after = tmp_path / "after.json"
+ before.write_text(json.dumps(results({"a": True})))
+ after.write_text(json.dumps(results({"a": False})))
+ original = before.read_bytes(), after.read_bytes()
+ report = tmp_path / "comparison.md"
+ command = [
+ sys.executable,
+ "-S",
+ "-m",
+ "benchmark.compare",
+ str(before),
+ str(after),
+ "--out",
+ str(report),
+ ]
+ completed = subprocess.run(command, capture_output=True, text=True, timeout=10)
+ assert completed.returncode == 0, completed.stderr
+ assert "pass→fail" in report.read_text()
+ assert (before.read_bytes(), after.read_bytes()) == original
+ existing = report.read_bytes()
+ repeated = subprocess.run(command, capture_output=True, text=True, timeout=10)
+ assert repeated.returncode == 2
+ assert report.read_bytes() == existing
+
+
+def test_runner_saved_results_compare_without_changing_legacy_reports(
+ tmp_path, monkeypatch
+):
+ from benchmark.runner import run_benchmark
+ from benchmark.report import write_reports
+
+ monkeypatch.setattr(
+ "benchmark.runner.collect_cli_fingerprint",
+ lambda: {"cli_commit": "test-revision"},
+ )
+ monkeypatch.setattr(
+ "seatunnel_cli.llm_provider.create_provider", lambda _: object()
+ )
+ monkeypatch.setattr(
+ "benchmark.runner.run_task_with_repairs", lambda *args: trial(True)
+ )
+ tasks = [
+ {
+ "id": "a",
+ "tier": 1,
+ "prompt": "Generate a batch job",
+ "expect": {"mode": "BATCH"},
+ }
+ ]
+ models = [{"name": "model-a", "provider": "openai", "model": "model-a"}]
+ original_tasks = copy.deepcopy(tasks)
+ first = run_benchmark(models, tasks, ["l1"], 3, 2, tmp_path / "before")
+ second = run_benchmark(models, tasks, ["l1"], 3, 2, tmp_path / "after")
+ before = json.loads((tmp_path / "before/results.json").read_text())
+ after = json.loads((tmp_path / "after/results.json").read_text())
+ rows = compare_results(before, after)["rows"]
+ assert len(rows) == 2 and all(row["first"] == "pass→pass" for row in rows)
+ assert tasks == original_tasks
+
+ # An additive raw-result field must not change the published reports.
+ legacy = copy.deepcopy(first)
+ for task in legacy["models"][0]["tasks"]:
+ del task["task_sha256"]
+ write_reports(first, tmp_path / "new-reports")
+ write_reports(legacy, tmp_path / "old-reports")
+ for filename in ("summary.md", "summary.csv"):
+ assert (tmp_path / "new-reports" / filename).read_bytes() == (
+ tmp_path / "old-reports" / filename
+ ).read_bytes()
+ assert "fingerprint" in compare_results(legacy, second)["rows"][0]["reason"]
+
+ tasks[0]["prompt"] += " with different semantics"
+ changed = run_benchmark(models, tasks, ["l1"], 3, 2, tmp_path / "changed")
+ assert (
+ compare_results(first, changed)["rows"][0]["reason"]
+ == "task definition differs"
+ )
+
+
+@pytest.mark.parametrize("field", ["models", "tasks"])
+def test_duplicate_identities_are_rejected(field):
+ before = results({"a": True})
+ records = before["models"] if field == "models" else before["models"][0]["tasks"]
+ records.append(copy.deepcopy(records[0]))
+ with pytest.raises(ValueError, match="duplicate"):
+ compare_results(before, results({"a": True}))
+
+
+def test_task_and_model_order_does_not_change_report():
+ before = results({"b": True, "a": False})
+ extra = copy.deepcopy(before["models"][0])
+ extra["name"] = "model-b"
+ before["models"].append(extra)
+ after = copy.deepcopy(before)
+ after["models"].reverse()
+ for model in after["models"]:
+ model["tasks"].reverse()
+ assert render_markdown(compare_results(before, after)) == render_markdown(
+ compare_results(after, before)
+ )
+
+
+@pytest.mark.parametrize(
+ "mutate,reason",
+ [
+ (
+ lambda run: run["models"][0].update(error="SECRET initialization failure"),
+ "did not run",
+ ),
+ (lambda run: run["models"][0]["config"].pop("model"), "metadata missing"),
+ (
+ lambda run: run["models"][0]["tasks"][0]["trials"][0].update(
+ first_pass_round=2
+ ),
+ "contradicts",
+ ),
+ (
+ lambda run: run["models"][0]["tasks"][0]["trials"][0].pop(
+ "first_pass_round"
+ ),
+ "missing",
+ ),
+ (
+ lambda run: run["models"][0]["tasks"][0]["trials"][0]["attempts"][0].update(
+ round=2
+ ),
+ "rounds invalid",
+ ),
+ ],
+)
+def test_incomplete_or_contradictory_evidence_is_excluded(mutate, reason):
+ before = results({"a": True})
+ after = copy.deepcopy(before)
+ mutate(after)
+ report = render_markdown(compare_results(before, after))
+ assert reason in report and "No comparable trials" in report
+ assert "SECRET" not in report
+
+
+def test_short_circuited_gate_failure_is_not_missing_coverage():
+ before = results({"a": False})
+ before["levels"] = ["l1", "l2", "l3"]
+ row = compare_results(before, before)["rows"][0]
+ assert not row["reason"] and row["first"] == "fail→fail"
+
+
+@pytest.mark.parametrize("cli", [None, [], {}, {"cli_commit": True}])
+def test_missing_revision_metadata_is_not_an_unlabeled_delta(cli):
+ before = results({"a": True})
+ after = copy.deepcopy(before)
+ after["cli"] = cli
+ report = render_markdown(compare_results(before, after))
+ assert "revision metadata missing" in report and "No comparable trials" in report
+
+
+def test_report_escapes_untrusted_labels():
+ before = results({"<script>|[label](url)\nnext": True})
+ report = render_markdown(compare_results(before, before))
+ assert "<script>" not in report
+ assert "|" in report and "<script>" in report
+ assert "\\[label\\]" in report
+
+
+@pytest.mark.parametrize(
+ "response",
+ [
+ {"type": "config", "config": ""},
+ {"type": "config"},
+ {"type": "explanation"},
+ RuntimeError("provider unavailable"),
+ ],
+)
+def test_actual_runner_generation_failures_remain_failures(
+ tmp_path, monkeypatch, response
+):
+ from unittest.mock import patch
+ from benchmark.runner import run_benchmark
+
+ monkeypatch.setattr(
+ "benchmark.runner.collect_cli_fingerprint",
+ lambda: {"cli_commit": "test-revision"},
+ )
+ monkeypatch.setattr(
+ "seatunnel_cli.llm_provider.create_provider", lambda _: object()
+ )
+ tasks = [{"id": "a", "tier": 1, "prompt": "Generate a batch job"}]
+ with patch("seatunnel_cli.agents.Orchestrator") as orchestrator:
+ if isinstance(response, Exception):
+ orchestrator.return_value.process_user_input.side_effect = response
+ else:
+ orchestrator.return_value.process_user_input.return_value = response
+ run_benchmark(
+ [{"name": "a", "provider": "openai", "model": "a"}],
+ tasks,
+ ["l1"],
+ 3,
+ 1,
+ tmp_path,
+ )
+ saved = json.loads((tmp_path / "results.json").read_text())
+ row = compare_results(saved, saved)["rows"][0]
+ assert row["first"] == "fail→fail" and not row["reason"]
+
+
+def test_actual_runner_outer_harness_failure_remains_failure(tmp_path, monkeypatch):
+ from benchmark.runner import run_benchmark
+
+ def crash(*args):
+ raise RuntimeError("scoring crashed")
+
+ monkeypatch.setattr(
+ "benchmark.runner.collect_cli_fingerprint",
+ lambda: {"cli_commit": "test-revision"},
+ )
+ monkeypatch.setattr(
+ "seatunnel_cli.llm_provider.create_provider", lambda _: object()
+ )
+ monkeypatch.setattr("benchmark.runner.run_task_with_repairs", crash)
+ run_benchmark(
+ [{"name": "a", "provider": "openai", "model": "a"}],
+ [{"id": "a", "tier": 1}],
+ ["l1"],
+ 3,
+ 1,
+ tmp_path,
+ )
+ saved = json.loads((tmp_path / "results.json").read_text())
+ assert saved["models"][0]["tasks"][0]["trials"][0]["attempts"] == []
+ row = compare_results(saved, saved)["rows"][0]
+ assert row["first"] == "fail→fail" and not row["reason"]
+
+
+def test_declared_trial_count_does_not_allocate_missing_records():
+ before = results({"a": True})
+ before["trials"] = 10**12
+ row = compare_results(before, before)["rows"][0]
+ assert "trial IDs" in row["reason"] and row["first"] is None
+
+
+def test_actual_static_gate_results_can_be_compared(tmp_path, monkeypatch):
+ from unittest.mock import patch
+ from benchmark.runner import run_benchmark
+
+ monkeypatch.setattr(
+ "benchmark.runner.collect_cli_fingerprint",
+ lambda: {"cli_commit": "test-revision"},
+ )
+ monkeypatch.setattr(
+ "seatunnel_cli.llm_provider.create_provider", lambda _: object()
+ )
+ config = """
+ env { parallelism = 1
+ job.mode = "BATCH" }
+ source { FakeSource { row.num = 5
+ schema { fields { id = "bigint" } }
+ plugin_output = "f" } }
+ sink { Console { plugin_input = "f" } }
+ """
+ tasks = [
+ {
+ "id": "a",
+ "tier": 1,
+ "prompt": "Generate a batch job",
+ "expect": {
+ "source": ["FakeSource"],
+ "sink": ["Console"],
+ "job_mode": "BATCH",
+ },
+ }
+ ]
+ with patch("seatunnel_cli.agents.Orchestrator") as orchestrator:
+ orchestrator.return_value.process_user_input.return_value = {
+ "type": "config",
+ "config": config,
+ }
+ run_benchmark(
+ [{"name": "a", "provider": "openai", "model": "a"}],
+ tasks,
+ ["l1"],
+ 0,
+ 1,
+ tmp_path,
+ )
+ saved = json.loads((tmp_path / "results.json").read_text())
+ row = compare_results(saved, saved)["rows"][0]
+ assert row["first"] == "pass→pass" and not row["reason"]
+
+
+@pytest.mark.parametrize("passed", [True, False])
+@pytest.mark.parametrize("flag", ["all_passed", "full_gate_passed"])
+def test_contradictory_aggregate_gate_flags_are_excluded(passed, flag):
+ before = results({"a": passed})
+ after = copy.deepcopy(before)
+ after["models"][0]["tasks"][0]["trials"][0]["attempts"][0]["layers"][
+ flag
+ ] = not passed
+ row = compare_results(before, after)["rows"][0]
+ assert row["first"] is None and f"{flag} contradicts" in row["reason"]
+
+
+@pytest.mark.parametrize(
+ "flag", ["all_passed", "full_gate_passed", "all_gates_executed"]
+)
+def test_gate_flags_require_boolean_values_when_present(flag):
+ before = results({"a": True})
+ after = copy.deepcopy(before)
+ after["models"][0]["tasks"][0]["trials"][0]["attempts"][0]["layers"][flag] = "false"
+ row = compare_results(before, after)["rows"][0]
+ assert row["first"] is None and row["reason"]