From 556bb12937653d74b88e338a985eb44339fab546 Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 20 Sep 2026 17:23:54 +0800 Subject: [PATCH 01/29] Add Moli version resource comparison chart --- harness/web_fetch/report_i18n.py | 3 +- research/report-changes.json | 56 ++++++++ scripts/plot_moli_version_resources.py | 154 ++++++++++++++++++++++ tests/test_moli_version_resource_chart.py | 88 +++++++++++++ tests/test_report_changes.py | 4 +- 5 files changed, 303 insertions(+), 2 deletions(-) create mode 100644 scripts/plot_moli_version_resources.py create mode 100644 tests/test_moli_version_resource_chart.py diff --git a/harness/web_fetch/report_i18n.py b/harness/web_fetch/report_i18n.py index 13b34289e..256f421fb 100644 --- a/harness/web_fetch/report_i18n.py +++ b/harness/web_fetch/report_i18n.py @@ -2789,7 +2789,8 @@ def _register_release_translations() -> None: for release in history['releases']: if any(kind in release.get('comparison_kinds', []) for kind in ( 'webmainbench_frozen_html_to_markdown', 'public_benchmark_research', - 'wcxb_frozen_html_to_markdown')): + 'wcxb_frozen_html_to_markdown', 'moli_historical_failure_retest', + 'moli_process_tree_resource_profile')): continue english = release.get('i18n', {}).get('en', {}) if (not english.get('title') or not english.get('summary') diff --git a/research/report-changes.json b/research/report-changes.json index af91b8468..49c6d598a 100644 --- a/research/report-changes.json +++ b/research/report-changes.json @@ -1252,6 +1252,62 @@ } ], "releases": [ + { + "id": "2026-09-20-moli-version-layout-resource-summary", + "comparison_kinds": [ + "moli_historical_failure_retest", + "moli_process_tree_resource_profile" + ], + "date": "2026-09-20", + "title": "增加 Moli 1.1.4 / 1.1.8 成功率与资源汇总", + "summary": "首页新增三种配置的 372 题成功率、峰值 PSS 和 CPU 时间汇总。成功率与资源实验分别标明分母;表格和图中都给出相对 1.1.4 关闭布局的带正负号变化,代码生成的双面板图共用成功率纵轴,并允许省略 CPU 面板。", + "i18n": { + "en": { + "title": "Add Moli 1.1.4 / 1.1.8 success and resource summary", + "summary": "The report home page now compares success on 372 cases, peak PSS, and CPU time for three configurations. Compatibility and resource experiments state separate populations; the table and chart show signed changes relative to Moli 1.1.4 layout off. The code-generated dual-panel chart shares one success-rate axis and can omit the CPU panel.", + "changes": [ + [ + "Version comparison", + "The previous report directly covered only Moli 1.1.8 with layout off and on across all 372 cases.", + "Layout-off Moli 1.1.8 passes one case. That sole candidate is rerun three times with layout-off Moli 1.1.4 and fails all three; the other 371 retain the shared-failure relation, and the home page compares all three configurations.", + "The success rate describes only the 372 historical Moli 0.1.1 failures and is not extrapolated to the full 1,928-case suite." + ], + [ + "Resource comparison", + "The compatibility and resource experiments use different task counts and sampling rules, so a single execution cannot be treated as one shared denominator.", + "The report separately presents a 557-task × 5-call resource experiment and compares median peak PSS and mean CPU time on the 1,045 task-attempt population frozen before execution.", + "Resource values compare versions and layout settings in the same environment; CPU sampling can miss short-lived child processes." + ], + [ + "Summary chart", + "A single horizontal axis cannot express MiB and milliseconds.", + "Two horizontal panels share the 372-case success-rate axis. Each point shows the absolute value and percentage change from Moli 1.1.4, and the plotting script supports PSS, CPU, or both.", + "The chart is generated from frozen data by code, with separate Chinese and English output; it is not a generated image." + ] + ] + } + }, + "changes": [ + [ + "版本对照", + "原报告只完整展示 Moli 1.1.8 关闭与开启布局的 372 题结果。", + "1.1.8 关闭布局只通过 1 题;对该唯一候选题用 Moli 1.1.4 关闭布局复测三次,均失败,其余 371 题沿用共同失败关系,并在首页统一比较三个方法。", + "通过率仍只描述 Moli 0.1.1 的 372 个历史失败用例,不外推为 1,928 题全量成绩。" + ], + [ + "资源对照", + "成功率实验和资源实验的任务数与采样规则不同,无法把单次执行直接当成同一分母。", + "独立展示 557 题 × 5 次资源实验,并用运行前冻结的 1,045 个任务-执行样本比较峰值 PSS 中位数和平均 CPU 时间。", + "资源值用于同环境版本与布局对照;CPU 采样存在短生命周期子进程遗漏风险。" + ], + [ + "汇总图", + "单一横轴不能同时表达 MiB 与毫秒。", + "使用两个水平面板,共用 372 题成功率纵轴;数据点同时标出绝对值和相对 1.1.4 的变化百分比,绘图脚本支持 PSS、CPU 或两者。", + "图由冻结数据和代码生成,中文与英文分别输出,不使用生成式图片。" + ] + ] + }, { "id": "2026-09-18-wcxb-frozen-html-reader-clarification", "comparison_kinds": ["wcxb_frozen_html_to_markdown"], diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py new file mode 100644 index 000000000..70ee3c330 --- /dev/null +++ b/scripts/plot_moli_version_resources.py @@ -0,0 +1,154 @@ +"""Render the three-configuration compatibility/resource summary as SVG. + +The two resource axes intentionally use separate panels because MiB and CPU +milliseconds are different units. Both panels share the 372-case success-rate +axis. CPU can be omitted with ``--metrics pss``. +""" +from __future__ import annotations + +import argparse +import html +import json +from pathlib import Path + + +COLORS = { + "114_off": "#239b68", + "118_off": "#d1841e", + "118_on": "#7652c7", +} + + +def _scale(value: float, lower: float, upper: float, start: float, end: float) -> float: + if upper == lower: + return (start + end) / 2 + return start + (value - lower) / (upper - lower) * (end - start) + + +def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "cpu"), language: str = "zh") -> None: + if not metrics or any(metric not in {"pss", "cpu"} for metric in metrics): + raise ValueError("metrics must contain pss and/or cpu") + if language not in {"zh", "en"}: + raise ValueError("language must be zh or en") + rows = data["configurations"] + resource = data["resource_population"] + text = { + "zh": { + "title": "372 题成功率与资源消耗", + "subtitle": f"资源实验:557 题 × 5 次;图中使用预先冻结的 {resource['chart_calls']:,} 次 / {resource['chart_tasks']} 题样本;越靠左资源消耗越低", + "y": "372 题通过率(每题 3 次全部通过)", + "pss": "峰值进程树 PSS 中位数(MiB)", + "cpu": "单次执行平均 CPU 时间(ms)", + "off": "关闭", + "on": "开启", + }, + "en": { + "title": "Success on 372 cases vs. resource use", + "subtitle": f"Resource experiment: 557 tasks × 5; plotted population: {resource['chart_calls']:,} pre-frozen calls / {resource['chart_tasks']} tasks; farther left is lower", + "y": "Success rate on 372 cases (all 3 attempts pass)", + "pss": "Median peak process-tree PSS (MiB)", + "cpu": "Mean CPU time per execution (ms)", + "off": "off", + "on": "on", + }, + }[language] + width = 1420 if len(metrics) == 2 else 820 + height = 780 + left, right, top, bottom = 105, 55, 145, 150 + gap = 90 + panel_width = (width - left - right - gap * (len(metrics) - 1)) / len(metrics) + chart_bottom = height - bottom + chart_height = chart_bottom - top + described_metrics = { + "zh": "、".join(text[metric] for metric in metrics), + "en": " and ".join(text[metric] for metric in metrics), + }[language] + description = ( + f"三种配置在 372 题通过率与{described_metrics}上的对比。" + if language == "zh" + else f"Three configurations compared by success rate on 372 cases and {described_metrics}." + ) + parts = [ + f'', + f'{html.escape(text["title"])}', + f'{html.escape(description)}', + '', + '', + f'{html.escape(text["title"])}', + f'{html.escape(text["subtitle"])}', + ] + for tick in range(0, 81, 20): + y = _scale(tick, 0, 80, chart_bottom, top) + parts.append(f'') + parts.append(f'{tick}%') + parts.append(f'{html.escape(text["y"])}') + specs = { + "pss": (text["pss"], "pss_mib", "pss_change_pct", "MiB"), + "cpu": (text["cpu"], "cpu_ms", "cpu_change_pct", "ms"), + } + for panel, metric in enumerate(metrics): + title, key, change_key, unit = specs[metric] + x0 = left + panel * (panel_width + gap) + x1 = x0 + panel_width + values = [float(row[key]) for row in rows] + spread = max(values) - min(values) + center = sum(values) / len(values) + padding = max(spread * 0.22, abs(center) * 0.03, 1.0) + low = max(0.0, min(values) - padding) + high = max(values) + padding + parts.append(f'') + parts.append(f'{html.escape(title)}') + for i in range(5): + value = low + (high - low) * i / 4 + x = _scale(value, low, high, x0, x1) + parts.append(f'') + parts.append(f'{value:.1f}') + label_offsets = { + "114_off": (14, -44, "start"), + "118_off": (-14, -14, "end"), + "118_on": (14, -18, "start"), + } + for row in rows: + x = _scale(float(row[key]), low, high, x0, x1) + y = _scale(float(row["success_rate_pct"]), 0, 80, chart_bottom, top) + color = COLORS[row["id"]] + parts.append(f'') + dx, dy, anchor = label_offsets[row["id"]] + short_label = row["short_label"] if language == "zh" else row["short_label_en"] + change = float(row[change_key]) + label = f'{short_label} · {row[key]:.2f} {unit} ({change:+.2f}%)' + parts.append(f'{html.escape(label)}') + method_note = ( + "1.1.4:仅复测 1.1.8 关闭布局唯一通过的候选题;3 次均失败,其余 371 题沿用共同失败关系。" + if language == "zh" + else "1.1.4: the sole case passed by layout-off 1.1.8 was retested 3 times and failed; the other 371 retain the shared-failure relation." + ) + parts.append(f'{html.escape(method_note)}') + legend_y = height - 42 + cursor = 55 + for row in rows: + color = COLORS[row["id"]] + row_label = row["label"] if language == "zh" else row["label_en"] + legend_text = f'{row_label}: {row["passed_cases"]}/372 ({row["success_rate_pct"]:.1f}%)' + parts.append(f'') + parts.append(f'{html.escape(legend_text)}') + cursor += 420 + parts.append('') + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text("\n".join(parts) + "\n") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--input", required=True, type=Path) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument("--metrics", default="pss,cpu") + parser.add_argument("--language", choices=("zh", "en"), default="zh") + args = parser.parse_args() + payload = json.loads(args.input.read_text()) + metrics = tuple(item.strip() for item in args.metrics.split(",") if item.strip()) + render_chart(payload, args.output, metrics, args.language) + + +if __name__ == "__main__": + main() diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py new file mode 100644 index 000000000..23fef2f8a --- /dev/null +++ b/tests/test_moli_version_resource_chart.py @@ -0,0 +1,88 @@ +import importlib.util +from pathlib import Path +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "scripts" / "plot_moli_version_resources.py" +SPEC = importlib.util.spec_from_file_location("plot_moli_version_resources", SCRIPT) +MODULE = importlib.util.module_from_spec(SPEC) +assert SPEC.loader is not None +SPEC.loader.exec_module(MODULE) + + +class MoliVersionResourceChartTests(unittest.TestCase): + def setUp(self): + self.data = { + "resource_population": {"chart_calls": 1045, "chart_tasks": 209}, + "configurations": [ + { + "id": "114_off", + "label": "Moli 1.1.4 · 关闭 layout", + "label_en": "Moli 1.1.4 · layout off", + "short_label": "1.1.4 关闭", + "short_label_en": "1.1.4 off", + "passed_cases": 0, + "success_rate_pct": 0, + "pss_mib": 77.216796875, + "pss_change_pct": 0, + "cpu_ms": 21.406698564593302, + "cpu_change_pct": 0, + }, + { + "id": "118_off", + "label": "Moli 1.1.8 · 关闭 layout", + "label_en": "Moli 1.1.8 · layout off", + "short_label": "1.1.8 关闭", + "short_label_en": "1.1.8 off", + "passed_cases": 1, + "success_rate_pct": 0.2688172043010753, + "pss_mib": 77.1015625, + "pss_change_pct": -0.1492348551916045, + "cpu_ms": 21.320574162679424, + "cpu_change_pct": -0.4023245417970611, + }, + { + "id": "118_on", + "label": "Moli 1.1.8 · 开启 layout", + "label_en": "Moli 1.1.8 · layout on", + "short_label": "1.1.8 开启", + "short_label_en": "1.1.8 on", + "passed_cases": 255, + "success_rate_pct": 68.54838709677419, + "pss_mib": 80.537109375, + "pss_change_pct": 4.299987352978363, + "cpu_ms": 21.6555023923445, + "cpu_change_pct": 1.1622708985248087, + }, + ], + } + + def render(self, metrics=("pss", "cpu"), language="zh"): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "chart.svg" + MODULE.render_chart(self.data, output, metrics, language) + return output.read_text() + + def test_dual_panel_labels_absolute_values_and_baseline_changes(self): + svg = self.render() + for expected in ( + "77.22 MiB (+0.00%)", + "77.10 MiB (-0.15%)", + "80.54 MiB (+4.30%)", + "21.41 ms (+0.00%)", + "21.32 ms (-0.40%)", + "21.66 ms (+1.16%)", + ): + self.assertIn(expected, svg) + + def test_pss_only_omits_cpu_content(self): + svg = self.render(("pss",), "en") + self.assertIn("Median peak process-tree PSS (MiB)", svg) + self.assertNotIn("CPU", svg) + self.assertNotIn("21.41 ms", svg) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_report_changes.py b/tests/test_report_changes.py index 77f9818e2..96deccb02 100644 --- a/tests/test_report_changes.py +++ b/tests/test_report_changes.py @@ -33,7 +33,9 @@ def test_web_fetch_release_translations_come_from_history(self): releases = [row for row in data['releases'] if 'webmainbench_frozen_html_to_markdown' not in row.get('comparison_kinds', []) and 'public_benchmark_research' not in row.get('comparison_kinds', []) - and 'wcxb_frozen_html_to_markdown' not in row.get('comparison_kinds', [])] + and 'wcxb_frozen_html_to_markdown' not in row.get('comparison_kinds', []) + and 'moli_historical_failure_retest' not in row.get('comparison_kinds', []) + and 'moli_process_tree_resource_profile' not in row.get('comparison_kinds', [])] self.assertEqual(len(releases), 20) for row in releases: english = row['i18n']['en'] From c1a8fcbcf7da1db4e75f3b0bfca3dcffbc660111 Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 20 Sep 2026 17:48:46 +0800 Subject: [PATCH 02/29] Harden Moli resource chart rendering --- scripts/plot_moli_version_resources.py | 26 ++++++++++++++--------- tests/test_moli_version_resource_chart.py | 25 +++++++++++++++++++++- 2 files changed, 40 insertions(+), 11 deletions(-) diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py index 70ee3c330..9d136b9ac 100644 --- a/scripts/plot_moli_version_resources.py +++ b/scripts/plot_moli_version_resources.py @@ -9,6 +9,7 @@ import argparse import html import json +import math from pathlib import Path @@ -31,6 +32,9 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c if language not in {"zh", "en"}: raise ValueError("language must be zh or en") rows = data["configurations"] + unknown_ids = sorted({str(row.get("id")) for row in rows} - COLORS.keys()) + if unknown_ids: + raise ValueError(f"unknown configuration id(s): {', '.join(unknown_ids)}") resource = data["resource_population"] text = { "zh": { @@ -58,7 +62,8 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c gap = 90 panel_width = (width - left - right - gap * (len(metrics) - 1)) / len(metrics) chart_bottom = height - bottom - chart_height = chart_bottom - top + max_success_rate = max(float(row["success_rate_pct"]) for row in rows) + y_max = max(20, math.ceil(max_success_rate / 20) * 20) described_metrics = { "zh": "、".join(text[metric] for metric in metrics), "en": " and ".join(text[metric] for metric in metrics), @@ -77,8 +82,8 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c f'{html.escape(text["title"])}', f'{html.escape(text["subtitle"])}', ] - for tick in range(0, 81, 20): - y = _scale(tick, 0, 80, chart_bottom, top) + for tick in range(0, y_max + 1, 20): + y = _scale(tick, 0, y_max, chart_bottom, top) parts.append(f'') parts.append(f'{tick}%') parts.append(f'{html.escape(text["y"])}') @@ -86,6 +91,11 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c "pss": (text["pss"], "pss_mib", "pss_change_pct", "MiB"), "cpu": (text["cpu"], "cpu_ms", "cpu_change_pct", "ms"), } + label_offsets = { + "114_off": (14, -44, "start"), + "118_off": (-14, -14, "end"), + "118_on": (14, -18, "start"), + } for panel, metric in enumerate(metrics): title, key, change_key, unit = specs[metric] x0 = left + panel * (panel_width + gap) @@ -103,14 +113,9 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c x = _scale(value, low, high, x0, x1) parts.append(f'') parts.append(f'{value:.1f}') - label_offsets = { - "114_off": (14, -44, "start"), - "118_off": (-14, -14, "end"), - "118_on": (14, -18, "start"), - } for row in rows: x = _scale(float(row[key]), low, high, x0, x1) - y = _scale(float(row["success_rate_pct"]), 0, 80, chart_bottom, top) + y = _scale(float(row["success_rate_pct"]), 0, y_max, chart_bottom, top) color = COLORS[row["id"]] parts.append(f'') dx, dy, anchor = label_offsets[row["id"]] @@ -126,13 +131,14 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c parts.append(f'{html.escape(method_note)}') legend_y = height - 42 cursor = 55 + legend_step = min(420, (width - 110) / len(rows)) for row in rows: color = COLORS[row["id"]] row_label = row["label"] if language == "zh" else row["label_en"] legend_text = f'{row_label}: {row["passed_cases"]}/372 ({row["success_rate_pct"]:.1f}%)' parts.append(f'') parts.append(f'{html.escape(legend_text)}') - cursor += 420 + cursor += legend_step parts.append('') output.parent.mkdir(parents=True, exist_ok=True) output.write_text("\n".join(parts) + "\n") diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index 23fef2f8a..cf67e1d6c 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -1,7 +1,8 @@ import importlib.util -from pathlib import Path +import re import tempfile import unittest +from pathlib import Path ROOT = Path(__file__).resolve().parents[1] @@ -80,9 +81,31 @@ def test_dual_panel_labels_absolute_values_and_baseline_changes(self): def test_pss_only_omits_cpu_content(self): svg = self.render(("pss",), "en") self.assertIn("Median peak process-tree PSS (MiB)", svg) + for label in ("Moli 1.1.4 · layout off", "Moli 1.1.8 · layout off", "Moli 1.1.8 · layout on"): + self.assertIn(label, svg) self.assertNotIn("CPU", svg) self.assertNotIn("21.41 ms", svg) + def test_english_dual_panel_contains_both_resources_and_changes(self): + svg = self.render(language="en") + self.assertIn("Median peak process-tree PSS (MiB)", svg) + self.assertIn("Mean CPU time per execution (ms)", svg) + self.assertIn("80.54 MiB (+4.30%)", svg) + self.assertIn("21.66 ms (+1.16%)", svg) + + def test_y_axis_expands_to_include_rates_above_eighty_percent(self): + self.data["configurations"][2]["success_rate_pct"] = 95 + svg = self.render() + self.assertIn(">100%", svg) + point = re.search(r' Date: Sun, 20 Sep 2026 17:56:10 +0800 Subject: [PATCH 03/29] Validate Moli chart resource population --- scripts/plot_moli_version_resources.py | 10 +++++++++- tests/test_moli_version_resource_chart.py | 5 +++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py index 9d136b9ac..13ea622bd 100644 --- a/scripts/plot_moli_version_resources.py +++ b/scripts/plot_moli_version_resources.py @@ -35,7 +35,15 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c unknown_ids = sorted({str(row.get("id")) for row in rows} - COLORS.keys()) if unknown_ids: raise ValueError(f"unknown configuration id(s): {', '.join(unknown_ids)}") - resource = data["resource_population"] + resource = data.get("resource_population") + required_resource_fields = {"chart_calls", "chart_tasks"} + if not isinstance(resource, dict) or not required_resource_fields.issubset(resource): + missing = ( + sorted(required_resource_fields - set(resource or {})) + if isinstance(resource, dict) + else sorted(required_resource_fields) + ) + raise ValueError(f"resource_population missing required field(s): {', '.join(missing)}") text = { "zh": { "title": "372 题成功率与资源消耗", diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index cf67e1d6c..a1f7ee1a1 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -106,6 +106,11 @@ def test_unknown_configuration_id_has_clear_error(self): with self.assertRaisesRegex(ValueError, "unknown configuration id.*future_config"): self.render() + def test_missing_resource_population_field_has_clear_error(self): + del self.data["resource_population"]["chart_tasks"] + with self.assertRaisesRegex(ValueError, "resource_population missing required field.*chart_tasks"): + self.render() + if __name__ == "__main__": unittest.main() From bab005021285aab1f1855c8a16e370e69d810f43 Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 20 Sep 2026 18:01:56 +0800 Subject: [PATCH 04/29] Fit single-metric Moli chart legends --- scripts/plot_moli_version_resources.py | 5 ++++- tests/test_moli_version_resource_chart.py | 11 ++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py index 13ea622bd..379159e06 100644 --- a/scripts/plot_moli_version_resources.py +++ b/scripts/plot_moli_version_resources.py @@ -142,7 +142,10 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c legend_step = min(420, (width - 110) / len(rows)) for row in rows: color = COLORS[row["id"]] - row_label = row["label"] if language == "zh" else row["label_en"] + label_key = "label" if len(metrics) == 2 else "short_label" + if language == "en": + label_key += "_en" + row_label = row[label_key] legend_text = f'{row_label}: {row["passed_cases"]}/372 ({row["success_rate_pct"]:.1f}%)' parts.append(f'') parts.append(f'{html.escape(legend_text)}') diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index a1f7ee1a1..bd2893b77 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -81,11 +81,20 @@ def test_dual_panel_labels_absolute_values_and_baseline_changes(self): def test_pss_only_omits_cpu_content(self): svg = self.render(("pss",), "en") self.assertIn("Median peak process-tree PSS (MiB)", svg) - for label in ("Moli 1.1.4 · layout off", "Moli 1.1.8 · layout off", "Moli 1.1.8 · layout on"): + for label in ("1.1.4 off", "1.1.8 off", "1.1.8 on"): self.assertIn(label, svg) + self.assertNotIn("Moli 1.1.8 · layout on:", svg) self.assertNotIn("CPU", svg) self.assertNotIn("21.41 ms", svg) + def test_cpu_only_omits_pss_content_and_keeps_all_legend_entries(self): + svg = self.render(("cpu",), "en") + self.assertIn("Mean CPU time per execution (ms)", svg) + for label in ("1.1.4 off", "1.1.8 off", "1.1.8 on"): + self.assertIn(label, svg) + self.assertNotIn("PSS", svg) + self.assertNotIn("77.22 MiB", svg) + def test_english_dual_panel_contains_both_resources_and_changes(self): svg = self.render(language="en") self.assertIn("Median peak process-tree PSS (MiB)", svg) From a578eb061807cd32cd454b72c4e625b24071c584 Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 20 Sep 2026 18:07:31 +0800 Subject: [PATCH 05/29] Reserve space for single-metric legends --- scripts/plot_moli_version_resources.py | 8 +++++++- tests/test_moli_version_resource_chart.py | 11 +++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py index 379159e06..bcb038145 100644 --- a/scripts/plot_moli_version_resources.py +++ b/scripts/plot_moli_version_resources.py @@ -32,6 +32,8 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c if language not in {"zh", "en"}: raise ValueError("language must be zh or en") rows = data["configurations"] + if not rows: + raise ValueError("configurations must contain at least one row") unknown_ids = sorted({str(row.get("id")) for row in rows} - COLORS.keys()) if unknown_ids: raise ValueError(f"unknown configuration id(s): {', '.join(unknown_ids)}") @@ -139,7 +141,11 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c parts.append(f'{html.escape(method_note)}') legend_y = height - 42 cursor = 55 - legend_step = min(420, (width - 110) / len(rows)) + if len(metrics) == 1: + reserved_label_width = 220 + legend_step = (width - 110 - reserved_label_width) / max(1, len(rows) - 1) + else: + legend_step = 420 for row in rows: color = COLORS[row["id"]] label_key = "label" if len(metrics) == 2 else "short_label" diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index bd2893b77..0b4191911 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -95,6 +95,12 @@ def test_cpu_only_omits_pss_content_and_keeps_all_legend_entries(self): self.assertNotIn("PSS", svg) self.assertNotIn("77.22 MiB", svg) + def test_chinese_single_metric_keeps_all_short_legend_entries(self): + svg = self.render(("pss",), "zh") + for label in ("1.1.4 关闭", "1.1.8 关闭", "1.1.8 开启"): + self.assertIn(label, svg) + self.assertNotIn("Moli 1.1.8 · 开启 layout:", svg) + def test_english_dual_panel_contains_both_resources_and_changes(self): svg = self.render(language="en") self.assertIn("Median peak process-tree PSS (MiB)", svg) @@ -120,6 +126,11 @@ def test_missing_resource_population_field_has_clear_error(self): with self.assertRaisesRegex(ValueError, "resource_population missing required field.*chart_tasks"): self.render() + def test_empty_configuration_list_has_clear_error(self): + self.data["configurations"] = [] + with self.assertRaisesRegex(ValueError, "configurations must contain at least one row"): + self.render() + if __name__ == "__main__": unittest.main() From 0a3581bf75191403b952d63e33dbddf3b0308885 Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 20 Sep 2026 18:13:52 +0800 Subject: [PATCH 06/29] Validate Moli chart configuration schema --- scripts/plot_moli_version_resources.py | 22 ++++++++++++++++++++-- tests/test_moli_version_resource_chart.py | 15 +++++++++++---- 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py index bcb038145..26d7227ed 100644 --- a/scripts/plot_moli_version_resources.py +++ b/scripts/plot_moli_version_resources.py @@ -31,9 +31,27 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c raise ValueError("metrics must contain pss and/or cpu") if language not in {"zh", "en"}: raise ValueError("language must be zh or en") - rows = data["configurations"] - if not rows: + rows = data.get("configurations") + if not isinstance(rows, list) or not rows: raise ValueError("configurations must contain at least one row") + required_row_fields = {"id", "passed_cases", "success_rate_pct"} + required_row_fields.update( + {"label", "short_label"} if language == "zh" else {"label_en", "short_label_en"} + ) + metric_fields = { + "pss": {"pss_mib", "pss_change_pct"}, + "cpu": {"cpu_ms", "cpu_change_pct"}, + } + for metric in metrics: + required_row_fields.update(metric_fields[metric]) + for index, row in enumerate(rows): + missing = ( + sorted(required_row_fields - set(row)) + if isinstance(row, dict) + else sorted(required_row_fields) + ) + if missing: + raise ValueError(f"configuration row {index} missing required field(s): {', '.join(missing)}") unknown_ids = sorted({str(row.get("id")) for row in rows} - COLORS.keys()) if unknown_ids: raise ValueError(f"unknown configuration id(s): {', '.join(unknown_ids)}") diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index 0b4191911..970140f7e 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -96,10 +96,12 @@ def test_cpu_only_omits_pss_content_and_keeps_all_legend_entries(self): self.assertNotIn("77.22 MiB", svg) def test_chinese_single_metric_keeps_all_short_legend_entries(self): - svg = self.render(("pss",), "zh") - for label in ("1.1.4 关闭", "1.1.8 关闭", "1.1.8 开启"): - self.assertIn(label, svg) - self.assertNotIn("Moli 1.1.8 · 开启 layout:", svg) + for metric in ("pss", "cpu"): + with self.subTest(metric=metric): + svg = self.render((metric,), "zh") + for label in ("1.1.4 关闭", "1.1.8 关闭", "1.1.8 开启"): + self.assertIn(label, svg) + self.assertNotIn("Moli 1.1.8 · 开启 layout:", svg) def test_english_dual_panel_contains_both_resources_and_changes(self): svg = self.render(language="en") @@ -131,6 +133,11 @@ def test_empty_configuration_list_has_clear_error(self): with self.assertRaisesRegex(ValueError, "configurations must contain at least one row"): self.render() + def test_missing_configuration_field_has_clear_error(self): + del self.data["configurations"][0]["pss_change_pct"] + with self.assertRaisesRegex(ValueError, "configuration row 0 missing required field.*pss_change_pct"): + self.render() + if __name__ == "__main__": unittest.main() From 16a94199152d16422db4577e5b71989db9d5d372 Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 20 Sep 2026 21:05:19 +0800 Subject: [PATCH 07/29] Generalize Moli comparison chart --- scripts/plot_moli_version_resources.py | 97 +++++++++++------------ tests/test_moli_version_resource_chart.py | 29 ++++++- 2 files changed, 72 insertions(+), 54 deletions(-) diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py index 26d7227ed..1b1973960 100644 --- a/scripts/plot_moli_version_resources.py +++ b/scripts/plot_moli_version_resources.py @@ -1,4 +1,4 @@ -"""Render the three-configuration compatibility/resource summary as SVG. +"""Render a compatibility/resource summary for any number of configurations. The two resource axes intentionally use separate panels because MiB and CPU milliseconds are different units. Both panels share the 372-case success-rate @@ -13,11 +13,7 @@ from pathlib import Path -COLORS = { - "114_off": "#239b68", - "118_off": "#d1841e", - "118_on": "#7652c7", -} +COLORS = ("#239b68", "#d1841e", "#7652c7", "#2775c9", "#c54f79", "#4c8793") def _scale(value: float, lower: float, upper: float, start: float, end: float) -> float: @@ -34,7 +30,7 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c rows = data.get("configurations") if not isinstance(rows, list) or not rows: raise ValueError("configurations must contain at least one row") - required_row_fields = {"id", "passed_cases", "success_rate_pct"} + required_row_fields = {"id", "passed_cases", "total_cases", "success_rate_pct"} required_row_fields.update( {"label", "short_label"} if language == "zh" else {"label_en", "short_label_en"} ) @@ -52,9 +48,10 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c ) if missing: raise ValueError(f"configuration row {index} missing required field(s): {', '.join(missing)}") - unknown_ids = sorted({str(row.get("id")) for row in rows} - COLORS.keys()) - if unknown_ids: - raise ValueError(f"unknown configuration id(s): {', '.join(unknown_ids)}") + totals = {int(row["total_cases"]) for row in rows} + if len(totals) != 1 or next(iter(totals)) <= 0: + raise ValueError("all configurations must use the same positive total_cases") + total_cases = next(iter(totals)) resource = data.get("resource_population") required_resource_fields = {"chart_calls", "chart_tasks"} if not isinstance(resource, dict) or not required_resource_fields.issubset(resource): @@ -66,18 +63,18 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c raise ValueError(f"resource_population missing required field(s): {', '.join(missing)}") text = { "zh": { - "title": "372 题成功率与资源消耗", + "title": f"{total_cases} 题成功率与资源消耗", "subtitle": f"资源实验:557 题 × 5 次;图中使用预先冻结的 {resource['chart_calls']:,} 次 / {resource['chart_tasks']} 题样本;越靠左资源消耗越低", - "y": "372 题通过率(每题 3 次全部通过)", + "y": f"{total_cases} 题通过率(每题 3 次全部通过)", "pss": "峰值进程树 PSS 中位数(MiB)", "cpu": "单次执行平均 CPU 时间(ms)", "off": "关闭", "on": "开启", }, "en": { - "title": "Success on 372 cases vs. resource use", + "title": f"Success on {total_cases} cases vs. resource use", "subtitle": f"Resource experiment: 557 tasks × 5; plotted population: {resource['chart_calls']:,} pre-frozen calls / {resource['chart_tasks']} tasks; farther left is lower", - "y": "Success rate on 372 cases (all 3 attempts pass)", + "y": f"Success rate on {total_cases} cases (all 3 attempts pass)", "pss": "Median peak process-tree PSS (MiB)", "cpu": "Mean CPU time per execution (ms)", "off": "off", @@ -85,8 +82,8 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c }, }[language] width = 1420 if len(metrics) == 2 else 820 - height = 780 - left, right, top, bottom = 105, 55, 145, 150 + height = 700 + 30 * len(rows) + left, right, top, bottom = 105, 55, 145, 115 + 30 * len(rows) gap = 90 panel_width = (width - left - right - gap * (len(metrics) - 1)) / len(metrics) chart_bottom = height - bottom @@ -97,9 +94,9 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c "en": " and ".join(text[metric] for metric in metrics), }[language] description = ( - f"三种配置在 372 题通过率与{described_metrics}上的对比。" + f"{len(rows)} 种配置在 {total_cases} 题通过率与{described_metrics}上的对比。" if language == "zh" - else f"Three configurations compared by success rate on 372 cases and {described_metrics}." + else f"{len(rows)} configurations compared by success rate on {total_cases} cases and {described_metrics}." ) parts = [ f'', @@ -119,10 +116,9 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c "pss": (text["pss"], "pss_mib", "pss_change_pct", "MiB"), "cpu": (text["cpu"], "cpu_ms", "cpu_change_pct", "ms"), } - label_offsets = { - "114_off": (14, -44, "start"), - "118_off": (-14, -14, "end"), - "118_on": (14, -18, "start"), + row_colors = { + row["id"]: str(row.get("color") or COLORS[index % len(COLORS)]) + for index, row in enumerate(rows) } for panel, metric in enumerate(metrics): title, key, change_key, unit = specs[metric] @@ -141,39 +137,40 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c x = _scale(value, low, high, x0, x1) parts.append(f'') parts.append(f'{value:.1f}') + plotted: list[tuple[float, float]] = [] + offsets = ((0, 0), (-18, -18), (18, 18), (-18, 18), (18, -18), (0, -24), (0, 24)) for row in rows: - x = _scale(float(row[key]), low, high, x0, x1) - y = _scale(float(row["success_rate_pct"]), 0, y_max, chart_bottom, top) - color = COLORS[row["id"]] - parts.append(f'') - dx, dy, anchor = label_offsets[row["id"]] - short_label = row["short_label"] if language == "zh" else row["short_label_en"] - change = float(row[change_key]) - label = f'{short_label} · {row[key]:.2f} {unit} ({change:+.2f}%)' - parts.append(f'{html.escape(label)}') - method_note = ( - "1.1.4:仅复测 1.1.8 关闭布局唯一通过的候选题;3 次均失败,其余 371 题沿用共同失败关系。" - if language == "zh" - else "1.1.4: the sole case passed by layout-off 1.1.8 was retested 3 times and failed; the other 371 retain the shared-failure relation." - ) - parts.append(f'{html.escape(method_note)}') - legend_y = height - 42 - cursor = 55 - if len(metrics) == 1: - reserved_label_width = 220 - legend_step = (width - 110 - reserved_label_width) / max(1, len(rows) - 1) - else: - legend_step = 420 - for row in rows: - color = COLORS[row["id"]] + exact_x = _scale(float(row[key]), low, high, x0, x1) + exact_y = _scale(float(row["success_rate_pct"]), 0, y_max, chart_bottom, top) + x, y = exact_x, exact_y + for dx, dy in offsets: + candidate = (exact_x + dx, exact_y + dy) + if all(math.hypot(candidate[0] - px, candidate[1] - py) >= 27 for px, py in plotted): + x, y = candidate + break + plotted.append((x, y)) + color = row_colors[row["id"]] + number = rows.index(row) + 1 + if (x, y) != (exact_x, exact_y): + parts.append(f'') + parts.append(f'') + parts.append(f'') + parts.append(f'{number}') + legend_y = chart_bottom + 82 + for index, row in enumerate(rows): + color = row_colors[row["id"]] label_key = "label" if len(metrics) == 2 else "short_label" if language == "en": label_key += "_en" row_label = row[label_key] - legend_text = f'{row_label}: {row["passed_cases"]}/372 ({row["success_rate_pct"]:.1f}%)' - parts.append(f'') - parts.append(f'{html.escape(legend_text)}') - cursor += legend_step + fields = [f'{row["passed_cases"]}/{total_cases} ({row["success_rate_pct"]:.1f}%)'] + for metric in metrics: + _, key, change_key, unit = specs[metric] + fields.append(f'{row[key]:.2f} {unit} ({float(row[change_key]):+.2f}%)') + y = legend_y + index * 30 + parts.append(f'') + parts.append(f'{index+1}') + parts.append(f'{html.escape(row_label + ": " + " · ".join(fields))}') parts.append('') output.parent.mkdir(parents=True, exist_ok=True) output.write_text("\n".join(parts) + "\n") diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index 970140f7e..9b06bf41a 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -25,6 +25,7 @@ def setUp(self): "short_label": "1.1.4 关闭", "short_label_en": "1.1.4 off", "passed_cases": 0, + "total_cases": 372, "success_rate_pct": 0, "pss_mib": 77.216796875, "pss_change_pct": 0, @@ -38,6 +39,7 @@ def setUp(self): "short_label": "1.1.8 关闭", "short_label_en": "1.1.8 off", "passed_cases": 1, + "total_cases": 372, "success_rate_pct": 0.2688172043010753, "pss_mib": 77.1015625, "pss_change_pct": -0.1492348551916045, @@ -51,6 +53,7 @@ def setUp(self): "short_label": "1.1.8 开启", "short_label_en": "1.1.8 on", "passed_cases": 255, + "total_cases": 372, "success_rate_pct": 68.54838709677419, "pss_mib": 80.537109375, "pss_change_pct": 4.299987352978363, @@ -114,13 +117,31 @@ def test_y_axis_expands_to_include_rates_above_eighty_percent(self): self.data["configurations"][2]["success_rate_pct"] = 95 svg = self.render() self.assertIn(">100%", svg) - point = re.search(r' Date: Sun, 20 Sep 2026 21:43:47 +0800 Subject: [PATCH 08/29] Validate Moli chart inputs safely --- scripts/plot_moli_version_resources.py | 25 +++++++++++++++++++---- tests/test_moli_version_resource_chart.py | 16 +++++++++++++++ 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py index 1b1973960..1b8a31e7e 100644 --- a/scripts/plot_moli_version_resources.py +++ b/scripts/plot_moli_version_resources.py @@ -11,9 +11,11 @@ import json import math from pathlib import Path +import re COLORS = ("#239b68", "#d1841e", "#7652c7", "#2775c9", "#c54f79", "#4c8793") +COLOR_RE = re.compile(r"#[0-9a-fA-F]{6}") def _scale(value: float, lower: float, upper: float, start: float, end: float) -> float: @@ -48,10 +50,25 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c ) if missing: raise ValueError(f"configuration row {index} missing required field(s): {', '.join(missing)}") - totals = {int(row["total_cases"]) for row in rows} + color = row.get("color") + if color is not None and (not isinstance(color, str) or COLOR_RE.fullmatch(color) is None): + raise ValueError(f"configuration row {index} color must be a six-digit hex color") + numeric_fields = {"passed_cases", "total_cases", "success_rate_pct"} + for metric in metrics: + numeric_fields.update(metric_fields[metric]) + for field in sorted(numeric_fields): + try: + number = float(row[field]) + except (TypeError, ValueError) as exc: + raise ValueError(f"configuration row {index} field {field} must be numeric") from exc + if not math.isfinite(number): + raise ValueError(f"configuration row {index} field {field} must be finite") + totals = {float(row["total_cases"]) for row in rows} + if any(not total.is_integer() for total in totals): + raise ValueError("all configurations must use an integer total_cases") if len(totals) != 1 or next(iter(totals)) <= 0: raise ValueError("all configurations must use the same positive total_cases") - total_cases = next(iter(totals)) + total_cases = int(next(iter(totals))) resource = data.get("resource_population") required_resource_fields = {"chart_calls", "chart_tasks"} if not isinstance(resource, dict) or not required_resource_fields.issubset(resource): @@ -139,7 +156,7 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c parts.append(f'{value:.1f}') plotted: list[tuple[float, float]] = [] offsets = ((0, 0), (-18, -18), (18, 18), (-18, 18), (18, -18), (0, -24), (0, 24)) - for row in rows: + for row_index, row in enumerate(rows, 1): exact_x = _scale(float(row[key]), low, high, x0, x1) exact_y = _scale(float(row["success_rate_pct"]), 0, y_max, chart_bottom, top) x, y = exact_x, exact_y @@ -150,7 +167,7 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c break plotted.append((x, y)) color = row_colors[row["id"]] - number = rows.index(row) + 1 + number = row_index if (x, y) != (exact_x, exact_y): parts.append(f'') parts.append(f'') diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index 9b06bf41a..e8d70d111 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -159,6 +159,22 @@ def test_missing_configuration_field_has_clear_error(self): with self.assertRaisesRegex(ValueError, "configuration row 0 missing required field.*pss_change_pct"): self.render() + def test_color_rejects_svg_attribute_injection(self): + self.data["configurations"][0]["color"] = '#fff\" onload=\"alert(1)' + with self.assertRaisesRegex(ValueError, "color must be a six-digit hex color"): + self.render() + + def test_fractional_total_cases_has_clear_error(self): + for row in self.data["configurations"]: + row["total_cases"] = "372.5" + with self.assertRaisesRegex(ValueError, "integer total_cases"): + self.render() + + def test_nonfinite_metric_has_clear_error(self): + self.data["configurations"][0]["pss_mib"] = float("nan") + with self.assertRaisesRegex(ValueError, "field pss_mib must be finite"): + self.render() + if __name__ == "__main__": unittest.main() From c791f1e83f181df11748816daa1193bac4545836 Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 20 Sep 2026 22:04:37 +0800 Subject: [PATCH 09/29] Validate Moli chart cohort metadata --- scripts/plot_moli_version_resources.py | 16 ++++++++++++---- tests/test_moli_version_resource_chart.py | 17 ++++++++++++++++- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py index 1b8a31e7e..afd6c983a 100644 --- a/scripts/plot_moli_version_resources.py +++ b/scripts/plot_moli_version_resources.py @@ -63,6 +63,12 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c raise ValueError(f"configuration row {index} field {field} must be numeric") from exc if not math.isfinite(number): raise ValueError(f"configuration row {index} field {field} must be finite") + ids = [str(row["id"]) for row in rows] + if len(set(ids)) != len(ids): + raise ValueError("configuration ids must be unique") + for field in ("passed_cases", "total_cases"): + if any(not float(row[field]).is_integer() for row in rows): + raise ValueError(f"all configurations must use an integer {field}") totals = {float(row["total_cases"]) for row in rows} if any(not total.is_integer() for total in totals): raise ValueError("all configurations must use an integer total_cases") @@ -70,7 +76,9 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c raise ValueError("all configurations must use the same positive total_cases") total_cases = int(next(iter(totals))) resource = data.get("resource_population") - required_resource_fields = {"chart_calls", "chart_tasks"} + required_resource_fields = { + "chart_calls", "chart_tasks", "total_tasks", "calls_per_task" + } if not isinstance(resource, dict) or not required_resource_fields.issubset(resource): missing = ( sorted(required_resource_fields - set(resource or {})) @@ -81,7 +89,7 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c text = { "zh": { "title": f"{total_cases} 题成功率与资源消耗", - "subtitle": f"资源实验:557 题 × 5 次;图中使用预先冻结的 {resource['chart_calls']:,} 次 / {resource['chart_tasks']} 题样本;越靠左资源消耗越低", + "subtitle": f"资源实验:{resource['total_tasks']} 题 × {resource['calls_per_task']} 次;图中使用预先冻结的 {resource['chart_calls']:,} 次 / {resource['chart_tasks']} 题样本;越靠左资源消耗越低", "y": f"{total_cases} 题通过率(每题 3 次全部通过)", "pss": "峰值进程树 PSS 中位数(MiB)", "cpu": "单次执行平均 CPU 时间(ms)", @@ -90,7 +98,7 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c }, "en": { "title": f"Success on {total_cases} cases vs. resource use", - "subtitle": f"Resource experiment: 557 tasks × 5; plotted population: {resource['chart_calls']:,} pre-frozen calls / {resource['chart_tasks']} tasks; farther left is lower", + "subtitle": f"Resource experiment: {resource['total_tasks']} tasks × {resource['calls_per_task']}; plotted population: {resource['chart_calls']:,} pre-frozen calls / {resource['chart_tasks']} tasks; farther left is lower", "y": f"Success rate on {total_cases} cases (all 3 attempts pass)", "pss": "Median peak process-tree PSS (MiB)", "cpu": "Mean CPU time per execution (ms)", @@ -180,7 +188,7 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c if language == "en": label_key += "_en" row_label = row[label_key] - fields = [f'{row["passed_cases"]}/{total_cases} ({row["success_rate_pct"]:.1f}%)'] + fields = [f'{int(float(row["passed_cases"]))}/{total_cases} ({float(row["success_rate_pct"]):.1f}%)'] for metric in metrics: _, key, change_key, unit = specs[metric] fields.append(f'{row[key]:.2f} {unit} ({float(row[change_key]):+.2f}%)') diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index e8d70d111..d8facbe91 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -16,7 +16,12 @@ class MoliVersionResourceChartTests(unittest.TestCase): def setUp(self): self.data = { - "resource_population": {"chart_calls": 1045, "chart_tasks": 209}, + "resource_population": { + "chart_calls": 1045, + "chart_tasks": 209, + "total_tasks": 557, + "calls_per_task": 5, + }, "configurations": [ { "id": "114_off", @@ -170,6 +175,16 @@ def test_fractional_total_cases_has_clear_error(self): with self.assertRaisesRegex(ValueError, "integer total_cases"): self.render() + def test_duplicate_configuration_ids_have_clear_error(self): + self.data["configurations"][1]["id"] = "114_off" + with self.assertRaisesRegex(ValueError, "configuration ids must be unique"): + self.render() + + def test_fractional_passed_cases_have_clear_error(self): + self.data["configurations"][0]["passed_cases"] = 0.5 + with self.assertRaisesRegex(ValueError, "integer passed_cases"): + self.render() + def test_nonfinite_metric_has_clear_error(self): self.data["configurations"][0]["pss_mib"] = float("nan") with self.assertRaisesRegex(ValueError, "field pss_mib must be finite"): From 4d0865353be442fb3fbc51c63e811c1e29fb619e Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 20 Sep 2026 22:22:27 +0800 Subject: [PATCH 10/29] Validate Moli chart resource values --- scripts/plot_moli_version_resources.py | 6 +++++- tests/test_moli_version_resource_chart.py | 24 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py index afd6c983a..734845893 100644 --- a/scripts/plot_moli_version_resources.py +++ b/scripts/plot_moli_version_resources.py @@ -86,6 +86,10 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c else sorted(required_resource_fields) ) raise ValueError(f"resource_population missing required field(s): {', '.join(missing)}") + for field in sorted(required_resource_fields): + value = resource[field] + if isinstance(value, bool) or not isinstance(value, int) or value <= 0: + raise ValueError(f"resource_population field {field} must be a positive integer") text = { "zh": { "title": f"{total_cases} 题成功率与资源消耗", @@ -191,7 +195,7 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c fields = [f'{int(float(row["passed_cases"]))}/{total_cases} ({float(row["success_rate_pct"]):.1f}%)'] for metric in metrics: _, key, change_key, unit = specs[metric] - fields.append(f'{row[key]:.2f} {unit} ({float(row[change_key]):+.2f}%)') + fields.append(f'{float(row[key]):.2f} {unit} ({float(row[change_key]):+.2f}%)') y = legend_y + index * 30 parts.append(f'') parts.append(f'{index+1}') diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index d8facbe91..cf8a4688d 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -154,6 +154,30 @@ def test_missing_resource_population_field_has_clear_error(self): with self.assertRaisesRegex(ValueError, "resource_population missing required field.*chart_tasks"): self.render() + def test_resource_population_values_must_be_positive_integers(self): + for value in ("557", 557.0, 0, True): + with self.subTest(value=value): + self.data["resource_population"]["total_tasks"] = value + with self.assertRaisesRegex( + ValueError, + "resource_population field total_tasks must be a positive integer", + ): + self.render() + self.data["resource_population"]["total_tasks"] = 557 + + def test_numeric_string_metric_values_render_after_validation(self): + self.data["configurations"][0]["pss_mib"] = "77.216796875" + self.data["configurations"][0]["cpu_ms"] = "21.406698564593302" + svg = self.render() + self.assertIn("77.22 MiB (+0.00%)", svg) + self.assertIn("21.41 ms (+0.00%)", svg) + + def test_chinese_cpu_only_panel_has_cpu_labels_and_no_pss(self): + svg = self.render(("cpu",), "zh") + self.assertIn("单次执行平均 CPU 时间(ms)", svg) + self.assertIn("21.66 ms (+1.16%)", svg) + self.assertNotIn("PSS", svg) + def test_empty_configuration_list_has_clear_error(self): self.data["configurations"] = [] with self.assertRaisesRegex(ValueError, "configurations must contain at least one row"): From 97e035c46e58b51ca77857b31e259aed0d71ae56 Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 20 Sep 2026 22:33:15 +0800 Subject: [PATCH 11/29] Document Moli 1.1.9 benchmark method --- research/report-changes.json | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/research/report-changes.json b/research/report-changes.json index 49c6d598a..4bbce7607 100644 --- a/research/report-changes.json +++ b/research/report-changes.json @@ -1259,12 +1259,12 @@ "moli_process_tree_resource_profile" ], "date": "2026-09-20", - "title": "增加 Moli 1.1.4 / 1.1.8 成功率与资源汇总", - "summary": "首页新增三种配置的 372 题成功率、峰值 PSS 和 CPU 时间汇总。成功率与资源实验分别标明分母;表格和图中都给出相对 1.1.4 关闭布局的带正负号变化,代码生成的双面板图共用成功率纵轴,并允许省略 CPU 面板。", + "title": "增加 Moli 1.1.4 / 1.1.8 / 1.1.9 成功率与资源汇总", + "summary": "首页比较四种方法在 372 个历史失败用例上的恢复结果,并展示三种固定配置的 Linux PSS/CPU 对照。Moli 1.1.9 先关闭布局,失败题再开启布局,仅以完整通过的重跑替换原结果;其 macOS RSS/CPU 资源实验单列物理重跑成本,不与 Linux PSS 混算百分比。", "i18n": { "en": { - "title": "Add Moli 1.1.4 / 1.1.8 success and resource summary", - "summary": "The report home page now compares success on 372 cases, peak PSS, and CPU time for three configurations. Compatibility and resource experiments state separate populations; the table and chart show signed changes relative to Moli 1.1.4 layout off. The code-generated dual-panel chart shares one success-rate axis and can omit the CPU panel.", + "title": "Add Moli 1.1.4 / 1.1.8 / 1.1.9 success and resource summary", + "summary": "The report home page compares four methods on the 372 historical failures and retains the Linux PSS/CPU comparison for three fixed configurations. Moli 1.1.9 starts with layout off and reruns failed cases with layout on, replacing an initial result only after a complete successful retry. Its macOS RSS/CPU experiment reports retry execution cost separately and is not combined with Linux PSS percentages.", "changes": [ [ "Version comparison", @@ -1278,12 +1278,18 @@ "The report separately presents a 557-task × 5-call resource experiment and compares median peak PSS and mean CPU time on the 1,045 task-attempt population frozen before execution.", "Resource values compare versions and layout settings in the same environment; CPU sampling can miss short-lived child processes." ], - [ - "Summary chart", + [ + "Summary chart", "A single horizontal axis cannot express MiB and milliseconds.", "Two horizontal panels share the 372-case success-rate axis. Each point shows the absolute value and percentage change from Moli 1.1.4, and the plotting script supports PSS, CPU, or both.", - "The chart is generated from frozen data by code, with separate Chinese and English output; it is not a generated image." - ] + "The chart is generated from frozen data by code, with separate Chinese and English output; it is not a generated image." + ], + [ + "Moli 1.1.9 try-layout method", + "The earlier comparison had no method that changed layout only after a case failed.", + "Moli 1.1.9 runs every case three times with layout off, reruns each non-passing case three times with layout on, and replaces the initial case result only when all three retry attempts pass. A separate 557-task resource pair retains one final logical result per task-attempt and reports extra retry calls as physical cost.", + "The macOS experiment reports process-tree RSS rather than PSS. Its values are shown separately from the Linux PSS chart and receive no cross-platform percentage delta." + ] ] } }, @@ -1300,12 +1306,18 @@ "独立展示 557 题 × 5 次资源实验,并用运行前冻结的 1,045 个任务-执行样本比较峰值 PSS 中位数和平均 CPU 时间。", "资源值用于同环境版本与布局对照;CPU 采样存在短生命周期子进程遗漏风险。" ], - [ - "汇总图", + [ + "汇总图", "单一横轴不能同时表达 MiB 与毫秒。", "使用两个水平面板,共用 372 题成功率纵轴;数据点同时标出绝对值和相对 1.1.4 的变化百分比,绘图脚本支持 PSS、CPU 或两者。", - "图由冻结数据和代码生成,中文与英文分别输出,不使用生成式图片。" - ] + "图由冻结数据和代码生成,中文与英文分别输出,不使用生成式图片。" + ], + [ + "Moli 1.1.9 尝试布局方法", + "此前对照中没有只在用例失败后切换布局的方法。", + "Moli 1.1.9 先对每题关闭布局运行三次,再对未通过题开启布局运行三次;仅当重跑三次全部通过时替换初跑结果。独立的 557 题资源实验每个任务-次数保留一个最终逻辑结果,并把额外重跑作为物理成本单列。", + "macOS 实验报告进程树 RSS,不是 PSS;该结果与 Linux PSS 图分开展示,不计算跨平台百分比变化。" + ] ] }, { From 4478097e2184f39248b21bd03d9e94a74e320e01 Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 20 Sep 2026 22:33:49 +0800 Subject: [PATCH 12/29] Clarify Moli resource chart population --- scripts/plot_moli_version_resources.py | 4 +--- tests/test_moli_version_resource_chart.py | 1 + 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py index 734845893..c93c2fe0a 100644 --- a/scripts/plot_moli_version_resources.py +++ b/scripts/plot_moli_version_resources.py @@ -70,8 +70,6 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c if any(not float(row[field]).is_integer() for row in rows): raise ValueError(f"all configurations must use an integer {field}") totals = {float(row["total_cases"]) for row in rows} - if any(not total.is_integer() for total in totals): - raise ValueError("all configurations must use an integer total_cases") if len(totals) != 1 or next(iter(totals)) <= 0: raise ValueError("all configurations must use the same positive total_cases") total_cases = int(next(iter(totals))) @@ -102,7 +100,7 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c }, "en": { "title": f"Success on {total_cases} cases vs. resource use", - "subtitle": f"Resource experiment: {resource['total_tasks']} tasks × {resource['calls_per_task']}; plotted population: {resource['chart_calls']:,} pre-frozen calls / {resource['chart_tasks']} tasks; farther left is lower", + "subtitle": f"Resource experiment: {resource['total_tasks']} tasks × {resource['calls_per_task']} calls; plotted population: {resource['chart_calls']:,} pre-frozen calls / {resource['chart_tasks']} tasks; farther left is lower", "y": f"Success rate on {total_cases} cases (all 3 attempts pass)", "pss": "Median peak process-tree PSS (MiB)", "cpu": "Mean CPU time per execution (ms)", diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index cf8a4688d..9c371cf85 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -113,6 +113,7 @@ def test_chinese_single_metric_keeps_all_short_legend_entries(self): def test_english_dual_panel_contains_both_resources_and_changes(self): svg = self.render(language="en") + self.assertIn("Resource experiment: 557 tasks × 5 calls", svg) self.assertIn("Median peak process-tree PSS (MiB)", svg) self.assertIn("Mean CPU time per execution (ms)", svg) self.assertIn("80.54 MiB (+4.30%)", svg) From f1274ca411f614b3477876277083a25e5c950e3f Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 20 Sep 2026 22:40:19 +0800 Subject: [PATCH 13/29] Clarify adaptive Moli resource accounting --- research/report-changes.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/research/report-changes.json b/research/report-changes.json index 4bbce7607..abe4c7206 100644 --- a/research/report-changes.json +++ b/research/report-changes.json @@ -1260,11 +1260,11 @@ ], "date": "2026-09-20", "title": "增加 Moli 1.1.4 / 1.1.8 / 1.1.9 成功率与资源汇总", - "summary": "首页比较四种方法在 372 个历史失败用例上的恢复结果,并展示三种固定配置的 Linux PSS/CPU 对照。Moli 1.1.9 先关闭布局,失败题再开启布局,仅以完整通过的重跑替换原结果;其 macOS RSS/CPU 资源实验单列物理重跑成本,不与 Linux PSS 混算百分比。", + "summary": "首页比较四种方法在 372 个历史失败用例上的恢复结果,并展示三种固定配置的 Linux PSS/CPU 对照。Moli 1.1.9 先关闭布局,失败题再开启布局,仅以完整通过的重跑替换原结果;其 macOS RSS/CPU 资源实验把初跑与重跑折算为每个逻辑调用的有效成本,并单列物理重跑,不与 Linux PSS 混算百分比。", "i18n": { "en": { "title": "Add Moli 1.1.4 / 1.1.8 / 1.1.9 success and resource summary", - "summary": "The report home page compares four methods on the 372 historical failures and retains the Linux PSS/CPU comparison for three fixed configurations. Moli 1.1.9 starts with layout off and reruns failed cases with layout on, replacing an initial result only after a complete successful retry. Its macOS RSS/CPU experiment reports retry execution cost separately and is not combined with Linux PSS percentages.", + "summary": "The report home page compares four methods on the 372 historical failures and retains the Linux PSS/CPU comparison for three fixed configurations. Moli 1.1.9 starts with layout off and reruns failed cases with layout on, replacing an initial result only after a complete successful retry. Its macOS RSS/CPU experiment folds initial and retry work into an effective per-logical-call cost, reports physical retries separately, and is not combined with Linux PSS percentages.", "changes": [ [ "Version comparison", @@ -1287,7 +1287,7 @@ [ "Moli 1.1.9 try-layout method", "The earlier comparison had no method that changed layout only after a case failed.", - "Moli 1.1.9 runs every case three times with layout off, reruns each non-passing case three times with layout on, and replaces the initial case result only when all three retry attempts pass. A separate 557-task resource pair retains one final logical result per task-attempt and reports extra retry calls as physical cost.", + "Moli 1.1.9 runs every case three times with layout off, reruns each non-passing case three times with layout on, and replaces the initial case result only when all three retry attempts pass. A separate 557-task resource pair sums initial and retry CPU per task-attempt, takes the larger physical-call peak RSS, and reports extra retry calls as physical cost.", "The macOS experiment reports process-tree RSS rather than PSS. Its values are shown separately from the Linux PSS chart and receive no cross-platform percentage delta." ] ] @@ -1315,7 +1315,7 @@ [ "Moli 1.1.9 尝试布局方法", "此前对照中没有只在用例失败后切换布局的方法。", - "Moli 1.1.9 先对每题关闭布局运行三次,再对未通过题开启布局运行三次;仅当重跑三次全部通过时替换初跑结果。独立的 557 题资源实验每个任务-次数保留一个最终逻辑结果,并把额外重跑作为物理成本单列。", + "Moli 1.1.9 先对每题关闭布局运行三次,再对未通过题开启布局运行三次;仅当重跑三次全部通过时替换初跑结果。独立的 557 题资源实验按任务-次数累加初跑与重跑 CPU、取两次物理调用中较大的峰值 RSS,并把额外重跑作为物理成本单列。", "macOS 实验报告进程树 RSS,不是 PSS;该结果与 Linux PSS 图分开展示,不计算跨平台百分比变化。" ] ] From a2be828a701196e5ac3327d26eccc9c551912885 Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 20 Sep 2026 22:41:55 +0800 Subject: [PATCH 14/29] Defer Moli 1.1.9 release note until publication --- research/report-changes.json | 36 ++++++++++++------------------------ 1 file changed, 12 insertions(+), 24 deletions(-) diff --git a/research/report-changes.json b/research/report-changes.json index abe4c7206..49c6d598a 100644 --- a/research/report-changes.json +++ b/research/report-changes.json @@ -1259,12 +1259,12 @@ "moli_process_tree_resource_profile" ], "date": "2026-09-20", - "title": "增加 Moli 1.1.4 / 1.1.8 / 1.1.9 成功率与资源汇总", - "summary": "首页比较四种方法在 372 个历史失败用例上的恢复结果,并展示三种固定配置的 Linux PSS/CPU 对照。Moli 1.1.9 先关闭布局,失败题再开启布局,仅以完整通过的重跑替换原结果;其 macOS RSS/CPU 资源实验把初跑与重跑折算为每个逻辑调用的有效成本,并单列物理重跑,不与 Linux PSS 混算百分比。", + "title": "增加 Moli 1.1.4 / 1.1.8 成功率与资源汇总", + "summary": "首页新增三种配置的 372 题成功率、峰值 PSS 和 CPU 时间汇总。成功率与资源实验分别标明分母;表格和图中都给出相对 1.1.4 关闭布局的带正负号变化,代码生成的双面板图共用成功率纵轴,并允许省略 CPU 面板。", "i18n": { "en": { - "title": "Add Moli 1.1.4 / 1.1.8 / 1.1.9 success and resource summary", - "summary": "The report home page compares four methods on the 372 historical failures and retains the Linux PSS/CPU comparison for three fixed configurations. Moli 1.1.9 starts with layout off and reruns failed cases with layout on, replacing an initial result only after a complete successful retry. Its macOS RSS/CPU experiment folds initial and retry work into an effective per-logical-call cost, reports physical retries separately, and is not combined with Linux PSS percentages.", + "title": "Add Moli 1.1.4 / 1.1.8 success and resource summary", + "summary": "The report home page now compares success on 372 cases, peak PSS, and CPU time for three configurations. Compatibility and resource experiments state separate populations; the table and chart show signed changes relative to Moli 1.1.4 layout off. The code-generated dual-panel chart shares one success-rate axis and can omit the CPU panel.", "changes": [ [ "Version comparison", @@ -1278,18 +1278,12 @@ "The report separately presents a 557-task × 5-call resource experiment and compares median peak PSS and mean CPU time on the 1,045 task-attempt population frozen before execution.", "Resource values compare versions and layout settings in the same environment; CPU sampling can miss short-lived child processes." ], - [ - "Summary chart", + [ + "Summary chart", "A single horizontal axis cannot express MiB and milliseconds.", "Two horizontal panels share the 372-case success-rate axis. Each point shows the absolute value and percentage change from Moli 1.1.4, and the plotting script supports PSS, CPU, or both.", - "The chart is generated from frozen data by code, with separate Chinese and English output; it is not a generated image." - ], - [ - "Moli 1.1.9 try-layout method", - "The earlier comparison had no method that changed layout only after a case failed.", - "Moli 1.1.9 runs every case three times with layout off, reruns each non-passing case three times with layout on, and replaces the initial case result only when all three retry attempts pass. A separate 557-task resource pair sums initial and retry CPU per task-attempt, takes the larger physical-call peak RSS, and reports extra retry calls as physical cost.", - "The macOS experiment reports process-tree RSS rather than PSS. Its values are shown separately from the Linux PSS chart and receive no cross-platform percentage delta." - ] + "The chart is generated from frozen data by code, with separate Chinese and English output; it is not a generated image." + ] ] } }, @@ -1306,18 +1300,12 @@ "独立展示 557 题 × 5 次资源实验,并用运行前冻结的 1,045 个任务-执行样本比较峰值 PSS 中位数和平均 CPU 时间。", "资源值用于同环境版本与布局对照;CPU 采样存在短生命周期子进程遗漏风险。" ], - [ - "汇总图", + [ + "汇总图", "单一横轴不能同时表达 MiB 与毫秒。", "使用两个水平面板,共用 372 题成功率纵轴;数据点同时标出绝对值和相对 1.1.4 的变化百分比,绘图脚本支持 PSS、CPU 或两者。", - "图由冻结数据和代码生成,中文与英文分别输出,不使用生成式图片。" - ], - [ - "Moli 1.1.9 尝试布局方法", - "此前对照中没有只在用例失败后切换布局的方法。", - "Moli 1.1.9 先对每题关闭布局运行三次,再对未通过题开启布局运行三次;仅当重跑三次全部通过时替换初跑结果。独立的 557 题资源实验按任务-次数累加初跑与重跑 CPU、取两次物理调用中较大的峰值 RSS,并把额外重跑作为物理成本单列。", - "macOS 实验报告进程树 RSS,不是 PSS;该结果与 Linux PSS 图分开展示,不计算跨平台百分比变化。" - ] + "图由冻结数据和代码生成,中文与英文分别输出,不使用生成式图片。" + ] ] }, { From bffff93bfd067a66f1fd38eded23d63a408281ed Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 20 Sep 2026 23:32:04 +0800 Subject: [PATCH 15/29] Support RSS and CPU resource comparison charts --- scripts/plot_moli_version_resources.py | 8 ++++++-- tests/test_moli_version_resource_chart.py | 13 +++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py index c93c2fe0a..3a4583a19 100644 --- a/scripts/plot_moli_version_resources.py +++ b/scripts/plot_moli_version_resources.py @@ -25,8 +25,8 @@ def _scale(value: float, lower: float, upper: float, start: float, end: float) - def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "cpu"), language: str = "zh") -> None: - if not metrics or any(metric not in {"pss", "cpu"} for metric in metrics): - raise ValueError("metrics must contain pss and/or cpu") + if not metrics or len(metrics) > 2 or any(metric not in {"pss", "rss", "cpu"} for metric in metrics): + raise ValueError("metrics must contain one or two of pss, rss and cpu") if language not in {"zh", "en"}: raise ValueError("language must be zh or en") rows = data.get("configurations") @@ -38,6 +38,7 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c ) metric_fields = { "pss": {"pss_mib", "pss_change_pct"}, + "rss": {"rss_mib", "rss_change_pct"}, "cpu": {"cpu_ms", "cpu_change_pct"}, } for metric in metrics: @@ -94,6 +95,7 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c "subtitle": f"资源实验:{resource['total_tasks']} 题 × {resource['calls_per_task']} 次;图中使用预先冻结的 {resource['chart_calls']:,} 次 / {resource['chart_tasks']} 题样本;越靠左资源消耗越低", "y": f"{total_cases} 题通过率(每题 3 次全部通过)", "pss": "峰值进程树 PSS 中位数(MiB)", + "rss": "峰值进程树 RSS 中位数(MiB)", "cpu": "单次执行平均 CPU 时间(ms)", "off": "关闭", "on": "开启", @@ -103,6 +105,7 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c "subtitle": f"Resource experiment: {resource['total_tasks']} tasks × {resource['calls_per_task']} calls; plotted population: {resource['chart_calls']:,} pre-frozen calls / {resource['chart_tasks']} tasks; farther left is lower", "y": f"Success rate on {total_cases} cases (all 3 attempts pass)", "pss": "Median peak process-tree PSS (MiB)", + "rss": "Median peak process-tree RSS (MiB)", "cpu": "Mean CPU time per execution (ms)", "off": "off", "on": "on", @@ -141,6 +144,7 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c parts.append(f'{html.escape(text["y"])}') specs = { "pss": (text["pss"], "pss_mib", "pss_change_pct", "MiB"), + "rss": (text["rss"], "rss_mib", "rss_change_pct", "MiB"), "cpu": (text["cpu"], "cpu_ms", "cpu_change_pct", "ms"), } row_colors = { diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index 9c371cf85..c92711124 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -95,6 +95,19 @@ def test_pss_only_omits_cpu_content(self): self.assertNotIn("CPU", svg) self.assertNotIn("21.41 ms", svg) + def test_macos_rss_cpu_chart_does_not_label_memory_as_pss(self): + for row in self.data["configurations"]: + row["rss_mib"] = row.pop("pss_mib") + row["rss_change_pct"] = row.pop("pss_change_pct") + for language in ("zh", "en"): + with self.subTest(language=language): + svg = self.render(("rss", "cpu"), language) + self.assertIn("RSS", svg) + self.assertIn("CPU", svg) + self.assertNotIn("PSS", svg) + self.assertIn("80.54 MiB (+4.30%)", svg) + self.assertIn("21.66 ms (+1.16%)", svg) + def test_cpu_only_omits_pss_content_and_keeps_all_legend_entries(self): svg = self.render(("cpu",), "en") self.assertIn("Mean CPU time per execution (ms)", svg) From c99eb28f4fd511e20fcb41460178009f4bbb8f68 Mon Sep 17 00:00:00 2001 From: kevin Date: Mon, 21 Sep 2026 00:02:18 +0800 Subject: [PATCH 16/29] Track reproducible Moli fixed-layout comparison report --- evaluation/moli/current-report.json | 14 + scripts/moli_report/BUILD.md | 28 + scripts/moli_report/README.md | 9 + scripts/moli_report/app.js | 1897 +++++++++++++++++++++ scripts/moli_report/build.py | 1116 ++++++++++++ scripts/moli_report/bundle-loader.js | 75 + scripts/moli_report/index.html | 50 + scripts/moli_report/pack.py | 109 ++ scripts/moli_report/run.py | 134 ++ scripts/moli_report/style.css | 888 ++++++++++ scripts/moli_report/ui_check.js | 554 ++++++ scripts/moli_report/verify.py | 808 +++++++++ tests/moli_report_render_contract.cjs | 158 ++ tests/test_moli_report_pack.py | 65 + tests/test_moli_report_render_contract.py | 15 + 15 files changed, 5920 insertions(+) create mode 100644 evaluation/moli/current-report.json create mode 100644 scripts/moli_report/BUILD.md create mode 100644 scripts/moli_report/README.md create mode 100644 scripts/moli_report/app.js create mode 100644 scripts/moli_report/build.py create mode 100644 scripts/moli_report/bundle-loader.js create mode 100644 scripts/moli_report/index.html create mode 100644 scripts/moli_report/pack.py create mode 100644 scripts/moli_report/run.py create mode 100644 scripts/moli_report/style.css create mode 100644 scripts/moli_report/ui_check.js create mode 100644 scripts/moli_report/verify.py create mode 100644 tests/moli_report_render_contract.cjs create mode 100644 tests/test_moli_report_pack.py create mode 100644 tests/test_moli_report_render_contract.py diff --git a/evaluation/moli/current-report.json b/evaluation/moli/current-report.json new file mode 100644 index 000000000..cab9bc4ed --- /dev/null +++ b/evaluation/moli/current-report.json @@ -0,0 +1,14 @@ +{ + "schema": "moli_report_profile/1", + "functional_population": {"cases": 372, "attempts_per_case": 3, "rule": "all_three_attempts_pass"}, + "resource_population": {"tasks": 557, "attempts_per_task": 5, "chart_tasks": 209, "chart_calls": 1045}, + "method_ids": ["114_off", "118_off", "118_on", "119_off", "119_on", "119_official_on"], + "macos_method_ids": ["119_off", "119_on", "119_official_on"], + "publication": { + "base_url": "https://artifact-site.lexmount.cn", + "slug": "gdwtSGOel0va", + "kind": "folder", + "expected_version": "ver_96cd695de0d54d72bc5e7bfe09ac3ba6", + "share_url": "https://artifact-site.lexmount.cn/v/w1vgSkFJjvmCL6kPaHmj4K8sUZ8iTI8t" + } +} diff --git a/scripts/moli_report/BUILD.md b/scripts/moli_report/BUILD.md new file mode 100644 index 000000000..fb0030576 --- /dev/null +++ b/scripts/moli_report/BUILD.md @@ -0,0 +1,28 @@ +# Build and verify the Moli report + +This directory owns the Moli comparison report renderer. Measured evidence stays outside Git under `BROWSER_EVAL_DATA_HOME` (default: `~/.browser-eval`). It does not use the Web Fetch publication target. + +The historical Linux source checkout is read from `LEXBENCH_REPORT_RUNNER_ROOT` (default: `$BROWSER_EVAL_DATA_HOME/work/moli-1.1.8-failures-linux`). Its recorded resource-calibration helper remains necessary to validate the historical measurements. Current macOS resource configurations each use one sampled run. + +Build from validated fixed-layout summaries generated by Lexbench's `tools/summarize_moli_fixed_layout.py` and `tools/summarize_moli_macos_resources.py`: + +```sh +uv run --frozen python scripts/moli_report/build.py \ + --output /tmp/moli-report-release \ + --fixed-summary 119_off /path/to/patched-off-summary.json \ + --fixed-summary 119_on /path/to/patched-on-summary.json \ + --fixed-summary 119_official_on /path/to/official-on-summary.json \ + --macos-resource-summary /path/to/patched-resource-summary.json \ + --official-resource-summary /path/to/official-resource-summary.json +uv run --frozen python scripts/moli_report/verify.py --site /tmp/moli-report-release --release +``` + +Choose a new output directory for each build; the builder does not delete existing output. `--vendor-dir` selects the retained Mermaid distribution and license. Their hashes are checked before copying. The default location is the original report asset directory under the data home; no vendored executable or measured output is committed here. + +The static verifier checks score/evidence bindings, resource populations and percentages, fixed-case log links, charts, bilingual rendering, unique resource extrema and negative controls. It invokes the same JavaScript rendering checks used by `tests/test_moli_report_render_contract.py`. + +For full release verification, serve the build with a static HTTP server and run `ui_check.js` with `MOLI_REPORT_SITE`, `MOLI_REPORT_ORIGIN`, and `MOLI_REPORT_SHOTS`. `LEXBENCH_NODE_MODULES` selects the provisioned Playwright installation. The browser check covers route classes, themes, widths, evidence dialogs and keyboard navigation. Run it after resource measurement to avoid contaminating the measurement host. + +Publish only after the complete requested method matrix and release checks pass, using the existing bound Artifact Site target and its freshly read remote version. Preserve binary identity, raw trials and previous report versions. + +Package the validated tree with `uv run --frozen python scripts/moli_report/pack.py --source /tmp/moli-report-release --output /tmp/moli-report-package`. The packer retains both English entry paths and checks bytes through the bundle manifest; it refuses symlinks, hidden paths, and existing destinations. Run the browser release check against this packaged directory before uploading. diff --git a/scripts/moli_report/README.md b/scripts/moli_report/README.md new file mode 100644 index 000000000..eb44c2956 --- /dev/null +++ b/scripts/moli_report/README.md @@ -0,0 +1,9 @@ +# Moli compatibility and resource comparison + +Success rates use the same 372 historical Moli 0.1.1 failures. A case passes only when all three attempts pass. Moli 1.1.8 and the supplied patched Moli 1.1.9 binary are compared with layout fixed off and on. Official Moli 1.1.9 is evaluated with layout on. Moli 1.1.4 layout off uses a differential check of the sole candidate, with inherited failures explicitly identified. + +Resources use a separate 557-task experiment, five calls per task. Each patched 1.1.9 layout configuration has one measured run (2,785 calls each); the official layout-on configuration has one measured run. The chart additionally uses the pre-frozen 1,045-call, 209-task population aligned with the historical resource comparison. Results from every task, including failures, remain in the declared population. + +Historical Linux measurements report process-tree PSS; macOS measurements report process-tree RSS. These memory metrics are shown separately. Historical percentage changes use 1.1.4 layout off as baseline. The macOS comparison uses official 1.1.9 layout on as baseline when available. The patched debug binary and official release asset differ in build configuration as well as code. + +Open index.html through a static HTTP server. Chinese and English routes share the same report model and evidence. Charts are rendered by the included Python script; RSS/PSS and CPU axes can be selected independently. Per-task results retain the exact program errors and sanitized grader, output, and protocol logs. diff --git a/scripts/moli_report/app.js b/scripts/moli_report/app.js new file mode 100644 index 000000000..2543b643c --- /dev/null +++ b/scripts/moli_report/app.js @@ -0,0 +1,1897 @@ +"use strict"; +const root = document.documentElement, + base = root.dataset.base || "", + zh = root.lang.startsWith("zh"); +const D = { + zh: { + nav: { + home: "总览", + dataset: "评测集", + method: "评测方法", + analysis: "结果分析", + results: "逐题结果", + review: "核验记录", + guide: "报告解读", + reproduce: "环境与复现", + }, + modes: { off: "无布局", on: "开布局" }, + strata: { + raw_read: "原始 CDP 读取", + raw_geometry_input: "几何与坐标输入", + playwright: "Playwright 常规操作", + puppeteer: "Puppeteer 常规操作", + agent_tool: "Agent 工具", + multi_step: "多步交互", + agent_scenario: "Agent 场景", + }, + pass: "通过", + fail: "失败", + all: "全部", + open: "查看", + evidence: "证据", + missing: "暂无证据", + loading: "正在载入…", + error: "数据读取失败", + noHuman: "未进行独立人工逐次复核", + methodLimit: + "覆盖 Moli 0.1.1 的全部 372 个历史失败用例;结果适用于这一失败子集。", + more: "查看详情", + task: "任务", + mode: "模式", + attempt: "第 {n} 次", + status: "状态", + duration: "耗时", + cpu: "CPU 时间", + pss: "结束 PSS", + traffic: "站点下行", + failure: "程序错误", + source: "脱敏证据", + search: "搜索任务、驱动或程序错误", + relation: "结果关系", + stratum: "任务类型", + bothPass: "两种模式均通过", + gain: "开启后新增通过用例", + mixed: "部分通过,次数相同", + bothFail: "两种模式均失败", + loss: "开启后退步用例", + back: "返回逐题结果", + close: "关闭", + unavailable: "未提供", + title: "Moli 1.1.4 / 1.1.8 / 1.1.9 · 成功率与资源对比", + start: "查看逐题结果", + method: "查看方法", + metricNote: + "P50 是中位数;P95 是第 95 百分位。耗时为驱动执行与验收的墙钟时间,不含浏览器启动、外围目标检查及最终证据落盘。", + winner: "较低", + higher: "较高", + scope: "适用范围", + observed: "观测到的采样最大值", + filterFail: "涉及失败或变化", + methodIntro: + "题目与验收预先冻结,两种浏览器配置只相差是否启用 --layout。默认模式使用低成本模拟几何;--layout 启用按需真实布局,并非持续绘制。可选图片等资源抓取由另一开关控制,本轮未改变。1.1.9 的每个固定配置各测一轮资源,557 题各五次;372 题成功率另测,每题三次。", + analysisIntro: "按相同任务与执行次数配对。成功变化和资源代价分开解读。", + guideIntro: + "从 Agent 使用者角度,先看能否完成,再看失败等待和完成任务的资源。", + details: "展开证据", + calibration: "采样校准", + resultCount: "显示 {n} / {total} 个任务", + rawContract: "原始任务合同", + noRows: "没有符合筛选条件的任务。", + }, + en: { + nav: { + home: "Overview", + dataset: "Dataset", + method: "Method", + analysis: "Analysis", + results: "Task results", + review: "Verification", + guide: "Interpretation", + reproduce: "Environment", + }, + modes: { off: "Layout off", on: "Layout on" }, + strata: { + raw_read: "Raw CDP reading", + raw_geometry_input: "Geometry and input", + playwright: "Playwright operations", + puppeteer: "Puppeteer operations", + agent_tool: "Agent tools", + multi_step: "Multi-step flows", + agent_scenario: "Agent scenarios", + }, + pass: "Pass", + fail: "Fail", + all: "All", + open: "Open", + evidence: "Evidence", + missing: "No evidence available", + loading: "Loading…", + error: "Could not load data", + noHuman: "No independent per-call review", + methodLimit: + "This cohort includes all 372 historical Moli 0.1.1 failures; results apply to this failure subset.", + more: "View details", + task: "Task", + mode: "Mode", + attempt: "Attempt {n}", + status: "Status", + duration: "Duration", + cpu: "CPU time", + pss: "Ending PSS", + traffic: "Fixture downlink", + failure: "Program error", + source: "Sanitized evidence", + search: "Search task, driver, or program error", + relation: "Outcome relation", + stratum: "Task family", + bothPass: "Both modes pass", + gain: "Cases gained with layout", + mixed: "Equal partial passes", + bothFail: "Both modes fail", + loss: "Cases lost with layout", + back: "Back to task results", + close: "Close", + unavailable: "Unavailable", + title: "Moli 1.1.4 / 1.1.8 / 1.1.9 · Compatibility and resources", + start: "Explore task results", + method: "Read methodology", + metricNote: + "P50 is the median and P95 the 95th percentile. Duration covers driver execution and grading, excluding browser startup, outer target checks and final evidence writing.", + winner: "Lower", + higher: "Higher", + scope: "Scope", + observed: "Observed sampled maximum", + filterFail: "Failures or changes", + methodIntro: + "Task contracts were frozen in advance. The browser configurations differ only in Moli's --layout flag. The default uses low-cost mock geometry; --layout enables real geometry on demand rather than continuous painting. Optional image and media fetching is a separate control and was unchanged. Each fixed 1.1.9 configuration has one 557-task resource run with five calls per task. Success is measured separately on 372 cases with three calls per task.", + analysisIntro: + "Pair the same task and attempt. Outcome changes and resource costs are interpreted separately.", + guideIntro: + "For an agent user, completion comes first, followed by failure waiting time and cost on completed tasks.", + details: "Expand evidence", + calibration: "Profiling calibration", + resultCount: "Showing {n} / {total} tasks", + rawContract: "Raw task contract", + noRows: "No tasks match these filters.", + }, +}; +Object.assign(D.zh.strata, { + node_cdp_probe: "Node CDP", + raw_cdp: "Raw CDP", + tool_agent_browser: "agent-browser", + thin_cdp_use: "cdp-use", + thin_chromedp: "chromedp", + thin_chrome_remote_interface: "chrome-remote-interface", + thin_ferrum: "Ferrum", + mcp_chrome_devtools: "Chrome DevTools MCP", + thin_chromiumoxide: "Chromiumoxide", + framework_puppeteer: "Puppeteer", + framework_playwright: "Playwright", + thin_pydoll: "Pydoll", + thin_rod: "Rod", + framework_stagehand: "Stagehand", + webdriver_selenium: "Selenium", +}); +Object.assign(D.en.strata, { + node_cdp_probe: "Node CDP", + raw_cdp: "Raw CDP", + tool_agent_browser: "agent-browser", + thin_cdp_use: "cdp-use", + thin_chromedp: "chromedp", + thin_chrome_remote_interface: "chrome-remote-interface", + thin_ferrum: "Ferrum", + mcp_chrome_devtools: "Chrome DevTools MCP", + thin_chromiumoxide: "Chromiumoxide", + framework_puppeteer: "Puppeteer", + framework_playwright: "Playwright", + thin_pydoll: "Pydoll", + thin_rod: "Rod", + framework_stagehand: "Stagehand", + webdriver_selenium: "Selenium", +}); +const T = zh ? D.zh : D.en; +let M = null, + dialog = document.getElementById("evidence-dialog"), + trigger = null; +const esc = (s) => + String(s ?? "").replace( + /[&<>"']/g, + (c) => + ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[ + c + ], + ); +const fmt = (v, d = 0) => + v === null || v === undefined + ? "—" + : Number(v).toLocaleString(zh ? "zh-CN" : "en-US", { + maximumFractionDigits: d, + minimumFractionDigits: d, + }); +const population = () => + zh + ? `同一组预先固定的 ${M.task_count} 个任务,每种模式各运行 ${M.protocol.k_runs} 次,共 ${M.attempts_per_mode} 次调用。` + : `The same ${M.task_count} preselected tasks, ${M.protocol.k_runs} calls each and ${M.attempts_per_mode} calls per mode.`; +const casePopulation = () => + zh + ? `通过数按 ${M.task_count} 个用例统计:本轮每题已记录的 ${M.protocol.k_runs} 次无采样执行全部通过,才计为 1 个通过用例。` + : `Pass counts use ${M.task_count} cases: a case passes only when all ${M.protocol.k_runs} recorded unprofiled attempts pass.`; +const caseVerdict = (n) => + statusChip(n === M.protocol.k_runs ? "pass" : "fail"); +const historicalScope = () => + zh + ? `历史 Moli 0.1.1 通过 1,556/1,928 个用例(80.71%),372 个用例未达到三次全部通过。1.1.8 关闭和开启布局均直接复测全部 372 题。1.1.8 关闭布局只恢复 1 题,因此 1.1.4 关闭布局只对这唯一候选题复测三次;该题三次均失败,其余 371 题沿用两版本均失败的集合关系,结果为 0/372。历史通过的 1,556 题未重测,不能据此推算新版本全量通过率。` + : `Moli 0.1.1 originally passed 1,556/1,928 cases (80.71%); 372 did not pass all three attempts. Moli 1.1.8 was directly tested on all 372 with layout off and on. Because layout-off 1.1.8 recovered only one case, layout-off 1.1.4 was tested three times on that sole candidate; all three attempts failed, while the other 371 retain the shared-failure relation, yielding 0/372. The 1,556 historical passes were not rerun, so no new full-suite rate is inferred.`; +const historicalSection = () => + section( + zh ? "与历史 80.7% 的关系" : "Relation to the historical 80.7%", + historicalScope(), + `${esc(zh ? "原始四引擎报告 · 2026-08-12" : "Original four-engine report · 2026-08-12")}`, + ); +const metricPopulation = () => + zh + ? `全部 ${M.attempts_per_mode} 次调用,成功与失败都计入;平均、P50 和 P95 使用同一组调用。` + : `All ${M.attempts_per_mode} predeclared calls, including failures; Mean, P50 and P95 use the same population.`; +const reportSubtitle = () => + Object.keys(M.fixed_candidates || {}).length + ? zh + ? `比较 ${M.functional_methods.length} 种固定配置在 ${M.task_count} 个历史失败用例上的成功率,并展示独立资源实验。` + : `Compare ${M.functional_methods.length} fixed configurations on ${M.task_count} historical failures, with separate resource experiments.` + : zh + ? `比较 Moli 1.1.4 关闭布局、1.1.8 关闭布局与 1.1.8 开启布局对 ${M.task_count} 个历史失败用例的恢复情况,并配套展示独立资源实验。` + : `Compare recovery of ${M.task_count} historical failures with Moli 1.1.4 layout off, Moli 1.1.8 layout off and Moli 1.1.8 layout on, with a separate resource experiment.`; +const reportVersion = () => + Object.keys(M?.fixed_candidates || {}).length + ? "Moli 1.1.4 / 1.1.8 / 1.1.9" + : "Moli 1.1.4 / 1.1.8"; +const reportTitle = () => + Object.keys(M?.fixed_candidates || {}).length + ? zh + ? `${reportVersion()} · 成功率与资源对比` + : `${reportVersion()} · Compatibility and resources` + : T.title; +const datasetIntro = () => + zh + ? `依据 Moli 0.1.1 原始结果选取全部 372 个失败用例,覆盖 15 类驱动;不使用本轮结果决定入选。` + : `All 372 historical Moli 0.1.1 failures are included across 15 driver types, without selection based on current outcomes.`; +const reproduceIntro = () => + zh + ? `历史失败集恢复测试和独立的 557 题资源实验均为诊断实验,不计入完整 1,928 题正式分数。1.1.8 直接覆盖 372 题;1.1.4 使用唯一差异候选题验证。三种固定配置使用 Moli 1.1.4 / 1.1.8 Linux aarch64 发行版;1.1.9 修复版使用固定的 macOS arm64 debug 二进制,官方版使用发布资产;每个版本的功能与资源实验绑定同一 SHA-256。` + : `The historical-failure recovery check and separate 557-task resource experiment are diagnostic and excluded from the formal 1,928-case score. Moli 1.1.8 directly covers all 372 cases; Moli 1.1.4 uses the sole differential candidate. The three fixed configurations use Moli 1.1.4 / 1.1.8 Linux aarch64 releases. Patched Moli 1.1.9 uses the frozen macOS arm64 debug binary; official 1.1.9 uses the release asset. Functional and resource runs are bound to the same binary hash for each build.`; +const ms = (v) => + v === null || v === undefined + ? "—" + : fmt(v, Math.abs(v) < 10 ? 1 : 0) + " ms"; +const mib = (v) => + v === null || v === undefined ? "—" : fmt(v / 1048576, 2) + " MiB"; +const link = (r) => "#page=" + encodeURIComponent(r); +const route = () => + decodeURIComponent((location.hash.match(/page=([^&]+)/) || [])[1] || "home"); +const section = (title, intro, html, id = "") => + `

${esc(title)}

${intro ? `

${esc(intro)}

` : ""}${html}
`; +const hero = (title, subtitle, links = "") => + `
${esc(reportVersion())} · Lexbench

${esc(title)}

${esc(subtitle)}

${links ? `` : ""}
`; +const table = (heads, rows, klass = "") => + `
${heads.map((x) => ``).join("")}${rows.join("")}
${esc(x)}
`; +const card = (label, value, detail) => + `
${esc(label)}
${value}
${detail}
`; +function best(a, b, direction) { + if (a === null || b === null || a === b) return null; + return direction === "max" ? (a > b ? "off" : "on") : a < b ? "off" : "on"; +} +function metricRow(label, off, on, format, direction = "min", note = "") { + let w = best(off, on, direction); + return `${esc(label)}${note ? `
${esc(note)}
` : ""}${format(off)}${w === "off" ? ` ${esc(direction === "min" ? T.winner : T.higher)}` : ""}${format(on)}${w === "on" ? ` ${esc(direction === "min" ? T.winner : T.higher)}` : ""}`; +} +const signed = (value, digits = 2, suffix = "%") => + `${value >= 0 ? "+" : ""}${fmt(value, digits)}${suffix}`; +function contractCorrectionNotice() { + let c = M.functional_contract_correction; + if (!c) return ""; + return `
${esc(zh ? "修正合同补测" : "Corrected-contract retest")} · ${esc(zh ? `受 Chromium 基线修正影响的 ${c.task_count} 题,已对三种 Moli 配置各重跑 3 次,共 ${c.calls} 次调用;三组均仍为失败,所以下表成功率不变。` : `The ${c.task_count} cases affected by the Chromium baseline correction were rerun three times for each Moli configuration (${c.calls} calls). All three configurations still fail both cases, so the success rates below are unchanged.`)}
`; +} +function functionalMethodSummary() { + if (!Object.keys(M.fixed_candidates || {}).length) return ""; + let rows = M.functional_methods, + total = M.task_count, + max = Math.max(...rows.map((x) => x.final_passed_cases)), + unique = rows.filter((x) => x.final_passed_cases === max).length === 1; + let body = rows.map((row) => { + let policy = + row.policy === "fixed_on" + ? zh + ? "全程开启" + : "Always on" + : zh + ? "全程关闭" + : "Always off"; + let scope = row.inherited_cases + ? `${row.direct_cases} ${zh ? "题实测" : "direct"} + ${row.inherited_cases} ${zh ? "题继承共同失败关系" : "shared failures"}` + : `${row.direct_cases} ${zh ? "题实测" : "direct cases"}`; + let evidence = row.evidence + ? `
` + : ""; + return `${esc(zh ? row.label : row.label_en)}${evidence}${esc(policy)}${esc(scope)}${fmt(row.final_passed_cases)}/${total} (${fmt((row.final_passed_cases / total) * 100, 1)}%)${signed(((row.final_passed_cases - rows[0].final_passed_cases) / total) * 100, 2, zh ? " 个百分点" : " pp")}${fmt(row.physical_calls || (row.id === "114_off" ? 3 : total * 3))}`; + }); + return section( + zh + ? `${rows.length} 种固定配置的成功率` + : `Success rates for ${rows.length} fixed configurations`, + zh + ? `同一 ${total} 题分母,每题三次全部通过才算成功。开启和关闭 layout 分别统计各自的实际结果;资源使用独立的 557 题实验。变化以 1.1.4 关闭 layout 为基准。` + : `The same ${total}-case denominator is used; all three attempts must pass. Layout on and off use their own observed results. Resources come from a separate 557-task experiment. Changes are relative to 1.1.4 layout off.`, + table( + [ + zh ? "方法" : "Method", + zh ? "布局" : "Layout", + zh ? "证据范围" : "Evidence scope", + zh ? "通过用例" : "Passed cases", + zh ? "通过率变化" : "Success-rate change", + zh ? "调用数" : "Calls", + ], + body, + "functional-method-table", + ), + ); +} +function versionSummary() { + let comparison = M.version_comparison, + rows = comparison.configurations; + let maxSuccess = Math.max(...rows.map((row) => row.success_rate_pct)), + minPss = Math.min(...rows.map((row) => row.pss_mib)), + minCpu = Math.min(...rows.map((row) => row.cpu_ms)); + let body = rows.map( + (row) => + `${esc(zh ? row.label : row.label_en)}${row.id === comparison.baseline ? `
${esc(zh ? "变化基线 · 差异验证" : "Change baseline · differential check")}
` : ""}${fmt(row.passed_cases)}/${fmt(row.total_cases)} (${fmt(row.success_rate_pct, 1)}%)${signed(row.success_change_pp, 1, zh ? " 个百分点" : " pp")}${fmt(row.pss_mib, 2)} MiB${signed(row.pss_change_pct, 2)}${fmt(row.cpu_ms, 2)} ms${signed(row.cpu_change_pct, 2)}`, + ); + let summary = table( + [ + zh ? "配置" : "Configuration", + zh ? "通过用例" : "Passed cases", + zh ? "通过率变化(相对 1.1.4)" : "Success-rate change vs. 1.1.4", + zh ? "峰值 PSS 中位数" : "Median peak PSS", + zh ? "PSS 变化(相对 1.1.4)" : "PSS change vs. 1.1.4", + zh ? "平均 CPU 时间 / 次" : "Mean CPU time / call", + zh ? "CPU 变化(相对 1.1.4)" : "CPU change vs. 1.1.4", + ], + body, + "version-summary-table", + ); + let population = zh + ? `纵轴使用同一组 372 个历史失败用例。1.1.8 两种模式直接各跑 372 题 × 3 次;1.1.4 对 1.1.8 关闭布局唯一通过的候选题跑三次,该题三次均失败,其余 371 题沿用两版本共同失败关系,因此为 0/372。横轴资源来自独立的 557 题 × 5 次实验;图表使用运行前冻结的 ${comparison.resource_population.chart_calls} 个任务-执行样本(${comparison.resource_population.chart_tasks} 题),采样间隔 ${comparison.resource_population.sample_interval_ms} ms。表格和图中的百分比变化均以 1.1.4 关闭 layout 为基准。` + : `The vertical axis uses the same set of 372 historical failures. Both 1.1.8 modes directly ran 372 cases × 3; 1.1.4 ran the sole case passed by layout-off 1.1.8 three times, failed all three, and retains the shared-failure relation for the other 371, yielding 0/372. Horizontal resources come from a separate 557-task × 5-call experiment; the chart uses ${comparison.resource_population.chart_calls} pre-frozen task-attempt samples (${comparison.resource_population.chart_tasks} tasks) at ${comparison.resource_population.sample_interval_ms} ms intervals. Percentage changes in the table and chart use 1.1.4 layout off as baseline.`; + let note = zh + ? `原图标注的 71 MiB 没有随 PR #535 提供对应执行记录;按可复现公开流程,本轮 1.1.4 测得 ${fmt(rows[0].pss_mib, 2)} MiB。CPU 是进程树用户态与内核态时间之和,不是墙钟耗时或 CPU 利用率。` + : `The published 71 MiB label has no matching execution record attached to PR #535; the reproducible public procedure measures ${fmt(rows[0].pss_mib, 2)} MiB for 1.1.4 here. CPU is process-tree user plus system time, not wall time or utilization.`; + let chart = zh + ? "moli-version-success-resources-zh.svg" + : "moli-version-success-resources-en.svg"; + return `
${contractCorrectionNotice()}${summary}
${esc(zh ? `${rows.length} 种 Moli 配置在 372 题成功率、峰值 PSS 和 CPU 时间上的对比图` : `${rows.length} Moli configurations compared by 372-case success rate, peak PSS and CPU time`)}
${esc(population)}

${esc(note)} ${esc(zh ? "下载机器可读数据" : "Download machine-readable data")}

`; +} +function macosResourceMethods() { + let result = []; + for (let [key, layouts] of [ + ["macos_resource", ["off", "on"]], + ["official_resource", ["on"]], + ]) { + let resource = M[key]; + if (!resource) continue; + for (let layout of layouts) { + let id = + key === "official_resource" ? "119_official_on" : `119_${layout}`, + method = M.functional_methods.find((row) => row.id === id); + result.push({ + id, + label: zh ? method.label : method.label_en, + config: resource.summary.configurations[layout], + resource, + }); + } + } + return result; +} +function candidateResourceSection() { + let methods = macosResourceMethods(); + if (!methods.length) return ""; + let baseline = methods.find((x) => x.id === M.macos_comparison.baseline), + scopes = [ + [ + "all_predeclared_calls", + zh ? "557 题全部调用" : "All calls on 557 tasks", + 2785, + ], + [ + "frozen_historical_common_pass_calls", + zh + ? "原图口径的冻结样本:209 题" + : "Frozen legacy-aligned sample: 209 tasks", + 1045, + ], + ]; + let specs = [ + ["rss_peak_mib", "mean", zh ? "峰值 RSS 均值" : "Peak RSS mean", "MiB"], + ["rss_peak_mib", "p50", zh ? "峰值 RSS P50" : "峰值 RSS P50", "MiB"], + ["rss_peak_mib", "p95", zh ? "峰值 RSS P95" : "峰值 RSS P95", "MiB"], + ["cpu_time_ms", "mean", zh ? "CPU 均值" : "CPU mean", "ms"], + ["cpu_time_ms", "p50", zh ? "CPU P50" : "CPU P50", "ms"], + ["cpu_time_ms", "p95", zh ? "CPU P95" : "CPU P95", "ms"], + ]; + let tables = scopes.map(([scope, title, calls]) => { + let minFor = (metric, stat) => + Math.min(...methods.map((x) => x.config.metrics[scope][metric][stat])); + let unique = (metric, stat, value) => + value === minFor(metric, stat) && + methods.filter((x) => x.config.metrics[scope][metric][stat] === value) + .length === 1; + let leader = (metric, stat) => { + let winners = methods.filter( + (x) => x.config.metrics[scope][metric][stat] === minFor(metric, stat), + ); + return winners.length === 1 ? winners[0].label : zh ? "并列" : "Tie"; + }; + let rows = methods.map((item) => { + let m = item.config.metrics[scope], + b = baseline.config.metrics[scope]; + return `${esc(item.label)}${fmt(calls)}${specs.map(([metric, stat, label, unit]) => `${fmt(m[metric][stat], 2)} ${unit}`).join("")}${signed((m.rss_peak_mib.p50 / b.rss_peak_mib.p50 - 1) * 100, 2)}${signed((m.cpu_time_ms.mean / b.cpu_time_ms.mean - 1) * 100, 2)}`; + }); + return ( + `

${esc(title)}

${esc(zh ? `峰值 RSS P50 最低:${leader("rss_peak_mib", "p50")};单次 CPU 均值最低:${leader("cpu_time_ms", "mean")}。资源最低与通过率最高分别判断。` : `Lowest peak 峰值 RSS P50: ${leader("rss_peak_mib", "p50")}; lowest mean CPU per call: ${leader("cpu_time_ms", "mean")}. Resource minima and task success are evaluated separately.`)}

` + + table( + [ + zh ? "方法" : "Method", + zh ? "调用数" : "Calls", + ...specs.map((x) => x[2]), + zh ? "峰值 RSS P50 变化" : "峰值 RSS P50 change", + zh ? "CPU 均值变化" : "CPU mean change", + ], + rows, + "candidate-resource-table", + ) + ); + }); + let chart = zh + ? "moli-macos-success-resources-zh.svg" + : "moli-macos-success-resources-en.svg"; + let intro = zh + ? `资源实验与 372 题成功率测试分开:每个配置固定 layout,557 题各执行 5 次。P50 是中位数,P95 是第 95 百分位;每组统计包含同一批成功与失败调用。变化基准:${baseline.label}。macOS 测量进程树 RSS;历史 Linux PSS 另表展示。` + : `Resources are measured separately from success on 372 cases: each configuration fixes layout and runs 557 tasks five times. P50 is the median and P95 the 95th percentile; every metric in a scope includes the same passing and failing calls. Change baseline: ${baseline.label}. macOS measures process-tree RSS; historical Linux PSS is shown separately.`; + let evidence = methods + .filter((x, i, a) => a.findIndex((y) => y.resource === x.resource) === i) + .map( + (x) => + ``, + ) + .join(" "); + return section( + zh + ? "Moli 1.1.9:成功率、RSS 与 CPU" + : "Moli 1.1.9: success rate, RSS and CPU", + intro, + tables.join("") + + `
${esc(zh ?
${esc(zh ? `纵轴为 372 题通过率,横轴使用运行前冻结的 209 题、1,045 次调用;括号内百分比相对 ${baseline.label}。` : `Success rates use 372 cases; resource axes use 1,045 calls on 209 tasks frozen before execution. Parenthesized changes are relative to ${baseline.label}.`)}

${esc(zh ? "修复版使用提供的 debug 二进制,官方版使用发布资产。两者资源差异同时包含代码与构建配置差异。CPU 指进程树用户态与内核态时间之和。" : "The patched build uses the supplied debug binary; the official build uses the release asset. Their resource differences include both code and build configuration. CPU is the sum of process-tree user and system time.")}

${evidence}
`, + ); +} +function resourceGroups() { + let off = M.metrics.off.profile, + on = M.metrics.on.profile, + rx = M.network_rx, + cold = M.cold_start; + let cpu = table( + [zh ? "CPU 指标" : "CPU metric", T.modes.off, T.modes.on], + [ + metricRow( + zh ? "单次 CPU 均值" : "Mean per-call CPU", + off.cpu_ms_all.mean, + on.cpu_ms_all.mean, + ms, + ), + metricRow( + zh ? "累计 CPU 时间" : "Total CPU time", + off.cpu_ms_all.sum, + on.cpu_ms_all.sum, + (v) => fmt(v / 1000, 2) + " s", + ), + metricRow( + zh ? "单次 CPU P50" : "Per-call CPU P50", + off.cpu_ms_all.p50, + on.cpu_ms_all.p50, + ms, + ), + metricRow( + zh ? "单次 CPU P95" : "Per-call CPU P95", + off.cpu_ms_all.p95, + on.cpu_ms_all.p95, + ms, + ), + ], + ); + let memory = table( + [zh ? "内存指标" : "Memory metric", T.modes.off, T.modes.on], + [ + metricRow( + zh ? "观测 PSS 最大值均值" : "Mean observed PSS maximum", + off.pss_peak_mib_all.mean, + on.pss_peak_mib_all.mean, + (v) => fmt(v, 2) + " MiB", + ), + metricRow( + zh ? "观测 PSS 最大值 P50" : "Observed PSS maximum P50", + off.pss_peak_mib_all.p50, + on.pss_peak_mib_all.p50, + (v) => fmt(v, 2) + " MiB", + ), + metricRow( + zh ? "观测 PSS 最大值 P95" : "Observed PSS maximum P95", + off.pss_peak_mib_all.p95, + on.pss_peak_mib_all.p95, + (v) => fmt(v, 2) + " MiB", + ), + metricRow( + zh ? "PSS 增量 P50" : "PSS increase P50", + off.pss_delta_mib_all.p50, + on.pss_delta_mib_all.p50, + (v) => fmt(v, 2) + " MiB", + ), + ], + ); + let network = table( + [ + zh ? "站点应用层流量" : "Fixture application traffic", + T.modes.off, + T.modes.on, + ], + [ + metricRow( + zh ? "下行总量" : "Total downlink", + off.fixture_tx_bytes_all.sum, + on.fixture_tx_bytes_all.sum, + (v) => fmt(v) + " B", + ), + metricRow( + zh ? "下行 P50" : "Downlink P50", + off.fixture_tx_bytes_all.p50, + on.fixture_tx_bytes_all.p50, + (v) => fmt(v) + " B", + ), + metricRow( + zh ? "上行总量" : "Total uplink", + rx.off.total_bytes, + rx.on.total_bytes, + (v) => fmt(v) + " B", + ), + metricRow( + zh ? "上行 P50" : "Uplink P50", + rx.off.p50_bytes, + rx.on.p50_bytes, + (v) => fmt(v) + " B", + ), + ], + ); + let startup = table( + [ + zh + ? `冷启动指标 · 关闭 ${M.cold_start.off.n} / 开启 ${M.cold_start.on.n} 次` + : `Cold-start metric · off ${M.cold_start.off.n} / on ${M.cold_start.on.n}`, + T.modes.off, + T.modes.on, + ], + [ + metricRow( + zh ? "就绪时间 P50" : "Ready time P50", + cold.off.ready_ms.p50, + cold.on.ready_ms.p50, + ms, + ), + metricRow( + zh ? "启动 CPU P50" : "Launch CPU P50", + cold.off.launch_cpu_ms.p50, + cold.on.launch_cpu_ms.p50, + ms, + ), + metricRow( + zh ? "启动观测 PSS P50" : "Launch observed PSS P50", + cold.off.launch_pss_bytes.p50, + cold.on.launch_pss_bytes.p50, + mib, + ), + ], + ); + let leaderOf = (a, b) => { + let winner = best(a, b, "min"); + return winner ? T.modes[winner] : zh ? "持平" : "tie"; + }; + let leader = `
${esc(zh ? "采样执行中的资源数值" : "Observed profiled resource values")} · ${esc(zh ? `全部调用 CPU:${leaderOf(off.cpu_ms_all.sum, on.cpu_ms_all.sum)};观测 PSS 最大值 P50:${leaderOf(off.pss_peak_mib_all.p50, on.pss_peak_mib_all.p50)};站点下行:${leaderOf(off.fixture_tx_bytes_all.sum, on.fixture_tx_bytes_all.sum)}。这些是采样执行的观测值;主耗时采用无采样轮。` : `All-call CPU: ${leaderOf(off.cpu_ms_all.sum, on.cpu_ms_all.sum)}; observed PSS maximum P50: ${leaderOf(off.pss_peak_mib_all.p50, on.pss_peak_mib_all.p50)}; fixture downlink: ${leaderOf(off.fixture_tx_bytes_all.sum, on.fixture_tx_bytes_all.sum)}. These are profiled observations; primary duration uses unprofiled calls.`)}
`; + return ( + leader + + `

${esc(zh ? "CPU 与计算" : "CPU and computation")}

${cpu}

${esc(zh ? "内存" : "Memory")}

${memory}

${esc(zh ? "网络流量" : "Network traffic")}

${network}

${esc(zh ? "冷启动" : "Cold start")}

${startup}
` + ); +} +function pairStatus(c) { + let a = c.off_passes === M.protocol.k_runs, + b = c.on_passes === M.protocol.k_runs; + return a && b ? "bothPass" : b ? "gain" : a ? "loss" : "bothFail"; +} +function statusChip(s) { + return `${esc(s === "pass" ? T.pass : T.fail)}`; +} +function simpleCard(label, value, detail) { + return card(label, `${value}`, esc(detail)); +} +function home() { + let a = M.metrics.off, + b = M.metrics.on; + let off = a.baseline, + on = b.baseline; + let common = M.common_pass.count; + let core = table( + [zh ? "指标" : "Metric", T.modes.off, T.modes.on], + [ + metricRow( + zh ? "通过用例" : "Passed cases", + M.case_outcomes.off, + M.case_outcomes.on, + (v) => + `${fmt(v)}/${M.task_count} (${fmt((v / M.task_count) * 100, 1)}%)`, + "max", + ), + metricRow( + zh ? "累计任务耗时" : "Total task time", + off.duration_ms_all.sum, + on.duration_ms_all.sum, + (v) => fmt(v / 1000, 2) + " s", + ), + metricRow( + zh ? "平均耗时" : "Mean duration", + off.duration_ms_all.mean, + on.duration_ms_all.mean, + ms, + ), + metricRow( + zh ? "P50 耗时" : "P50 duration", + off.duration_ms_all.p50, + on.duration_ms_all.p50, + ms, + ), + metricRow( + zh ? "P95 耗时" : "P95 duration", + off.duration_ms_all.p95, + on.duration_ms_all.p95, + ms, + ), + ], + "core-table", + ); + let commonRows = table( + [zh ? "共同成功的同题指标" : "Same-task metric", T.modes.off, T.modes.on], + [ + metricRow( + zh ? "累计 CPU" : "Total CPU", + M.common_pass.cpu_total_ms.off, + M.common_pass.cpu_total_ms.on, + ms, + ), + metricRow( + zh ? "结束 PSS 均值" : "Mean ending PSS", + M.common_pass.pss_end_mean_bytes.off, + M.common_pass.pss_end_mean_bytes.on, + mib, + ), + metricRow( + zh ? "站点下行量" : "Fixture downlink", + M.common_pass.fixture_tx_total_bytes.off, + M.common_pass.fixture_tx_total_bytes.on, + (v) => fmt(v) + " B", + ), + ], + ); + return ( + (M.host_context.concurrent_test_observed_at_start + ? `
${esc(zh ? "本轮与同机其他测试并行,耗时和资源代表共享宿主机条件;具体观测见核验记录。" : "Other tests were active on the same host. Duration and resource values reflect shared-host conditions; see Verification for observations.")}
` + : "") + + hero( + reportTitle(), + reportSubtitle(), + `${esc(T.start)}${esc(T.method)}`, + ) + + functionalMethodSummary() + + section( + zh + ? "历史 Linux 配置:成功率与资源" + : "Historical Linux configurations: success and resources", + zh + ? "以下三个配置使用 Linux PSS。1.1.9 的 macOS RSS/CPU 另表展示;成功率均覆盖同一 372 个历史失败用例。" + : "These three configurations use Linux PSS. Moli 1.1.9 macOS RSS/CPU is shown separately; success rates cover the same 372 historical failures.", + versionSummary(), + ) + + candidateResourceSection() + + section( + zh ? "1.1.8 布局模式核心结果" : "Moli 1.1.8 layout-mode results", + casePopulation() + " " + metricPopulation(), + core, + ) + + section( + zh ? "1.1.8 的 CPU、内存与网络" : "Moli 1.1.8 CPU, memory and network", + zh + ? `同一 ${M.attempts_per_mode} 次调用。绿色仅标识同一指标中较低的原始数值,不代表统计显著性或整体优胜。` + : `The same ${M.attempts_per_mode} calls. Green marks the lower raw value for the same metric, not statistical significance or overall leadership.`, + resourceGroups(), + ) + + section( + zh ? "各模式成功调用耗时" : "Duration on each mode’s accepted calls", + zh + ? "每种模式仅统计自身通过的调用,任务范围不同;平均、P50、P95 使用表头标出的同一分母。" + : "Each mode includes only its own accepted calls, with different task coverage. Mean, P50 and P95 share the population shown in each column heading.", + successfulDuration(), + ) + + section( + zh ? "共同成功任务的条件成本" : "Conditional cost on shared successes", + `${common}/${M.attempts_per_mode} ${zh ? "个同题同次配对在两种模式、无采样和采样四轮中均通过。这个诊断子集不决定任务入选或整体排行。" : "paired calls passed all four baseline and profiled rounds. This diagnostic subset does not select tasks or determine an overall ranking."}`, + commonRows, + ) + + section( + zh ? "任务类别概览" : "Task families", + T.methodLimit + " " + casePopulation(), + strataTable(), + ) + ); +} +function successfulDuration() { + let a = M.metrics.off.baseline, + b = M.metrics.on.baseline; + return table( + [ + zh ? "成功调用耗时" : "Accepted-call duration", + `${T.modes.off} · n=${a.passes}`, + `${T.modes.on} · n=${b.passes}`, + ], + [ + ["mean", zh ? "成功调用平均耗时" : "Mean accepted-call duration"], + ["p50", zh ? "成功调用 P50 耗时" : "Accepted-call P50 duration"], + ["p95", zh ? "成功调用 P95 耗时" : "Accepted-call P95 duration"], + ].map(([key, label]) => + metricRow(label, a.duration_ms_pass[key], b.duration_ms_pass[key], ms), + ), + ); +} +function strataTable() { + let rows = M.strata.map((s) => { + let a = M.cases.filter((c) => c.stratum === s), + off = a.filter((c) => c.off_passes === M.protocol.k_runs).length, + on = a.filter((c) => c.on_passes === M.protocol.k_runs).length, + total = a.length; + return `${esc(T.strata[s] || s)}
${a.length} ${zh ? "题" : "tasks"}
${off}/${total}${on}/${total}
`; + }); + return table( + [ + zh ? "任务类别" : "Family", + T.modes.off, + T.modes.on, + zh ? "开布局通过占比" : "Layout-on pass share", + ], + rows, + ); +} +function inventory(kind) { + let title = + kind === "dataset" + ? T.nav.dataset + : kind === "analysis" + ? T.nav.analysis + : T.nav.results; + let intro = + kind === "dataset" + ? datasetIntro() + : kind === "analysis" + ? T.analysisIntro + : population(); + let filters = `
`; + return ( + hero(title, intro) + + section( + zh ? "查找与筛选" : "Find and filter", + "", + filters + `
`, + ) + + (kind === "dataset" + ? section( + zh ? "选择规则" : "Selection rule", + T.methodLimit, + `

${esc(zh ? "选取历史 1,928 题中未能三次全部通过的全部 372 题。保留 Chrome 历史失败的题目;Chrome 的结果不作为排除依据。两个布局组使用同一组冻结任务与验收规则。" : M.selection)}

SHA-256: ${esc(M.manifest_sha256)}

`, + ) + : "") + ); +} +function failureSummary(c) { + let lines = []; + for (let mode of ["off", "on"]) { + for (let detail of c[mode + "_fail_details"] || []) { + lines.push( + ``, + ); + } + } + return lines.length + ? `
${lines.join("")}
` + : "—"; +} +function renderInventory() { + let dataset = route() === "dataset"; + let q = (document.getElementById("query")?.value || "").toLowerCase(), + s = document.getElementById("stratum")?.value || "", + r = document.getElementById("relation")?.value || ""; + let rows = M.cases.filter( + (c) => + (!q || + ( + c.id + + " " + + c.title + + " " + + c.subset + + " " + + (c.off_fail_details || []).join(" ") + + " " + + (c.on_fail_details || []).join(" ") + ) + .toLowerCase() + .includes(q)) && + (!s || c.stratum === s) && + (!r || + (r === "failure" ? pairStatus(c) !== "bothPass" : pairStatus(c) === r)), + ); + document.getElementById("count").textContent = T.resultCount + .replace("{n}", rows.length) + .replace("{total}", M.cases.length); + if (dataset) { + document.getElementById("relation").closest("label").hidden = true; + document.getElementById("inventory-table").innerHTML = table( + [T.task, T.stratum, zh ? "子集" : "Subset", T.rawContract], + rows.map( + (c) => + `${esc(c.title)}
${esc(c.id)}
${esc(T.strata[c.stratum] || c.stratum)}${esc(c.subset)}${esc(T.open)}`, + ), + "inventory", + ); + return; + } + document.getElementById("inventory-table").innerHTML = rows.length + ? table( + [ + T.task, + T.stratum, + T.modes.off, + T.modes.on, + T.relation, + T.failure, + T.open, + ], + rows.map( + (c) => + `${esc(c.title)}
${esc(c.id)}
${esc(T.strata[c.stratum] || c.stratum)}${caseVerdict(c.off_passes)}${caseVerdict(c.on_passes)}${esc(T[pairStatus(c)])}${failureSummary(c)}${esc(T.modes.off)} · ${esc(T.modes.on)}`, + ), + "inventory", + ) + : "
" + esc(T.noRows) + "
"; +} +function wireInventory() { + let query = new URLSearchParams(location.hash.split("&").slice(1).join("&")); + let initial = query.get("stratum"); + if (initial && M.strata.includes(initial)) + document.getElementById("stratum").value = initial; + for (let id of ["query", "stratum", "relation"]) + document + .getElementById(id) + ?.addEventListener(id === "query" ? "input" : "change", renderInventory); + renderInventory(); +} +const facts = (items) => + `
${items.map(([k, v]) => `
${esc(k)}
${v}
`).join("")}
`; +async function getCase(id) { + if (!M.cases.some((c) => c.id === id)) throw Error("Unknown task"); + let r = await fetch(base + "data/cases/" + id + ".json", { + cache: "no-store", + }); + if (!r.ok) throw Error("Task data unavailable"); + return r.json(); +} +function pairedAttempts(c) { + let rows = Array.from({ length: M.protocol.k_runs }, (_, i) => { + let off = c.modes.off.attempts[i], + on = c.modes.on.attempts[i], + n = i + 1; + let status = (mode, a) => + `${statusChip(a.status)}`; + return `${esc(T.attempt.replace("{n}", n))}${status("off", off)}${status("on", on)}${esc(ms(off.duration_ms))}${esc(ms(on.duration_ms))}${esc(ms(off.resource.cpu_total_ms))}${esc(ms(on.resource.cpu_total_ms))}${esc(mib(off.resource.pss_end_bytes))}${esc(mib(on.resource.pss_end_bytes))}`; + }); + return table( + [ + zh ? "序号" : "Attempt", + zh ? "无布局状态" : "Off status", + zh ? "开布局状态" : "On status", + zh ? "无布局耗时" : "Off duration", + zh ? "开布局耗时" : "On duration", + zh ? "无布局 CPU" : "Off CPU", + zh ? "开布局 CPU" : "On CPU", + zh ? "无布局结束 PSS" : "Off ending PSS", + zh ? "开布局结束 PSS" : "On ending PSS", + ], + rows, + "paired-matrix", + ); +} +async function taskPage(id, contract = false) { + let c = await getCase(id); + let f = facts([ + [zh ? "任务 ID" : "Task ID", `${esc(c.id)}`], + [zh ? "子集" : "Subset", esc(c.subset)], + [ + zh ? "任务定义 SHA-256" : "Task SHA-256", + `${esc(c.task_sha256)}`, + ], + [ + zh ? "协议特性" : "Features", + c.features.map((x) => `${esc(x)}`).join(" ") || + "—", + ], + ]); + let results = table( + [T.mode, zh ? "用例判定" : "Case verdict", T.open], + ["off", "on"].map( + (m) => + `${esc(T.modes[m])}${caseVerdict(c.modes[m].passes)}${esc(T.more)} →`, + ), + ); + return ( + `` + + hero(c.title, c.description) + + (contract + ? "" + : section( + zh ? "同题结果" : "Same-task results", + casePopulation(), + results, + ) + + section( + zh ? "逐次配对" : "Paired attempts", + zh + ? "耗时来自无采样轮;CPU 和结束 PSS 来自同题同次的资源采样轮。点击状态可直达对应调用的证据。" + : "Duration comes from the unprofiled run; CPU and ending PSS come from the matching profiled call. Open a status to inspect that exact call's evidence.", + pairedAttempts(c), + )) + + (contract + ? section( + T.rawContract, + "", + `
${f}

${esc(zh ? "驱动步骤" : "Driver steps")}

${esc(JSON.stringify(c.driver, null, 2))}
`, + ) + + section( + zh ? "验收合同" : "Acceptance contract", + "", + `

${esc(zh ? "场景" : "Scene")}

${esc(JSON.stringify(c.scene, null, 2))}

${esc(zh ? "评分规则" : "Grader")}

${esc(JSON.stringify(c.grader, null, 2))}
`, + ) + : section( + T.rawContract, + "", + `${esc(T.open)} →`, + )) + ); +} +function evidenceButtons(a, mode, id) { + let groups = []; + for (let phase of ["baseline", "profile"]) { + let files = a.evidence[phase] || {}, + phaseName = + phase === "baseline" + ? zh + ? "无采样" + : "Unprofiled" + : zh + ? "资源采样" + : "Profiled"; + for (let [name, info] of Object.entries(files)) + groups.push( + ``, + ); + } + return groups.join("") || `${esc(T.missing)}`; +} +function attemptCard(a, mode, id) { + let r = a.resource || {}, + err = a.failure?.detail || "", + details = `

${esc(zh ? "评分与响应" : "Verdict and response")}

${facts( + [ + [T.status, statusChip(a.status)], + [zh ? "采样轮状态" : "Profiled verdict", statusChip(a.profile_status)], + [T.duration, esc(ms(a.duration_ms))], + [zh ? "响应" : "Answer", `${esc(a.answer || "—")}`], + [T.failure, esc(a.failure?.class || "—")], + ], + )}

${esc(zh ? "Moli 资源" : "Moli resources")}

${facts([ + [T.cpu, esc(ms(r.cpu_total_ms))], + [T.pss, esc(mib(r.pss_end_bytes))], + [ + zh ? "观测 PSS 最大值" : "Observed PSS maximum", + esc(mib(r.pss_peak_bytes)), + ], + [T.traffic, esc(fmt(r.fixture_tx_bytes) + " B")], + [zh ? "采样点" : "Samples", esc(fmt(r.samples_seen))], + ])}
${err ? `
${esc(T.failure)}: ${esc(err)}
` : ""}`; + return `
${esc(T.attempt.replace("{n}", a.ordinal))}${statusChip(a.status)}${esc(ms(a.duration_ms))} · ${esc(ms(r.cpu_total_ms))} CPU
${esc(T.details)}${details}
`; +} +async function resultPage(id, mode) { + if (!["off", "on"].includes(mode)) throw Error("Unknown mode"); + let c = await getCase(id), + x = c.modes[mode], + y = c.modes[mode === "off" ? "on" : "off"]; + let firstFail = x.attempts.find((a) => a.status !== "pass"); + let summary = `
${card(zh ? "用例判定" : "Case verdict", caseVerdict(x.passes), zh ? `${x.passes}/${M.protocol.k_runs} 次执行通过;全部通过才计通过用例` : `${x.passes}/${M.protocol.k_runs} attempts passed; all must pass`)}${card(T.duration, ms(x.attempts.reduce((n, a) => n + a.duration_ms, 0)), zh ? `${M.protocol.k_runs} 次总耗时` : `Total for ${M.protocol.k_runs} calls`)}${card(T.relation, esc(T[pairStatus({ off_passes: c.modes.off.passes, on_passes: c.modes.on.passes })]), zh ? "与另一模式比较" : "Compared with the other mode")}
`; + let locator = firstFail + ? `
${esc(zh ? "失败定位" : "Failure locator")} · ${esc(T.attempt.replace("{n}", firstFail.ordinal))} · ${esc(firstFail.failure.class || T.unavailable)}
${esc(firstFail.failure.detail || T.unavailable)}
` + : `
${esc(zh ? `本模式 ${M.protocol.k_runs} 次调用均通过。` : `All ${M.protocol.k_runs} calls passed in this mode.`)}
`; + return ( + `` + + hero(c.title, `${T.modes[mode]} · ${c.subset}`) + + section(zh ? "结果摘要" : "Result summary", "", summary + locator) + + section( + zh ? "运行标识" : "Run identities", + "", + `
${facts([ + [ + zh ? "无采样轮" : "Unprofiled run", + `${esc(M.runs[mode + "_baseline"].run_id)}`, + ], + [ + zh ? "资源采样轮" : "Profiled run", + `${esc(M.runs[mode + "_engine"].run_id)}`, + ], + ])}
`, + ) + + section( + zh + ? `${M.protocol.k_runs} 次调用与证据` + : `${M.protocol.k_runs} calls and evidence`, + zh + ? "每次调用保留无采样的结果与耗时,以及同题同次资源采样值。点击证据可查看原始评分、输出、日志或 CDP 消息。" + : "Each call pairs the unprofiled verdict and duration with the profiled resource observation. Open evidence for exact grader, output, log or CDP data.", + `
${x.attempts.map((a) => attemptCard(a, mode, id)).join("")}
`, + ) + + section( + zh ? "另一模式" : "Other mode", + "", + ``, + ) + ); +} +function methodPage() { + let row = table( + [zh ? "控制项" : "Control", zh ? "设定" : "Setting"], + [ + ...[ + [zh ? "浏览器" : "Browser", "Moli 1.1.8 Linux aarch64"], + [ + zh ? "二进制 SHA-256" : "Binary SHA-256", + `${M.binary_sha256}`, + ], + [ + zh ? "任务" : "Tasks", + `${M.task_count} × ${M.protocol.k_runs} × ${zh ? "2 种模式" : "2 modes"}`, + ], + [ + zh ? "执行" : "Execution", + zh + ? "固定脚本;单工作进程;相同种子和任务顺序" + : "Fixed scripts; one worker; same seed and task order", + ], + [ + zh ? "进程复用" : "Process reuse", + zh + ? "按 runner 规则复用进程,崩溃或任务要求时重建;轮次之间重新启动" + : "Runner-controlled reuse; restart on crashes or task requirements and between rounds", + ], + [ + zh ? "资源" : "Resources", + zh + ? "500 ms 进程树 CPU/PSS,站点应用层流量" + : "500 ms process-tree CPU/PSS and fixture application traffic", + ], + [ + zh ? "冷启动" : "Cold start", + zh + ? "交替 5 次/模式,独立容器;不计入 372 题通过率" + : "Five alternating starts per mode in separate containers; excluded from the 372-case pass rate", + ], + ].map(([a, b]) => `${esc(a)}${b}`), + ], + ); + let versionMethod = + (zh + ? "汇总层先比较三种固定配置。1.1.8 关闭和开启布局直接各跑 372 题 × 3 次;关闭布局只通过 1 题。1.1.4 因此只验证这唯一候选题,三次均失败,其余 371 题沿用共同失败关系,得到 0/372。" + : "The summary first compares three fixed configurations. Both Moli 1.1.8 modes directly ran 372 cases × 3, and layout off passed only one case. Moli 1.1.4 therefore checks that sole candidate; it failed all three attempts, while the other 371 retain the shared-failure relation, yielding 0/372.") + + (Object.keys(M.fixed_candidates || {}).length + ? zh + ? " 1.1.9 修复版分别统计固定关闭与固定开启 layout 的 372 题结果,每题三次。官方 1.1.9 仅测开启 layout。" + : " Patched Moli 1.1.9 reports fixed layout off and on over 372 cases with three attempts each. Official 1.1.9 is measured with layout on only." + : "") + + (zh + ? " 三种固定配置的资源对照使用独立的 557 题 × 5 次 Linux 实验,图中使用运行前冻结的 1,045 个任务-执行样本。1.1.9 使用相同 557 题 × 5 次 macOS 实验,固定关闭与固定开启 layout 各执行一轮资源采样;资源分别对应同一布局配置的单次调用。逐题证据页聚焦 1.1.8 的两种布局配置。" + : " The three fixed configurations use a separate 557-task × 5-call Linux resource experiment and a pre-frozen 1,045 task-attempt sample. Moli 1.1.9 uses the same 557-task × 5-call macOS scope, with one profiled run each for fixed layout off and fixed layout on. Resources represent individual calls in the corresponding fixed-layout configuration. Per-task evidence pages focus on the two Moli 1.1.8 layout configurations."); + return ( + hero(T.nav.method, T.methodIntro) + + section( + Object.keys(M.fixed_candidates || {}).length + ? zh + ? "固定配置汇总口径" + : "Fixed-configuration summary" + : zh + ? "三方法汇总口径" + : "Three-configuration summary method", + versionMethod, + "", + ) + + section( + zh ? "实验流程" : "Protocol flow", + "", + `
flowchart TB
+A["${zh ? `冻结 ${M.task_count} 题、版本与种子` : `Freeze ${M.task_count} tasks, versions and seed`}"] --> B["${zh ? "无采样:先无布局,再开布局" : "Unprofiled: layout off, then on"}"]
+B --> C["${M.resource_window_corrections?.length ? (zh ? "500 ms 采样:两种模式完整重测" : "500 ms profiling: complete reruns of both modes") : zh ? "500 ms 采样:先开布局,再无布局" : "500 ms profiling: layout on, then off"}"]
+C --> D["${zh ? "按任务与调用序号核验;无失败恢复重跑" : "Verify paired task-attempts; no layout recovery retry"}"]
`, + ) + + section(zh ? "共同控制" : "Shared controls", "", row) + + section( + zh ? "指标边界" : "Metric boundaries", + T.metricNote, + `

${esc(zh ? "全部调用" : "All calls")}

${esc(zh ? "成功、失败和超时都保留。它表示 Agent 用户为同一批任务实际等待及消耗的资源。" : "Passes, failures and timeouts stay in the denominator, representing the user's full task cost.")}

${esc(zh ? `共同成功的 ${M.common_pass.count} 次调用` : `The ${M.common_pass.count} calls both modes passed`)}

${esc(zh ? "仅用于隔离模式成本的诊断;不能按结果重新选择要测试的任务。" : "A diagnostic to isolate the mode's cost; it cannot select tasks after outcomes are known.")}

${esc(zh ? "内存采样" : "Memory sampling")}

${esc(zh ? "短任务常只有起点和终点。观测最大值不是未采到的瞬时峰值;结束 PSS 更适合比较常驻内存。" : "Short calls often have only start and end points. The observed maximum is not a high-resolution instantaneous peak; ending PSS compares resident footprint.")}

${esc(zh ? "网络与 CPU" : "Traffic and CPU")}

${esc(zh ? "站点流量是应用层 HTTP/WebSocket 字节;CPU 来自 /proc 进程树,短命子进程可能漏计。驱动与容器启停不计入 Moli 进程指标。" : "Fixture traffic is application-layer HTTP/WebSocket bytes; CPU uses the /proc process tree and may miss short-lived child processes. Harness and container startup are excluded from Moli process metrics.")}

`, + ) + ); +} +function costSection() { + let rows = M.task_cost + .slice(0, 3) + .map( + (c) => + `${esc(c.id)}${caseVerdict(c.off_passes)} → ${caseVerdict(c.on_passes)}${fmt(c.off_duration_ms / 1000, 2)} → ${fmt(c.on_duration_ms / 1000, 2)} s${fmt((c.off_duration_ms - c.on_duration_ms) / 1000, 2)} s${fmt((c.off_cpu_ms - c.on_cpu_ms) / 1000, 2)} s`, + ); + let total = + M.metrics.off.baseline.duration_ms_all.sum - + M.metrics.on.baseline.duration_ms_all.sum, + top = M.task_cost + .slice(0, 3) + .reduce((n, c) => n + c.off_duration_ms - c.on_duration_ms, 0), + share = total === 0 ? "—" : fmt((top / total) * 100, 1); + return section( + zh ? "耗时下降来自哪些任务" : "Where the time reduction came from", + zh + ? `以下三题贡献净耗时变化的 ${share}%。正值表示开启布局后耗时下降;负值表示增加。CPU 差值来自资源采样轮,耗时差值来自无采样轮。` + : `These three tasks account for ${share}% of the net duration change. Positive differences mean lower duration with layout; negative values mean higher duration. CPU differences use profiled calls and duration differences use unprofiled calls.`, + table( + [ + T.task, + zh ? "用例判定" : "Case verdict", + zh + ? `${M.protocol.k_runs} 次总耗时` + : `${M.protocol.k_runs}-call duration`, + zh ? "耗时减少" : "Time reduction", + zh ? "CPU 减少" : "CPU reduction", + ], + rows, + "cost-contributors", + ), + ); +} +function fixedRelations() { + let ids = Object.keys(M.fixed_candidates || {}), + pairs = [ + [ + "119_off", + "119_on", + zh + ? "同一修复版:开启 layout 的变化" + : "Same patched build: enabling layout", + ], + [ + "119_official_on", + "119_on", + zh + ? "同为开启 layout:修复版与官方版" + : "Layout on: patched vs. official", + ], + ]; + return pairs + .filter(([a, b]) => ids.includes(a) && ids.includes(b)) + .map(([a, b, label]) => { + let counts = { gain: 0, loss: 0, bothPass: 0, bothFail: 0 }; + for (let c of M.fixed_case_outcomes) { + let x = c.passes[a] === 3, + y = c.passes[b] === 3; + counts[x && y ? "bothPass" : y ? "gain" : x ? "loss" : "bothFail"]++; + } + return { a, b, label, counts }; + }); +} +function fixedComparisonSection() { + let pairs = fixedRelations(); + if (!pairs.length) return ""; + let rows = pairs.map( + (p) => + `${esc(p.label)}${p.counts.gain}${p.counts.loss}${p.counts.bothPass}${p.counts.bothFail}`, + ); + return section( + zh ? "布局变化与版本变化" : "Layout changes and version changes", + zh + ? "同一修复版的开关对照用于判断布局变化;固定开启 layout 的官方版与修复版对照用于定位版本间变化。下表保留新增通过和退步,不能只看净增加。" + : "Compare layout off/on within the patched build to measure layout changes. Compare the official and patched builds with layout on to locate version differences. Gains and losses are both retained.", + table( + [ + zh ? "对照" : "Comparison", + zh ? "新增通过" : "Gained", + zh ? "退步" : "Lost", + zh ? "均通过" : "Both pass", + zh ? "均失败" : "Both fail", + ], + rows, + ) + + `
`, + ); +} +function wireFixedExplorer() { + let target = document.getElementById("fixed-explorer"); + if (!target) return; + let pairs = fixedRelations(), + methods = M.functional_methods.filter((x) => M.fixed_candidates[x.id]); + let draw = () => { + let p = pairs[Number(document.getElementById("fixed-relation").value)], + filter = document.getElementById("fixed-outcome").value, + items = M.fixed_case_outcomes.filter((c) => { + let a = c.passes[p.a] === 3, + b = c.passes[p.b] === 3, + key = a && b ? "bothPass" : b ? "gain" : a ? "loss" : "bothFail"; + return filter === "all" || key === filter; + }); + target.innerHTML = + `

${items.length} / ${M.task_count}

` + + table( + [T.task, ...methods.map((m) => (zh ? m.label : m.label_en))], + items.map( + (c) => + `${esc(c.id)}${methods.map((m) => `${c.passes[m.id]}/3 · ${esc(c.passes[m.id] === 3 ? T.pass : T.fail)}`).join("")}`, + ), + "fixed-explorer-table", + ); + }; + document.getElementById("fixed-relation").addEventListener("change", draw); + document.getElementById("fixed-outcome").addEventListener("change", draw); + draw(); +} +async function fixedCasePage(id) { + if (!M.fixed_case_outcomes.some((c) => c.id === id)) + throw Error("Unknown case"); + let response = await fetch( + base + "data/fixed-cases/" + encodeURIComponent(id) + ".json", + ); + if (!response.ok) throw Error("Case evidence unavailable"); + let c = await response.json(), + methods = M.functional_methods.filter((x) => c.methods[x.id]); + let summary = table( + [ + zh ? "方法" : "Method", + zh ? "通过次数" : "Passed attempts", + zh ? "用例判定" : "Case verdict", + ], + methods.map( + (m) => + `${esc(zh ? m.label : m.label_en)}${c.methods[m.id].passes}/3${esc(c.methods[m.id].passes === 3 ? T.pass : T.fail)}`, + ), + ); + let details = methods + .map((m) => + section( + zh ? m.label : m.label_en, + `SHA-256: ${m.moli_sha256}`, + c.methods[m.id].attempts + .map((a) => { + let evidence = Object.entries(a.evidence) + .map( + ([name, e]) => + ``, + ) + .join(" "); + return `
${esc(T.attempt.replace("{n}", a.ordinal))} · ${esc(a.status === "pass" ? T.pass : T.fail)}

${esc(a.answer || T.unavailable)}

${a.status !== "pass" ? `
${esc(a.failure.detail || a.failure.original_detail || T.unavailable)}

${esc(a.failure.class || T.unavailable)} · ${esc(T.noHuman)}

` : ""}
`; + }) + .join(""), + ), + ) + .join(""); + return ( + `` + + hero(c.title, id) + + section(zh ? "结果摘要" : "Result summary", "", summary) + + details + + section( + zh ? "任务与历史结果" : "Task and historical results", + "", + `${esc(zh ? "查看任务定义与 1.1.8 对照" : "View task definition and 1.1.8 comparison")}`, + ) + ); +} +function analysisPage() { + let p = M.case_outcomes.paired, + gains = M.cases.filter((c) => pairStatus(c) === "gain"), + losses = M.cases.filter((c) => pairStatus(c) === "loss"); + let changed = (items) => + table( + [T.task, T.stratum, T.modes.off, T.modes.on], + items.map( + (c) => + `${esc(c.id)}${esc(T.strata[c.stratum] || c.stratum)}${caseVerdict(c.off_passes)}${caseVerdict(c.on_passes)}`, + ), + ); + return ( + hero(T.nav.analysis, T.analysisIntro) + + fixedComparisonSection() + + section( + zh ? "用例通过关系" : "Case outcomes", + casePopulation(), + `
${[ + ["gain", p.off_fail_on_pass], + ["loss", p.off_pass_on_fail], + ["bothPass", p.both_pass], + ["bothFail", p.both_fail], + ] + .map(([key, n]) => card(T[key], `${n} / ${M.task_count}`, "")) + .join("")}
`, + ) + + section(zh ? "新增通过的用例" : "Cases gained", "", changed(gains)) + + section(zh ? "退步的用例" : "Cases lost", "", changed(losses)) + + section( + zh ? "失败证据" : "Failure evidence", + "", + ``, + ) + + costSection() + + section(zh ? "任务类型比较" : "By task family", "", strataTable()) + ); +} +function hostLoadTable() { + if (!M.host_context.rounds) return ""; + let labels = zh + ? { + off_baseline: "无布局 · 无采样", + on_baseline: "开布局 · 无采样", + off_engine: "无布局 · 资源采样", + on_engine: "开布局 · 资源采样", + } + : { + off_baseline: "Layout off · unprofiled", + on_baseline: "Layout on · unprofiled", + off_engine: "Layout off · profiled", + on_engine: "Layout on · profiled", + }; + return section( + zh ? "宿主机实际负载" : "Observed host load", + zh + ? "macOS 每 5 秒记录一次。1 分钟负载包含全部宿主机工作负载;数值不等于 CPU 利用率,也不用于性能排名。" + : "Recorded on macOS every five seconds. One-minute load includes all host workloads, is not CPU utilization, and is not ranked.", + table( + [ + zh ? "运行条件" : "Run condition", + zh ? "观测点数" : "Samples", + zh ? "1 分钟负载中位数" : "Median one-minute load", + zh ? "1 分钟负载最大值" : "Maximum one-minute load", + ], + Object.entries(M.host_context.rounds).map( + ([key, x]) => + `${esc(labels[key])}${x.samples}${fmt(x.macos_load1_median, 2)}${fmt(x.macos_load1_max, 2)}`, + ), + ), + ); +} +function correctionSection() { + return (M.resource_window_corrections || []) + .map((c) => + section( + `${T.modes[c.mode]} · ${zh ? "资源校准更正" : "Resource calibration correction"}`, + zh + ? `原 ${c.calls} 次资源测量的耗时变化中位数超过 10% 校准阈值,保留为诊断证据,并以同任务、同种子、同二进制的完整重测替换。成功率与无采样耗时口径保持不变。` + : `The original ${c.calls}-call resource round exceeded the 10% median timing calibration threshold. It remains diagnostic evidence and was replaced by a full rerun with identical tasks, seed and binary. Acceptance and unprofiled duration are unchanged.`, + table( + [ + zh ? "项目" : "Item", + zh ? "原采样轮" : "Original profiled round", + zh ? "完整重测轮" : "Complete replacement", + ], + [ + `${esc(zh ? "运行 ID" : "Run ID")}${esc(c.superseded_run)}${esc(c.replacement_run)}`, + `${esc(zh ? "累计 Moli CPU" : "Total Moli CPU")}${fmt(c.old_cpu_ms / 1000, 2)} s${fmt(c.replacement_cpu_ms / 1000, 2)} s`, + `${esc(zh ? "观测 PSS 最大值均值" : "Mean observed PSS maximum")}${fmt(c.old_pss_observed_max_mean_mib, 2)} MiB${fmt(c.replacement_pss_observed_max_mean_mib, 2)} MiB`, + ], + ) + + ``, + ), + ) + .join(""); +} +function functionalCorrectionSection() { + let c = M.functional_contract_correction; + if (!c) return ""; + return section( + zh + ? "Chromium 基线合同修正后的 Moli 补测" + : "Moli retest after Chromium baseline contract corrections", + zh + ? `两道受影响题在三种现有 Moli 配置下各重跑三次,共 ${c.calls} 次调用。结果均仍为失败,因此 0/372、1/372、255/372 不变。` + : `The two affected cases were rerun three times under each existing Moli configuration (${c.calls} calls). All remain failures, so 0/372, 1/372 and 255/372 are unchanged.`, + `
${facts([ + [ + zh ? "Lexbench 修正提交" : "Lexbench correction commit", + `${esc(c.harness_commit)}`, + ], + [ + zh ? "覆盖" : "Coverage", + `${c.task_count} × ${c.configuration_count} × 3 = ${c.calls}`, + ], + [ + zh ? "成功率变化" : "Success-rate change", + esc(c.success_rates_changed ? (zh ? "有" : "Yes") : zh ? "无" : "None"), + ], + ])}
`, + ); +} +function candidateResourceQuality() { + let methods = macosResourceMethods(); + if (!methods.length) return ""; + let rows = methods.map((item) => { + let m = item.config.metrics.all_predeclared_calls, + h = item.config.quality; + return `${esc(item.label)}${fmt(m.rss_peak_mib.n)}/2,785${fmt(m.cpu_time_ms.n)}/2,785${esc(h.profiled_host.polluted ? (zh ? "未通过" : "Failed") : zh ? "通过" : "Pass")}`; + }); + return section( + zh ? "Moli 1.1.9 资源证据质量" : "Moli 1.1.9 resource evidence quality", + zh + ? "每个固定配置测一轮,核验完整任务矩阵、二进制身份、资源覆盖与宿主机观测。未单独测量采样器带来的耗时影响。" + : "Each fixed configuration has one measured run. Checks cover the complete task matrix, binary identity, resource coverage, and host observations. Profiler overhead was not separately measured.", + table( + [ + zh ? "配置" : "Configuration", + zh ? "RSS 覆盖" : "RSS coverage", + zh ? "CPU 覆盖" : "CPU coverage", + zh ? "宿主机检查" : "Host check", + ], + rows, + ), + ); +} +function reviewPage() { + let q = M.quality; + let rows = ["off", "on"].map( + (m) => + `${esc(T.modes[m])}${M.attempts_per_mode}/${M.attempts_per_mode}${M.metrics[m].baseline.passes} / ${M.metrics[m].profile.passes}${q[m].status_mismatch_count}${q[m].baseline_host.polluted || q[m].engine_host.polluted ? esc(zh ? "有" : "Yes") : esc(zh ? "无" : "No")}${q[m].resource_missing}`, + ); + return ( + hero( + T.nav.review, + zh + ? "完整性、采样前后判定与运行环境分别核验。" + : "Completeness, profiling verdict changes and environment observations are checked separately.", + ) + + functionalCorrectionSection() + + candidateResourceQuality() + + section( + zh ? "机器证据完整性" : "Machine evidence coverage", + "", + table( + [ + T.mode, + zh ? "调用完整" : "Complete calls", + zh ? "无采样 / 采样通过数" : "Unprofiled / profiled passes", + zh ? "采样前后判定变化" : "Verdict changes", + zh ? "容器内环境标记" : "In-container environment flags", + zh ? "资源缺口" : "Missing resources", + ], + rows, + ), + ) + + section( + T.calibration, + zh + ? "与无采样轮逐对比较;时间差包含宿主机负载变化,不能单独解释为采样器开销。主耗时始终采用无采样值。10% 门槛约束 P50,不约束 P95;尾部偏移另列。" + : "Paired differences include changing host conditions and do not isolate profiler overhead. Primary duration always uses unprofiled values. The 10% limit applies to P50, not P95; tail differences are listed separately.", + table( + [ + T.mode, + zh ? "耗时变化 P50" : "Duration change P50", + zh ? "耗时变化 P95" : "Duration change P95", + zh ? "含采集变化 P50" : "Collection-inclusive change P50", + zh ? "含采集变化 P95" : "Collection-inclusive change P95", + zh ? "P50 校准阈值检查" : "P50 calibration threshold check", + ], + ["off", "on"].map( + (m) => + `${esc(T.modes[m])}${fmt(q[m].calibration.median_duration_delta_pct, 2)}%${fmt(q[m].calibration.p95_duration_delta_pct, 2)}%${fmt(q[m].calibration.median_collection_wall_delta_pct, 2)}%${fmt(q[m].calibration.p95_collection_wall_delta_pct, 2)}%${esc(q[m].calibration.acceptable ? (zh ? "通过" : "Pass") : zh ? "未通过,见数据模型" : "Failed; see data model")}`, + ), + ), + ) + + section( + zh ? "宿主机观测范围" : "Host observation scope", + "", + `
${esc(M.host_context.shared_macos_host ? (zh ? "容器运行于共享 macOS 宿主机,共用 CPU 与内存。宿主机负载与容器内遥测分别记录,观测范围见下表。" : "Containers share the macOS host CPU and memory. Host load and in-container telemetry are recorded separately; observed coverage appears below.") : zh ? "本组运行时未发现并行测试。容器内遥测的观测范围为 Docker Linux 环境。" : "No concurrent test was observed for this cohort. In-container telemetry covers the Docker Linux environment.")}
`, + ) + + section( + zh ? "独立复核" : "Independent review", + "", + `
${esc(T.noHuman)} · 0/${M.attempts_per_mode * 4} ${zh ? `次调用经过独立逐项审查。${M.review_coverage.unreviewed_program_passes} 次程序通过结果未作独立复核。` : `calls independently reviewed. ${M.review_coverage.unreviewed_program_passes} program passes have not been independently reviewed.`}
`, + ) + + hostLoadTable() + + correctionSection() + + section( + zh ? "冻结标识" : "Frozen identities", + "", + `
${facts([ + [ + zh ? "任务清单 SHA-256" : "Manifest SHA-256", + `${esc(M.manifest_sha256)}`, + ], + [ + zh ? "Moli 二进制 SHA-256" : "Moli binary SHA-256", + `${esc(M.binary_sha256)}`, + ], + ])}
`, + ) + ); +} +function guidePage() { + let p = M.case_outcomes.paired; + return ( + hero(T.nav.guide, T.guideIntro) + + functionalMethodSummary() + + fixedComparisonSection() + + section( + zh ? "完成任务的变化" : "Changes in completion", + "", + `
${esc(zh ? `按同一组 ${M.task_count} 个用例比较:开启布局新增通过 ${p.off_fail_on_pass} 个用例,${p.off_pass_on_fail} 个用例由通过变为失败。` : `Across the same ${M.task_count} cases, layout gained ${p.off_fail_on_pass} passed cases and lost ${p.off_pass_on_fail}.`)}
`, + ) + + historicalSection() + + candidateResourceSection() + + costSection() + + section( + zh ? "资源分项对照" : "Resource comparison", + zh + ? "全部调用与独立冷启动样本分开统计。每项绿色标记只表示本列原始数值更低。" + : "All calls and the separate cold-start sample are distinct populations. Green marks only the lower raw value in each metric.", + resourceGroups(), + ) + + section( + T.scope, + T.methodLimit, + `
${esc(zh ? `这 ${M.task_count} 题是 Moli 0.1.1 的全部历史失败用例。通过率描述这一失败子集的恢复情况;耗时包括超时与失败等待,不能当作布局计算的纯开销。` : `These ${M.task_count} tasks are all historical Moli 0.1.1 failures. Acceptance describes recovery within this failure subset. Duration includes timeouts and failed waits and does not isolate layout computation overhead.`)}
`, + ) + ); +} +function candidateReproductionSection() { + let methods = macosResourceMethods(); + if (!methods.length) return ""; + let rows = methods.map((item) => { + let run = item.config.provenance.profiled; + return `${esc(item.label)}${esc(run.run_id)}2,785/2,785${esc(run.manifest_sha256.slice(0, 16))}${esc(item.resource.summary.candidate.binary_sha256)}`; + }); + return section( + zh ? "Moli 1.1.9 资源运行身份" : "Moli 1.1.9 resource run identities", + zh + ? "每个固定配置执行 557 题 × 5 次;任务、种子与资源采样协议相同。" + : "Each fixed configuration runs 557 tasks × 5 calls with the same tasks, seed and sampling protocol.", + table( + [ + zh ? "配置" : "Configuration", + zh ? "运行 ID" : "Run ID", + zh ? "覆盖" : "Coverage", + zh ? "清单 SHA-256 前缀" : "Manifest SHA-256 prefix", + zh ? "二进制 SHA-256" : "Binary SHA-256", + ], + rows, + ), + ); +} +function reproducePage() { + let rows = Object.entries(M.runs).map( + ([k, v]) => + `${esc(k)}${esc(v.run_id)}${M.attempts_per_mode}/${M.attempts_per_mode}${esc(v.manifest_sha256.slice(0, 16))}`, + ); + return ( + hero(T.nav.reproduce, reproduceIntro()) + + section( + zh ? "运行身份" : "Run identities", + "", + table( + [ + T.mode, + zh ? "运行 ID" : "Run ID", + zh ? "结果覆盖" : "Coverage", + zh ? "清单哈希前缀" : "Manifest hash prefix", + ], + rows, + ), + ) + + candidateReproductionSection() + + section( + zh ? "复现要点" : "Reproduction controls", + "", + `

${esc(zh ? "使用官方 Moli 1.1.8 Linux aarch64 二进制,核对 SHA-256。固定任务文件、种子、单工作进程、相同任务顺序和 Docker 镜像。两种模式分别执行无采样与 500 ms 采样轮,每题每轮三次,比较采样前后判定。" : "Use official Moli 1.1.8 Linux aarch64, verify SHA-256, and freeze tasks, seed, one-worker order and Docker image. Run each mode unprofiled and with 500 ms profiling, three attempts per case per round, then compare verdicts.")}

${facts( + [ + [ + zh ? "宿主机" : "Host", + esc( + `${M.environment.macos.cpu} · ${M.environment.macos.logical_cpus} logical CPUs · ${M.environment.macos.memory_bytes / 1073741824} GiB`, + ), + ], + [ + zh ? "Linux 虚拟机" : "Linux VM", + esc( + `${M.environment.linux_vm.virtualization} · ${M.environment.linux_vm.cpu_count} vCPU · ${fmt(M.environment.linux_vm.memory_bytes / 1073741824, 2)} GiB · aarch64`, + ), + ], + [ + zh ? "容器镜像 SHA-256" : "Container image SHA-256", + `${esc(M.environment.image_id)}`, + ], + [ + zh ? "Moli SHA-256" : "Moli SHA-256", + `${esc(M.binary_sha256)}`, + ], + [ + zh ? "任务清单 SHA-256" : "Task manifest SHA-256", + `${esc(M.manifest_sha256)}`, + ], + [ + zh ? "评测器源码 SHA-256" : "Runner source SHA-256", + `${esc(M.protocol.runner_sha256)}`, + ], + [ + zh ? "测试站点 SHA-256" : "Fixture tree SHA-256", + `${esc(M.protocol.fixtures_sha256)}`, + ], + [zh ? "随机种子" : "Seed", `${esc(M.protocol.seed)}`], + [ + zh ? "每题调用次数与并发" : "Calls per task and concurrency", + `${M.protocol.k_runs} / ${M.protocol.jobs}`, + ], + ], + )}

${esc(zh ? "下载冻结任务集" : "Download frozen cohort")} · ${esc(zh ? "下载复现脚本" : "Download reproduction script")}

${esc(zh ? "下载报告数据模型" : "Download report data model")}

`, + ) + ); +} +function setNav(page) { + document + .getElementById("menu-toggle") + .setAttribute("aria-label", zh ? "展开或收起导航" : "Toggle navigation"); + document + .getElementById("site-nav") + .setAttribute("aria-label", zh ? "报告导航" : "Report navigation"); + document.getElementById("site-nav").innerHTML = Object.entries(T.nav) + .map( + ([k, v]) => + `${esc(v)}`, + ) + .join(""); + let other = zh ? "en.html" : "index.html"; + document.getElementById("language").href = base + other + location.hash; + document.getElementById("language").textContent = zh ? "EN" : "中文"; + document.querySelector(".skip").textContent = zh + ? "跳到正文" + : "Skip to content"; + document + .getElementById("theme") + .setAttribute("aria-label", zh ? "切换明暗主题" : "Toggle theme"); + document.getElementById("dialog-close").setAttribute("aria-label", T.close); + document.querySelector(".brand small").textContent = zh + ? "/ 版本与布局" + : "/ Versions and layout"; + document.querySelector(".footer span").textContent = zh + ? `${reportVersion()} · 成功率与资源实验` + : `${reportVersion()} · compatibility and resource study`; + document.querySelector(".footer a").textContent = zh + ? "方法与证据" + : "Method & evidence"; +} +async function render() { + let r = route(), + parts = r.split("/"), + page = parts[0]; + delete document.getElementById("main").dataset.route; + if (dialog.open) dialog.close(); + try { + if (!M) { + let resp = await fetch(base + "data/model.json", { cache: "no-store" }); + if (!resp.ok) throw Error("Model unavailable"); + M = await resp.json(); + } + setNav(page); + let html = + page === "home" + ? home() + : ["dataset", "analysis", "results"].includes(page) + ? page === "analysis" + ? analysisPage() + : inventory(page) + : page === "task" + ? await taskPage(parts[1]) + : page === "contract" + ? await taskPage(parts[1], true) + : page === "fixed" + ? await fixedCasePage(parts[1]) + : page === "result" + ? await resultPage(parts[1], parts[2]) + : page === "method" + ? methodPage() + : page === "review" + ? reviewPage() + : page === "guide" + ? guidePage() + : page === "reproduce" + ? reproducePage() + : home(); + document.getElementById("main").innerHTML = html; + wireFixedExplorer(); + if (page === "method" && window.mermaid) { + mermaid.initialize({ + startOnLoad: false, + securityLevel: "strict", + theme: + document.documentElement.dataset.theme === "dark" + ? "dark" + : "default", + }); + await mermaid.run({ querySelector: ".mermaid" }); + } + let caseTitle = M.cases.find((c) => c.id === parts[1])?.title; + document.title = + (caseTitle || T.nav[page] || reportTitle()) + ` · ${reportVersion()}`; + if (["dataset", "results"].includes(page)) wireInventory(); + document.getElementById("site-nav").classList.remove("open"); + document + .getElementById("menu-toggle") + .setAttribute("aria-expanded", "false"); + window.scrollTo(0, 0); + if (page === "result") { + let n = new URLSearchParams( + location.hash.split("&").slice(1).join("&"), + ).get("attempt"); + if (/^[1-5]$/.test(n || "")) { + let key = parts[1] + "-" + parts[2] + "-" + n; + let target = [ + ...document.querySelectorAll("[data-report-detail]"), + ].find((x) => x.dataset.reportDetail === key); + if (target) { + target.querySelector("details").open = true; + target.scrollIntoView({ block: "center" }); + target.querySelector("summary").focus(); + } + } + } + document.getElementById("main").dataset.route = r; + } catch (e) { + document.getElementById("main").innerHTML = hero(T.error, e.message); + } +} + +async function showDiagnosis(button) { + if (!dialog.open) trigger = button; + let id = button.dataset.diagnosis, + mode = button.dataset.mode; + document.getElementById("evidence-title").textContent = + (zh ? "失败诊断" : "Failure diagnosis") + " · " + T.modes[mode]; + document.getElementById("evidence-body").textContent = T.loading; + dialog.showModal(); + try { + let c = await getCase(id), + a = c.modes[mode].attempts.find((x) => x.status !== "pass"); + if (!a) throw Error("No failure in this result"); + document.getElementById("evidence-body").innerHTML = + "

" + + esc(c.title) + + "

" + + facts([ + [T.task, "" + esc(id) + ""], + [T.attempt.replace("{n}", a.ordinal), esc(T.modes[mode])], + [ + zh ? "程序分类" : "Program classification", + esc(a.failure.class || T.unavailable), + ], + [zh ? "独立复核原因" : "Independently reviewed cause", esc(T.noHuman)], + ]) + + '
' + + esc(a.failure.detail || T.unavailable) + + '

' + + esc(zh ? "完整结果与对应调用" : "Full result and exact attempt") + + ' →

"; + } catch (e) { + document.getElementById("evidence-body").textContent = + T.error + ": " + e.message; + } +} +document.addEventListener("click", (e) => { + let b = e.target.closest("[data-diagnosis]"); + if (b) showDiagnosis(b); +}); + +let close = () => { + dialog.close(); + trigger?.focus(); +}; +document.getElementById("dialog-close").addEventListener("click", close); +dialog.addEventListener("close", () => trigger?.focus()); +document.addEventListener("click", async (e) => { + let b = e.target.closest("[data-evidence]"); + if (!b) return; + if (!dialog.open) trigger = b; + let title = b.dataset.title || T.evidence; + document.getElementById("evidence-title").textContent = title; + document.getElementById("evidence-body").innerHTML = + `

SHA-256: ${esc(b.dataset.sha)}

${esc(T.loading)}
`; + dialog.showModal(); + try { + let resp = await fetch(base + b.dataset.evidence, { cache: "no-store" }); + if (!resp.ok) throw Error("Evidence unavailable"); + let raw = await resp.text(); + document.getElementById("evidence-body").innerHTML = + `

SHA-256: ${esc(b.dataset.sha)}

${esc(raw)}

${esc(T.source)} ↗

`; + let field = document.getElementById("evidence-query"), + content = document.getElementById("evidence-text"); + let find = () => { + let needle = field.value, + index = needle ? raw.toLowerCase().indexOf(needle.toLowerCase()) : -1; + content.innerHTML = + index < 0 + ? esc(raw) + : esc(raw.slice(0, index)) + + '' + + esc(raw.slice(index, index + needle.length)) + + "" + + esc(raw.slice(index + needle.length)); + document.getElementById("evidence-matches").textContent = needle + ? index < 0 + ? zh + ? "未找到" + : "No match" + : zh + ? "已定位首处" + : "First match located" + : ""; + content.querySelector("mark")?.scrollIntoView({ block: "center" }); + }; + field.addEventListener("input", find); + if (b.dataset.find && raw.includes(b.dataset.find)) { + field.value = b.dataset.find; + find(); + } + } catch (err) { + document.getElementById("evidence-body").textContent = + T.error + ": " + err.message; + } +}); +document.getElementById("theme").addEventListener("click", () => { + let next = root.dataset.theme === "dark" ? "light" : "dark"; + root.dataset.theme = next; + try { + localStorage.setItem("moli-layout-theme", next); + } catch { + // Sandboxed report viewers may disable storage; theme switching still works. + } + if (route() === "method") render(); +}); +try { + root.dataset.theme = localStorage.getItem("moli-layout-theme") || "light"; +} catch { + root.dataset.theme = "light"; +} +document.getElementById("menu-toggle").addEventListener("click", (e) => { + let nav = document.getElementById("site-nav"), + open = nav.classList.toggle("open"); + e.currentTarget.setAttribute("aria-expanded", String(open)); +}); +window.addEventListener("hashchange", render); +render(); diff --git a/scripts/moli_report/build.py b/scripts/moli_report/build.py new file mode 100644 index 000000000..fa3afdbaa --- /dev/null +++ b/scripts/moli_report/build.py @@ -0,0 +1,1116 @@ +from __future__ import annotations + +import argparse +import collections +import datetime +import hashlib +import json +import os +import pathlib +import re +import shutil +import statistics +import sys + +ROOT = pathlib.Path(os.environ.get("BROWSER_EVAL_DATA_HOME", pathlib.Path.home() / ".browser-eval")) +BENCH_ROOT = pathlib.Path( + os.environ.get("LEXBENCH_REPORT_RUNNER_ROOT", ROOT / "work/moli-1.1.8-failures-linux") +) +sys.path.insert(0, str(BENCH_ROOT)) +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from plot_moli_version_resources import render_chart # noqa: E402 +from runner.resources import duration_calibration # noqa: E402 + +RUNS = ROOT / "runs/moli-1.1.8-failures-linux" +SRC = pathlib.Path(__file__).resolve().parent +OUT = ROOT / "reports/moli-1.1.8-failures-site" +VERSION_RUNS = ROOT / "runs/moli-114-118-memory-repro" +FUNCTIONAL_CORRECTION = ROOT / "runs/moli-method-corrections-20260920" +parser = argparse.ArgumentParser() +parser.add_argument("--cohort", type=pathlib.Path, default=RUNS / "report-cohort.json") +parser.add_argument("--summary", type=pathlib.Path, default=RUNS / "report-runs.json") +parser.add_argument("--source", type=pathlib.Path, default=SRC) +parser.add_argument("--output", type=pathlib.Path, default=OUT) +parser.add_argument( + "--vendor-dir", type=pathlib.Path, default=ROOT / "reports/moli-1.1.8-failures-src" +) +parser.add_argument("--functional-correction", type=pathlib.Path, default=FUNCTIONAL_CORRECTION) +parser.add_argument( + "--fixed-summary", action="append", nargs=2, metavar=("METHOD_ID", "SUMMARY_PATH"), default=[] +) +parser.add_argument("--macos-resource-summary", type=pathlib.Path) +parser.add_argument("--official-resource-summary", type=pathlib.Path) +args = parser.parse_args() +SRC = args.source.resolve() +OUT = args.output.resolve() +FUNCTIONAL_CORRECTION = args.functional_correction.resolve() +cohort = json.loads(args.cohort.read_text()) +summary = json.loads(args.summary.read_text()) +selected = { + x["task_id"]: (group, x["sha256"]) for group, items in cohort["strata"].items() for x in items +} +contract = json.loads((RUNS / "protocol.json").read_text()) +certificate = json.loads((RUNS / "certification.json").read_text()) +assert ( + certificate["protocol_sha256"] + == hashlib.sha256((RUNS / "protocol.json").read_bytes()).hexdigest() +) +for rel, digest in certificate["artifact_sha256"].items(): + path = RUNS / rel + assert ( + path.is_file() + and not path.is_symlink() + and hashlib.sha256(path.read_bytes()).hexdigest() == digest + ) +assert set(selected) == set(contract["task_ids"]) and not contract["try_layout"] +assert {t: h for t, (_, h) in selected.items()} == { + t: v["sha256"] for t, v in contract["tasks"].items() +} +task_count = len(selected) +k_runs = cohort["k_runs"] +call_count = task_count * k_runs +assert task_count == 372 and k_runs == 3 +assert task_count > 0 and k_runs > 0 +label = summary.get("runs") or { + "off_baseline": "m117_layout_off_baseline_init_0918", + "on_baseline": "m117_layout_on_baseline_init_0918", + "off_engine": "m117_layout_off_engine_init_0918", + "on_engine": "m117_layout_on_engine_init_0918", +} +path_re = re.compile(r'/(?:Users|home|private/tmp|tmp|results|work)/[^\s\'"<>]+') +endpoint_re = re.compile(r"(?:(?:https?|wss?)://)?127\.0\.0\.1:\d+") + + +def sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def clean(s: str) -> str: + return path_re.sub("", endpoint_re.sub("", s)) + + +def read_run(name: str): + p = RUNS / label[name] + assert p.is_dir() and not p.is_symlink() + assert all( + not (p / f).is_symlink() + for f in ("run_manifest.json", "results.jsonl", "host_summary.json") + ) + m = json.loads((p / "run_manifest.json").read_text()) + rows = [json.loads(x) for x in (p / "results.jsonl").read_text().splitlines()] + assert m["run_id"] == label[name] + assert ( + len(rows) == call_count + and m["completion_status"] == "completed" + and m["expected_result_rows"] == call_count + ) + assert m["engines"]["moli"]["sha256"] == cohort["moli_sha256"] + assert m["bench_manifest"]["sha256"] == cohort["manifest_sha256"] + assert {x["task_id"]: x["sha256"] for x in m["resolved_tasks"]} == { + t: h for t, (_, h) in selected.items() + } + mode = name.split("_")[0] + prof = name.split("_")[1] + assert m["resource_profile"]["mode"] == prof + assert all(r["engine_provenance"]["layout_enabled"] == (mode == "on") for r in rows) + by = {(r["task_id"], r["attempt"]): r for r in rows} + assert set(by) == {(task, attempt) for task in selected for attempt in range(1, k_runs + 1)} + return p, m, by + + +runs = {name: read_run(name) for name in label} +first_manifest = runs["off_baseline"][1] +protocol = { + "runner_sha256": first_manifest["runner"]["source"]["tree_sha256"], + "fixtures_sha256": first_manifest["runner"]["fixtures"]["tree_sha256"], + "seed": first_manifest["seed"], + "k_runs": first_manifest["k_runs"], + "timing_primary": "unprofiled_driver_and_grade", + "resource_scope": "observed_profiled_process_tree", + "timing_calibration_scope": "paired profiler-off/on rounds; one worker per round", + "jobs": first_manifest["runner"]["jobs"], + "browser_reuse": first_manifest["runner"]["browser_reuse"], + "score_eligible": first_manifest["score_eligible"], + "try_layout": False, + "historical_version": "0.1.1", + "historical_failed_cases": 372, +} +for run_path, manifest, _ in runs.values(): + assert not (run_path / "layout_retry_results.jsonl").exists() + assert manifest["k_runs"] == 3 and manifest["runner"]["jobs"] == 1 + assert manifest["runner"]["source"]["tree_sha256"] == protocol["runner_sha256"] + assert manifest["runner"]["fixtures"]["tree_sha256"] == protocol["fixtures_sha256"] + assert manifest["seed"] == protocol["seed"] and manifest["k_runs"] == protocol["k_runs"] + assert ( + manifest["runner"]["jobs"] == protocol["jobs"] + and manifest["runner"]["browser_reuse"] == protocol["browser_reuse"] + ) + assert manifest["score_eligible"] is False and protocol["score_eligible"] is False +for key, row in runs["off_baseline"][2].items(): + assert all(by[key]["seed"] == row["seed"] for _, _, by in runs.values()) + + +def percentile(values, p): + values = sorted(values) + position = (len(values) - 1) * p + low = int(position) + high = min(low + 1, len(values) - 1) + return values[low] + (values[high] - values[low]) * (position - low) + + +def stats(values): + values = list(values) + return { + "n": len(values), + "sum": sum(values), + "mean": statistics.mean(values) if values else None, + "p50": percentile(values, 0.5) if values else None, + "p95": percentile(values, 0.95) if values else None, + } + + +metrics = {} +quality = {} +paired = {} +for mode in ("off", "on"): + metrics[mode] = {} + for phase in ("baseline", "engine"): + rows = list(runs[mode + "_" + phase][2].values()) + passes = [r for r in rows if r["status"] == "pass"] + data = { + "calls": len(rows), + "passes": len(passes), + "status_counts": dict(collections.Counter(r["status"] for r in rows)), + "duration_ms_all": stats(r["duration_ms"] for r in rows), + "duration_ms_pass": stats(r["duration_ms"] for r in passes), + } + if phase == "engine": + for population, items in [("all", rows), ("pass", passes)]: + for name, key, scale in [ + ("cpu_ms", "cpu_total_ms", 1), + ("pss_peak_mib", "pss_peak_bytes", 1048576), + ("pss_delta_mib", "pss_peak_delta_bytes", 1048576), + ]: + data[name + "_" + population] = stats(r["resource"][key] / scale for r in items) + data["fixture_tx_bytes_" + population] = stats( + r["resource"]["fixture_traffic"]["fixture_app_tx_body_bytes"] for r in items + ) + metrics[mode]["profile" if phase == "engine" else phase] = data + b = runs[mode + "_baseline"][2] + e = runs[mode + "_engine"][2] + mismatch = [list(key) for key in b if b[key]["status"] != e[key]["status"]] + quality[mode] = { + "status_mismatch_count": len(mismatch), + "status_mismatch_keys": mismatch, + "baseline_host": json.loads( + (runs[mode + "_baseline"][0] / "host_summary.json").read_text() + ), + "engine_host": json.loads((runs[mode + "_engine"][0] / "host_summary.json").read_text()), + "resource_missing": sum(not r.get("resource") for r in e.values()), + "resource_quality_flags": dict( + collections.Counter( + flag for r in e.values() for flag in r.get("resource", {}).get("quality_flags", []) + ) + ), + "resource_unavailable": dict( + collections.Counter( + key for r in e.values() for key in r.get("resource", {}).get("unavailable", {}) + ) + ), + } +for mode in ("off", "on"): + quality[mode]["calibration"] = duration_calibration( + list(runs[mode + "_engine"][2].values()), + list(runs[mode + "_baseline"][2].values()), + 10, + profiled_manifest=runs[mode + "_engine"][1], + baseline_manifest=runs[mode + "_baseline"][1], + ) +for phase in ("baseline", "engine"): + counts = collections.Counter() + for key, off in runs["off_" + phase][2].items(): + on = runs["on_" + phase][2][key] + a = off["status"] == "pass" + b = on["status"] == "pass" + counts[ + "both_pass" + if a and b + else "off_pass_on_fail" + if a + else "off_fail_on_pass" + if b + else "both_fail" + ] += 1 + paired[phase] = { + key: counts[key] + for key in ("off_fail_on_pass", "off_pass_on_fail", "both_pass", "both_fail") + } + +if OUT.exists(): + raise ValueError("Output already exists; choose a new build directory") +(OUT / "data/cases").mkdir(parents=True) +(OUT / "data/evidence").mkdir(parents=True) + + +def evidence_for(run_name: str, row: dict, run_root=None): + p = run_root if run_root is not None else runs[run_name][0] + rel = pathlib.Path(row["artifact_dir"]) + assert ".." not in rel.parts and not rel.is_absolute() + folder = p / rel + assert folder.resolve().is_relative_to(p.resolve()) + result = {} + for filename in ( + "grader.json", + "stdout.log", + "stderr.log", + "cdp.jsonl", + "resource.jsonl", + "run.json", + ): + source = folder / filename + if not source.exists(): + continue + for parent in source.parents: + if parent == p: + break + assert not parent.is_symlink() + assert source.is_file() and not source.is_symlink() and source.stat().st_size < 8_000_000 + source_hash = sha(source.read_bytes()) + raw = source.read_text(errors="replace") + data = clean(raw).encode() + target = OUT / "data/evidence" / run_name / row["task_id"] / str(row["attempt"]) / filename + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + result[filename] = { + "url": str(target.relative_to(OUT)), + "sha256": sha(data), + "source_sha256": source_hash, + "bytes": len(data), + } + return result + + +def safe_failure(run_name, r, run_root=None): + f = r.get("failure") or {} + original = str(f.get("detail") or "") + detail = original + generic = { + "script-reported checks failed", + "inline assertions failed", + "answer did not match server-side expectation", + } + if original in generic: + root = run_root if run_root is not None else runs[run_name][0] + folder = root / r["artifact_dir"] + assert folder.resolve().is_relative_to(root.resolve()) + for filename in ("stdout.log", "grader.json"): + path = folder / filename + if not path.is_file(): + continue + assert not path.is_symlink() + raw = path.read_text(errors="replace") + payload = None + for text in [raw, *reversed(raw.splitlines())]: + try: + payload = json.loads(text) + except ValueError: + continue + if isinstance(payload, dict): + break + if not isinstance(payload, dict): + continue + checks = ( + (payload.get("observations") or {}).get("checks") or payload.get("checks") or [] + ) + failed = next( + (c for c in checks if c.get("status") == "fail" and c.get("evidence")), None + ) + if failed: + detail = str(failed["name"]) + ": " + str(failed["evidence"]) + break + return { + "class": str(f.get("class") or ""), + "detail": clean(detail), + "original_detail": clean(original), + } + + +def resource_scalar(r): + x = r.get("resource") or {} + t = x.get("fixture_traffic") or {} + return { + k: x.get(k) + for k in ( + "cpu_total_ms", + "cpu_user_ms", + "cpu_system_ms", + "pss_baseline_bytes", + "pss_end_bytes", + "pss_peak_bytes", + "pss_peak_delta_bytes", + "samples_seen", + "quality_flags", + "measurement_backend", + "unavailable", + ) + } | { + "fixture_rx_bytes": t.get("fixture_app_rx_body_bytes"), + "fixture_tx_bytes": t.get("fixture_app_tx_body_bytes"), + } + + +cases = [] +for task_id, (stratum, digest) in selected.items(): + definition_path = BENCH_ROOT / next( + x["path"] for x in runs["off_baseline"][1]["resolved_tasks"] if x["task_id"] == task_id + ) + raw = definition_path.read_bytes() + assert sha(raw) == digest + definition = json.loads(raw) + item = { + "id": task_id, + "stratum": stratum, + "title": definition.get("title", task_id), + "description": definition.get("description", ""), + "subset": definition["subset_id"], + "features": definition.get("features", []), + "scene": definition.get("scene", {}), + "driver": definition.get("driver", {}), + "grader": definition.get("grader", {}), + "task_sha256": digest, + "modes": {}, + } + for mode in ("off", "on"): + attempts = [] + for attempt in range(1, k_runs + 1): + b = runs[mode + "_baseline"][2][(task_id, attempt)] + e = runs[mode + "_engine"][2][(task_id, attempt)] + attempts.append( + { + "ordinal": attempt, + "status": b["status"], + "duration_ms": b["duration_ms"], + "profile_status": e["status"], + "profile_duration_ms": e["duration_ms"], + "answer": clean(str(b.get("answer") or "")), + "failure": safe_failure(mode + "_baseline", b), + "resource": resource_scalar(e), + "evidence": { + "baseline": evidence_for(mode + "_baseline", b), + "profile": evidence_for(mode + "_engine", e), + }, + } + ) + item["modes"][mode] = { + "passes": sum(a["status"] == "pass" for a in attempts), + "attempts": attempts, + } + cases.append(item) + (OUT / "data/cases" / f"{task_id}.json").write_text( + json.dumps(item, ensure_ascii=False, separators=(",", ":")) + "\n" + ) +cases.sort(key=lambda c: (list(cohort["strata"]).index(c["stratum"]), c["id"])) +network_rx = {} +cold_start = {} +for mode in ("off", "on"): + rx = [a["resource"]["fixture_rx_bytes"] for c in cases for a in c["modes"][mode]["attempts"]] + network_rx[mode] = { + "total_bytes": sum(rx), + "p50_bytes": percentile(rx, 0.5), + "p95_bytes": percentile(rx, 0.95), + } + starts = [] + for i in range(1, 6): + directory = RUNS / f"cold_{i:02d}_{mode}" + manifest = json.loads((directory / "run_manifest.json").read_text()) + assert manifest["engines"]["moli"]["sha256"] == cohort["moli_sha256"] + values = [ + json.loads(line) for line in (directory / "cold_start.jsonl").read_text().splitlines() + ] + assert len(values) == 1 and values[0]["status"] == "ready" + starts.extend(values) + cold_start[mode] = { + "n": 5, + "ready_ms": { + "p50": percentile([x["ready_ms"] for x in starts], 0.5), + "p95": percentile([x["ready_ms"] for x in starts], 0.95), + }, + "launch_cpu_ms": {"p50": percentile([x["launch_cpu_ms"] for x in starts], 0.5)}, + "launch_pss_bytes": {"p50": percentile([x["launch_peak_pss_bytes"] for x in starts], 0.5)}, + } + +shared = [ + (c["modes"]["off"]["attempts"][i], c["modes"]["on"]["attempts"][i]) + for c in cases + for i in range(k_runs) + if all( + c["modes"][m]["attempts"][i][key] == "pass" + for m in ("off", "on") + for key in ("status", "profile_status") + ) +] +assert len(shared) <= paired["baseline"]["both_pass"] +common_pass = { + "count": len(shared), + "baseline_count": paired["baseline"]["both_pass"], + "scope": "Same task-attempt pairs that passed all four baseline and profiled rounds", + "cpu_total_ms": { + m: sum(pair[0 if m == "off" else 1]["resource"]["cpu_total_ms"] for pair in shared) + for m in ("off", "on") + }, + "pss_end_mean_bytes": { + m: sum(pair[0 if m == "off" else 1]["resource"]["pss_end_bytes"] for pair in shared) + / len(shared) + if shared + else None + for m in ("off", "on") + }, + "fixture_tx_total_bytes": { + m: sum(pair[0 if m == "off" else 1]["resource"]["fixture_tx_bytes"] for pair in shared) + for m in ("off", "on") + }, +} +task_cost = [] +for c in cases: + off = c["modes"]["off"]["attempts"] + on = c["modes"]["on"]["attempts"] + task_cost.append( + { + "id": c["id"], + "off_duration_ms": sum(a["duration_ms"] for a in off), + "on_duration_ms": sum(a["duration_ms"] for a in on), + "off_cpu_ms": sum(a["resource"]["cpu_total_ms"] for a in off), + "on_cpu_ms": sum(a["resource"]["cpu_total_ms"] for a in on), + "off_passes": c["modes"]["off"]["passes"], + "on_passes": c["modes"]["on"]["passes"], + } + ) +task_cost.sort(key=lambda x: x["off_duration_ms"] - x["on_duration_ms"], reverse=True) +assert ( + sum(x["off_duration_ms"] - x["on_duration_ms"] for x in task_cost) + == metrics["off"]["baseline"]["duration_ms_all"]["sum"] + - metrics["on"]["baseline"]["duration_ms_all"]["sum"] +) +launch_receipts = { + name: json.loads((RUNS / (run_id + "_launch.json")).read_text()) + for name, run_id in label.items() + if (RUNS / (run_id + "_launch.json")).exists() +} +host_context = { + "shared_macos_host": True, + "concurrent_test_observed_at_start": any( + r["host_busy_at_start"] for r in launch_receipts.values() + ) + if launch_receipts + else None, + "launch_receipts": launch_receipts, + "scope": "Docker VM telemetry does not establish macOS host isolation.", +} +observation_file = RUNS / "macos-observations.jsonl" +if observation_file.exists(): + observations = [json.loads(line) for line in observation_file.read_text().splitlines()] + + def timestamp(value): + return datetime.datetime.fromisoformat(value).timestamp() + + host_context["observation_sha256"] = sha(observation_file.read_bytes()) + host_context["rounds"] = {} + for name, (_, manifest, _) in runs.items(): + start = timestamp(manifest["started_at"]) + end = timestamp(manifest["completed_at"]) + samples = [row for row in observations if start <= timestamp(row["utc"]) <= end] + host_context["rounds"][name] = { + "samples": len(samples), + "samples_with_other_moli_tests": sum( + bool(row["other_moli_test_processes"]) for row in samples + ), + "first_sample": samples[0]["utc"] if samples else None, + "last_sample": samples[-1]["utc"] if samples else None, + "run_started_at": manifest["started_at"], + "run_completed_at": manifest["completed_at"], + "macos_load1_median": statistics.median(row["load"][0] for row in samples) + if samples + else None, + "macos_load1_max": max((row["load"][0] for row in samples), default=None), + "broad_process_observer_samples": sum( + row.get("observer_version") == 2 for row in samples + ), + } +corrections = [] +case_outcomes = { + "rule": "all_recorded_attempts_pass", + "repeats": k_runs, + "total": task_count, + "off": 0, + "on": 0, + "paired": dict.fromkeys(("both_pass", "both_fail", "off_fail_on_pass", "off_pass_on_fail"), 0), +} +for c in cases: + a = all(x["status"] == "pass" for x in c["modes"]["off"]["attempts"]) + b = all(x["status"] == "pass" for x in c["modes"]["on"]["attempts"]) + case_outcomes["off"] += a + case_outcomes["on"] += b + case_outcomes["paired"][ + "both_pass" + if a and b + else "off_pass_on_fail" + if a + else "off_fail_on_pass" + if b + else "both_fail" + ] += 1 +resource_comparison = json.loads((VERSION_RUNS / "resource-comparison.json").read_text()) +resource_certificate = json.loads((VERSION_RUNS / "resource-certification.json").read_text()) +assert ( + sha((VERSION_RUNS / "resource-comparison.json").read_bytes()) + == resource_certificate["comparison_sha256"] +) +assert sha((VERSION_RUNS / "protocol.json").read_bytes()) == resource_certificate["protocol_sha256"] +for rel, digest in resource_certificate["artifact_sha256"].items(): + path = VERSION_RUNS / rel + assert path.is_file() and not path.is_symlink() and sha(path.read_bytes()) == digest +version_protocol = json.loads((VERSION_RUNS / "protocol.json").read_text()) +assert set(version_protocol["functional_tasks"]) == set(selected) and len( + version_protocol["functional_tasks"] +) == len(selected) +functional_114 = VERSION_RUNS / "114_off_differential_candidate_20260920" +functional_manifest = json.loads((functional_114 / "run_manifest.json").read_text()) +functional_rows = [ + json.loads(line) for line in (functional_114 / "results.jsonl").read_text().splitlines() +] +candidate_114 = "v4_cdp_emulation_setdefaultbackgroundcoloroverride" +assert ( + functional_manifest["completion_status"] == "completed" + and functional_manifest["expected_result_rows"] == 3 +) +assert len(functional_rows) == 3 +assert {(row["task_id"], row["attempt"]) for row in functional_rows} == { + (candidate_114, attempt) for attempt in range(1, 4) +} +assert all(not row["engine_provenance"]["layout_enabled"] for row in functional_rows) +assert all( + row["engine_provenance"]["binary_sha256"] == version_protocol["configs"]["114_off"]["sha256"] + for row in functional_rows +) +assert case_outcomes["off"] == 1 +assert [ + c["id"] for c in cases if all(row["status"] == "pass" for row in c["modes"]["off"]["attempts"]) +] == [candidate_114] +assert all(row["status"] != "pass" for row in functional_rows) +passed_114 = 0 +population = "frozen_historical_common_pass_calls" +version_rows = [] +for config, label_text, label_en, short_label, short_label_en, passed in ( + ( + "114_off", + "Moli 1.1.4 · 关闭 layout", + "Moli 1.1.4 · layout off", + "1.1.4 关闭", + "1.1.4 off", + passed_114, + ), + ( + "118_off", + "Moli 1.1.8 · 关闭 layout", + "Moli 1.1.8 · layout off", + "1.1.8 关闭", + "1.1.8 off", + case_outcomes["off"], + ), + ( + "118_on", + "Moli 1.1.8 · 开启 layout", + "Moli 1.1.8 · layout on", + "1.1.8 开启", + "1.1.8 on", + case_outcomes["on"], + ), +): + resource = resource_comparison["memory"][config][population] + version_rows.append( + { + "id": config, + "label": label_text, + "label_en": label_en, + "short_label": short_label, + "short_label_en": short_label_en, + "passed_cases": passed, + "total_cases": 372, + "success_rate_pct": passed / 372 * 100, + "pss_mib": resource["pss_peak_mib"]["median"], + "cpu_ms": resource["cpu_time_ms"]["mean"], + "cpu_p50_ms": resource["cpu_time_ms"]["median"], + "cpu_p95_ms": resource["cpu_time_ms"]["p95"], + } + ) +baseline = version_rows[0] +for row in version_rows: + row["success_change_pp"] = row["success_rate_pct"] - baseline["success_rate_pct"] + row["pss_change_pct"] = (row["pss_mib"] / baseline["pss_mib"] - 1) * 100 + row["cpu_change_pct"] = (row["cpu_ms"] / baseline["cpu_ms"] - 1) * 100 +version_comparison = { + "baseline": "114_off", + "configurations": version_rows, + "functional_population": { + "cases": 372, + "attempts_per_case": 3, + "rule": "all_three_attempts_pass", + "version_118_direct_cases": 372, + "version_114_candidate_cases": 1, + "version_114_inherited_failures": 371, + "version_114_candidate": candidate_114, + "version_114_method": "differential_candidate_check", + }, + "resource_population": { + "experiment_cases": 557, + "attempts_per_case": 5, + "total_tasks": 557, + "calls_per_task": 5, + "chart_calls": resource_comparison["resource_populations"][population]["calls"], + "chart_tasks": resource_comparison["resource_populations"][population]["tasks"], + "selection": population, + "sample_interval_ms": 250, + }, + "bindings": { + "resource_comparison_sha256": resource_certificate["comparison_sha256"], + "resource_protocol_sha256": resource_certificate["protocol_sha256"], + "functional_114_results_sha256": sha((functional_114 / "results.jsonl").read_bytes()), + "functional_114_manifest_sha256": sha((functional_114 / "run_manifest.json").read_bytes()), + }, + "published_71_mib": { + "value": 71, + "status": resource_comparison["original_image_memory_status"], + }, +} +functional_methods = [ + { + "id": "114_off", + "label": "Moli 1.1.4 · 关闭 layout", + "label_en": "Moli 1.1.4 · layout off", + "policy": "fixed_off", + "direct_cases": 1, + "inherited_cases": 371, + "initial_passed_cases": 0, + "recovered_cases": 0, + "final_passed_cases": 0, + "retried_cases": 0, + "extra_physical_calls": 0, + }, + { + "id": "118_off", + "label": "Moli 1.1.8 · 关闭 layout", + "label_en": "Moli 1.1.8 · layout off", + "policy": "fixed_off", + "direct_cases": 372, + "inherited_cases": 0, + "initial_passed_cases": case_outcomes["off"], + "recovered_cases": 0, + "final_passed_cases": case_outcomes["off"], + "retried_cases": 0, + "extra_physical_calls": 0, + }, + { + "id": "118_on", + "label": "Moli 1.1.8 · 开启 layout", + "label_en": "Moli 1.1.8 · layout on", + "policy": "fixed_on", + "direct_cases": 372, + "inherited_cases": 0, + "initial_passed_cases": case_outcomes["on"], + "recovered_cases": 0, + "final_passed_cases": case_outcomes["on"], + "retried_cases": 0, + "extra_physical_calls": 0, + }, +] +fixed_candidates = {} +fixed_case_data = {c["id"]: {"id": c["id"], "title": c["title"], "methods": {}} for c in cases} +public_candidate_files = {} +labels = { + "119_off": ("Moli 1.1.9 修复版 · 关闭 layout", "Moli 1.1.9 patched · layout off", "off"), + "119_on": ("Moli 1.1.9 修复版 · 开启 layout", "Moli 1.1.9 patched · layout on", "on"), + "119_official_on": ("Moli 1.1.9 官方版 · 开启 layout", "Moli 1.1.9 official · layout on", "on"), +} +functional_task_ids_sha256 = sha("".join(task_id + "\n" for task_id in sorted(selected)).encode()) +for method_id, summary_path in args.fixed_summary: + assert method_id in labels and method_id not in fixed_candidates + source_bytes = pathlib.Path(summary_path).read_bytes() + candidate = json.loads(source_bytes) + assert candidate["schema"] == "lexbench_moli_fixed_layout_summary/1" + label_zh, label_en, layout = labels[method_id] + assert candidate["layout"] == layout + assert candidate["population"] == { + "cases": 372, + "attempts_per_case": 3, + "calls": 1116, + "task_ids_sha256": functional_task_ids_sha256, + } + assert {c["task_id"] for c in candidate["cases"]} == set(selected) and len( + candidate["cases"] + ) == 372 + for case in candidate["cases"]: + assert len(case["attempts"]) == 3 and {a["attempt"] for a in case["attempts"]} == {1, 2, 3} + assert case["passes"] == sum(a["status"] == "pass" for a in case["attempts"]) + source_runs = {} + for binding in candidate["sources"]: + run_id = binding["run_id"] + assert re.fullmatch(r"[A-Za-z0-9_-]+", run_id) + run_root = ROOT / "work/lexbench-layout-policy-v3/runs" / run_id + assert ( + not run_root.is_symlink() + and sha((run_root / "run_manifest.json").read_bytes()) == binding["manifest_sha256"] + ) + source_result = run_root / binding["results_file"] + assert ( + source_result.resolve().parent == run_root.resolve() and not source_result.is_symlink() + ) + assert sha(source_result.read_bytes()) == binding["results_sha256"] + source_runs[run_id] = run_root + for case in candidate["cases"]: + detail = [] + for attempt in case["attempts"]: + run_root = source_runs[attempt["source_run_id"]] + raw = {**attempt, "task_id": case["task_id"]} + evidence = evidence_for(method_id, raw, run_root) + detail.append( + { + "ordinal": attempt["attempt"], + "status": attempt["status"], + "answer": clean(str(attempt.get("answer") or "")), + "failure": safe_failure(method_id, raw, run_root), + "evidence": evidence, + } + ) + fixed_case_data[case["task_id"]]["methods"][method_id] = { + "passes": case["passes"], + "attempts": detail, + } + passed = sum(c["passes"] == 3 for c in candidate["cases"]) + assert ( + candidate["outcomes"]["passed_cases"] == passed + and abs(candidate["outcomes"]["success_rate_pct"] - passed / 372 * 100) < 1e-9 + ) + assert sum(source["calls"] for source in candidate["sources"]) == 1116 + public_bytes = (clean(json.dumps(candidate, ensure_ascii=False, indent=2)) + "\n").encode() + url = f"data/candidates/{method_id}-fixed-summary.json" + public_candidate_files[url] = public_bytes + evidence = {"url": url, "sha256": sha(public_bytes), "bytes": len(public_bytes)} + fixed_candidates[method_id] = { + "population": candidate["population"], + "outcomes": candidate["outcomes"], + "binary": candidate["binary"], + "sources": candidate["sources"], + "evidence": evidence, + "source_summary_sha256": sha(source_bytes), + } + functional_methods.append( + { + "id": method_id, + "label": label_zh, + "label_en": label_en, + "policy": f"fixed_{layout}", + "direct_cases": 372, + "inherited_cases": 0, + "final_passed_cases": passed, + "physical_calls": 1116, + "moli_sha256": candidate["binary"]["moli_sha256"], + "evidence": evidence, + } + ) +macos_resource = None +official_resource = None +for resource_path, is_official in [ + (args.macos_resource_summary, False), + (args.official_resource_summary, True), +]: + if resource_path is None: + continue + resource = json.loads(resource_path.read_text()) + assert resource["schema"] == "lexbench_moli_macos_fixed_resource_summary/1" + expected_layouts = ["layout_on"] if is_official else ["layout_off", "layout_on"] + assert ( + resource["method"]["configurations"] == expected_layouts + and resource["method"]["layout_retry"] is False + ) + assert resource["method"]["resource_runs"] == len(expected_layouts) + assert resource["population"] == { + "tasks": 557, + "attempts_per_task": 5, + "calls_per_configuration": 2785, + "frozen_comparison_calls": 1045, + "frozen_comparison_tasks": 209, + } + assert ( + resource["quality"]["memory_metric"] == "process_tree_rss" + and resource["quality"]["pss_available"] is False + and resource["quality"]["publishable"] is True + ) + for layout, config in resource["configurations"].items(): + method_id = "119_official_on" if is_official else f"119_{layout}" + assert ( + resource["candidate"]["binary_sha256"] + == fixed_candidates[method_id]["binary"]["moli_sha256"] + ) + for population_name, n in [ + ("all_predeclared_calls", 2785), + ("frozen_historical_common_pass_calls", 1045), + ]: + for metric in ("rss_peak_mib", "cpu_time_ms"): + stat = config["metrics"][population_name][metric] + assert stat["n"] == n and abs(stat["sum"] - stat["mean"] * n) < max( + 1e-6, abs(stat["sum"]) * 1e-10 + ) + public_bytes = (clean(json.dumps(resource, ensure_ascii=False, indent=2)) + "\n").encode() + url = ( + "data/candidates/" + + ("official" if is_official else "patched") + + "-119-macos-resource-summary.json" + ) + public_candidate_files[url] = public_bytes + entry = { + "summary": json.loads(public_bytes), + "evidence": {"url": url, "sha256": sha(public_bytes), "bytes": len(public_bytes)}, + } + if is_official: + official_resource = entry + else: + macos_resource = entry +functional_correction = json.loads((FUNCTIONAL_CORRECTION / "receipt.json").read_text()) +assert functional_correction["schema"] == "moli_functional_contract_correction/1" +assert functional_correction["effect"]["report_success_rates_changed"] is False +assert [row["id"] for row in functional_correction["configurations"]] == [ + "114_off", + "118_off", + "118_on", +] +for item in functional_correction["configurations"]: + correction_run = FUNCTIONAL_CORRECTION / item["run_id"] + assert sha((correction_run / "results.jsonl").read_bytes()) == item["results_sha256"] + assert sha((correction_run / "run_manifest.json").read_bytes()) == item["manifest_sha256"] + assert item["rows"] == 6 + assert all( + status == "fail" for task in item["outcomes"].values() for status in task["attempts"] + ) +correction_bytes = (json.dumps(functional_correction, ensure_ascii=False, indent=2) + "\n").encode() +functional_correction_public = { + "task_count": len(functional_correction["tasks"]), + "configuration_count": len(functional_correction["configurations"]), + "calls": sum(row["rows"] for row in functional_correction["configurations"]), + "harness_commit": functional_correction["harness_commit"], + "success_rates_changed": False, + "evidence": { + "url": "data/corrections/chromium-contract-retest.json", + "sha256": sha(correction_bytes), + "bytes": len(correction_bytes), + }, +} +macos_comparison = None +if macos_resource: + mac_rows = [] + for method_id, resource, layout in [ + ("119_off", macos_resource, "off"), + ("119_on", macos_resource, "on"), + ("119_official_on", official_resource, "on"), + ]: + if resource is None: + continue + metric = resource["summary"]["configurations"][layout]["metrics"][ + "frozen_historical_common_pass_calls" + ] + method = next(row for row in functional_methods if row["id"] == method_id) + mac_rows.append( + { + "id": method_id, + "label": method["label"], + "label_en": method["label_en"], + "short_label": method["label"].replace("Moli ", ""), + "short_label_en": method["label_en"].replace("Moli ", ""), + "passed_cases": method["final_passed_cases"], + "total_cases": 372, + "success_rate_pct": method["final_passed_cases"] / 372 * 100, + "rss_mib": metric["rss_peak_mib"]["p50"], + "cpu_ms": metric["cpu_time_ms"]["mean"], + } + ) + mac_baseline = next((row for row in mac_rows if row["id"] == "119_official_on"), mac_rows[0]) + for row in mac_rows: + row["rss_change_pct"] = (row["rss_mib"] / mac_baseline["rss_mib"] - 1) * 100 + row["cpu_change_pct"] = (row["cpu_ms"] / mac_baseline["cpu_ms"] - 1) * 100 + macos_comparison = { + "baseline": mac_baseline["id"], + "configurations": mac_rows, + "resource_population": { + "chart_calls": 1045, + "chart_tasks": 209, + "total_tasks": 557, + "calls_per_task": 5, + }, + } +public = { + "fixed_case_outcomes": [ + { + "id": c["id"], + "passes": {method: value["passes"] for method, value in c["methods"].items()}, + } + for c in fixed_case_data.values() + ], + "macos_comparison": macos_comparison, + "version_comparison": version_comparison, + "functional_methods": functional_methods, + "fixed_candidates": fixed_candidates, + "macos_resource": macos_resource, + "official_resource": official_resource, + "case_outcomes": case_outcomes, + "schema": "moli_layout_report/2", + "functional_contract_correction": functional_correction_public, + "resource_window_corrections": corrections, + "environment": json.loads((RUNS / "environment.json").read_text()), + "title": "Moli 1.1.4 / 1.1.8 / 1.1.9 comparison", + "task_count": task_count, + "attempts_per_mode": call_count, + "binary_sha256": cohort["moli_sha256"], + "manifest_sha256": cohort["manifest_sha256"], + "host_context": host_context, + "selection": cohort["selection"], + "protocol": protocol, + "strata": list(cohort["strata"]), + "metrics": metrics, + "network_rx": network_rx, + "cold_start": cold_start, + "common_pass": common_pass, + "task_cost": task_cost, + "paired": paired, + "quality": quality, + "review_coverage": { + "reviewed_calls": 0, + "total_calls": call_count * 4, + "unreviewed_program_passes": sum( + metrics[mode][phase]["passes"] + for mode in ("off", "on") + for phase in ("baseline", "profile") + ), + }, + "cases": [ + { + "id": c["id"], + "title": c["title"], + "stratum": c["stratum"], + "subset": c["subset"], + "off_passes": c["modes"]["off"]["passes"], + "on_passes": c["modes"]["on"]["passes"], + "off_fail_classes": sorted( + set( + a["failure"]["class"] + for a in c["modes"]["off"]["attempts"] + if a["status"] != "pass" + ) + ), + "on_fail_classes": sorted( + set( + a["failure"]["class"] + for a in c["modes"]["on"]["attempts"] + if a["status"] != "pass" + ) + ), + "off_fail_details": sorted( + set( + a["failure"]["detail"] + for a in c["modes"]["off"]["attempts"] + if a["status"] != "pass" + ) + ), + "on_fail_details": sorted( + set( + a["failure"]["detail"] + for a in c["modes"]["on"]["attempts"] + if a["status"] != "pass" + ) + ), + } + for c in cases + ], + "runs": { + name: { + "run_id": label[name], + "manifest_sha256": sha((RUNS / label[name] / "run_manifest.json").read_bytes()), + "rows": call_count, + } + for name in label + }, +} +(OUT / "data/model.json").write_text( + json.dumps(public, ensure_ascii=False, separators=(",", ":")) + "\n" +) +(OUT / "data/corrections").mkdir() +(OUT / "data/corrections/chromium-contract-retest.json").write_bytes(correction_bytes) +if fixed_candidates: + (OUT / "data/fixed-cases").mkdir() + for task_id, case in fixed_case_data.items(): + (OUT / "data/fixed-cases" / f"{task_id}.json").write_text( + json.dumps(case, ensure_ascii=False, separators=(",", ":")) + "\n" + ) +for relative, data in public_candidate_files.items(): + target = OUT / relative + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) +(OUT / "data/version-comparison.json").write_text( + json.dumps(version_comparison, ensure_ascii=False, indent=2) + "\n" +) +(OUT / "assets").mkdir() +if macos_comparison: + for language in ("zh", "en"): + render_chart( + macos_comparison, + OUT / f"assets/moli-macos-success-resources-{language}.svg", + ("rss", "cpu"), + language, + ) + (OUT / "data/macos-comparison.json").write_text( + json.dumps(macos_comparison, ensure_ascii=False, indent=2) + "\n" + ) +render_chart( + version_comparison, OUT / "assets/moli-version-success-resources-zh.svg", ("pss", "cpu"), "zh" +) +render_chart( + version_comparison, OUT / "assets/moli-version-success-resources-en.svg", ("pss", "cpu"), "en" +) +for language, base, entry in [ + ("zh-CN", "", "index.html"), + ("en", "", "en.html"), + ("en", "../", "en/index.html"), +]: + target = OUT / entry + target.parent.mkdir(exist_ok=True) + shell = (SRC / "index.html").read_text().replace("{{lang}}", language).replace("{{base}}", base) + shell = shell.replace( + "style.css", f"style.css?v={sha((SRC / 'style.css').read_bytes())[:12]}" + ).replace("app.js", f"app.js?v={sha((SRC / 'app.js').read_bytes())[:12]}") + target.write_text(shell) +for name in ("app.js", "style.css", "README.md"): + shutil.copy2(SRC / name, OUT / name) +for name, digest in { + "mermaid.min.js": "07e37dfa97b337ccc85365d57eddf99b9706f09db3b59b260d0333b23b343c4b", + "mermaid-LICENSE.txt": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80", +}.items(): + asset = args.vendor_dir / name + assert not asset.is_symlink() and sha(asset.read_bytes()) == digest + shutil.copy2(asset, OUT / name) +(OUT / "reproduction").mkdir() +(OUT / "reproduction/cohort.json").write_text(clean(args.cohort.read_text())) +shutil.copy2(SRC / "run.py", OUT / "reproduction/run.py") +shutil.copy2( + pathlib.Path(__file__).resolve().parents[1] / "plot_moli_version_resources.py", + OUT / "reproduction/plot_version_summary.py", +) +(OUT / "reproduction/protocol.json").write_text(json.dumps(contract, indent=2) + "\n") +print( + json.dumps( + { + "site": str(OUT), + "cases": len(cases), + "evidence_files": len(list((OUT / "data/evidence").rglob("*.*"))), + "bytes": sum(p.stat().st_size for p in OUT.rglob("*") if p.is_file()), + }, + indent=2, + ) +) diff --git a/scripts/moli_report/bundle-loader.js b/scripts/moli_report/bundle-loader.js new file mode 100644 index 000000000..ec9e6db9e --- /dev/null +++ b/scripts/moli_report/bundle-loader.js @@ -0,0 +1,75 @@ +"use strict"; +(() => { + const nativeFetch = window.fetch.bind(window), + script = document.currentScript, + root = new URL(".", script.src), + decoder = new TextDecoder(); + let catalogPromise; + const packs = new Map(); + function catalog() { + return (catalogPromise ??= nativeFetch( + new URL("bundle-manifest.json", root), + ).then((r) => { + if (!r.ok) throw Error("Bundle manifest unavailable"); + return r.json(); + })); + } + function keyFor(value) { + const url = new URL( + value instanceof Request ? value.url : value, + document.baseURI, + ); + if (url.origin !== root.origin || !url.pathname.startsWith(root.pathname)) + return null; + return decodeURIComponent(url.pathname.slice(root.pathname.length)); + } + async function pack(name) { + if (!packs.has(name)) + packs.set( + name, + nativeFetch(new URL(name, root)).then(async (r) => { + if (!r.ok) throw Error("Evidence pack unavailable: " + name); + const stream = r.body.pipeThrough(new DecompressionStream("gzip")); + return new Uint8Array(await new Response(stream).arrayBuffer()); + }), + ); + return packs.get(name); + } + async function bundled(key) { + const manifest = await catalog(), + entry = manifest.files[key]; + if (!entry) return null; + const bytes = (await pack(entry.pack)).slice( + entry.offset, + entry.offset + entry.size, + ); + return new Response(bytes, { + status: 200, + headers: { + "Content-Type": entry.mime, + "Content-Length": String(entry.size), + "X-Content-SHA256": entry.sha256, + }, + }); + } + window.fetch = async (input, init) => { + const key = keyFor(input), + response = key && (await bundled(key)); + return response ?? nativeFetch(input, init); + }; + document.addEventListener("click", async (event) => { + const anchor = event.target.closest("a[href]"); + if (!anchor || anchor.hasAttribute("download")) return; + const key = keyFor(anchor.href); + if (!key) return; + const manifest = await catalog(), + entry = manifest.files[key]; + if (!entry) return; + event.preventDefault(); + const response = await bundled(key), + blob = await response.blob(), + url = URL.createObjectURL(blob); + window.open(url, "_blank", "noopener"); + setTimeout(() => URL.revokeObjectURL(url), 60000); + }); +})(); diff --git a/scripts/moli_report/index.html b/scripts/moli_report/index.html new file mode 100644 index 000000000..b3a6cd7f3 --- /dev/null +++ b/scripts/moli_report/index.html @@ -0,0 +1,50 @@ + + + + + + + Moli 1.1.8 · Layout modes + + + + + + +
+
+ MMoli / Layout modes + +
+ EN +
+
+
+
+
Loading report…
+
+ + +
+

Evidence

+ +
+
+
+ + diff --git a/scripts/moli_report/pack.py b/scripts/moli_report/pack.py new file mode 100644 index 000000000..5ec497082 --- /dev/null +++ b/scripts/moli_report/pack.py @@ -0,0 +1,109 @@ +"""Pack report evidence into lazy-loaded gzip files for the existing static host.""" + +from __future__ import annotations + +import argparse +import gzip +import hashlib +import json +import mimetypes +import shutil +from pathlib import Path + + +def package(source: Path, destination: Path, pack_limit: int = 8 * 1024 * 1024) -> dict: + source = source.resolve() + if destination.exists(): + raise ValueError("Output already exists; choose a new package directory") + if pack_limit <= 0: + raise ValueError("pack_limit must be positive") + paths = sorted(source.rglob("*")) + if any(path.is_symlink() for path in paths): + raise ValueError("Report bundle must not contain symlinks") + if any( + part.startswith(".") or part == "node_modules" + for p in paths + for part in p.relative_to(source).parts + ): + raise ValueError("Report bundle contains an excluded path") + files = [path for path in paths if path.is_file()] + physical = { + "index.html", + "en.html", + "en/index.html", + "app.js", + "style.css", + "mermaid.min.js", + "mermaid-LICENSE.txt", + } + physical.update( + p.relative_to(source).as_posix() for p in files if p.is_relative_to(source / "assets") + ) + if not all((source / name).is_file() for name in physical): + raise ValueError("Report is missing a required entry or runtime asset") + destination.mkdir(parents=True) + for name in sorted(physical): + target = destination / name + target.parent.mkdir(parents=True, exist_ok=True) + if name.endswith(".html"): + text = (source / name).read_text() + prefix = "../" if name.startswith("en/") else "" + marker = f'' + if text.count(marker) != 1: + raise ValueError("HTML entry must have one Mermaid runtime marker") + target.write_text( + text.replace( + marker, f'' + marker + ) + ) + else: + shutil.copy2(source / name, target) + shutil.copy2(Path(__file__).with_name("bundle-loader.js"), destination / "bundle-loader.js") + index, payload, catalog = 0, bytearray(), {} + + def flush(): + nonlocal index, payload + if not payload: + return + (destination / f"evidence-{index:02d}.bin.gz").write_bytes( + gzip.compress(bytes(payload), compresslevel=6, mtime=0) + ) + index += 1 + payload = bytearray() + + for path in files: + name = path.relative_to(source).as_posix() + if name in physical: + continue + data = path.read_bytes() + if payload and len(payload) + len(data) > pack_limit: + flush() + catalog[name] = { + "pack": f"evidence-{index:02d}.bin.gz", + "offset": len(payload), + "size": len(data), + "sha256": hashlib.sha256(data).hexdigest(), + "mime": mimetypes.guess_type(name)[0] or "application/octet-stream", + } + payload.extend(data) + flush() + (destination / "bundle-manifest.json").write_text( + json.dumps({"files": catalog}, separators=(",", ":")) + "\n" + ) + return { + "bundled_files": len(catalog), + "packs": index, + "physical_files": sum(p.is_file() for p in destination.rglob("*")), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(package(args.source, args.output))) + + +if __name__ == "__main__": + main() diff --git a/scripts/moli_report/run.py b/scripts/moli_report/run.py new file mode 100644 index 000000000..58e5dc649 --- /dev/null +++ b/scripts/moli_report/run.py @@ -0,0 +1,134 @@ +"""Replay one frozen layout cohort inside the captured Linux runtime image.""" + +import argparse +import hashlib +import json +import pathlib +import subprocess + +p = argparse.ArgumentParser() +p.add_argument("--repo", required=True, type=pathlib.Path) +p.add_argument("--output", required=True, type=pathlib.Path) +p.add_argument("--image", required=True, help="Captured runtime image identity shown in the report") +p.add_argument( + "--node-modules", required=True, type=pathlib.Path, help="Provisioned Linux Node dependencies" +) +p.add_argument( + "--agent-browser", required=True, type=pathlib.Path, help="Linux ARM64 agent-browser executable" +) +p.add_argument( + "--execute", action="store_true", help="Execute after verification; otherwise print the command" +) +p.add_argument("--mode", required=True, choices=["off", "on"]) +p.add_argument("--phase", required=True, choices=["baseline", "engine"]) +a = p.parse_args() +repo = a.repo.resolve() +out = a.output.resolve() +modules = a.node_modules.resolve() +agent = a.agent_browser.resolve() +c = json.loads(pathlib.Path(__file__).with_name("cohort.json").read_text()) + + +def sha(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +assert sha(repo / "manifest.json") == c["manifest_sha256"] +assert sha(repo / "build_artifacts/moli/bin/moli") == c["moli_sha256"] +for tasks in c["strata"].values(): + for task in tasks: + assert sha(repo / task["path"]) == task["sha256"] +contract = json.loads(pathlib.Path(__file__).with_name("protocol.json").read_text()) +for name, digest in contract["inputs"].items(): + assert sha(repo / name) == digest, name +assert sha(modules / ".package-lock.json") == contract["node_modules_lock"] +assert sha(agent) == contract["agent_browser_sha256"] +assert a.image == contract["image"], "Use the exact captured image identity" +name = a.mode + "_" + a.phase +args = [ + "run", + "--engines", + "moli", + "--moli-layout", + a.mode, + "--k", + str(c["k_runs"]), + "--jobs", + "1", + "--seed", + c["seed"], + "--chrome-baseline", + "off", + "--score-mode", + "independent", + "--resource-profile", + a.phase, + "--resource-sample-interval-ms", + "500", + "--host-telemetry", + "on", + "--host-sample-interval-s", + "0.5", + "--run-id", + name, + "--run-id-conflict", + "error", + "--out", + "/results", + "--no-report", + "--no-progress", + "--provenance-level", + "minimal", +] +if a.phase == "engine": + args += [ + "--resource-calibration-baseline", + "/results/" + a.mode + "_baseline", + "--resource-max-observer-effect-pct", + "10", + ] +for task in c["ordered_task_ids"]: + args += ["--task", task] +assert "--try-layout" not in args +command = [ + "docker", + "run", + "--rm", + "--init", + "--mount", + f"type=bind,src={repo},dst=/work,readonly", + "--mount", + f"type=bind,src={modules},dst=/work/node_modules,readonly", + "--mount", + f"type=bind,src={agent},dst=/work/node_modules/agent-browser/bin/agent-browser-linux-arm64,readonly", + "--mount", + f"type=bind,src={out},dst=/results", + "-w", + "/work", + "-e", + "NODE_PATH=/work/node_modules", + "-e", + "PATH=/work/node_modules/.bin:/home/evaluator/.cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin", + "-e", + "AGENT_BROWSER_SOCKET_DIR=/tmp/ab", + "-e", + "ALL_PROXY=", + "-e", + "HTTP_PROXY=", + "-e", + "HTTPS_PROXY=", + "-e", + "http_proxy=", + "-e", + "https_proxy=", + "-e", + "NO_PROXY=*", + "--entrypoint", + "python3", + a.image, + "runner/run.py", +] + args +print(json.dumps(command, indent=2)) +if a.execute: + out.mkdir(parents=True, exist_ok=True) + subprocess.run(command, check=True) diff --git a/scripts/moli_report/style.css b/scripts/moli_report/style.css new file mode 100644 index 000000000..08673bfbb --- /dev/null +++ b/scripts/moli_report/style.css @@ -0,0 +1,888 @@ +:root { + font-family: + Inter, + -apple-system, + BlinkMacSystemFont, + "Segoe UI", + "Noto Sans SC", + sans-serif; + color: #17212f; + background: #f6f8fb; + --ink: #17212f; + --muted: #607084; + --line: #dce4ee; + --surface: #fff; + --surface2: #f2f6fa; + --accent: #1c5caa; + --accent2: #0b756b; + --good: #14724d; + --bad: #a63b3b; + --shadow: 0 12px 36px rgba(28, 53, 80, 0.07); +} +* { + box-sizing: border-box; +} +html { + scroll-behavior: smooth; +} +body { + margin: 0; + min-width: 320px; +} +a { + color: var(--accent); + text-decoration: none; +} +a:hover { + text-decoration: underline; +} +button, +input, +select { + font: inherit; +} +button { + cursor: pointer; + color: inherit; +} +h1, +h2, +h3, +p { + margin-top: 0; +} +h1 { + font-size: clamp(2rem, 4vw, 3.1rem); + line-height: 1.12; + letter-spacing: -0.035em; + margin-bottom: 0.65rem; +} +h2 { + font-size: 1.55rem; + letter-spacing: -0.025em; +} +h3 { + font-size: 1.07rem; +} +p { + line-height: 1.65; +} +.skip { + position: absolute; + top: -100px; + left: 1rem; + z-index: 100; + background: #fff; + padding: 0.5rem; +} +.skip:focus { + top: 1rem; +} +.topbar { + position: sticky; + top: 0; + z-index: 20; + background: var(--surface); + border-bottom: 1px solid var(--line); +} +.topbar-inner { + max-width: 1440px; + margin: auto; + display: flex; + align-items: center; + gap: 1.35rem; + padding: 0.75rem clamp(1rem, 3vw, 2.5rem); +} +.brand { + display: flex; + align-items: center; + gap: 0.65rem; + color: var(--ink); + font-weight: 750; + white-space: nowrap; +} +.brand small { + font-weight: 500; + color: var(--muted); +} +.brand-glyph { + display: inline-grid; + place-items: center; + width: 32px; + height: 32px; + border-radius: 9px; + color: white; + background: #153e76; + font-size: 1rem; +} +nav { + display: flex; + gap: 0.12rem; + flex-wrap: wrap; + align-items: center; + flex: 1; +} +nav a { + padding: 0.5rem 0.65rem; + border-radius: 8px; + color: var(--muted); + font-size: 0.88rem; + white-space: nowrap; +} +nav a[aria-current="page"], +nav a:hover { + background: var(--surface2); + color: var(--accent); + text-decoration: none; +} +.actions { + display: flex; + align-items: center; + gap: 0.45rem; + margin-left: auto; +} +.actions > a, +.actions > button, +.menu-toggle { + border: 1px solid var(--line); + background: var(--surface); + border-radius: 8px; + padding: 0.42rem 0.7rem; +} +.menu-toggle { + display: none; +} +main { + max-width: 1440px; + margin: auto; + padding: 0 clamp(1rem, 3vw, 2.5rem) 4rem; +} +.hero { + padding: 2.8rem 0 1.3rem; +} +.eyebrow { + text-transform: uppercase; + letter-spacing: 0.14em; + font-size: 0.7rem; + font-weight: 800; + color: var(--accent); +} +.subtitle { + font-size: 1.06rem; + color: var(--muted); + max-width: 850px; +} +.hero-links { + display: flex; + gap: 0.6rem; + flex-wrap: wrap; + margin-top: 1.3rem; +} +.button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 0.35rem; + padding: 0.68rem 1rem; + border-radius: 9px; + background: var(--accent); + color: white; + font-weight: 650; + border: 1px solid var(--accent); +} +.button:hover { + color: white; + text-decoration: none; + filter: brightness(1.07); +} +.button.secondary { + color: var(--accent); + background: var(--surface); + border-color: var(--line); +} +.button.secondary:hover { + color: var(--accent); +} +.section { + margin: 1.6rem 0 2.5rem; +} +.section-head { + display: flex; + align-items: end; + justify-content: space-between; + gap: 1rem; + flex-wrap: wrap; + margin-bottom: 0.9rem; +} +.section-head h2 { + margin: 0; +} +.section-intro { + color: var(--muted); + margin: 0.35rem 0 1rem; +} +.grid { + display: grid; + gap: 1rem; +} +.grid.two { + grid-template-columns: repeat(2, minmax(0, 1fr)); +} +.grid.three { + grid-template-columns: repeat(3, minmax(0, 1fr)); +} +.panel, +.metric-card { + background: var(--surface); + border: 1px solid var(--line); + border-radius: 14px; + padding: 1.15rem; + box-shadow: var(--shadow); +} +.metric-card .label { + font-size: 0.83rem; + color: var(--muted); +} +.metric-card .value { + font-size: 1.65rem; + font-weight: 800; + letter-spacing: -0.03em; + margin: 0.25rem 0; +} +.metric-card .detail { + font-size: 0.82rem; + color: var(--muted); +} +.notice { + padding: 1rem 1.15rem; + background: #eaf7f1; + border-left: 4px solid var(--good); + border-radius: 0 9px 9px 0; +} +.notice.warn { + background: #fff5e9; + border-color: #c77621; +} +.table-scroll { + overflow: auto; + max-width: 100%; + background: var(--surface); + border: 1px solid var(--line); + border-radius: 13px; + box-shadow: var(--shadow); +} +table { + width: 100%; + border-collapse: collapse; + font-size: 0.9rem; +} +th, +td { + text-align: left; + padding: 0.72rem 0.82rem; + border-bottom: 1px solid var(--line); + vertical-align: top; +} +th { + position: sticky; + top: 0; + background: var(--surface2); + color: var(--muted); + font-size: 0.8rem; + letter-spacing: 0.01em; + z-index: 1; +} +tr:last-child td { + border-bottom: 0; +} +tbody tr:hover { + background: var(--surface2); +} +td.num, +th.num { + text-align: right; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} +td:first-child, +th:first-child { + padding-left: 1rem; +} +.winner { + color: var(--good); + font-weight: 780; + background: rgba(31, 142, 92, 0.08); +} +.subtle { + color: var(--muted); + font-size: 0.83rem; +} +.tag, +.status { + display: inline-flex; + align-items: center; + white-space: nowrap; + border-radius: 999px; + padding: 0.18rem 0.48rem; + font-size: 0.73rem; + font-weight: 700; + background: var(--surface2); + border: 1px solid var(--line); +} +.status.pass { + color: var(--good); + border-color: #b8dfc9; + background: #eaf7f0; +} +.status.fail { + color: var(--bad); + border-color: #ecc4c4; + background: #fff0f0; +} +.status.neutral { + color: var(--muted); +} +.filters { + display: flex; + align-items: end; + gap: 0.65rem; + flex-wrap: wrap; + margin-bottom: 0.8rem; +} +.filters label { + display: grid; + gap: 0.25rem; + font-size: 0.78rem; + color: var(--muted); + font-weight: 650; +} +.filters input, +.filters select { + border: 1px solid var(--line); + border-radius: 8px; + padding: 0.55rem 0.68rem; + background: var(--surface); + color: var(--ink); + min-width: 180px; +} +.filters input { + min-width: min(320px, 80vw); +} +.inventory { + max-height: 560px; + overflow: auto; +} +.inventory th { + top: 0; +} +.inventory td { + white-space: nowrap; +} +.inventory td.title-cell { + white-space: normal; + min-width: 260px; + max-width: 400px; +} +.inventory .error-cell { + max-width: 180px; + overflow: hidden; + text-overflow: ellipsis; +} +.flow { + display: flex; + align-items: center; + gap: 0.5rem; + flex-wrap: wrap; +} +.flow span { + background: var(--surface); + border: 1px solid var(--line); + border-radius: 9px; + padding: 0.55rem 0.7rem; +} +.flow i { + font-style: normal; + color: var(--muted); +} +.bar { + height: 11px; + border-radius: 8px; + overflow: hidden; + background: var(--surface2); + display: flex; +} +.bar > span { + height: 100%; +} +.bar .pass { + background: #3eab78; +} +.bar .fail { + background: #d78585; +} +.detail-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 1rem; +} +.detail-grid .panel { + min-width: 0; +} +.facts { + display: grid; + grid-template-columns: minmax(145px, 210px) 1fr; + margin: 0; +} +.facts dt, +.facts dd { + border-bottom: 1px solid var(--line); + padding: 0.52rem 0; + margin: 0; + overflow-wrap: anywhere; +} +.facts dt { + color: var(--muted); + font-size: 0.85rem; +} +.facts dd { + font-size: 0.88rem; +} +.attempts { + display: grid; + gap: 0.7rem; +} +.attempt { + border: 1px solid var(--line); + border-radius: 10px; + padding: 0.8rem; + background: var(--surface); +} +.attempt-head { + display: flex; + align-items: center; + gap: 0.5rem; + flex-wrap: wrap; +} +.attempt .scalar { + font-variant-numeric: tabular-nums; + color: var(--muted); + font-size: 0.84rem; +} +.attempt details { + margin-top: 0.65rem; +} +.attempt summary { + cursor: pointer; + color: var(--accent); + font-weight: 650; +} +.evidence-links { + display: flex; + gap: 0.4rem; + flex-wrap: wrap; + margin-top: 0.55rem; +} +.evidence-links button, +.evidence-links a { + border: 1px solid var(--line); + background: var(--surface2); + padding: 0.35rem 0.55rem; + border-radius: 7px; + color: var(--accent); + font-size: 0.78rem; +} +.evidence-links button:hover { + background: var(--surface); +} +.error-message { + overflow-wrap: anywhere; + white-space: pre-wrap; + background: #fff4f3; + border-left: 3px solid var(--bad); + padding: 0.65rem; + margin: 0.6rem 0; + color: #6f2828; + font-size: 0.82rem; +} +.code, +pre, +code { + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; +} +code { + font-size: 0.82em; + overflow-wrap: anywhere; +} +pre { + white-space: pre-wrap; + overflow: auto; + max-height: 60vh; + background: #101c2d; + color: #f2f5f9; + padding: 1rem; + border-radius: 9px; + font-size: 0.78rem; + line-height: 1.55; +} +.footer { + border-top: 1px solid var(--line); + padding: 1.4rem clamp(1rem, 3vw, 2.5rem); + color: var(--muted); + display: flex; + justify-content: space-between; + gap: 1rem; +} +.loading { + padding: 4rem 0; + color: var(--muted); +} +dialog { + width: min(1000px, calc(100vw - 2rem)); + max-height: 88vh; + border: 1px solid var(--line); + border-radius: 14px; + padding: 0; + background: var(--surface); + color: var(--ink); + box-shadow: 0 35px 80px rgba(0, 0, 0, 0.25); +} +dialog::backdrop { + background: rgba(14, 29, 49, 0.65); +} +.dialog-head { + position: sticky; + top: 0; + background: var(--surface); + border-bottom: 1px solid var(--line); + padding: 0.85rem 1rem; + display: flex; + align-items: center; + justify-content: space-between; + z-index: 2; +} +.dialog-head h2 { + font-size: 1rem; + margin: 0; + overflow-wrap: anywhere; +} +.dialog-head button { + border: 1px solid var(--line); + background: var(--surface2); + border-radius: 7px; + padding: 0.3rem 0.55rem; +} +#evidence-body { + padding: 1rem; + max-height: calc(88vh - 58px); + overflow: auto; +} +.empty { + color: var(--muted); + padding: 1.2rem; +} +.mini { + font-size: 0.8rem; +} +.result-summary { + display: flex; + gap: 1rem; + flex-wrap: wrap; +} +.result-summary .metric-card { + flex: 1; + min-width: 155px; +} +.breadcrumb { + font-size: 0.8rem; + color: var(--muted); + margin-top: 1.5rem; +} +.breadcrumb a { + color: var(--muted); +} +[data-theme="dark"] { + --ink: #e9eef5; + --muted: #a2b1c2; + --line: #354357; + --surface: #1b2939; + --surface2: #243348; + --accent: #8dbaf8; + --accent2: #7fd3c7; + --good: #83dbad; + --bad: #f29b9b; + --shadow: none; + background: #111c2a; + color: var(--ink); +} +[data-theme="dark"] .notice { + background: #193d35; +} +[data-theme="dark"] .notice.warn { + background: #463423; +} +[data-theme="dark"] .winner { + background: rgba(67, 177, 117, 0.14); +} +[data-theme="dark"] .status.pass { + background: #1b4438; + border-color: #326952; +} +[data-theme="dark"] .status.fail, +[data-theme="dark"] .error-message { + background: #472a31; + color: #ffd2d2; + border-color: #805158; +} +[data-theme="dark"] .button.secondary { + background: var(--surface); +} +[data-theme="dark"] .brand-glyph { + background: #2e6fb7; +} +@media (max-width: 1000px) { + .topbar-inner { + flex-wrap: wrap; + } + nav { + order: 3; + flex-basis: 100%; + } +} +@media (max-width: 680px) { + .menu-toggle { + display: inline-block; + margin-left: auto; + } + .topbar-inner { + gap: 0.7rem; + } + nav { + display: none; + order: 4; + flex-basis: 100%; + padding: 0.35rem 0; + } + nav.open { + display: flex; + } + .actions { + margin-left: 0; + } + .grid.two, + .grid.three, + .detail-grid { + grid-template-columns: 1fr; + } + .hero { + padding-top: 2rem; + } + .section { + margin: 1.3rem 0 2rem; + } + .facts { + grid-template-columns: 125px 1fr; + } + .footer { + flex-direction: column; + } + .inventory { + max-height: 62vh; + } + dialog { + width: calc(100vw - 0.6rem); + max-height: 92vh; + } + #evidence-body { + max-height: calc(92vh - 58px); + } +} +h1, +.breadcrumb, +.subtitle { + overflow-wrap: anywhere; +} +.facts dt, +.facts dd { + min-width: 0; +} +.tag { + white-space: normal; + overflow-wrap: anywhere; +} +.grid > * { + min-width: 0; +} + +.failure-cell { + min-width: 230px; + max-width: 320px; +} +.failure-cell a { + display: block; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + font-size: 0.82rem; +} +.failure-cell a + a { + margin-top: 0.25rem; +} + +[hidden] { + display: none !important; +} + +.protocol-diagram { + display: flex; + justify-content: center; + overflow: auto; + padding: 1rem; + border: 1px solid var(--line); + border-radius: 12px; +} +.protocol-diagram .mermaid { + background: transparent; + max-width: 100%; + margin: 0; +} +.protocol-diagram svg { + max-width: 100%; + height: auto; +} + +.failure-cell button { + display: block; + width: 100%; + border: 0; + background: transparent; + color: var(--accent); + text-align: left; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + font-size: 0.82rem; + padding: 0; +} +.failure-cell button + button { + margin-top: 0.25rem; +} +.failure-cell button:hover { + text-decoration: underline; +} + +.table-scroll table { + min-width: 620px; +} +.table-scroll th { + white-space: nowrap; +} +.table-scroll td:first-child { + min-width: 120px; +} +.table-scroll td code { + white-space: nowrap; +} +.evidence-search { + display: flex; + gap: 0.5rem; + align-items: center; + flex-wrap: wrap; + margin: 0.7rem 0; +} +.evidence-search input { + flex: 1; + min-width: 160px; + padding: 0.45rem; + background: var(--surface); + color: var(--ink); + border: 1px solid var(--line); + border-radius: 6px; +} +.evidence-match { + background: #ffe59b; + color: #182536; + padding: 2px; +} + +.version-summary-table table { + min-width: 1120px; +} +.version-summary-table th:not(:first-child), +.version-summary-table td:not(:first-child) { + text-align: right; +} +.summary-chart { + margin: 1rem 0 0; + background: #fff; + border: 1px solid var(--line); + border-radius: 14px; + overflow: hidden; +} +.summary-chart img { + display: block; + width: 100%; + height: auto; +} +.summary-chart figcaption { + padding: 0.85rem 1rem; + border-top: 1px solid var(--line); + color: var(--muted); + font-size: 0.84rem; + line-height: 1.55; +} +[data-theme="dark"] .summary-chart { + background: #fff; +} +.version-summary > .subtle { + margin-top: 0.8rem; +} +.functional-method-table table { + min-width: 1040px; +} +.method-evidence { + margin-top: 0.45rem; +} +.method-evidence button { + border: 1px solid var(--line); + background: var(--surface2); + padding: 0.3rem 0.5rem; + border-radius: 7px; + color: var(--accent); + font-size: 0.76rem; +} + +.fixed-explorer-table { + max-height: 560px; +} +.fixed-explorer-table table { + min-width: 1000px; +} +.fixed-explorer-table td:first-child { + min-width: 340px; +} +.candidate-resource-table table { + min-width: 1500px; +} +.candidate-resource-table th { + white-space: nowrap; +} +[data-fixed-detail] { + margin: 0.6rem 0; + padding: 0.8rem; + border: 1px solid var(--line); + border-radius: 8px; +} +[data-fixed-detail] summary { + cursor: pointer; + font-weight: 650; +} +[data-fixed-detail] .error-message { + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.summary-chart { + overflow-x: auto; +} +.summary-chart img { + min-width: 1200px; +} diff --git a/scripts/moli_report/ui_check.js b/scripts/moli_report/ui_check.js new file mode 100644 index 000000000..ebc20fc92 --- /dev/null +++ b/scripts/moli_report/ui_check.js @@ -0,0 +1,554 @@ +"use strict"; +const path = require("path"), + os = require("os"); +const dataHome = + process.env.BROWSER_EVAL_DATA_HOME || + path.join(os.homedir(), ".browser-eval"); +const site = + process.env.MOLI_REPORT_SITE || + path.join(dataHome, "reports/moli-1.1.8-failures-site"); +const { chromium } = require( + path.join( + process.env.LEXBENCH_NODE_MODULES || + path.join(dataHome, "work/lexbench-headless-repro/node_modules"), + "playwright-core", + ), +); +const fs = require("fs"); +const model = JSON.parse( + fs.readFileSync(path.join(site, "data/model.json"), "utf8"), +); +const successId = model.cases.find( + (c) => c.on_passes === model.protocol.k_runs, +).id; +const shots = + process.env.MOLI_REPORT_SHOTS || + path.join(dataHome, "reports/moli-visual-qa"); +fs.mkdirSync(shots, { recursive: true }); +async function ready(page) { + let expected = decodeURIComponent( + (new URL(page.url()).hash.match(/page=([^&]+)/) || [])[1] || "home", + ); + await page + .locator('main[data-route="' + expected + '"] h1') + .waitFor({ timeout: 15000 }); +} +const origin = process.env.MOLI_REPORT_ORIGIN || "http://127.0.0.1:18766"; +const routes = [ + "home", + "dataset", + "method", + "analysis", + "results", + "review", + "guide", + "reproduce", + "contract/pw_raw_browser_getbrowsercommandline", + "task/pw_raw_browser_getbrowsercommandline", + "result/pw_raw_browser_getbrowsercommandline/off", + "result/" + successId + "/on", +]; +const urls = [origin + "/", origin + "/en/index.html"]; +const fixedIds = Object.keys(model.fixed_candidates || {}); +const fixedPass = model.fixed_case_outcomes?.find( + (c) => c.passes["119_on"] === 3, +)?.id; +const fixedFail = model.fixed_case_outcomes?.find( + (c) => c.passes["119_on"] < 3, +)?.id; +for (const id of new Set([fixedPass, fixedFail].filter(Boolean))) + routes.push("fixed/" + id); +async function metrics(page) { + return page.evaluate(() => { + let groups = new Map(); + for (let cell of document.querySelectorAll("[data-metric]")) { + let key = cell.getAttribute("data-metric"), + list = groups.get(key) || []; + list.push(cell); + groups.set(key, list); + } + for (let [key, cells] of groups) { + if (cells.length !== 2) throw Error("metric pair " + key); + let values = cells.map((c) => Number(c.dataset.sort)); + if (values.some((v) => !Number.isFinite(v))) + throw Error("numeric value " + key); + let direction = cells[0].dataset.metricDirection; + let expected = + values[0] === values[1] + ? -1 + : direction === "max" + ? values[0] > values[1] + ? 0 + : 1 + : values[0] < values[1] + ? 0 + : 1; + let marked = cells + .map((c, i) => (c.classList.contains("winner") ? i : -1)) + .filter((i) => i >= 0); + if (expected < 0 && marked.length) + throw Error("tied metric highlighted " + key); + if (expected >= 0 && (marked.length !== 1 || marked[0] !== expected)) + throw Error("wrong or missing highlight " + key); + } + return groups.size; + }); +} +async function caseMetric(page) { + let cells = await page + .locator(".core-table tbody tr") + .first() + .locator("[data-metric]") + .evaluateAll((xs) => + xs.map((x) => ({ value: Number(x.dataset.sort), text: x.textContent })), + ); + if ( + cells.length !== 2 || + cells.some( + (c, i) => + c.value !== model.case_outcomes[i ? "on" : "off"] || + !c.text.includes("/" + model.task_count + " "), + ) + ) + throw Error("primary metric must count cases"); +} +async function versionMetrics(page) { + let groups = await page + .locator("[data-version-metric]") + .evaluateAll((cells) => { + let out = {}; + for (let cell of cells) { + let key = cell.dataset.versionMetric; + (out[key] ??= []).push({ + value: Number(cell.dataset.value), + direction: cell.dataset.direction, + winner: cell.classList.contains("winner"), + }); + } + return out; + }); + for (let [key, cells] of Object.entries(groups)) { + if (cells.length !== 3) throw Error("version metric cardinality " + key); + let values = cells.map((cell) => cell.value), + target = + cells[0].direction === "max" + ? Math.max(...values) + : Math.min(...values), + unique = values.filter((value) => value === target).length === 1, + winners = cells.filter((cell) => cell.winner); + if (unique && (winners.length !== 1 || winners[0].value !== target)) + throw Error("version metric highlight " + key); + if (!unique && winners.length) + throw Error("tied version metric highlighted " + key); + } + return Object.keys(groups).length; +} +async function fixedMetrics(page) { + let groups = await page + .locator("[data-resource-metric]") + .evaluateAll((cells) => { + let groups = {}; + for (let cell of cells) { + let key = cell.dataset.resourceMetric + ":" + cell.dataset.population; + (groups[key] ??= []).push({ + value: Number(cell.dataset.value), + winner: cell.classList.contains("winner"), + }); + } + return groups; + }); + if (Object.keys(groups).length !== 12) throw Error("macOS metric coverage"); + for (let cells of Object.values(groups)) { + if (cells.length !== fixedIds.length) + throw Error("macOS participant coverage"); + let min = Math.min(...cells.map((x) => x.value)), + unique = cells.filter((x) => x.value === min).length === 1; + for (let cell of cells) + if (cell.winner !== (unique && cell.value === min)) + throw Error("macOS unique minimum"); + } + let functional = page.locator("[data-functional-method]"); + if ((await functional.count()) !== model.functional_methods.length) + throw Error("functional method coverage"); +} +async function run() { + let browser = await chromium.launch({ + executablePath: + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + headless: true, + args: ["--no-sandbox"], + }); + let checked = 0; + try { + for (let width of [1440, 390]) + for (let theme of ["light", "dark"]) + for (let base of urls) { + let page = await browser.newPage({ + viewport: { width, height: 900 }, + }); + await page.goto(base); + await page.evaluate((theme) => { + localStorage.setItem("moli-layout-theme", theme); + document.documentElement.dataset.theme = theme; + }, theme); + for (let route of routes) { + await page.goto(base + "#page=" + encodeURIComponent(route)); + await ready(page); + let err = await page.locator("main h1").innerText(); + if (/data read|读取失败|Could not load/.test(err)) + throw Error("route failed " + route); + let overflow = await page.evaluate( + () => + document.documentElement.scrollWidth - + document.documentElement.clientWidth, + ); + if (overflow > 1) + throw Error( + "horizontal viewport overflow " + + route + + " " + + width + + " " + + overflow, + ); + if ( + width === 390 && + !(await page + .locator("th") + .evaluateAll((cells) => + cells.every( + (c) => getComputedStyle(c).whiteSpace === "nowrap", + ), + )) + ) + throw Error("vertical table labels " + route); + if (route === "method") { + await page.locator(".mermaid svg").waitFor({ timeout: 10000 }); + } + if (["home", "guide"].includes(route) && model.macos_resource) + await fixedMetrics(page); + if (route === "home") { + await caseMetric(page); + let n = await metrics(page); + if (n < 8) throw Error("missing comparison metrics"); + if ((await versionMetrics(page)) !== 3) + throw Error("missing version summary metrics"); + if ( + (await page + .locator(".version-summary-table tbody tr") + .count()) !== 3 + ) + throw Error("version summary rows"); + let chart = page.locator(".summary-chart img"); + if ( + (await chart.count()) !== (model.macos_resource ? 2 : 1) || + !(await chart.evaluateAll((imgs) => + imgs.every((img) => img.complete && img.naturalWidth > 0), + )) + ) + throw Error("summary chart unavailable"); + if ((await page.locator("main h1").count()) !== 1) + throw Error("home summary count"); + } + if (route === "analysis") { + let actual = await page + .locator(".metric-card .value") + .allTextContents(); + let p = model.case_outcomes.paired; + let expected = [ + p.off_fail_on_pass, + p.off_pass_on_fail, + p.both_pass, + p.both_fail, + ].map((n) => n + " / " + model.task_count); + if (JSON.stringify(actual) !== JSON.stringify(expected)) + throw Error("case relation counts"); + let contributors = page.locator(".cost-contributors tbody tr"); + if ((await contributors.count()) !== 3) + throw Error("missing cost decomposition"); + if ( + !(await page + .locator("main") + .innerText() + .then((x) => + model.task_cost.slice(0, 3).every((c) => x.includes(c.id)), + )) + ) + throw Error("cost contributors missing"); + } + if (route.startsWith("result/")) { + if ( + (await page + .locator("section") + .filter({ has: page.locator("h2") }) + .count()) < 2 + ) + throw Error("detail sections"); + if ( + (await page.locator("[data-report-detail]").count()) !== + model.protocol.k_runs + ) + throw Error("attempt details"); + } + if ( + (await page.locator("html").getAttribute("data-theme")) !== theme + ) + throw Error("theme not applied"); + await page.screenshot({ + path: + shots + + "/" + + (base.includes("/en/") ? "en" : "zh") + + "-" + + width + + "-" + + theme + + "-" + + route.replaceAll("/", "_") + + ".png", + }); + if ( + width === 1440 && + theme === "light" && + !base.includes("/en/") && + ["home", "review", "guide"].includes(route) + ) + await page.screenshot({ + path: shots + "/full-" + route + ".png", + fullPage: true, + }); + checked++; + } + await page.close(); + } + let page = await browser.newPage(); + await page.goto(origin + "/#page=home"); + await ready(page); + await caseMetric(page); + await page + .locator(".core-table [data-metric]") + .first() + .evaluate((el) => { + el.dataset.sort = "580"; + el.textContent = "580/750"; + }); + let caseRejected = false; + try { + await caseMetric(page); + } catch { + caseRejected = true; + } + if (!caseRejected) throw Error("call-count headline negative control"); + await page.reload(); + await ready(page); + let baseline = await metrics(page); + if (baseline < 8) throw Error("metric coverage"); + let cell = page.locator(".winner[data-metric]").first(); + await cell.evaluate((el) => el.classList.remove("winner")); + let wrongRejected = false; + try { + await metrics(page); + } catch { + wrongRejected = true; + } + if (!wrongRejected) throw Error("missing-highlight negative control"); + await page.reload(); + await ready(page); + await page.evaluate(() => { + let old = document.querySelector(".winner[data-metric]"); + let other = [...document.querySelectorAll("[data-metric]")].find( + (x) => x !== old && x.dataset.metric === old.dataset.metric, + ); + old.classList.remove("winner"); + other.classList.add("winner"); + }); + let shiftedRejected = false; + try { + await metrics(page); + } catch { + shiftedRejected = true; + } + if (!shiftedRejected) throw Error("wrong-highlight negative control"); + await page.reload(); + await ready(page); + let tied = page.locator("[data-metric]").first(); + await tied.evaluate((el) => { + let other = [...document.querySelectorAll("[data-metric]")].find( + (x) => x !== el && x.dataset.metric === el.dataset.metric, + ); + other.dataset.sort = el.dataset.sort; + }); + let tieRejected = false; + try { + await metrics(page); + } catch { + tieRejected = true; + } + if (!tieRejected) throw Error("tie-highlight negative control"); + await page.reload(); + await ready(page); + await versionMetrics(page); + let versionWinner = page.locator(".winner[data-version-metric]").first(); + await versionWinner.evaluate((el) => el.classList.remove("winner")); + let versionRejected = false; + try { + await versionMetrics(page); + } catch { + versionRejected = true; + } + if (!versionRejected) throw Error("version-highlight negative control"); + await page.goto( + origin + "/#page=result%2Fpw_raw_browser_getbrowsercommandline%2Foff", + ); + await ready(page); + let section = page + .locator("section") + .filter({ has: page.locator("h2") }) + .filter({ hasText: "结果摘要" }); + if ((await section.count()) !== 1) throw Error("duplicate summary"); + await page.evaluate(() => { + let clone = document.querySelector("section").cloneNode(true); + document.querySelector("main").append(clone); + }); + if ((await section.count()) === 1) + throw Error("duplicate-summary negative control"); + await page.reload(); + await ready(page); + await page.locator("details").first().locator("summary").click(); + let button = page.locator('button[data-evidence$="/cdp.jsonl"]').first(); + await button.click(); + await page.locator("dialog[open]").waitFor(); + await page.waitForFunction(() => + document.querySelector("dialog")?.innerText.includes("UnknownMethod"), + ); + if ( + !(await page + .locator("dialog") + .innerText() + .then( + (x) => + x.includes("Browser.getBrowserCommandLine") && + x.includes("UnknownMethod"), + )) + ) + throw Error("failure evidence missing"); + await page.locator("mark.evidence-match").waitFor({ state: "visible" }); + if ( + (await page.locator("mark.evidence-match").innerText()) !== + "UnknownMethod" + ) + throw Error("error log locator"); + await page.screenshot({ path: shots + "/failure-evidence-dialog.png" }); + await page.keyboard.press("Escape"); + if (await page.locator("dialog[open]").count()) + throw Error("Escape did not close"); + if (!(await button.evaluate((el) => document.activeElement === el))) + throw Error("focus not restored"); + await page.goto( + origin + "/#page=" + encodeURIComponent("result/" + successId + "/on"), + ); + await ready(page); + await page.locator("details").first().locator("summary").click(); + await page.locator('button[data-evidence$="/grader.json"]').first().click(); + await page.locator("dialog[open]").waitFor(); + await page.waitForFunction(() => + document.querySelector("dialog")?.innerText.includes('"ok": true'), + ); + if ( + !(await page + .locator("dialog") + .innerText() + .then((x) => x.includes('"ok": true'))) + ) + throw Error("success evidence missing"); + await page.goto(origin + "/#page=results"); + await ready(page); + await page.locator("#query").fill("Browser.getBrowserCommandLine"); + if ((await page.locator("#inventory-table tbody tr").count()) < 1) + throw Error("error search mismatch"); + let diagnosisTrigger = page.locator(".failure-cell button").first(); + await diagnosisTrigger.click(); + await page.locator("dialog[open] [data-canonical-result]").waitFor(); + if ( + !(await page + .locator("dialog") + .innerText() + .then((x) => + x.includes("Browser.getBrowserCommandLine: UnknownMethod"), + )) + ) + throw Error("inventory diagnosis missing"); + await page.screenshot({ path: shots + "/inventory-diagnosis-dialog.png" }); + await page.locator("dialog [data-canonical-result]").click(); + await ready(page); + if ( + !(await page + .locator("main") + .innerText() + .then((x) => + x.includes("Browser.getBrowserCommandLine: UnknownMethod"), + )) + ) + throw Error("error drilldown mismatch"); + await page.goto( + origin + "/#page=task%2Fpw_raw_browser_getbrowsercommandline", + ); + await ready(page); + if ( + (await page.locator("[data-pair-row]").count()) !== model.protocol.k_runs + ) + throw Error("paired attempt coverage"); + await page.locator('[data-pair-row="3"] a').first().click(); + await page + .locator( + '[data-report-detail="pw_raw_browser_getbrowsercommandline-off-3"] details[open]', + ) + .waitFor(); + if (!page.url().includes("attempt=3")) throw Error("paired attempt target"); + if (fixedPass && fixedFail) { + for (let id of [fixedPass, fixedFail]) { + await page.goto(origin + "/#page=" + encodeURIComponent("fixed/" + id)); + await ready(page); + let detail = page.locator('[data-fixed-detail="119_on-1"]'); + await detail.locator("summary").click(); + let button = detail + .locator( + 'button[data-evidence$="/grader.json"],button[data-evidence$="/stdout.log"]', + ) + .first(); + await button.click(); + await page.locator("dialog[open] #evidence-text").waitFor(); + if (!(await page.locator("#evidence-text").innerText()).trim()) + throw Error("empty fixed-mode evidence"); + await page.keyboard.press("Escape"); + if (await page.locator("dialog[open]").count()) + throw Error("fixed evidence Escape"); + if (!(await button.evaluate((el) => document.activeElement === el))) + throw Error("fixed evidence focus"); + await page.locator(".breadcrumb a").click(); + await ready(page); + } + await page.locator("#fixed-relation").selectOption("1"); + await page.locator("#fixed-outcome").selectOption("all"); + if ( + (await page.locator(".fixed-explorer-table tbody tr").count()) !== 372 + ) + throw Error("fixed case explorer coverage"); + } + await page.close(); + console.log( + JSON.stringify({ + route_theme_viewport_checks: checked, + negative_controls: 6, + evidence_flows: fixedPass && fixedFail ? 6 : 4, + result: "pass", + }), + ); + } finally { + await browser.close(); + } +} +run().catch((e) => { + console.error(e); + process.exit(1); +}); diff --git a/scripts/moli_report/verify.py b/scripts/moli_report/verify.py new file mode 100644 index 000000000..71353c16a --- /dev/null +++ b/scripts/moli_report/verify.py @@ -0,0 +1,808 @@ +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +import math +import pathlib +import re +import shutil +import statistics +import subprocess +import tempfile + +parser = argparse.ArgumentParser() +parser.add_argument( + "--site", + type=pathlib.Path, + default=pathlib.Path.home() / ".browser-eval/reports/moli-1.1.8-failures-site", +) +parser.add_argument( + "--release", action="store_true", help="Require the complete bound method matrix" +) +args = parser.parse_args() +SITE = args.site.resolve() + + +def digest(p): + return hashlib.sha256(p.read_bytes()).hexdigest() + + +def near(a, b): + return math.isclose(float(a), float(b), rel_tol=1e-8, abs_tol=1e-6) + + +def fail(message): + raise ValueError(message) + + +def validate(model, site, check_files=True): + if model.get("schema") != "moli_layout_report/2": + fail("schema") + count = model.get("task_count") + calls_per_mode = model.get("attempts_per_mode") + if not isinstance(count, int) or count != 372 or calls_per_mode != count * 3: + fail("denominator") + protocol = model.get("protocol") or {} + if ( + protocol.get("k_runs") != 3 + or protocol.get("jobs") != 1 + or not protocol.get("seed") + or protocol.get("score_eligible") is not False + ): + fail("diagnostic protocol") + if not all( + re.fullmatch(r"[0-9a-f]{64}", str(protocol.get(k, ""))) + for k in ("runner_sha256", "fixtures_sha256") + ): + fail("source identity") + inv = model.get("cases") or [] + if len(inv) != count or len({c["id"] for c in inv}) != count: + fail("inventory") + if len(model.get("strata") or []) != 15: + fail("strata") + outcome = model.get("case_outcomes") or {} + expected_pair = dict.fromkeys( + ("both_pass", "both_fail", "off_fail_on_pass", "off_pass_on_fail"), 0 + ) + accepted = {"off": 0, "on": 0} + for item in inv: + case = json.loads((site / "data/cases" / f"{item['id']}.json").read_text()) + flags = { + mode: len(case["modes"][mode]["attempts"]) == protocol["k_runs"] + and all(a["status"] == "pass" for a in case["modes"][mode]["attempts"]) + for mode in ("off", "on") + } + a, b = flags["off"], flags["on"] + for mode in flags: + accepted[mode] += flags[mode] + expected_pair[ + "both_pass" + if a and b + else "off_pass_on_fail" + if a + else "off_fail_on_pass" + if b + else "both_fail" + ] += 1 + if outcome != { + "rule": "all_recorded_attempts_pass", + "repeats": protocol["k_runs"], + "total": count, + **accepted, + "paired": expected_pair, + }: + fail("case outcome aggregation") + comparison = model.get("version_comparison") or {} + version_rows = comparison.get("configurations") or [] + expected_version_ids = ["114_off", "118_off", "118_on"] + if ( + comparison.get("baseline") != "114_off" + or [row.get("id") for row in version_rows] != expected_version_ids + ): + fail("version comparison registry") + functional_population = comparison.get("functional_population") or {} + if any( + functional_population.get(k) != v + for k, v in { + "cases": 372, + "attempts_per_case": 3, + "rule": "all_three_attempts_pass", + "version_118_direct_cases": 372, + "version_114_candidate_cases": 1, + "version_114_inherited_failures": 371, + "version_114_candidate": "v4_cdp_emulation_setdefaultbackgroundcoloroverride", + "version_114_method": "differential_candidate_check", + }.items() + ): + fail("version functional population") + resource_population = comparison.get("resource_population", {}) + if ( + resource_population.get("experiment_cases") != 557 + or resource_population.get("attempts_per_case") != 5 + or resource_population.get("total_tasks") != 557 + or resource_population.get("calls_per_task") != 5 + or resource_population.get("chart_calls") != 1045 + ): + fail("version resource population") + baseline = version_rows[0] + for row in version_rows: + if row.get("total_cases") != 372 or not 0 <= row.get("passed_cases", -1) <= 372: + fail("version pass denominator") + if not near(row["success_rate_pct"], row["passed_cases"] / 372 * 100): + fail("version success rate") + if not near( + row["success_change_pp"], row["success_rate_pct"] - baseline["success_rate_pct"] + ): + fail("version success change") + if not near(row["pss_change_pct"], (row["pss_mib"] / baseline["pss_mib"] - 1) * 100): + fail("version PSS change") + if not near(row["cpu_change_pct"], (row["cpu_ms"] / baseline["cpu_ms"] - 1) * 100): + fail("version CPU change") + functional_methods = model.get("functional_methods") or [] + candidates = model.get("fixed_candidates") or {} + expected_ids = ["114_off", "118_off", "118_on"] + list(candidates) + if [row.get("id") for row in functional_methods] != expected_ids: + fail("functional method registry") + if [ + (row.get("final_passed_cases"), row.get("direct_cases"), row.get("inherited_cases")) + for row in functional_methods[:3] + ] != [(0, 1, 371), (1, 372, 0), (255, 372, 0)]: + fail("fixed functional methods") + for method_id, candidate in candidates.items(): + if method_id not in {"119_off", "119_on", "119_official_on"}: + fail("unknown fixed method") + info = candidate.get("evidence") or {} + path = site / info.get("url", "") + if not path.resolve().is_relative_to(site.resolve()): + fail("unsafe fixed summary target") + if ( + not path.is_file() + or path.is_symlink() + or digest(path) != info.get("sha256") + or path.stat().st_size != info.get("bytes") + ): + fail("fixed summary integrity") + summary = json.loads(path.read_text()) + if summary.get("schema") != "lexbench_moli_fixed_layout_summary/1": + fail("fixed summary schema") + layout = "off" if method_id == "119_off" else "on" + if summary.get("layout") != layout: + fail("fixed layout identity") + for field in ("population", "outcomes", "binary", "sources"): + if summary.get(field) != candidate.get(field): + fail("fixed summary binding") + population = summary.get("population") or {} + if ( + population.get("cases") != 372 + or population.get("attempts_per_case") != 3 + or population.get("calls") != 1116 + ): + fail("fixed summary population") + cases = summary.get("cases") or [] + if len(cases) != 372 or {c["task_id"] for c in cases} != {c["id"] for c in inv}: + fail("fixed summary cases") + passed = 0 + for case in cases: + attempts = case.get("attempts") or [] + if len(attempts) != 3 or {a["attempt"] for a in attempts} != {1, 2, 3}: + fail("fixed summary attempts") + passes = sum(a["status"] == "pass" for a in attempts) + if case.get("passes") != passes: + fail("fixed summary case verdict") + passed += passes == 3 + if summary["outcomes"].get("passed_cases") != passed or not near( + summary["outcomes"]["success_rate_pct"], passed / 372 * 100 + ): + fail("fixed summary result") + row = next(x for x in functional_methods if x["id"] == method_id) + if ( + row.get("final_passed_cases") != passed + or row.get("physical_calls") != 1116 + or row.get("policy") != f"fixed_{layout}" + ): + fail("fixed method row") + if row.get("moli_sha256") != summary["binary"]["moli_sha256"]: + fail("fixed method binary") + if candidates: + compact = model.get("fixed_case_outcomes") or [] + if len(compact) != 372 or {c["id"] for c in compact} != {c["id"] for c in inv}: + fail("fixed outcome inventory") + for item in compact: + path = site / "data/fixed-cases" / f"{item['id']}.json" + if not path.is_file() or path.is_symlink(): + fail("fixed case evidence target") + detail = json.loads(path.read_text()) + if set(detail["methods"]) != set(candidates) or set(item["passes"]) != set(candidates): + fail("fixed case registry") + for method_id, result in detail["methods"].items(): + if result["passes"] != item["passes"][method_id] or result["passes"] != sum( + a["status"] == "pass" for a in result["attempts"] + ): + fail("fixed case count") + if len(result["attempts"]) != 3: + fail("fixed detail attempts") + for attempt in result["attempts"]: + if attempt["status"] != "pass" and not attempt.get("failure", {}).get("detail"): + fail("fixed failure locator") + if not attempt.get("evidence"): + fail("fixed attempt lacks evidence") + for evidence in attempt["evidence"].values(): + target = site / evidence["url"] + if ( + not target.resolve().is_relative_to(site.resolve()) + or not target.is_file() + or target.is_symlink() + ): + fail("fixed log target") + if check_files and ( + digest(target) != evidence["sha256"] + or target.stat().st_size != evidence["bytes"] + ): + fail("fixed log integrity") + for resource_key in ("macos_resource", "official_resource"): + resource = model.get(resource_key) + if not resource: + continue + official = resource_key == "official_resource" + info = resource.get("evidence") or {} + path = site / info.get("url", "") + if not path.resolve().is_relative_to(site.resolve()): + fail("unsafe resource target") + if check_files and ( + not path.is_file() + or path.is_symlink() + or digest(path) != info.get("sha256") + or path.stat().st_size != info.get("bytes") + ): + fail("resource integrity") + summary = json.loads(path.read_text()) if check_files else resource.get("summary") + if ( + summary != resource.get("summary") + or summary.get("schema") != "lexbench_moli_macos_fixed_resource_summary/1" + ): + fail("resource identity") + population = summary.get("population") or {} + if population != { + "tasks": 557, + "attempts_per_task": 5, + "calls_per_configuration": 2785, + "frozen_comparison_calls": 1045, + "frozen_comparison_tasks": 209, + }: + fail("resource population") + quality = summary.get("quality") or {} + if ( + quality.get("memory_metric") != "process_tree_rss" + or quality.get("pss_available") is not False + or quality.get("publishable") is not True + ): + fail("resource quality") + layouts = ["on"] if official else ["off", "on"] + method = summary.get("method") or {} + if ( + method.get("configurations") != [f"layout_{x}" for x in layouts] + or method.get("resource_runs") != len(layouts) + or method.get("layout_retry") is not False + or method.get("attempts_per_case") != 5 + or method.get("resource_sample_interval_ms") != 250 + ): + fail("resource method") + configs = summary.get("configurations") or {} + if set(configs) != set(layouts): + fail("resource configurations") + for layout, config in configs.items(): + method_id = "119_official_on" if official else f"119_{layout}" + if ( + summary["candidate"]["binary_sha256"] + != candidates[method_id]["binary"]["moli_sha256"] + ): + fail("resource binary") + if ( + config.get("layout") != layout + or config.get("quality", {}).get("publishable") is not True + ): + fail("configuration quality") + for name, n in ( + ("all_predeclared_calls", 2785), + ("frozen_historical_common_pass_calls", 1045), + ): + for metric in ("rss_peak_mib", "cpu_time_ms"): + stats = config.get("metrics", {}).get(name, {}).get(metric, {}) + if stats.get("n") != n: + fail("metric denominator") + if any( + not isinstance(stats.get(key), (float, int)) + or not math.isfinite(stats[key]) + for key in ("mean", "p50", "p95", "sum") + ): + fail("metric finite values") + if not near(stats["sum"], stats["mean"] * n): + fail("metric mean/sum agreement") + if not official: + for name in ("all_predeclared_calls", "frozen_historical_common_pass_calls"): + change_values = summary["comparisons"][name] + for metric, stat, key in [ + ("rss_peak_mib", "p50", "layout_on_vs_off_rss_p50_change_pct"), + ("cpu_time_ms", "mean", "layout_on_vs_off_cpu_mean_change_pct"), + ]: + expected = ( + configs["on"]["metrics"][name][metric][stat] + / configs["off"]["metrics"][name][metric][stat] + - 1 + ) * 100 + if not near(change_values[key], expected): + fail("resource percentage change") + chart = model.get("macos_comparison") + if model.get("macos_resource"): + if not chart or {r["id"] for r in chart["configurations"]} != set(candidates): + fail("macOS chart registry") + baseline = next(r for r in chart["configurations"] if r["id"] == chart["baseline"]) + for row in chart["configurations"]: + resource = ( + model["official_resource"] + if row["id"] == "119_official_on" + else model["macos_resource"] + ) + layout = "off" if row["id"] == "119_off" else "on" + metrics = resource["summary"]["configurations"][layout]["metrics"][ + "frozen_historical_common_pass_calls" + ] + if row["passed_cases"] != candidates[row["id"]]["outcomes"]["passed_cases"] or not near( + row["success_rate_pct"], row["passed_cases"] / 372 * 100 + ): + fail("macOS chart success") + for value, change, expected in [ + ("rss_mib", "rss_change_pct", metrics["rss_peak_mib"]["p50"]), + ("cpu_ms", "cpu_change_pct", metrics["cpu_time_ms"]["mean"]), + ]: + if not near(row[value], expected) or not near( + row[change], (row[value] / baseline[value] - 1) * 100 + ): + fail("macOS chart metric or change") + for lang in ("zh", "en"): + path = site / f"assets/moli-macos-success-resources-{lang}.svg" + if ( + not path.is_file() + or "RSS" not in path.read_text() + or "CPU" not in path.read_text() + or "PSS" in path.read_text() + ): + fail("macOS chart axes") + correction = model.get("functional_contract_correction") or {} + if ( + correction.get("task_count") != 2 + or correction.get("configuration_count") != 3 + or correction.get("calls") != 18 + or correction.get("success_rates_changed") is not False + ): + fail("functional correction summary") + correction_info = correction.get("evidence") or {} + correction_path = site / correction_info.get("url", "") + if not correction_path.resolve().is_relative_to(site.resolve()): + fail("unsafe functional correction target") + if check_files and ( + not correction_path.is_file() + or correction_path.is_symlink() + or digest(correction_path) != correction_info.get("sha256") + or correction_path.stat().st_size != correction_info.get("bytes") + ): + fail("functional correction evidence integrity") + if check_files: + receipt = json.loads(correction_path.read_text()) + if receipt.get("schema") != "moli_functional_contract_correction/1" or receipt.get( + "harness_commit" + ) != correction.get("harness_commit"): + fail("functional correction identity") + if [row.get("id") for row in receipt.get("configurations", [])] != [ + "114_off", + "118_off", + "118_on", + ]: + fail("functional correction configurations") + if any( + status != "fail" + for row in receipt["configurations"] + for task in row["outcomes"].values() + for status in task["attempts"] + ): + fail("functional correction outcomes") + costs = model.get("task_cost") or [] + if len(costs) != count or {x["id"] for x in costs} != {x["id"] for x in inv}: + fail("task cost coverage") + cost_by_id = {x["id"]: x for x in costs} + if len(cost_by_id) != count: + fail("duplicate task cost") + full = [] + for item in inv: + p = site / "data/cases" / f"{item['id']}.json" + if check_files and not p.is_file(): + fail("broken case target") + c = json.loads(p.read_text()) if check_files else item.get("_case") + if not c: + fail("missing case") + if c["id"] != item["id"] or c["stratum"] != item["stratum"]: + fail("case identity") + cost = cost_by_id[c["id"]] + for mode in ("off", "on"): + attempts = c["modes"][mode]["attempts"] + if len(attempts) != 3 or [x["ordinal"] for x in attempts] != [1, 2, 3]: + fail("attempt coverage") + passes = sum(x["status"] == "pass" for x in attempts) + if passes != c["modes"][mode]["passes"] or passes != item[mode + "_passes"]: + fail("pass summary") + if passes != cost[mode + "_passes"]: + fail("task cost pass count") + if not near(cost[mode + "_duration_ms"], sum(a["duration_ms"] for a in attempts)): + fail("task cost duration") + if not near( + cost[mode + "_cpu_ms"], sum(a["resource"]["cpu_total_ms"] for a in attempts) + ): + fail("task cost CPU") + details = sorted({x["failure"]["detail"] for x in attempts if x["status"] != "pass"}) + if details != item.get(mode + "_fail_details"): + fail("failure summary") + for a in attempts: + if a["status"] != "pass" and not ( + a["failure"]["detail"] or a["failure"]["class"] == "unavailable" + ): + fail("failure without exact error or unavailable state") + if not isinstance(a["resource"].get("cpu_total_ms"), (int, float)): + fail("missing CPU") + if not isinstance(a["resource"].get("pss_end_bytes"), (int, float)): + fail("missing PSS") + if a["resource"].get("fixture_tx_bytes") is None: + fail("missing fixture traffic") + if not a.get("evidence", {}).get("baseline", {}).get("grader.json"): + fail("missing grader target") + if a["status"] != "pass" and not ( + a["evidence"]["baseline"].get("stderr.log") + or a["evidence"]["baseline"].get("cdp.jsonl") + ): + fail("failure without log target") + for files in a["evidence"].values(): + for _name, info in files.items(): + if not info.get("url") or not info.get("sha256"): + fail("broken evidence reference") + target = site / info["url"] + if not target.resolve().is_relative_to(site.resolve()): + fail("unsafe evidence target") + if check_files and ( + not target.is_file() + or target.is_symlink() + or digest(target) != info["sha256"] + or target.stat().st_size != info["bytes"] + ): + fail("bad evidence hash or target") + full.extend((mode, a) for a in attempts) + for mode in ("off", "on"): + calls = [a for m, a in full if m == mode] + if len(calls) != calls_per_mode: + fail("call matrix") + b = model["metrics"][mode]["baseline"] + p = model["metrics"][mode]["profile"] + if b["passes"] != sum(a["status"] == "pass" for a in calls): + fail("headline pass count") + if not near(b["duration_ms_all"]["sum"], sum(a["duration_ms"] for a in calls)): + fail("headline duration") + if not near(p["cpu_ms_all"]["sum"], sum(a["resource"]["cpu_total_ms"] for a in calls)): + fail("headline CPU") + if p["fixture_tx_bytes_all"]["sum"] != sum( + a["resource"]["fixture_tx_bytes"] for a in calls + ): + fail("headline traffic") + counts = {key: 0 for key in ("both_pass", "both_fail", "off_fail_on_pass", "off_pass_on_fail")} + for item in inv: + c = json.loads((site / "data/cases" / f"{item['id']}.json").read_text()) + for off, on in zip( + c["modes"]["off"]["attempts"], c["modes"]["on"]["attempts"], strict=True + ): + a = off["status"] == "pass" + b = on["status"] == "pass" + counts[ + "both_pass" + if a and b + else "off_pass_on_fail" + if a + else "off_fail_on_pass" + if b + else "both_fail" + ] += 1 + if model["paired"]["baseline"] != counts: + fail("paired relation counts") + if not near( + sum(x["off_duration_ms"] - x["on_duration_ms"] for x in costs), + model["metrics"]["off"]["baseline"]["duration_ms_all"]["sum"] + - model["metrics"]["on"]["baseline"]["duration_ms_all"]["sum"], + ): + fail("task cost total") + common = [ + (c["modes"]["off"]["attempts"][i], c["modes"]["on"]["attempts"][i]) + for c in ( + json.loads((site / "data/cases" / f"{item['id']}.json").read_text()) for item in inv + ) + for i in range(3) + if all( + c["modes"][m]["attempts"][i][key] == "pass" + for m in ("off", "on") + for key in ("status", "profile_status") + ) + ] + if ( + len(common) != model["common_pass"]["count"] + or len(common) > model["paired"]["baseline"]["both_pass"] + ): + fail("common pass denominator") + for mode, index in [("off", 0), ("on", 1)]: + c = model["common_pass"] + if not near( + c["cpu_total_ms"][mode], sum(x[index]["resource"]["cpu_total_ms"] for x in common) + ): + fail("common pass CPU") + if not near( + c["pss_end_mean_bytes"][mode], + statistics.mean(x[index]["resource"]["pss_end_bytes"] for x in common), + ): + fail("common pass PSS") + if not near( + c["fixture_tx_total_bytes"][mode], + sum(x[index]["resource"]["fixture_tx_bytes"] for x in common), + ): + fail("common pass traffic") + q = model["quality"][mode] + if q["resource_missing"]: + fail("missing resource evidence") + calibration = q.get("calibration", {}) + if not calibration.get("acceptable"): + fail("resource timing calibration failed") + if ( + calibration.get("matched_attempts") != calls_per_mode + or not calibration.get("complete_pairing") + or calibration.get("provenance_mismatches") + ): + fail("invalid calibration pairing") + if ( + model["protocol"].get("timing_primary") != "unprofiled_driver_and_grade" + or model["protocol"].get("resource_scope") != "observed_profiled_process_tree" + ): + fail("measurement scope conflated") + mismatch = sum(a["status"] != a["profile_status"] for m, a in full if m == mode) + if q["status_mismatch_count"] != mismatch: + fail("profile mismatch disclosure") + if not isinstance(model.get("host_context", {}).get("shared_macos_host"), bool): + fail("missing host scope") + for correction in model.get("resource_window_corrections", []): + info = correction["evidence"] + path = site / info["url"] + if ( + not path.resolve().is_relative_to(site.resolve()) + or not path.is_file() + or digest(path) != info["sha256"] + ): + fail("correction evidence integrity") + rows = json.loads(path.read_text()) + if len(rows) != calls_per_mode or correction["calls"] != calls_per_mode: + fail("correction scope") + if not near(sum(x["cpu_total_ms"] for x in rows), correction["old_cpu_ms"]): + fail("correction CPU") + for path, language in [(site / "index.html", "zh-CN"), (site / "en/index.html", "en")]: + if not path.is_file() or f'lang="{language}"' not in path.read_text(): + fail("locale shell") + for asset in ("app.js", "style.css"): + if not (site / asset).is_file(): + fail("missing shared asset") + if not (site / "README.md").is_file(): + fail("missing offline bundle instructions") + if ( + not (site / "data/version-comparison.json").is_file() + or json.loads((site / "data/version-comparison.json").read_text()) != comparison + ): + fail("version comparison data target") + charts = { + "zh": (site / "assets/moli-version-success-resources-zh.svg", "372 题成功率与资源消耗"), + "en": ( + site / "assets/moli-version-success-resources-en.svg", + "Success on 372 cases vs. resource use", + ), + } + for chart_name, (chart, title) in charts.items(): + if ( + not chart.is_file() + or '' not in chart.read_text() + or title not in chart.read_text() + ): + fail("summary chart target " + chart_name) + chart_text = chart.read_text() + for row in version_rows: + for key in ("pss_change_pct", "cpu_change_pct"): + if f"{row[key]:+.2f}%" not in chart_text: + fail( + "summary chart missing baseline change " + + chart_name + + " " + + row["id"] + + " " + + key + ) + if not (site / "reproduction/plot_version_summary.py").is_file(): + fail("missing chart reproduction script") + js = (site / "app.js").read_text() + css = (site / "style.css").read_text() + if ( + "data-report-detail" not in js + or "data-evidence" not in js + or "showModal()" not in js + or "trigger?.focus()" not in js + ): + fail("evidence interaction contract") + if "data-metric-direction" not in js or "winner" not in css: + fail("highlight contract") + if check_files: + bad = re.compile( + r"/(?:Users|home|private/tmp|tmp|results|work)/|127\.0\.0\.1:\d+|ARTIFACT_SITE_TOKEN" + ) + for p in site.rglob("*"): + if ( + p.is_file() + and p.suffix in (".json", ".jsonl", ".log", ".html", ".js", ".css") + and bad.search(p.read_text(errors="replace")) + ): + fail("private path or endpoint leaked") + return True + + +model = json.loads((SITE / "data/model.json").read_text()) +if args.release: + profile_path = ( + pathlib.Path(__file__).resolve().parents[2] / "evaluation/moli/current-report.json" + ) + profile = json.loads(profile_path.read_text()) + if [row["id"] for row in model["functional_methods"]] != profile["method_ids"]: + fail("release requires the complete bound functional method matrix") + if ( + not model.get("macos_comparison") + or [row["id"] for row in model["macos_comparison"]["configurations"]] + != profile["macos_method_ids"] + ): + fail("release requires all bound macOS resource configurations") +validate(model, SITE) +# Semantic negative controls must fail through the same validator. +negative_controls = 0 + + +def rejected(change): + global negative_controls + copy_model = copy.deepcopy(model) + change(copy_model) + try: + validate(copy_model, SITE) + except ValueError: + negative_controls += 1 + return + fail("negative control passed unexpectedly") + + +rejected( + lambda m: m["metrics"]["on"]["baseline"].update( + passes=m["metrics"]["on"]["baseline"]["passes"] + 1 + ) +) +rejected(lambda m: m["case_outcomes"].update(on=m["case_outcomes"]["on"] + 1)) +rejected( + lambda m: m["case_outcomes"]["paired"].update( + off_fail_on_pass=m["case_outcomes"]["paired"]["off_fail_on_pass"] + 1 + ) +) +rejected(lambda m: m["common_pass"]["cpu_total_ms"].update(off=0)) +rejected(lambda m: m["cases"].pop()) +rejected(lambda m: m["protocol"].update(score_eligible=True)) +rejected(lambda m: m["cases"][0].update(off_fail_details=["wrong error"])) +rejected(lambda m: m["task_cost"][0].update(off_duration_ms=0)) +rejected(lambda m: m["version_comparison"]["configurations"][1].update(pss_change_pct=99)) +rejected(lambda m: m["version_comparison"]["configurations"][2].update(success_rate_pct=0)) +rejected(lambda m: m["functional_contract_correction"].update(calls=17)) +rejected(lambda m: m["functional_contract_correction"].update(success_rates_changed=True)) +if model.get("fixed_candidates"): + rejected( + lambda m: m["functional_methods"][-1].update( + final_passed_cases=m["functional_methods"][-1]["final_passed_cases"] + 1 + ) + ) + rejected(lambda m: next(iter(m["fixed_candidates"].values()))["population"].update(calls=1115)) +for resource_key in ("macos_resource", "official_resource"): + if not model.get(resource_key): + continue + rejected( + lambda m, resource_key=resource_key: m[resource_key]["summary"]["population"].update( + calls_per_configuration=2784 + ) + ) + rejected( + lambda m, resource_key=resource_key: m[resource_key]["summary"]["population"].update( + frozen_comparison_calls=1044 + ) + ) + rejected( + lambda m, resource_key=resource_key: m[resource_key]["summary"]["quality"].update( + pss_available=True + ) + ) + rejected( + lambda m, resource_key=resource_key: next( + iter(m[resource_key]["summary"]["configurations"].values()) + )["metrics"]["all_predeclared_calls"]["cpu_time_ms"].update(sum=0) + ) +# Evidence target and missing-error mutations run on an isolated validation view. + +with tempfile.TemporaryDirectory() as td: + temp = pathlib.Path(td) / "site" + shutil.copytree(SITE, temp) + failure_id = next(x["id"] for x in model["cases"] if x["off_passes"] == 0) + bad_case = temp / "data/cases" / f"{failure_id}.json" + original = bad_case.read_text() + item = json.loads(original) + item["modes"]["off"]["attempts"][0]["failure"] = {"class": "cdp_semantic", "detail": ""} + bad_case.write_text(json.dumps(item)) + try: + validate(model, temp) + except ValueError: + negative_controls += 1 + else: + fail("missing-error negative control passed") + bad_case.write_text(original) + item = json.loads(original) + item["modes"]["off"]["attempts"][0]["evidence"]["baseline"]["grader.json"]["url"] = ( + "data/evidence/absent.json" + ) + bad_case.write_text(json.dumps(item)) + try: + validate(model, temp) + except ValueError: + negative_controls += 1 + else: + fail("broken-target negative control passed") + bad_case.write_text(original) + item = json.loads(original) + item["modes"]["off"]["attempts"][0]["evidence"]["baseline"].pop("stderr.log", None) + item["modes"]["off"]["attempts"][0]["evidence"]["baseline"].pop("cdp.jsonl", None) + bad_case.write_text(json.dumps(item)) + try: + validate(model, temp) + except ValueError: + negative_controls += 1 + else: + fail("missing-failure-log negative control passed") + bad_case.write_text(original) + leak = temp / "data/leak.log" + leak.write_text("evidence stored at /results/internal/attempt.json") + try: + validate(model, temp) + except ValueError: + negative_controls += 1 + else: + fail("private-path negative control passed") +candidate_calls = sum(c["population"]["calls"] for c in model.get("fixed_candidates", {}).values()) + +subprocess.run( + [ + "node", + str(pathlib.Path(__file__).resolve().parents[2] / "tests/moli_report_render_contract.cjs"), + "--site", + str(SITE), + ], + check=True, +) +print( + json.dumps( + { + "verified_cases": model["task_count"], + "verified_calls": model["attempts_per_mode"] * 4 + + model["functional_contract_correction"]["calls"] + + candidate_calls, + "verified_evidence_files": len(list((SITE / "data/evidence").rglob("*.*"))), + "negative_controls": negative_controls, + "result": "pass", + } + ) +) diff --git a/tests/moli_report_render_contract.cjs b/tests/moli_report_render_contract.cjs new file mode 100644 index 000000000..8282e9b92 --- /dev/null +++ b/tests/moli_report_render_contract.cjs @@ -0,0 +1,158 @@ +"use strict"; +const assert = require("node:assert/strict"), + fs = require("node:fs"), + vm = require("node:vm"), + path = require("node:path"); +const siteFlag = process.argv.indexOf("--site"), + site = siteFlag >= 0 ? process.argv[siteFlag + 1] : null; +const app = site + ? path.join(site, "app.js") + : path.join(__dirname, "../scripts/moli_report/app.js"); +const source = fs + .readFileSync(app, "utf8") + .split(/async function render\(\)\s*\{/)[0]; +function render(model, lang, expression) { + let context = { + document: { + documentElement: { dataset: { base: "" }, lang }, + getElementById: () => null, + }, + location: { hash: "" }, + MODEL: model, + }; + vm.createContext(context); + vm.runInContext(source + "\nM=MODEL;", context); + return vm.runInContext(expression, context); +} +function resourceHighlights(html) { + let groups = new Map(); + for (let match of html.matchAll( + /<td class="([^"]*)" data-resource-metric="([^"]*)" data-population="([^"]*)" data-value="([^"]*)">/g, + )) { + let key = match[2] + ":" + match[3]; + let group = groups.get(key) || []; + group.push({ + value: Number(match[4]), + highlight: match[1].split(/\s+/).includes("winner"), + }); + groups.set(key, group); + } + assert.equal(groups.size, 12); + for (let group of groups.values()) { + let min = Math.min(...group.map((x) => x.value)), + unique = group.filter((x) => x.value === min).length === 1; + for (let cell of group) + assert.equal(cell.highlight, unique && cell.value === min); + } +} +const stat = (n, value) => ({ + n, + sum: n * value, + mean: value, + p50: value, + p95: value, +}); +const config = (rss, cpu) => ({ + metrics: Object.fromEntries( + [ + ["all_predeclared_calls", 2785], + ["frozen_historical_common_pass_calls", 1045], + ].map(([scope, n]) => [ + scope, + { rss_peak_mib: stat(n, rss), cpu_time_ms: stat(n, cpu) }, + ]), + ), +}); +const methods = [ + ["119_off", "fixed_off", 1], + ["119_on", "fixed_on", 2], + ["119_official_on", "fixed_on", 2], +].map(([id, policy, count]) => ({ + id, + policy, + label: id, + label_en: id, + direct_cases: 372, + inherited_cases: 0, + final_passed_cases: count, + physical_calls: 1116, +})); +const resource = (configurations, profile) => ({ + summary: { candidate: { profile }, configurations }, + evidence: { url: "data/resource.json", sha256: "a".repeat(64) }, +}); +const model = { + task_count: 372, + functional_methods: methods, + fixed_candidates: Object.fromEntries(methods.map((m) => [m.id, {}])), + macos_resource: resource( + { off: config(100, 10), on: config(100, 20) }, + "debug", + ), + official_resource: resource({ on: config(120, 15) }, "official_release"), + macos_comparison: { baseline: "119_official_on" }, + fixed_case_outcomes: [ + { id: "a", passes: { "119_off": 3, "119_on": 0, "119_official_on": 3 } }, + { id: "b", passes: { "119_off": 0, "119_on": 3, "119_official_on": 3 } }, + { id: "c", passes: { "119_off": 0, "119_on": 3, "119_official_on": 0 } }, + ], +}; +for (let lang of ["zh", "en"]) { + const html = render(model, lang, "candidateResourceSection()"); + resourceHighlights(html); + assert.throws(() => resourceHighlights(html.replace("num winner", "num"))); + const missing = html.replace( + 'data-resource-metric="rss_peak_mib-mean"', + 'data-metric-removed="rss_peak_mib-mean"', + ); + assert.throws(() => resourceHighlights(missing)); + assert.ok(html.includes("-16.67%")); + assert.ok(html.includes("+33.33%")); + for (let id of methods.map((m) => m.id)) + assert.ok(html.includes(`data-macos-method="${id}"`)); + const summary = render(model, lang, "functionalMethodSummary()"); + assert.ok(!summary.includes("num winner")); + assert.ok(summary.includes("2/372")); + assert.ok(!summary.includes("try-layout")); + const relations = JSON.parse( + JSON.stringify(render(model, lang, "fixedRelations()")), + ); + assert.deepEqual(relations[0].counts, { + gain: 2, + loss: 1, + bothPass: 0, + bothFail: 0, + }); + assert.deepEqual(relations[1].counts, { + gain: 1, + loss: 1, + bothPass: 1, + bothFail: 0, + }); +} +console.log( + "PASS: bilingual fixed methods, gains/losses, resource extrema, ties, percentages and negative controls", +); + +if (site) { + const measured = JSON.parse( + fs.readFileSync(path.join(site, "data/model.json"), "utf8"), + ); + for (let lang of ["zh", "en"]) { + if (measured.macos_resource) { + for (let page of ["home()", "guidePage()"]) { + const html = render(measured, lang, page); + resourceHighlights(html); + assert.ok(html.includes("moli-macos-success-resources-")); + } + } + for (let relation of render(measured, lang, "fixedRelations()")) + assert.equal( + Object.values(relation.counts).reduce((a, b) => a + b, 0), + 372, + ); + } + console.log( + "PASS: delivered report home/guide comparisons and complete relation counts", + ); +} diff --git a/tests/test_moli_report_pack.py b/tests/test_moli_report_pack.py new file mode 100644 index 000000000..c847cafad --- /dev/null +++ b/tests/test_moli_report_pack.py @@ -0,0 +1,65 @@ +"""The hosted evidence package must preserve every logical file byte for byte.""" + +import gzip +import hashlib +import importlib.util +import json +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location( + "moli_report_pack", ROOT / "scripts/moli_report/pack.py" +) +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + + +class MoliReportPackTests(unittest.TestCase): + def create_report(self, root): + root.mkdir() + for name, prefix in [("index.html", ""), ("en.html", ""), ("en/index.html", "../")]: + path = root / name + path.parent.mkdir(exist_ok=True) + path.write_text(f'<html><script defer src="{prefix}mermaid.min.js"></script></html>') + for name in ("app.js", "style.css", "mermaid.min.js", "mermaid-LICENSE.txt"): + (root / name).write_text(name) + (root / "data").mkdir() + contents = { + "data/model.json": '{"message":"中文证据"}'.encode(), + "data/error.log": b"exact error\n" * 10, + "data/frame.bin": bytes(range(256)), + } + for name, data in contents.items(): + (root / name).write_bytes(data) + return contents + + def test_round_trip_binary_unicode_and_pack_boundaries(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + expected = self.create_report(root / "source") + summary = MODULE.package(root / "source", root / "package", pack_limit=80) + self.assertEqual(summary["bundled_files"], 3) + self.assertGreater(summary["packs"], 1) + catalog = json.loads((root / "package/bundle-manifest.json").read_text())["files"] + self.assertEqual(set(catalog), set(expected)) + for name, entry in catalog.items(): + payload = gzip.decompress((root / "package" / entry["pack"]).read_bytes()) + data = payload[entry["offset"] : entry["offset"] + entry["size"]] + self.assertEqual(data, expected[name]) + self.assertEqual(hashlib.sha256(data).hexdigest(), entry["sha256"]) + for name in ("index.html", "en.html", "en/index.html"): + self.assertIn("bundle-loader.js", (root / "package" / name).read_text()) + with self.assertRaisesRegex(ValueError, "already exists"): + MODULE.package(root / "source", root / "package") + + def test_rejects_symlinked_evidence(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self.create_report(root / "source") + (root / "outside").write_text("not public") + (root / "source/data/link").symlink_to(root / "outside") + with self.assertRaisesRegex(ValueError, "symlinks"): + MODULE.package(root / "source", root / "package") + self.assertFalse((root / "package").exists()) diff --git a/tests/test_moli_report_render_contract.py b/tests/test_moli_report_render_contract.py new file mode 100644 index 000000000..49f837c3c --- /dev/null +++ b/tests/test_moli_report_render_contract.py @@ -0,0 +1,15 @@ +"""Exercise the report's public fixed-layout comparison components.""" + +import shutil +import subprocess +import unittest +from pathlib import Path + + +class MoliReportRenderContractTests(unittest.TestCase): + def test_fixed_layout_comparisons_in_both_languages(self): + node = shutil.which("node") + if node is None: + self.skipTest("Node.js is required for report component checks") + script = Path(__file__).with_name("moli_report_render_contract.cjs") + subprocess.run([node, str(script)], check=True, capture_output=True, text=True) From d24bee35c150ab43a4c55965bf2084ba964d7a2a Mon Sep 17 00:00:00 2001 From: kevin <xxx> Date: Mon, 21 Sep 2026 00:20:24 +0800 Subject: [PATCH 17/29] Bind fixed results to current task contracts and validate chart metrics --- scripts/moli_report/app.js | 15 ++- scripts/moli_report/build.py | 18 +++ scripts/plot_moli_version_resources.py | 135 ++++++++++++++++------ tests/test_moli_version_resource_chart.py | 37 +++--- 4 files changed, 153 insertions(+), 52 deletions(-) diff --git a/scripts/moli_report/app.js b/scripts/moli_report/app.js index 2543b643c..997f2bff8 100644 --- a/scripts/moli_report/app.js +++ b/scripts/moli_report/app.js @@ -1129,7 +1129,7 @@ function methodPage() { "", ) + section( - zh ? "实验流程" : "Protocol flow", + zh ? "1.1.8 历史实验流程" : "Historical 1.1.8 protocol", "", `<div class="protocol-diagram"><pre class="mermaid">flowchart TB A["${zh ? `冻结 ${M.task_count} 题、版本与种子` : `Freeze ${M.task_count} tasks, versions and seed`}"] --> B["${zh ? "无采样:先无布局,再开布局" : "Unprofiled: layout off, then on"}"] @@ -1305,11 +1305,16 @@ async function fixedCasePage(id) { `<div class="breadcrumb"><a href="${link("analysis")}">${esc(T.nav.analysis)}</a> / <code>${esc(id)}</code></div>` + hero(c.title, id) + section(zh ? "结果摘要" : "Result summary", "", summary) + + section( + zh ? "本轮任务合同" : "Task contract for this comparison", + esc(c.task_definition.description), + `<details><summary>${esc(zh ? "查看冻结任务定义" : "Inspect frozen task definition")}</summary><p>SHA-256: <code>${esc(c.task_sha256)}</code></p><pre>${esc(JSON.stringify(c.task_definition, null, 2))}</pre></details>`, + ) + details + section( zh ? "任务与历史结果" : "Task and historical results", "", - `<a href="${link("task/" + id)}">${esc(zh ? "查看任务定义与 1.1.8 对照" : "View task definition and 1.1.8 comparison")}</a>`, + `<a href="${link("task/" + id)}">${esc(zh ? "查看 1.1.8 原始任务记录与对照" : "View the original 1.1.8 task record and comparison")}</a>`, ) ); } @@ -1329,7 +1334,7 @@ function analysisPage() { hero(T.nav.analysis, T.analysisIntro) + fixedComparisonSection() + section( - zh ? "用例通过关系" : "Case outcomes", + zh ? "1.1.8 用例通过关系" : "Moli 1.1.8 case outcomes", casePopulation(), `<div class="grid two">${[ ["gain", p.off_fail_on_pass], @@ -1545,7 +1550,7 @@ function guidePage() { functionalMethodSummary() + fixedComparisonSection() + section( - zh ? "完成任务的变化" : "Changes in completion", + zh ? "1.1.8 完成任务的变化" : "Moli 1.1.8 changes in completion", "", `<div class="notice">${esc(zh ? `按同一组 ${M.task_count} 个用例比较:开启布局新增通过 ${p.off_fail_on_pass} 个用例,${p.off_pass_on_fail} 个用例由通过变为失败。` : `Across the same ${M.task_count} cases, layout gained ${p.off_fail_on_pass} passed cases and lost ${p.off_pass_on_fail}.`)}</div>`, ) + @@ -1553,7 +1558,7 @@ function guidePage() { candidateResourceSection() + costSection() + section( - zh ? "资源分项对照" : "Resource comparison", + zh ? "1.1.8 资源分项对照" : "Moli 1.1.8 resource comparison", zh ? "全部调用与独立冷启动样本分开统计。每项绿色标记只表示本列原始数值更低。" : "All calls and the separate cold-start sample are distinct populations. Green marks only the lower raw value in each metric.", diff --git a/scripts/moli_report/build.py b/scripts/moli_report/build.py index fa3afdbaa..c4073462e 100644 --- a/scripts/moli_report/build.py +++ b/scripts/moli_report/build.py @@ -752,6 +752,7 @@ def timestamp(value): assert len(case["attempts"]) == 3 and {a["attempt"] for a in case["attempts"]} == {1, 2, 3} assert case["passes"] == sum(a["status"] == "pass" for a in case["attempts"]) source_runs = {} + source_tasks = {} for binding in candidate["sources"]: run_id = binding["run_id"] assert re.fullmatch(r"[A-Za-z0-9_-]+", run_id) @@ -766,7 +767,24 @@ def timestamp(value): ) assert sha(source_result.read_bytes()) == binding["results_sha256"] source_runs[run_id] = run_root + for task in json.loads((run_root / "run_manifest.json").read_text())["resolved_tasks"]: + if task["task_id"] in source_tasks: + assert source_tasks[task["task_id"]]["sha256"] == task["sha256"] + source_tasks[task["task_id"]] = task for case in candidate["cases"]: + task = source_tasks[case["task_id"]] + bench_root = ROOT / "work/lexbench-layout-policy-v3" + task_path = bench_root / task["path"] + assert ( + task_path.resolve().is_relative_to(bench_root.resolve()) and not task_path.is_symlink() + ) + task_bytes = task_path.read_bytes() + assert sha(task_bytes) == task["sha256"] == case["task_sha256"] + case_detail = fixed_case_data[case["task_id"]] + if "task_sha256" in case_detail: + assert case_detail["task_sha256"] == task["sha256"] + case_detail["task_sha256"] = task["sha256"] + case_detail["task_definition"] = json.loads(clean(task_bytes.decode())) detail = [] for attempt in case["attempts"]: run_root = source_runs[attempt["source_run_id"]] diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py index 3a4583a19..5db4d161a 100644 --- a/scripts/plot_moli_version_resources.py +++ b/scripts/plot_moli_version_resources.py @@ -4,15 +4,15 @@ milliseconds are different units. Both panels share the 372-case success-rate axis. CPU can be omitted with ``--metrics pss``. """ + from __future__ import annotations import argparse import html import json import math -from pathlib import Path import re - +from pathlib import Path COLORS = ("#239b68", "#d1841e", "#7652c7", "#2775c9", "#c54f79", "#4c8793") COLOR_RE = re.compile(r"#[0-9a-fA-F]{6}") @@ -24,9 +24,17 @@ def _scale(value: float, lower: float, upper: float, start: float, end: float) - return start + (value - lower) / (upper - lower) * (end - start) -def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "cpu"), language: str = "zh") -> None: - if not metrics or len(metrics) > 2 or any(metric not in {"pss", "rss", "cpu"} for metric in metrics): +def render_chart( + data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "cpu"), language: str = "zh" +) -> None: + if ( + not metrics + or len(metrics) > 2 + or any(metric not in {"pss", "rss", "cpu"} for metric in metrics) + ): raise ValueError("metrics must contain one or two of pss, rss and cpu") + if len(set(metrics)) != len(metrics): + raise ValueError("metrics must not contain duplicates") if language not in {"zh", "en"}: raise ValueError("language must be zh or en") rows = data.get("configurations") @@ -50,7 +58,9 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c else sorted(required_row_fields) ) if missing: - raise ValueError(f"configuration row {index} missing required field(s): {', '.join(missing)}") + raise ValueError( + f"configuration row {index} missing required field(s): {', '.join(missing)}" + ) color = row.get("color") if color is not None and (not isinstance(color, str) or COLOR_RE.fullmatch(color) is None): raise ValueError(f"configuration row {index} color must be a six-digit hex color") @@ -61,7 +71,9 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c try: number = float(row[field]) except (TypeError, ValueError) as exc: - raise ValueError(f"configuration row {index} field {field} must be numeric") from exc + raise ValueError( + f"configuration row {index} field {field} must be numeric" + ) from exc if not math.isfinite(number): raise ValueError(f"configuration row {index} field {field} must be finite") ids = [str(row["id"]) for row in rows] @@ -75,9 +87,7 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c raise ValueError("all configurations must use the same positive total_cases") total_cases = int(next(iter(totals))) resource = data.get("resource_population") - required_resource_fields = { - "chart_calls", "chart_tasks", "total_tasks", "calls_per_task" - } + required_resource_fields = {"chart_calls", "chart_tasks", "total_tasks", "calls_per_task"} if not isinstance(resource, dict) or not required_resource_fields.issubset(resource): missing = ( sorted(required_resource_fields - set(resource or {})) @@ -92,7 +102,11 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c text = { "zh": { "title": f"{total_cases} 题成功率与资源消耗", - "subtitle": f"资源实验:{resource['total_tasks']} 题 × {resource['calls_per_task']} 次;图中使用预先冻结的 {resource['chart_calls']:,} 次 / {resource['chart_tasks']} 题样本;越靠左资源消耗越低", + "subtitle": ( + f"资源实验:{resource['total_tasks']} 题 × {resource['calls_per_task']} 次;" + f"图中使用预先冻结的 {resource['chart_calls']:,} 次 / " + f"{resource['chart_tasks']} 题样本;越靠左资源消耗越低" + ), "y": f"{total_cases} 题通过率(每题 3 次全部通过)", "pss": "峰值进程树 PSS 中位数(MiB)", "rss": "峰值进程树 RSS 中位数(MiB)", @@ -102,7 +116,12 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c }, "en": { "title": f"Success on {total_cases} cases vs. resource use", - "subtitle": f"Resource experiment: {resource['total_tasks']} tasks × {resource['calls_per_task']} calls; plotted population: {resource['chart_calls']:,} pre-frozen calls / {resource['chart_tasks']} tasks; farther left is lower", + "subtitle": ( + f"Resource experiment: {resource['total_tasks']} tasks × " + f"{resource['calls_per_task']} calls; plotted population: " + f"{resource['chart_calls']:,} pre-frozen calls / " + f"{resource['chart_tasks']} tasks; farther left is lower" + ), "y": f"Success rate on {total_cases} cases (all 3 attempts pass)", "pss": "Median peak process-tree PSS (MiB)", "rss": "Median peak process-tree RSS (MiB)", @@ -126,22 +145,39 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c description = ( f"{len(rows)} 种配置在 {total_cases} 题通过率与{described_metrics}上的对比。" if language == "zh" - else f"{len(rows)} configurations compared by success rate on {total_cases} cases and {described_metrics}." + else ( + f"{len(rows)} configurations compared by success rate on " + f"{total_cases} cases and {described_metrics}." + ) ) parts = [ - f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" role="img" aria-labelledby="title desc">', + f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" ' + f'viewBox="0 0 {width} {height}" role="img" aria-labelledby="title desc">', f'<title id="title">{html.escape(text["title"])}', f'{html.escape(description)}', '', - '', + '', f'{html.escape(text["title"])}', f'{html.escape(text["subtitle"])}', ] for tick in range(0, y_max + 1, 20): y = _scale(tick, 0, y_max, chart_bottom, top) - parts.append(f'') - parts.append(f'{tick}%') - parts.append(f'{html.escape(text["y"])}') + parts.append( + f'' + ) + parts.append( + f'{tick}%' + ) + parts.append( + f'{html.escape(text["y"])}' + ) specs = { "pss": (text["pss"], "pss_mib", "pss_change_pct", "MiB"), "rss": (text["rss"], "rss_mib", "rss_change_pct", "MiB"), @@ -151,6 +187,7 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c row["id"]: str(row.get("color") or COLORS[index % len(COLORS)]) for index, row in enumerate(rows) } + offsets = ((0, 0), (-18, -18), (18, 18), (-18, 18), (18, -18), (0, -24), (0, 24)) for panel, metric in enumerate(metrics): title, key, change_key, unit = specs[metric] x0 = left + panel * (panel_width + gap) @@ -161,32 +198,55 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c padding = max(spread * 0.22, abs(center) * 0.03, 1.0) low = max(0.0, min(values) - padding) high = max(values) + padding - parts.append(f'') - parts.append(f'{html.escape(title)}') + parts.append( + f'' + ) + parts.append( + f'{html.escape(title)}' + ) for i in range(5): value = low + (high - low) * i / 4 x = _scale(value, low, high, x0, x1) - parts.append(f'') - parts.append(f'{value:.1f}') + parts.append( + f'' + ) + parts.append( + f'{value:.1f}' + ) plotted: list[tuple[float, float]] = [] - offsets = ((0, 0), (-18, -18), (18, 18), (-18, 18), (18, -18), (0, -24), (0, 24)) for row_index, row in enumerate(rows, 1): exact_x = _scale(float(row[key]), low, high, x0, x1) exact_y = _scale(float(row["success_rate_pct"]), 0, y_max, chart_bottom, top) x, y = exact_x, exact_y for dx, dy in offsets: candidate = (exact_x + dx, exact_y + dy) - if all(math.hypot(candidate[0] - px, candidate[1] - py) >= 27 for px, py in plotted): + if all( + math.hypot(candidate[0] - px, candidate[1] - py) >= 27 for px, py in plotted + ): x, y = candidate break plotted.append((x, y)) color = row_colors[row["id"]] number = row_index if (x, y) != (exact_x, exact_y): - parts.append(f'') - parts.append(f'') - parts.append(f'') - parts.append(f'{number}') + parts.append( + f'' + ) + parts.append( + f'' + ) + parts.append( + f'' + ) + parts.append( + f'{number}' + ) legend_y = chart_bottom + 82 for index, row in enumerate(rows): color = row_colors[row["id"]] @@ -194,15 +254,24 @@ def render_chart(data: dict, output: Path, metrics: tuple[str, ...] = ("pss", "c if language == "en": label_key += "_en" row_label = row[label_key] - fields = [f'{int(float(row["passed_cases"]))}/{total_cases} ({float(row["success_rate_pct"]):.1f}%)'] + fields = [ + f"{int(float(row['passed_cases']))}/{total_cases} " + f"({float(row['success_rate_pct']):.1f}%)" + ] for metric in metrics: _, key, change_key, unit = specs[metric] - fields.append(f'{float(row[key]):.2f} {unit} ({float(row[change_key]):+.2f}%)') + fields.append(f"{float(row[key]):.2f} {unit} ({float(row[change_key]):+.2f}%)") y = legend_y + index * 30 - parts.append(f'') - parts.append(f'{index+1}') - parts.append(f'{html.escape(row_label + ": " + " · ".join(fields))}') - parts.append('') + parts.append(f'') + parts.append( + f'{index + 1}' + ) + parts.append( + f'' + f'{html.escape(row_label + ": " + " · ".join(fields))}' + ) + parts.append("") output.parent.mkdir(parents=True, exist_ok=True) output.write_text("\n".join(parts) + "\n") diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index c92711124..a557e4fd4 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -4,7 +4,6 @@ import unittest from pathlib import Path - ROOT = Path(__file__).resolve().parents[1] SCRIPT = ROOT / "scripts" / "plot_moli_version_resources.py" SPEC = importlib.util.spec_from_file_location("plot_moli_version_resources", SCRIPT) @@ -108,6 +107,10 @@ def test_macos_rss_cpu_chart_does_not_label_memory_as_pss(self): self.assertIn("80.54 MiB (+4.30%)", svg) self.assertIn("21.66 ms (+1.16%)", svg) + def test_duplicate_metric_selection_is_rejected(self): + with self.assertRaisesRegex(ValueError, "duplicates"): + self.render(("pss", "pss")) + def test_cpu_only_omits_pss_content_and_keeps_all_legend_entries(self): svg = self.render(("cpu",), "en") self.assertIn("Mean CPU time per execution (ms)", svg) @@ -142,16 +145,18 @@ def test_y_axis_expands_to_include_rates_above_eighty_percent(self): def test_future_configuration_is_rendered_without_code_changes(self): future = dict(self.data["configurations"][2]) - future.update({ - "id": "pr640_try_layout", - "label": "Moli PR #640 · 失败后尝试 layout", - "label_en": "Moli PR #640 · try layout after failure", - "short_label": "PR #640 尝试布局", - "short_label_en": "PR #640 try layout", - "passed_cases": 300, - "success_rate_pct": 300 / 372 * 100, - "color": "#2775c9", - }) + future.update( + { + "id": "pr640_try_layout", + "label": "Moli PR #640 · 失败后尝试 layout", + "label_en": "Moli PR #640 · try layout after failure", + "short_label": "PR #640 尝试布局", + "short_label_en": "PR #640 try layout", + "passed_cases": 300, + "success_rate_pct": 300 / 372 * 100, + "color": "#2775c9", + } + ) self.data["configurations"].append(future) svg = self.render() self.assertIn("4 种配置", svg) @@ -165,7 +170,9 @@ def test_mismatched_denominators_have_clear_error(self): def test_missing_resource_population_field_has_clear_error(self): del self.data["resource_population"]["chart_tasks"] - with self.assertRaisesRegex(ValueError, "resource_population missing required field.*chart_tasks"): + with self.assertRaisesRegex( + ValueError, "resource_population missing required field.*chart_tasks" + ): self.render() def test_resource_population_values_must_be_positive_integers(self): @@ -199,11 +206,13 @@ def test_empty_configuration_list_has_clear_error(self): def test_missing_configuration_field_has_clear_error(self): del self.data["configurations"][0]["pss_change_pct"] - with self.assertRaisesRegex(ValueError, "configuration row 0 missing required field.*pss_change_pct"): + with self.assertRaisesRegex( + ValueError, "configuration row 0 missing required field.*pss_change_pct" + ): self.render() def test_color_rejects_svg_attribute_injection(self): - self.data["configurations"][0]["color"] = '#fff\" onload=\"alert(1)' + self.data["configurations"][0]["color"] = '#fff" onload="alert(1)' with self.assertRaisesRegex(ValueError, "color must be a six-digit hex color"): self.render() From 4ae3af20972a2a2268f3b605c5a28d6dd71eb798 Mon Sep 17 00:00:00 2001 From: kevin Date: Mon, 21 Sep 2026 00:28:52 +0800 Subject: [PATCH 18/29] Fix mobile evidence layout and run browser checks in ESM project --- scripts/moli_report/app.js | 4 ++-- scripts/moli_report/index.html | 2 +- scripts/moli_report/style.css | 1 + scripts/moli_report/ui_check.js | 3 ++- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/scripts/moli_report/app.js b/scripts/moli_report/app.js index 997f2bff8..e26e0afed 100644 --- a/scripts/moli_report/app.js +++ b/scripts/moli_report/app.js @@ -1306,8 +1306,8 @@ async function fixedCasePage(id) { hero(c.title, id) + section(zh ? "结果摘要" : "Result summary", "", summary) + section( - zh ? "本轮任务合同" : "Task contract for this comparison", - esc(c.task_definition.description), + zh ? "本轮任务要求" : "Task requirements for this comparison", + c.task_definition.description, `
${esc(zh ? "查看冻结任务定义" : "Inspect frozen task definition")}

SHA-256: ${esc(c.task_sha256)}

${esc(JSON.stringify(c.task_definition, null, 2))}
`, ) + details + diff --git a/scripts/moli_report/index.html b/scripts/moli_report/index.html index b3a6cd7f3..911f5ecc5 100644 --- a/scripts/moli_report/index.html +++ b/scripts/moli_report/index.html @@ -4,7 +4,7 @@ - Moli 1.1.8 · Layout modes + Moli 1.1.4 / 1.1.8 / 1.1.9 · Success and resources diff --git a/scripts/moli_report/style.css b/scripts/moli_report/style.css index 08673bfbb..04dcb7e9c 100644 --- a/scripts/moli_report/style.css +++ b/scripts/moli_report/style.css @@ -220,6 +220,7 @@ main { .section-intro { color: var(--muted); margin: 0.35rem 0 1rem; + overflow-wrap: anywhere; } .grid { display: grid; diff --git a/scripts/moli_report/ui_check.js b/scripts/moli_report/ui_check.js index ebc20fc92..eab59105b 100644 --- a/scripts/moli_report/ui_check.js +++ b/scripts/moli_report/ui_check.js @@ -1,4 +1,5 @@ -"use strict"; +import { createRequire } from "node:module"; +const require = createRequire(import.meta.url); const path = require("path"), os = require("os"); const dataHome = From e8e97f952bd887e219c1f7a7bb8710c42452f4a9 Mon Sep 17 00:00:00 2001 From: kevin Date: Mon, 21 Sep 2026 00:32:48 +0800 Subject: [PATCH 19/29] Record published Moli 1.1.9 fixed-layout comparison --- evaluation/moli/current-report.json | 30 +++++++++++--- research/report-changes.json | 62 +++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 5 deletions(-) diff --git a/evaluation/moli/current-report.json b/evaluation/moli/current-report.json index cab9bc4ed..99aa19a85 100644 --- a/evaluation/moli/current-report.json +++ b/evaluation/moli/current-report.json @@ -1,14 +1,34 @@ { "schema": "moli_report_profile/1", - "functional_population": {"cases": 372, "attempts_per_case": 3, "rule": "all_three_attempts_pass"}, - "resource_population": {"tasks": 557, "attempts_per_task": 5, "chart_tasks": 209, "chart_calls": 1045}, - "method_ids": ["114_off", "118_off", "118_on", "119_off", "119_on", "119_official_on"], - "macos_method_ids": ["119_off", "119_on", "119_official_on"], + "functional_population": { + "cases": 372, + "attempts_per_case": 3, + "rule": "all_three_attempts_pass" + }, + "resource_population": { + "tasks": 557, + "attempts_per_task": 5, + "chart_tasks": 209, + "chart_calls": 1045 + }, + "method_ids": [ + "114_off", + "118_off", + "118_on", + "119_off", + "119_on", + "119_official_on" + ], + "macos_method_ids": [ + "119_off", + "119_on", + "119_official_on" + ], "publication": { "base_url": "https://artifact-site.lexmount.cn", "slug": "gdwtSGOel0va", "kind": "folder", - "expected_version": "ver_96cd695de0d54d72bc5e7bfe09ac3ba6", + "expected_version": "ver_4d7cfe448a8e4ac98287607dc6a2266a", "share_url": "https://artifact-site.lexmount.cn/v/w1vgSkFJjvmCL6kPaHmj4K8sUZ8iTI8t" } } diff --git a/research/report-changes.json b/research/report-changes.json index 49c6d598a..6cea1d5c5 100644 --- a/research/report-changes.json +++ b/research/report-changes.json @@ -1252,6 +1252,68 @@ } ], "releases": [ + { + "id": "2026-09-21-moli-119-fixed-layout-comparison", + "comparison_kinds": [ + "moli_historical_failure_retest", + "moli_process_tree_resource_profile" + ], + "date": "2026-09-21", + "title": "加入 Moli 1.1.9 固定布局与官方版本对照", + "summary": "新增修复版 1.1.9 关闭布局、开启布局及官方 1.1.9 开启布局:372 题分别通过 1、360、255 题。三个方法各完成独立的 557 题 × 5 次资源实验;macOS RSS 与历史 Linux PSS 分开展示,图表和表格给出带正负号的资源变化。", + "publication": { + "service": "Artifact Site", + "site_slug": "gdwtSGOel0va", + "share_url": "https://artifact-site.lexmount.cn/v/w1vgSkFJjvmCL6kPaHmj4K8sUZ8iTI8t", + "version": "ver_4d7cfe448a8e4ac98287607dc6a2266a" + }, + "changes": [ + [ + "固定布局功能对照", + "每个方法需要同一布局状态下的完整三次执行。", + "每题三次全部通过才算通过;修复版开启布局比官方版新增通过 105 题,无退步。新增同题结果筛选及三种方法的逐次证据。", + "保留历史 1.1.4 / 1.1.8 结果;两个任务合同修正后的 18 次复测均失败,历史通过数不变。" + ], + [ + "独立资源实验", + "功能通过率与资源采样使用不同任务群体。", + "每个方法各采样 2,785 次;同时展示全部 557 题统计和预先冻结的 209 题、1,045 次图表样本,macOS 百分比以官方 1.1.9 开启布局为基准。", + "修复版为 debug 构建,官方版为发布资产;资源差异同时包含代码和构建配置差异。" + ], + [ + "图表与证据", + "报告需要可复现图表及可读的手机端证据。", + "保留按 PSS、RSS、CPU 选择面板的代码绘图;完成 112 个页面状态及 6 条证据交互验收,部署的 26 个文件逐一核对。", + "分享链接保持不变。功能校验覆盖 372 题、7,830 条历史及当前调用和 41,292 个证据文件。" + ] + ], + "i18n": { + "en": { + "title": "Add Moli 1.1.9 fixed-layout and official-release comparisons", + "summary": "Added patched 1.1.9 with layout off and on, and official 1.1.9 with layout on: 1, 360 and 255 passes out of 372 cases. Each method completes a separate 557-task × 5-call resource experiment. macOS RSS and historical Linux PSS remain separate, with signed resource changes in tables and code-generated charts.", + "changes": [ + [ + "Fixed-layout functional comparison", + "Each method requires three complete attempts under the same layout setting.", + "A case passes only when all three attempts pass. Patched layout on gains 105 cases over official layout on and loses none. Same-case filters and individual attempt evidence cover all three methods.", + "Historical 1.1.4 / 1.1.8 results remain; all 18 calls after correcting two task contracts fail, leaving historical pass counts unchanged." + ], + [ + "Separate resource experiments", + "Compatibility and resource sampling use different task populations.", + "Each method has 2,785 sampled calls. Tables show all 557 tasks and the pre-frozen 209-task / 1,045-call chart population. macOS percentage changes use official 1.1.9 layout on as the baseline.", + "The patched binary is a debug build; the official binary is a release asset. Resource differences include both code and build-configuration differences." + ], + [ + "Charts and evidence", + "Charts must be reproducible and evidence readable on narrow screens.", + "Code-generated charts support PSS, RSS and CPU panels. Verification covers 112 page states and six evidence flows; all 26 deployed files match the submitted package.", + "The share link is unchanged. Functional validation covers 372 cases, 7,830 historical and current calls, and 41,292 evidence files." + ] + ] + } + } + }, { "id": "2026-09-20-moli-version-layout-resource-summary", "comparison_kinds": [ From d2e30fc234d3e3403c73ea66d4cf4d01c99a18fc Mon Sep 17 00:00:00 2001 From: kevin Date: Mon, 21 Sep 2026 00:40:05 +0800 Subject: [PATCH 20/29] Clarify report population mapping and historical publication binding --- research/report-changes.json | 7 +++++++ scripts/moli_report/BUILD.md | 2 ++ 2 files changed, 9 insertions(+) diff --git a/research/report-changes.json b/research/report-changes.json index 6cea1d5c5..c0763b3c9 100644 --- a/research/report-changes.json +++ b/research/report-changes.json @@ -1254,6 +1254,7 @@ "releases": [ { "id": "2026-09-21-moli-119-fixed-layout-comparison", + "date_timezone": "Asia/Shanghai", "comparison_kinds": [ "moli_historical_failure_retest", "moli_process_tree_resource_profile" @@ -1316,6 +1317,12 @@ }, { "id": "2026-09-20-moli-version-layout-resource-summary", + "publication": { + "service": "Artifact Site", + "site_slug": "gdwtSGOel0va", + "share_url": "https://artifact-site.lexmount.cn/v/w1vgSkFJjvmCL6kPaHmj4K8sUZ8iTI8t", + "version": "ver_96cd695de0d54d72bc5e7bfe09ac3ba6" + }, "comparison_kinds": [ "moli_historical_failure_retest", "moli_process_tree_resource_profile" diff --git a/scripts/moli_report/BUILD.md b/scripts/moli_report/BUILD.md index fb0030576..d314e6765 100644 --- a/scripts/moli_report/BUILD.md +++ b/scripts/moli_report/BUILD.md @@ -4,6 +4,8 @@ This directory owns the Moli comparison report renderer. Measured evidence stays The historical Linux source checkout is read from `LEXBENCH_REPORT_RUNNER_ROOT` (default: `$BROWSER_EVAL_DATA_HOME/work/moli-1.1.8-failures-linux`). Its recorded resource-calibration helper remains necessary to validate the historical measurements. Current macOS resource configurations each use one sampled run. +The report profile and chart payload have separate schemas. In `moli_report_profile/1`, resource `tasks` and `attempts_per_task` map to the chart's `total_tasks` and `calls_per_task`; `chart_tasks` and `chart_calls` retain their names. The builder validates the measured populations before constructing the chart payload. Do not pass the profile directly to the plotting API. + Build from validated fixed-layout summaries generated by Lexbench's `tools/summarize_moli_fixed_layout.py` and `tools/summarize_moli_macos_resources.py`: ```sh From 20e938000e10a967c32b477b4907aedf60ac5344 Mon Sep 17 00:00:00 2001 From: kevin Date: Mon, 21 Sep 2026 11:14:28 +0800 Subject: [PATCH 21/29] Unify six Moli configurations and streamline the reader-facing report --- scripts/moli_report/app.js | 564 ++++++---------------- scripts/moli_report/build.py | 17 +- scripts/moli_report/style.css | 16 + scripts/moli_report/ui_check.js | 156 +++--- scripts/moli_report/verify.py | 21 + scripts/plot_moli_version_resources.py | 110 ++++- tests/moli_report_render_contract.cjs | 18 +- tests/test_moli_version_resource_chart.py | 46 ++ 8 files changed, 415 insertions(+), 533 deletions(-) diff --git a/scripts/moli_report/app.js b/scripts/moli_report/app.js index e26e0afed..9a070da01 100644 --- a/scripts/moli_report/app.js +++ b/scripts/moli_report/app.js @@ -10,7 +10,7 @@ const D = { method: "评测方法", analysis: "结果分析", results: "逐题结果", - review: "核验记录", + review: "证据与可靠性", guide: "报告解读", reproduce: "环境与复现", }, @@ -34,7 +34,7 @@ const D = { error: "数据读取失败", noHuman: "未进行独立人工逐次复核", methodLimit: - "覆盖 Moli 0.1.1 的全部 372 个历史失败用例;结果适用于这一失败子集。", + "覆盖 Moli 0.1.1 的全部 372 个所选用例;结果适用于这一失败子集。", more: "查看详情", task: "任务", mode: "模式", @@ -68,7 +68,7 @@ const D = { observed: "观测到的采样最大值", filterFail: "涉及失败或变化", methodIntro: - "题目与验收预先冻结,两种浏览器配置只相差是否启用 --layout。默认模式使用低成本模拟几何;--layout 启用按需真实布局,并非持续绘制。可选图片等资源抓取由另一开关控制,本轮未改变。1.1.9 的每个固定配置各测一轮资源,557 题各五次;372 题成功率另测,每题三次。", + "题目与验收预先冻结,两种浏览器配置只相差是否启用 --layout。默认模式使用低成本模拟几何;--layout 启用按需真实布局,并非持续绘制。可选图片等资源抓取由另一开关控制,未改变。1.1.9 的每个固定配置各测一轮资源,557 题各五次;372 题成功率另测,每题三次。", analysisIntro: "按相同任务与执行次数配对。成功变化和资源代价分开解读。", guideIntro: "从 Agent 使用者角度,先看能否完成,再看失败等待和完成任务的资源。", @@ -85,7 +85,7 @@ const D = { method: "Method", analysis: "Analysis", results: "Task results", - review: "Verification", + review: "Evidence quality", guide: "Interpretation", reproduce: "Environment", }, @@ -109,7 +109,7 @@ const D = { error: "Could not load data", noHuman: "No independent per-call review", methodLimit: - "This cohort includes all 372 historical Moli 0.1.1 failures; results apply to this failure subset.", + "This cohort includes all 372 cases selected from Moli 0.1.1 failures; results apply to this failure subset.", more: "View details", task: "Task", mode: "Mode", @@ -214,20 +214,10 @@ const population = () => : `The same ${M.task_count} preselected tasks, ${M.protocol.k_runs} calls each and ${M.attempts_per_mode} calls per mode.`; const casePopulation = () => zh - ? `通过数按 ${M.task_count} 个用例统计:本轮每题已记录的 ${M.protocol.k_runs} 次无采样执行全部通过,才计为 1 个通过用例。` + ? `通过数按 ${M.task_count} 个用例统计:每题已记录的 ${M.protocol.k_runs} 次无采样执行全部通过,才计为 1 个通过用例。` : `Pass counts use ${M.task_count} cases: a case passes only when all ${M.protocol.k_runs} recorded unprofiled attempts pass.`; const caseVerdict = (n) => statusChip(n === M.protocol.k_runs ? "pass" : "fail"); -const historicalScope = () => - zh - ? `历史 Moli 0.1.1 通过 1,556/1,928 个用例(80.71%),372 个用例未达到三次全部通过。1.1.8 关闭和开启布局均直接复测全部 372 题。1.1.8 关闭布局只恢复 1 题,因此 1.1.4 关闭布局只对这唯一候选题复测三次;该题三次均失败,其余 371 题沿用两版本均失败的集合关系,结果为 0/372。历史通过的 1,556 题未重测,不能据此推算新版本全量通过率。` - : `Moli 0.1.1 originally passed 1,556/1,928 cases (80.71%); 372 did not pass all three attempts. Moli 1.1.8 was directly tested on all 372 with layout off and on. Because layout-off 1.1.8 recovered only one case, layout-off 1.1.4 was tested three times on that sole candidate; all three attempts failed, while the other 371 retain the shared-failure relation, yielding 0/372. The 1,556 historical passes were not rerun, so no new full-suite rate is inferred.`; -const historicalSection = () => - section( - zh ? "与历史 80.7% 的关系" : "Relation to the historical 80.7%", - historicalScope(), - `${esc(zh ? "原始四引擎报告 · 2026-08-12" : "Original four-engine report · 2026-08-12")}`, - ); const metricPopulation = () => zh ? `全部 ${M.attempts_per_mode} 次调用,成功与失败都计入;平均、P50 和 P95 使用同一组调用。` @@ -235,11 +225,11 @@ const metricPopulation = () => const reportSubtitle = () => Object.keys(M.fixed_candidates || {}).length ? zh - ? `比较 ${M.functional_methods.length} 种固定配置在 ${M.task_count} 个历史失败用例上的成功率,并展示独立资源实验。` - : `Compare ${M.functional_methods.length} fixed configurations on ${M.task_count} historical failures, with separate resource experiments.` + ? `比较 ${M.functional_methods.length} 种固定配置在 ${M.task_count} 个所选用例上的成功率,并展示独立资源实验。` + : `Compare ${M.functional_methods.length} fixed configurations on ${M.task_count} selected cases, with separate resource experiments.` : zh - ? `比较 Moli 1.1.4 关闭布局、1.1.8 关闭布局与 1.1.8 开启布局对 ${M.task_count} 个历史失败用例的恢复情况,并配套展示独立资源实验。` - : `Compare recovery of ${M.task_count} historical failures with Moli 1.1.4 layout off, Moli 1.1.8 layout off and Moli 1.1.8 layout on, with a separate resource experiment.`; + ? `比较 Moli 1.1.4 关闭布局、1.1.8 关闭布局与 1.1.8 开启布局对 ${M.task_count} 个所选用例的恢复情况,并配套展示独立资源实验。` + : `Compare recovery of ${M.task_count} selected cases with Moli 1.1.4 layout off, Moli 1.1.8 layout off and Moli 1.1.8 layout on, with a separate resource experiment.`; const reportVersion = () => Object.keys(M?.fixed_candidates || {}).length ? "Moli 1.1.4 / 1.1.8 / 1.1.9" @@ -252,12 +242,12 @@ const reportTitle = () => : T.title; const datasetIntro = () => zh - ? `依据 Moli 0.1.1 原始结果选取全部 372 个失败用例,覆盖 15 类驱动;不使用本轮结果决定入选。` - : `All 372 historical Moli 0.1.1 failures are included across 15 driver types, without selection based on current outcomes.`; + ? `依据 Moli 0.1.1 原始结果选取全部 372 个失败用例,覆盖 15 类驱动;不使用结果决定入选。` + : `All 372 cases selected from Moli 0.1.1 failures are included across 15 driver types, without selection based on current outcomes.`; const reproduceIntro = () => zh - ? `历史失败集恢复测试和独立的 557 题资源实验均为诊断实验,不计入完整 1,928 题正式分数。1.1.8 直接覆盖 372 题;1.1.4 使用唯一差异候选题验证。三种固定配置使用 Moli 1.1.4 / 1.1.8 Linux aarch64 发行版;1.1.9 修复版使用固定的 macOS arm64 debug 二进制,官方版使用发布资产;每个版本的功能与资源实验绑定同一 SHA-256。` - : `The historical-failure recovery check and separate 557-task resource experiment are diagnostic and excluded from the formal 1,928-case score. Moli 1.1.8 directly covers all 372 cases; Moli 1.1.4 uses the sole differential candidate. The three fixed configurations use Moli 1.1.4 / 1.1.8 Linux aarch64 releases. Patched Moli 1.1.9 uses the frozen macOS arm64 debug binary; official 1.1.9 uses the release asset. Functional and resource runs are bound to the same binary hash for each build.`; + ? `所选用例测试和独立的 557 题资源实验均为诊断实验,不计入完整 1,928 题正式分数。1.1.8 直接覆盖 372 题;1.1.4 使用唯一差异候选题验证。三种固定配置使用 Moli 1.1.4 / 1.1.8 Linux aarch64 发行版;1.1.9 修复版使用固定的 macOS arm64 debug 二进制,官方版使用发布资产;每个版本的功能与资源实验绑定同一 SHA-256。` + : `The selected-case evaluation and separate 557-task resource experiment are diagnostic and excluded from the formal 1,928-case score. Moli 1.1.8 directly covers all 372 cases; Moli 1.1.4 uses the sole differential candidate. The three fixed configurations use Moli 1.1.4 / 1.1.8 Linux aarch64 releases. Patched Moli 1.1.9 uses the frozen macOS arm64 debug binary; official 1.1.9 uses the release asset. Functional and resource runs are bound to the same binary hash for each build.`; const ms = (v) => v === null || v === undefined ? "—" @@ -285,18 +275,33 @@ function metricRow(label, off, on, format, direction = "min", note = "") { } const signed = (value, digits = 2, suffix = "%") => `${value >= 0 ? "+" : ""}${fmt(value, digits)}${suffix}`; -function contractCorrectionNotice() { - let c = M.functional_contract_correction; - if (!c) return ""; - return `
${esc(zh ? "修正合同补测" : "Corrected-contract retest")} · ${esc(zh ? `受 Chromium 基线修正影响的 ${c.task_count} 题,已对三种 Moli 配置各重跑 3 次,共 ${c.calls} 次调用;三组均仍为失败,所以下表成功率不变。` : `The ${c.task_count} cases affected by the Chromium baseline correction were rerun three times for each Moli configuration (${c.calls} calls). All three configurations still fail both cases, so the success rates below are unchanged.`)}
`; -} function functionalMethodSummary() { if (!Object.keys(M.fixed_candidates || {}).length) return ""; let rows = M.functional_methods, total = M.task_count, max = Math.max(...rows.map((x) => x.final_passed_cases)), unique = rows.filter((x) => x.final_passed_cases === max).length === 1; - let body = rows.map((row) => { + let resourceRows = M.combined_comparison?.configurations || []; + let body = rows.map((row, index) => { + let resource = resourceRows.find((r) => r.id === row.id); + let resourceCells = resource + ? ["memory", "cpu"] + .map((metric) => { + let key = metric === "memory" ? "memory_mib" : "cpu_ms"; + let delta = resource[metric + "_change_pct"]; + let peers = resourceRows.filter( + (r) => r.platform === resource.platform, + ); + let minimum = Math.min(...peers.map((r) => r[key])); + let winner = + resource[key] === minimum && + peers.filter((r) => r[key] === minimum).length === 1; + let unit = + metric === "memory" ? resource.memory_kind + " MiB" : "ms"; + return `${fmt(resource[key], 2)} ${unit}
${delta === null ? esc(zh ? "跨平台 · 不计算变化" : "Cross-platform · no delta") : signed(delta, 2)}
`; + }) + .join("") + : ""; let policy = row.policy === "fixed_on" ? zh @@ -311,15 +316,15 @@ function functionalMethodSummary() { let evidence = row.evidence ? `
` : ""; - return `${esc(zh ? row.label : row.label_en)}${evidence}${esc(policy)}${esc(scope)}${fmt(row.final_passed_cases)}/${total} (${fmt((row.final_passed_cases / total) * 100, 1)}%)${signed(((row.final_passed_cases - rows[0].final_passed_cases) / total) * 100, 2, zh ? " 个百分点" : " pp")}${fmt(row.physical_calls || (row.id === "114_off" ? 3 : total * 3))}`; + return `${index + 1} ${esc(zh ? row.label : row.label_en)}${resource ? `
${esc(resource.platform)}${row.id === "114_off" ? (zh ? " · 基线" : " · baseline") : ""}
` : ""}${evidence}${esc(policy)}${esc(scope)}${fmt(row.final_passed_cases)}/${total} (${fmt((row.final_passed_cases / total) * 100, 1)}%)${signed(((row.final_passed_cases - rows[0].final_passed_cases) / total) * 100, 2, zh ? " 个百分点" : " pp")}${fmt(row.physical_calls || (row.id === "114_off" ? 3 : total * 3))}${resourceCells}`; }); return section( zh ? `${rows.length} 种固定配置的成功率` : `Success rates for ${rows.length} fixed configurations`, zh - ? `同一 ${total} 题分母,每题三次全部通过才算成功。开启和关闭 layout 分别统计各自的实际结果;资源使用独立的 557 题实验。变化以 1.1.4 关闭 layout 为基准。` - : `The same ${total}-case denominator is used; all three attempts must pass. Layout on and off use their own observed results. Resources come from a separate 557-task experiment. Changes are relative to 1.1.4 layout off.`, + ? `同一 ${total} 题分母,每题三次全部通过才算成功。开启和关闭 layout 分别统计各自的实际结果;资源使用独立的 557 题实验。变化以 1.1.4 关闭 layout 为基准;资源列为图中的 209 题样本。PSS 与 RSS 不直接比较,绿色标识同平台内唯一最低资源值。` + : `The same ${total}-case denominator is used; all three attempts must pass. Layout on and off use their own observed results. Resources come from a separate 557-task experiment. Changes are relative to 1.1.4 layout off; resource columns use the plotted 209-task sample. PSS and RSS are not directly comparable. Green marks the unique resource minimum within each platform.`, table( [ zh ? "方法" : "Method", @@ -328,45 +333,23 @@ function functionalMethodSummary() { zh ? "通过用例" : "Passed cases", zh ? "通过率变化" : "Success-rate change", zh ? "调用数" : "Calls", + ...(resourceRows.length + ? [ + zh + ? "峰值内存 P50 / 基线变化" + : "Peak memory P50 / baseline change", + zh ? "CPU 均值 / 基线变化" : "Mean CPU / baseline change", + ] + : []), ], body, "functional-method-table", ), ); } -function versionSummary() { - let comparison = M.version_comparison, - rows = comparison.configurations; - let maxSuccess = Math.max(...rows.map((row) => row.success_rate_pct)), - minPss = Math.min(...rows.map((row) => row.pss_mib)), - minCpu = Math.min(...rows.map((row) => row.cpu_ms)); - let body = rows.map( - (row) => - `${esc(zh ? row.label : row.label_en)}${row.id === comparison.baseline ? `
${esc(zh ? "变化基线 · 差异验证" : "Change baseline · differential check")}
` : ""}${fmt(row.passed_cases)}/${fmt(row.total_cases)} (${fmt(row.success_rate_pct, 1)}%)${signed(row.success_change_pp, 1, zh ? " 个百分点" : " pp")}${fmt(row.pss_mib, 2)} MiB${signed(row.pss_change_pct, 2)}${fmt(row.cpu_ms, 2)} ms${signed(row.cpu_change_pct, 2)}`, - ); - let summary = table( - [ - zh ? "配置" : "Configuration", - zh ? "通过用例" : "Passed cases", - zh ? "通过率变化(相对 1.1.4)" : "Success-rate change vs. 1.1.4", - zh ? "峰值 PSS 中位数" : "Median peak PSS", - zh ? "PSS 变化(相对 1.1.4)" : "PSS change vs. 1.1.4", - zh ? "平均 CPU 时间 / 次" : "Mean CPU time / call", - zh ? "CPU 变化(相对 1.1.4)" : "CPU change vs. 1.1.4", - ], - body, - "version-summary-table", - ); - let population = zh - ? `纵轴使用同一组 372 个历史失败用例。1.1.8 两种模式直接各跑 372 题 × 3 次;1.1.4 对 1.1.8 关闭布局唯一通过的候选题跑三次,该题三次均失败,其余 371 题沿用两版本共同失败关系,因此为 0/372。横轴资源来自独立的 557 题 × 5 次实验;图表使用运行前冻结的 ${comparison.resource_population.chart_calls} 个任务-执行样本(${comparison.resource_population.chart_tasks} 题),采样间隔 ${comparison.resource_population.sample_interval_ms} ms。表格和图中的百分比变化均以 1.1.4 关闭 layout 为基准。` - : `The vertical axis uses the same set of 372 historical failures. Both 1.1.8 modes directly ran 372 cases × 3; 1.1.4 ran the sole case passed by layout-off 1.1.8 three times, failed all three, and retains the shared-failure relation for the other 371, yielding 0/372. Horizontal resources come from a separate 557-task × 5-call experiment; the chart uses ${comparison.resource_population.chart_calls} pre-frozen task-attempt samples (${comparison.resource_population.chart_tasks} tasks) at ${comparison.resource_population.sample_interval_ms} ms intervals. Percentage changes in the table and chart use 1.1.4 layout off as baseline.`; - let note = zh - ? `原图标注的 71 MiB 没有随 PR #535 提供对应执行记录;按可复现公开流程,本轮 1.1.4 测得 ${fmt(rows[0].pss_mib, 2)} MiB。CPU 是进程树用户态与内核态时间之和,不是墙钟耗时或 CPU 利用率。` - : `The published 71 MiB label has no matching execution record attached to PR #535; the reproducible public procedure measures ${fmt(rows[0].pss_mib, 2)} MiB for 1.1.4 here. CPU is process-tree user plus system time, not wall time or utilization.`; - let chart = zh - ? "moli-version-success-resources-zh.svg" - : "moli-version-success-resources-en.svg"; - return `
${contractCorrectionNotice()}${summary}
${esc(zh ? `${rows.length} 种 Moli 配置在 372 题成功率、峰值 PSS 和 CPU 时间上的对比图` : `${rows.length} Moli configurations compared by 372-case success rate, peak PSS and CPU time`)}
${esc(population)}

${esc(note)} ${esc(zh ? "下载机器可读数据" : "Download machine-readable data")}

`; +function combinedSummaryChart() { + const chart = `moli-all-success-resources-${zh ? "zh" : "en"}.svg`; + return `
${esc(zh ?
${esc(zh ? "成功率:372 个所选用例,每题 3 次全部通过;资源:独立的 557 题 × 5 次实验,图中使用预先冻结的 209 题、1,045 次样本。成功率变化以 1.1.4 为基线;内存和 CPU 仅在同一平台内计算相对基线的变化。" : "Success: 372 selected cases, all three attempts must pass. Resources: a separate 557-task × 5-call experiment; the plot uses the pre-frozen 209-task / 1,045-call sample. Success changes use 1.1.4 as baseline; memory and CPU changes are calculated only within the baseline platform.")}
`; } function macosResourceMethods() { let result = []; @@ -402,16 +385,14 @@ function candidateResourceSection() { ], [ "frozen_historical_common_pass_calls", - zh - ? "原图口径的冻结样本:209 题" - : "Frozen legacy-aligned sample: 209 tasks", + zh ? "图表样本:209 题" : "Chart sample: 209 tasks", 1045, ], ]; let specs = [ ["rss_peak_mib", "mean", zh ? "峰值 RSS 均值" : "Peak RSS mean", "MiB"], - ["rss_peak_mib", "p50", zh ? "峰值 RSS P50" : "峰值 RSS P50", "MiB"], - ["rss_peak_mib", "p95", zh ? "峰值 RSS P95" : "峰值 RSS P95", "MiB"], + ["rss_peak_mib", "p50", zh ? "峰值 RSS P50" : "Peak RSS P50", "MiB"], + ["rss_peak_mib", "p95", zh ? "峰值 RSS P95" : "Peak RSS P95", "MiB"], ["cpu_time_ms", "mean", zh ? "CPU 均值" : "CPU mean", "ms"], ["cpu_time_ms", "p50", zh ? "CPU P50" : "CPU P50", "ms"], ["cpu_time_ms", "p95", zh ? "CPU P95" : "CPU P95", "ms"], @@ -435,13 +416,13 @@ function candidateResourceSection() { return `${esc(item.label)}${fmt(calls)}${specs.map(([metric, stat, label, unit]) => `${fmt(m[metric][stat], 2)} ${unit}`).join("")}${signed((m.rss_peak_mib.p50 / b.rss_peak_mib.p50 - 1) * 100, 2)}${signed((m.cpu_time_ms.mean / b.cpu_time_ms.mean - 1) * 100, 2)}`; }); return ( - `

${esc(title)}

${esc(zh ? `峰值 RSS P50 最低:${leader("rss_peak_mib", "p50")};单次 CPU 均值最低:${leader("cpu_time_ms", "mean")}。资源最低与通过率最高分别判断。` : `Lowest peak 峰值 RSS P50: ${leader("rss_peak_mib", "p50")}; lowest mean CPU per call: ${leader("cpu_time_ms", "mean")}. Resource minima and task success are evaluated separately.`)}

` + + `

${esc(title)}

${esc(zh ? `峰值 RSS P50 最低:${leader("rss_peak_mib", "p50")};单次 CPU 均值最低:${leader("cpu_time_ms", "mean")}。资源最低与通过率最高分别判断。` : `Lowest peak RSS P50: ${leader("rss_peak_mib", "p50")}; lowest mean CPU per call: ${leader("cpu_time_ms", "mean")}. Resource minima and task success are evaluated separately.`)}

` + table( [ zh ? "方法" : "Method", zh ? "调用数" : "Calls", ...specs.map((x) => x[2]), - zh ? "峰值 RSS P50 变化" : "峰值 RSS P50 change", + zh ? "峰值 RSS P50 变化" : "Peak RSS P50 change", zh ? "CPU 均值变化" : "CPU mean change", ], rows, @@ -449,12 +430,9 @@ function candidateResourceSection() { ) ); }); - let chart = zh - ? "moli-macos-success-resources-zh.svg" - : "moli-macos-success-resources-en.svg"; let intro = zh - ? `资源实验与 372 题成功率测试分开:每个配置固定 layout,557 题各执行 5 次。P50 是中位数,P95 是第 95 百分位;每组统计包含同一批成功与失败调用。变化基准:${baseline.label}。macOS 测量进程树 RSS;历史 Linux PSS 另表展示。` - : `Resources are measured separately from success on 372 cases: each configuration fixes layout and runs 557 tasks five times. P50 is the median and P95 the 95th percentile; every metric in a scope includes the same passing and failing calls. Change baseline: ${baseline.label}. macOS measures process-tree RSS; historical Linux PSS is shown separately.`; + ? `资源实验与 372 题成功率测试分开:每个配置固定 layout,557 题各执行 5 次。P50 是中位数,P95 是第 95 百分位;每组统计包含同一批成功与失败调用。变化基准:${baseline.label}。macOS 测量进程树 RSS;Linux PSS 另表展示。` + : `Resources are measured separately from success on 372 cases: each configuration fixes layout and runs 557 tasks five times. P50 is the median and P95 the 95th percentile; every metric in a scope includes the same passing and failing calls. Change baseline: ${baseline.label}. macOS measures process-tree RSS; Linux PSS is shown separately.`; let evidence = methods .filter((x, i, a) => a.findIndex((y) => y.resource === x.resource) === i) .map( @@ -463,12 +441,10 @@ function candidateResourceSection() { ) .join(" "); return section( - zh - ? "Moli 1.1.9:成功率、RSS 与 CPU" - : "Moli 1.1.9: success rate, RSS and CPU", + zh ? "Moli 1.1.9 资源统计" : "Moli 1.1.9 resource statistics", intro, tables.join("") + - `
${esc(zh ?
${esc(zh ? `纵轴为 372 题通过率,横轴使用运行前冻结的 209 题、1,045 次调用;括号内百分比相对 ${baseline.label}。` : `Success rates use 372 cases; resource axes use 1,045 calls on 209 tasks frozen before execution. Parenthesized changes are relative to ${baseline.label}.`)}

${esc(zh ? "修复版使用提供的 debug 二进制,官方版使用发布资产。两者资源差异同时包含代码与构建配置差异。CPU 指进程树用户态与内核态时间之和。" : "The patched build uses the supplied debug binary; the official build uses the release asset. Their resource differences include both code and build configuration. CPU is the sum of process-tree user and system time.")}

${evidence}
`, + `

${esc(zh ? "修复版使用 debug 构建,官方版使用发布资产。两者资源差异同时包含代码与构建配置差异。CPU 指进程树用户态与内核态时间之和。" : "The patched binary is a debug build; the official build uses the release asset. Their resource differences include both code and build configuration. CPU is the sum of process-tree user and system time.")}

${evidence}
`, ); } function resourceGroups() { @@ -618,120 +594,19 @@ function simpleCard(label, value, detail) { return card(label, `${value}`, esc(detail)); } function home() { - let a = M.metrics.off, - b = M.metrics.on; - let off = a.baseline, - on = b.baseline; - let common = M.common_pass.count; - let core = table( - [zh ? "指标" : "Metric", T.modes.off, T.modes.on], - [ - metricRow( - zh ? "通过用例" : "Passed cases", - M.case_outcomes.off, - M.case_outcomes.on, - (v) => - `${fmt(v)}/${M.task_count} (${fmt((v / M.task_count) * 100, 1)}%)`, - "max", - ), - metricRow( - zh ? "累计任务耗时" : "Total task time", - off.duration_ms_all.sum, - on.duration_ms_all.sum, - (v) => fmt(v / 1000, 2) + " s", - ), - metricRow( - zh ? "平均耗时" : "Mean duration", - off.duration_ms_all.mean, - on.duration_ms_all.mean, - ms, - ), - metricRow( - zh ? "P50 耗时" : "P50 duration", - off.duration_ms_all.p50, - on.duration_ms_all.p50, - ms, - ), - metricRow( - zh ? "P95 耗时" : "P95 duration", - off.duration_ms_all.p95, - on.duration_ms_all.p95, - ms, - ), - ], - "core-table", - ); - let commonRows = table( - [zh ? "共同成功的同题指标" : "Same-task metric", T.modes.off, T.modes.on], - [ - metricRow( - zh ? "累计 CPU" : "Total CPU", - M.common_pass.cpu_total_ms.off, - M.common_pass.cpu_total_ms.on, - ms, - ), - metricRow( - zh ? "结束 PSS 均值" : "Mean ending PSS", - M.common_pass.pss_end_mean_bytes.off, - M.common_pass.pss_end_mean_bytes.on, - mib, - ), - metricRow( - zh ? "站点下行量" : "Fixture downlink", - M.common_pass.fixture_tx_total_bytes.off, - M.common_pass.fixture_tx_total_bytes.on, - (v) => fmt(v) + " B", - ), - ], - ); return ( - (M.host_context.concurrent_test_observed_at_start - ? `
${esc(zh ? "本轮与同机其他测试并行,耗时和资源代表共享宿主机条件;具体观测见核验记录。" : "Other tests were active on the same host. Duration and resource values reflect shared-host conditions; see Verification for observations.")}
` - : "") + hero( reportTitle(), reportSubtitle(), - `${esc(T.start)}${esc(T.method)}`, + `${esc(T.nav.analysis)}${esc(T.method)}`, ) + functionalMethodSummary() + + combinedSummaryChart() + + `
${esc(zh ? "查看完整资源统计与测量范围" : "Inspect resource statistics and measurement scope")}${candidateResourceSection()}

${esc(zh ? "Linux PSS 与 CPU 数值见总表。全部资源统计包含成功与失败调用;图表样本在运行前固定。" : "Linux PSS and CPU values appear in the summary table. Resource statistics include successful and failed calls; the chart sample is fixed before execution.")}

${esc(zh ? "下载 Linux 资源数据" : "Download Linux resource data")}
` + section( - zh - ? "历史 Linux 配置:成功率与资源" - : "Historical Linux configurations: success and resources", - zh - ? "以下三个配置使用 Linux PSS。1.1.9 的 macOS RSS/CPU 另表展示;成功率均覆盖同一 372 个历史失败用例。" - : "These three configurations use Linux PSS. Moli 1.1.9 macOS RSS/CPU is shown separately; success rates cover the same 372 historical failures.", - versionSummary(), - ) + - candidateResourceSection() + - section( - zh ? "1.1.8 布局模式核心结果" : "Moli 1.1.8 layout-mode results", - casePopulation() + " " + metricPopulation(), - core, - ) + - section( - zh ? "1.1.8 的 CPU、内存与网络" : "Moli 1.1.8 CPU, memory and network", - zh - ? `同一 ${M.attempts_per_mode} 次调用。绿色仅标识同一指标中较低的原始数值,不代表统计显著性或整体优胜。` - : `The same ${M.attempts_per_mode} calls. Green marks the lower raw value for the same metric, not statistical significance or overall leadership.`, - resourceGroups(), - ) + - section( - zh ? "各模式成功调用耗时" : "Duration on each mode’s accepted calls", - zh - ? "每种模式仅统计自身通过的调用,任务范围不同;平均、P50、P95 使用表头标出的同一分母。" - : "Each mode includes only its own accepted calls, with different task coverage. Mean, P50 and P95 share the population shown in each column heading.", - successfulDuration(), - ) + - section( - zh ? "共同成功任务的条件成本" : "Conditional cost on shared successes", - `${common}/${M.attempts_per_mode} ${zh ? "个同题同次配对在两种模式、无采样和采样四轮中均通过。这个诊断子集不决定任务入选或整体排行。" : "paired calls passed all four baseline and profiled rounds. This diagnostic subset does not select tasks or determine an overall ranking."}`, - commonRows, - ) + - section( - zh ? "任务类别概览" : "Task families", - T.methodLimit + " " + casePopulation(), - strataTable(), + zh ? "如何查看结果" : "Explore the results", + "", + `

${esc(zh ? "修复版为 debug 构建,官方版为发布资产。macOS 与 Linux 的资源数值分别解释,不能把跨平台差异归因于代码修复。" : "The patched binary is a debug build; the official binary is a release asset. Interpret macOS and Linux resources separately; cross-platform differences cannot be attributed to the code changes.")}

${esc(zh ? "比较新增通过与仍然失败的用例" : "Compare gained passes and remaining failures")} · ${esc(T.nav.guide)} · ${esc(T.nav.reproduce)}`, ) ); } @@ -796,7 +671,7 @@ function inventory(kind) { ? section( zh ? "选择规则" : "Selection rule", T.methodLimit, - `

${esc(zh ? "选取历史 1,928 题中未能三次全部通过的全部 372 题。保留 Chrome 历史失败的题目;Chrome 的结果不作为排除依据。两个布局组使用同一组冻结任务与验收规则。" : M.selection)}

SHA-256: ${esc(M.manifest_sha256)}

`, + `

${esc(zh ? "选取 1,928 题中未能三次全部通过的全部 372 题。保留 Chrome 未通过的题目;Chrome 的结果不作为排除依据。两个布局组使用同一组冻结任务与验收规则。" : M.selection)}

SHA-256: ${esc(M.manifest_sha256)}

`, ) : "") ); @@ -1063,84 +938,44 @@ async function resultPage(id, mode) { ); } function methodPage() { - let row = table( - [zh ? "控制项" : "Control", zh ? "设定" : "Setting"], - [ - ...[ - [zh ? "浏览器" : "Browser", "Moli 1.1.8 Linux aarch64"], - [ - zh ? "二进制 SHA-256" : "Binary SHA-256", - `${M.binary_sha256}`, - ], - [ - zh ? "任务" : "Tasks", - `${M.task_count} × ${M.protocol.k_runs} × ${zh ? "2 种模式" : "2 modes"}`, - ], - [ - zh ? "执行" : "Execution", - zh - ? "固定脚本;单工作进程;相同种子和任务顺序" - : "Fixed scripts; one worker; same seed and task order", - ], - [ - zh ? "进程复用" : "Process reuse", - zh - ? "按 runner 规则复用进程,崩溃或任务要求时重建;轮次之间重新启动" - : "Runner-controlled reuse; restart on crashes or task requirements and between rounds", - ], - [ - zh ? "资源" : "Resources", - zh - ? "500 ms 进程树 CPU/PSS,站点应用层流量" - : "500 ms process-tree CPU/PSS and fixture application traffic", - ], - [ - zh ? "冷启动" : "Cold start", - zh - ? "交替 5 次/模式,独立容器;不计入 372 题通过率" - : "Five alternating starts per mode in separate containers; excluded from the 372-case pass rate", - ], - ].map(([a, b]) => `${esc(a)}${b}`), - ], - ); - let versionMethod = - (zh - ? "汇总层先比较三种固定配置。1.1.8 关闭和开启布局直接各跑 372 题 × 3 次;关闭布局只通过 1 题。1.1.4 因此只验证这唯一候选题,三次均失败,其余 371 题沿用共同失败关系,得到 0/372。" - : "The summary first compares three fixed configurations. Both Moli 1.1.8 modes directly ran 372 cases × 3, and layout off passed only one case. Moli 1.1.4 therefore checks that sole candidate; it failed all three attempts, while the other 371 retain the shared-failure relation, yielding 0/372.") + - (Object.keys(M.fixed_candidates || {}).length - ? zh - ? " 1.1.9 修复版分别统计固定关闭与固定开启 layout 的 372 题结果,每题三次。官方 1.1.9 仅测开启 layout。" - : " Patched Moli 1.1.9 reports fixed layout off and on over 372 cases with three attempts each. Official 1.1.9 is measured with layout on only." - : "") + - (zh - ? " 三种固定配置的资源对照使用独立的 557 题 × 5 次 Linux 实验,图中使用运行前冻结的 1,045 个任务-执行样本。1.1.9 使用相同 557 题 × 5 次 macOS 实验,固定关闭与固定开启 layout 各执行一轮资源采样;资源分别对应同一布局配置的单次调用。逐题证据页聚焦 1.1.8 的两种布局配置。" - : " The three fixed configurations use a separate 557-task × 5-call Linux resource experiment and a pre-frozen 1,045 task-attempt sample. Moli 1.1.9 uses the same 557-task × 5-call macOS scope, with one profiled run each for fixed layout off and fixed layout on. Resources represent individual calls in the corresponding fixed-layout configuration. Per-task evidence pages focus on the two Moli 1.1.8 layout configurations."); return ( - hero(T.nav.method, T.methodIntro) + + hero( + T.nav.method, + zh + ? "固定任务、固定布局与独立资源实验。" + : "Fixed tasks, fixed layout and a separate resource experiment.", + ) + section( - Object.keys(M.fixed_candidates || {}).length - ? zh - ? "固定配置汇总口径" - : "Fixed-configuration summary" - : zh - ? "三方法汇总口径" - : "Three-configuration summary method", - versionMethod, + zh ? "评测流程" : "Evaluation protocol", + "", + `
flowchart TB
+A["${zh ? "冻结任务、二进制与验收规则" : "Freeze tasks, binaries and acceptance rules"}"] --> B["${zh ? "固定版本与 layout 配置" : "Fix version and layout configuration"}"]
+B --> C["${zh ? "功能:372 题,每题 3 次" : "Functional: 372 cases, three attempts each"}"]
+B --> D["${zh ? "资源:557 题,每题 5 次" : "Resources: 557 tasks, five calls each"}"]
+C --> E["${zh ? "三次全部通过才算通过" : "A case passes only when all three attempts pass"}"]
+D --> F["${zh ? "全部调用统计与固定 209 题图表样本" : "All-call statistics and fixed 209-task chart sample"}"]
+E --> G["${zh ? "六配置总表与总图" : "Six-configuration table and chart"}"]
+F --> G
`, + ) + + section( + zh ? "功能评分与基线" : "Functional scoring and baseline", "", + `

${esc(zh ? "六种配置共用 372 题分母。每题三次执行全部通过运行与验收检查,才记为一个通过用例。1.1.8 的两种布局、修复版 1.1.9 的两种布局和官方 1.1.9 开启布局均覆盖全部 372 题。" : "All six configurations use the same 372-case denominator. A case passes only when execution and acceptance checks pass in all three attempts. Both 1.1.8 layouts, both patched 1.1.9 layouts and official 1.1.9 layout on directly cover all 372 cases.")}

${esc(zh ? "1.1.4 关闭布局为基线:对 1.1.8 关闭布局唯一通过的候选题实测三次,均失败;其余 371 题沿用共同失败关系。因此表中的 0/372 包含 1 题直接验证和 371 题继承结果,并非对 1.1.4 的完整重测。基线通过率为 0%,通过率变化用百分点表示。" : "Layout-off 1.1.4 is the baseline: the sole candidate passed by layout-off 1.1.8 failed all three direct checks; the other 371 retain the shared-failure relation. Its 0/372 consists of one directly checked case and 371 inherited outcomes, not a complete 1.1.4 rerun. Because baseline success is zero, success changes are expressed in percentage points.")}

`, ) + section( - zh ? "1.1.8 历史实验流程" : "Historical 1.1.8 protocol", + zh ? "任务来源与适用范围" : "Task selection and scope", "", - `
flowchart TB
-A["${zh ? `冻结 ${M.task_count} 题、版本与种子` : `Freeze ${M.task_count} tasks, versions and seed`}"] --> B["${zh ? "无采样:先无布局,再开布局" : "Unprofiled: layout off, then on"}"]
-B --> C["${M.resource_window_corrections?.length ? (zh ? "500 ms 采样:两种模式完整重测" : "500 ms profiling: complete reruns of both modes") : zh ? "500 ms 采样:先开布局,再无布局" : "500 ms profiling: layout on, then off"}"]
-C --> D["${zh ? "按任务与调用序号核验;无失败恢复重跑" : "Verify paired task-attempts; no layout recovery retry"}"]
`, + `

${esc(zh ? "372 题选自 Moli 0.1.1 在 1,928 题中未达到三次全部通过的全部用例,覆盖 15 类驱动。Chrome 结果不影响入选。其余 1,556 题不在评测范围内,这里的通过率不代表完整 1,928 题的通过率。" : "The 372 cases are all cases from the 1,928-case suite that Moli 0.1.1 did not pass in all three attempts, spanning 15 driver types. Chrome outcomes do not affect selection. The other 1,556 cases are outside this evaluation, so these rates do not describe the full suite.")}

${esc(T.nav.dataset)}`, ) + - section(zh ? "共同控制" : "Shared controls", "", row) + section( - zh ? "指标边界" : "Metric boundaries", - T.metricNote, - `

${esc(zh ? "全部调用" : "All calls")}

${esc(zh ? "成功、失败和超时都保留。它表示 Agent 用户为同一批任务实际等待及消耗的资源。" : "Passes, failures and timeouts stay in the denominator, representing the user's full task cost.")}

${esc(zh ? `共同成功的 ${M.common_pass.count} 次调用` : `The ${M.common_pass.count} calls both modes passed`)}

${esc(zh ? "仅用于隔离模式成本的诊断;不能按结果重新选择要测试的任务。" : "A diagnostic to isolate the mode's cost; it cannot select tasks after outcomes are known.")}

${esc(zh ? "内存采样" : "Memory sampling")}

${esc(zh ? "短任务常只有起点和终点。观测最大值不是未采到的瞬时峰值;结束 PSS 更适合比较常驻内存。" : "Short calls often have only start and end points. The observed maximum is not a high-resolution instantaneous peak; ending PSS compares resident footprint.")}

${esc(zh ? "网络与 CPU" : "Traffic and CPU")}

${esc(zh ? "站点流量是应用层 HTTP/WebSocket 字节;CPU 来自 /proc 进程树,短命子进程可能漏计。驱动与容器启停不计入 Moli 进程指标。" : "Fixture traffic is application-layer HTTP/WebSocket bytes; CPU uses the /proc process tree and may miss short-lived child processes. Harness and container startup are excluded from Moli process metrics.")}

`, + zh ? "资源测量与可比范围" : "Resource measurement and comparability", + "", + `

${esc(zh ? "资源实验单独执行 557 题,每题五次,每种配置共 2,785 次调用。图和总表使用运行前固定的 209 题、1,045 次样本;完整资源表另列全部 557 题。P50 是中位数,P95 是第 95 百分位。" : "Resources use a separate 557-task experiment with five calls per task, or 2,785 calls per configuration. The chart and overview table use 1,045 calls on 209 tasks fixed before execution; detailed resource tables also show all 557 tasks. P50 is the median and P95 the 95th percentile.")}

${esc(zh ? "1.1.4 / 1.1.8 的资源来自 Linux PSS;1.1.9 来自 macOS RSS。CPU 为进程树用户态与内核态时间之和。跨平台的内存和 CPU 不计算相对 1.1.4 的百分比变化;同平台百分比是样本数值对照。修复版为 debug 构建,官方版为发布资产。" : "Moli 1.1.4 / 1.1.8 resources use Linux PSS; 1.1.9 uses macOS RSS. CPU is process-tree user plus system time. Cross-platform memory and CPU changes relative to 1.1.4 are not calculated; same-platform percentages describe the measured sample. The patched binary is a debug build and the official binary is a release asset.")}

`, + ) + + section( + zh ? "执行与证据" : "Execution and evidence", + "", + `

${esc(zh ? "使用冻结脚本和单工作进程执行。每个版本的功能与资源调用绑定同一二进制哈希;任务定义、程序判定、标准输出与错误日志可从逐题详情检查。未进行独立人工逐次复核。" : "Frozen scripts run with one worker. Functional and resource calls for each build bind the same binary hash. Task definitions, program verdicts, stdout and error logs are available in task details. No independent per-call human review was performed.")}

${esc(T.nav.reproduce)}`, ) ); } @@ -1306,15 +1141,15 @@ async function fixedCasePage(id) { hero(c.title, id) + section(zh ? "结果摘要" : "Result summary", "", summary) + section( - zh ? "本轮任务要求" : "Task requirements for this comparison", + zh ? "任务要求" : "Task requirements for this comparison", c.task_definition.description, `
${esc(zh ? "查看冻结任务定义" : "Inspect frozen task definition")}

SHA-256: ${esc(c.task_sha256)}

${esc(JSON.stringify(c.task_definition, null, 2))}
`, ) + details + section( - zh ? "任务与历史结果" : "Task and historical results", + zh ? "同题版本对照" : "Same-task version comparison", "", - `${esc(zh ? "查看 1.1.8 原始任务记录与对照" : "View the original 1.1.8 task record and comparison")}`, + `${esc(zh ? "查看 1.1.8 任务要求与结果" : "View 1.1.8 task requirements and results")}`, ) ); } @@ -1356,91 +1191,6 @@ function analysisPage() { section(zh ? "任务类型比较" : "By task family", "", strataTable()) ); } -function hostLoadTable() { - if (!M.host_context.rounds) return ""; - let labels = zh - ? { - off_baseline: "无布局 · 无采样", - on_baseline: "开布局 · 无采样", - off_engine: "无布局 · 资源采样", - on_engine: "开布局 · 资源采样", - } - : { - off_baseline: "Layout off · unprofiled", - on_baseline: "Layout on · unprofiled", - off_engine: "Layout off · profiled", - on_engine: "Layout on · profiled", - }; - return section( - zh ? "宿主机实际负载" : "Observed host load", - zh - ? "macOS 每 5 秒记录一次。1 分钟负载包含全部宿主机工作负载;数值不等于 CPU 利用率,也不用于性能排名。" - : "Recorded on macOS every five seconds. One-minute load includes all host workloads, is not CPU utilization, and is not ranked.", - table( - [ - zh ? "运行条件" : "Run condition", - zh ? "观测点数" : "Samples", - zh ? "1 分钟负载中位数" : "Median one-minute load", - zh ? "1 分钟负载最大值" : "Maximum one-minute load", - ], - Object.entries(M.host_context.rounds).map( - ([key, x]) => - `${esc(labels[key])}${x.samples}${fmt(x.macos_load1_median, 2)}${fmt(x.macos_load1_max, 2)}`, - ), - ), - ); -} -function correctionSection() { - return (M.resource_window_corrections || []) - .map((c) => - section( - `${T.modes[c.mode]} · ${zh ? "资源校准更正" : "Resource calibration correction"}`, - zh - ? `原 ${c.calls} 次资源测量的耗时变化中位数超过 10% 校准阈值,保留为诊断证据,并以同任务、同种子、同二进制的完整重测替换。成功率与无采样耗时口径保持不变。` - : `The original ${c.calls}-call resource round exceeded the 10% median timing calibration threshold. It remains diagnostic evidence and was replaced by a full rerun with identical tasks, seed and binary. Acceptance and unprofiled duration are unchanged.`, - table( - [ - zh ? "项目" : "Item", - zh ? "原采样轮" : "Original profiled round", - zh ? "完整重测轮" : "Complete replacement", - ], - [ - `${esc(zh ? "运行 ID" : "Run ID")}${esc(c.superseded_run)}${esc(c.replacement_run)}`, - `${esc(zh ? "累计 Moli CPU" : "Total Moli CPU")}${fmt(c.old_cpu_ms / 1000, 2)} s${fmt(c.replacement_cpu_ms / 1000, 2)} s`, - `${esc(zh ? "观测 PSS 最大值均值" : "Mean observed PSS maximum")}${fmt(c.old_pss_observed_max_mean_mib, 2)} MiB${fmt(c.replacement_pss_observed_max_mean_mib, 2)} MiB`, - ], - ) + - ``, - ), - ) - .join(""); -} -function functionalCorrectionSection() { - let c = M.functional_contract_correction; - if (!c) return ""; - return section( - zh - ? "Chromium 基线合同修正后的 Moli 补测" - : "Moli retest after Chromium baseline contract corrections", - zh - ? `两道受影响题在三种现有 Moli 配置下各重跑三次,共 ${c.calls} 次调用。结果均仍为失败,因此 0/372、1/372、255/372 不变。` - : `The two affected cases were rerun three times under each existing Moli configuration (${c.calls} calls). All remain failures, so 0/372, 1/372 and 255/372 are unchanged.`, - `
${facts([ - [ - zh ? "Lexbench 修正提交" : "Lexbench correction commit", - `${esc(c.harness_commit)}`, - ], - [ - zh ? "覆盖" : "Coverage", - `${c.task_count} × ${c.configuration_count} × 3 = ${c.calls}`, - ], - [ - zh ? "成功率变化" : "Success-rate change", - esc(c.success_rates_changed ? (zh ? "有" : "Yes") : zh ? "无" : "None"), - ], - ])}
`, - ); -} function candidateResourceQuality() { let methods = macosResourceMethods(); if (!methods.length) return ""; @@ -1466,109 +1216,79 @@ function candidateResourceQuality() { ); } function reviewPage() { - let q = M.quality; - let rows = ["off", "on"].map( + let rows = M.functional_methods.map( (m) => - `${esc(T.modes[m])}${M.attempts_per_mode}/${M.attempts_per_mode}${M.metrics[m].baseline.passes} / ${M.metrics[m].profile.passes}${q[m].status_mismatch_count}${q[m].baseline_host.polluted || q[m].engine_host.polluted ? esc(zh ? "有" : "Yes") : esc(zh ? "无" : "No")}${q[m].resource_missing}`, + `${esc(zh ? m.label : m.label_en)}${m.direct_cases}${m.inherited_cases}${m.physical_calls || (m.id === "114_off" ? 3 : 1116)}${esc(m.moli_sha256)}`, ); return ( hero( T.nav.review, zh - ? "完整性、采样前后判定与运行环境分别核验。" - : "Completeness, profiling verdict changes and environment observations are checked separately.", + ? "核对评测覆盖、二进制身份与证据来源。" + : "Verify evaluation coverage, binary identities and evidence sources.", ) + - functionalCorrectionSection() + - candidateResourceQuality() + section( - zh ? "机器证据完整性" : "Machine evidence coverage", + zh ? "功能证据覆盖" : "Functional evidence coverage", "", table( [ - T.mode, - zh ? "调用完整" : "Complete calls", - zh ? "无采样 / 采样通过数" : "Unprofiled / profiled passes", - zh ? "采样前后判定变化" : "Verdict changes", - zh ? "容器内环境标记" : "In-container environment flags", - zh ? "资源缺口" : "Missing resources", + zh ? "方法" : "Method", + zh ? "直接验证题数" : "Direct cases", + zh ? "继承结果题数" : "Inherited cases", + zh ? "调用数" : "Calls", + "SHA-256", ], rows, ), ) + + candidateResourceQuality() + section( - T.calibration, - zh - ? "与无采样轮逐对比较;时间差包含宿主机负载变化,不能单独解释为采样器开销。主耗时始终采用无采样值。10% 门槛约束 P50,不约束 P95;尾部偏移另列。" - : "Paired differences include changing host conditions and do not isolate profiler overhead. Primary duration always uses unprofiled values. The 10% limit applies to P50, not P95; tail differences are listed separately.", - table( - [ - T.mode, - zh ? "耗时变化 P50" : "Duration change P50", - zh ? "耗时变化 P95" : "Duration change P95", - zh ? "含采集变化 P50" : "Collection-inclusive change P50", - zh ? "含采集变化 P95" : "Collection-inclusive change P95", - zh ? "P50 校准阈值检查" : "P50 calibration threshold check", - ], - ["off", "on"].map( - (m) => - `${esc(T.modes[m])}${fmt(q[m].calibration.median_duration_delta_pct, 2)}%${fmt(q[m].calibration.p95_duration_delta_pct, 2)}%${fmt(q[m].calibration.median_collection_wall_delta_pct, 2)}%${fmt(q[m].calibration.p95_collection_wall_delta_pct, 2)}%${esc(q[m].calibration.acceptable ? (zh ? "通过" : "Pass") : zh ? "未通过,见数据模型" : "Failed; see data model")}`, - ), - ), - ) + - section( - zh ? "宿主机观测范围" : "Host observation scope", - "", - `
${esc(M.host_context.shared_macos_host ? (zh ? "容器运行于共享 macOS 宿主机,共用 CPU 与内存。宿主机负载与容器内遥测分别记录,观测范围见下表。" : "Containers share the macOS host CPU and memory. Host load and in-container telemetry are recorded separately; observed coverage appears below.") : zh ? "本组运行时未发现并行测试。容器内遥测的观测范围为 Docker Linux 环境。" : "No concurrent test was observed for this cohort. In-container telemetry covers the Docker Linux environment.")}
`, - ) + - section( - zh ? "独立复核" : "Independent review", - "", - `
${esc(T.noHuman)} · 0/${M.attempts_per_mode * 4} ${zh ? `次调用经过独立逐项审查。${M.review_coverage.unreviewed_program_passes} 次程序通过结果未作独立复核。` : `calls independently reviewed. ${M.review_coverage.unreviewed_program_passes} program passes have not been independently reviewed.`}
`, - ) + - hostLoadTable() + - correctionSection() + - section( - zh ? "冻结标识" : "Frozen identities", + zh ? "评分与复核范围" : "Scoring and review coverage", "", - `
${facts([ - [ - zh ? "任务清单 SHA-256" : "Manifest SHA-256", - `${esc(M.manifest_sha256)}`, - ], - [ - zh ? "Moli 二进制 SHA-256" : "Moli binary SHA-256", - `${esc(M.binary_sha256)}`, - ], - ])}
`, + `

${esc(zh ? "结果来自冻结验收规则的程序判定。报告检查调用矩阵、版本和任务哈希、资源样本数、聚合数值及证据文件完整性。未进行独立人工逐次复核;程序通过结果不等同于人工审查结论。" : "Outcomes come from programmatic evaluation against frozen acceptance rules. Report checks cover call matrices, binary and task hashes, resource sample counts, aggregates and evidence integrity. No independent per-call human review was performed; program passes are not human-review conclusions.")}

${esc(zh ? "下载完整数据与证据索引" : "Download the data model and evidence index")}`, ) ); } function guidePage() { - let p = M.case_outcomes.paired; + const relations = fixedRelations(); + const example = M.fixed_case_outcomes.find( + (c) => c.passes["119_official_on"] !== 3 && c.passes["119_on"] === 3, + ); + const patched = M.functional_methods.find((m) => m.id === "119_on"); + const official = M.functional_methods.find((m) => m.id === "119_official_on"); + const relationText = relations + .map( + (r) => + `

${esc(r.label)}:${esc(zh ? `新增通过 ${r.counts.gain} 题,退步 ${r.counts.loss} 题。` : `${r.counts.gain} cases gained, ${r.counts.loss} lost.`)}

`, + ) + .join(""); return ( - hero(T.nav.guide, T.guideIntro) + + hero( + T.nav.guide, + zh + ? `修复版开启布局通过 ${patched.final_passed_cases}/${M.task_count} 题,官方版开启布局通过 ${official.final_passed_cases}/${M.task_count} 题。` + : `Patched layout on passes ${patched.final_passed_cases}/${M.task_count} cases; official layout on passes ${official.final_passed_cases}/${M.task_count}.`, + ) + functionalMethodSummary() + - fixedComparisonSection() + + combinedSummaryChart() + section( - zh ? "1.1.8 完成任务的变化" : "Moli 1.1.8 changes in completion", + zh ? "布局与版本分别改变了什么" : "Effects of layout and version", "", - `
${esc(zh ? `按同一组 ${M.task_count} 个用例比较:开启布局新增通过 ${p.off_fail_on_pass} 个用例,${p.off_pass_on_fail} 个用例由通过变为失败。` : `Across the same ${M.task_count} cases, layout gained ${p.off_fail_on_pass} passed cases and lost ${p.off_pass_on_fail}.`)}
`, + relationText + + `${esc(zh ? "查看对应的新增通过和失败用例" : "Inspect gained passes and failures")}`, ) + - historicalSection() + - candidateResourceSection() + - costSection() + section( - zh ? "1.1.8 资源分项对照" : "Moli 1.1.8 resource comparison", - zh - ? "全部调用与独立冷启动样本分开统计。每项绿色标记只表示本列原始数值更低。" - : "All calls and the separate cold-start sample are distinct populations. Green marks only the lower raw value in each metric.", - resourceGroups(), + zh ? "如何理解一个通过结果" : "What a passed case means", + "", + `

${esc(zh ? "每个任务定义固定操作和验收条件。单次工具返回成功不足以判为用例通过;每次执行必须满足评分器检查,而且三次执行全部通过。" : "Each task defines fixed actions and acceptance conditions. A successful tool response alone is insufficient: the evaluator must accept every execution, and all three attempts must pass.")}

${example ? `

${esc(example.id)} · ${esc(zh ? `官方开启布局 ${example.passes["119_official_on"]}/3,修复版开启布局 ${example.passes["119_on"]}/3。` : `Official layout on: ${example.passes["119_official_on"]}/3; patched layout on: ${example.passes["119_on"]}/3.`)} ${esc(zh ? "检查任务要求、实际输出和评分证据" : "Inspect requirements, actual output and evaluator evidence")}

` : ""}`, ) + + candidateResourceSection() + section( - T.scope, - T.methodLimit, - `
${esc(zh ? `这 ${M.task_count} 题是 Moli 0.1.1 的全部历史失败用例。通过率描述这一失败子集的恢复情况;耗时包括超时与失败等待,不能当作布局计算的纯开销。` : `These ${M.task_count} tasks are all historical Moli 0.1.1 failures. Acceptance describes recovery within this failure subset. Duration includes timeouts and failed waits and does not isolate layout computation overhead.`)}
`, - ) + zh ? "结论与适用范围" : "Conclusions and scope", + "", + `

${esc(zh ? "固定开启布局显著扩大了修复版在这组任务上的通过范围;在相同开启布局设置下,修复版比官方版通过更多任务。资源消耗与任务成功分别判断:修复版 debug 构建的 CPU 和 RSS 更高,不能把这一差异单独归因于代码修复。1.1.4 的验证范围及任务选择条件见评测方法。" : "Fixed layout on substantially expands the patched build's passing coverage on this cohort. Under layout on, the patched build passes more tasks than the official build. Evaluate resources separately from success: the patched debug build uses more CPU and RSS, and that difference cannot be attributed solely to code changes. The method page defines task selection and 1.1.4 coverage.")}

${esc(T.nav.method)}`, + ) + + `
${esc(zh ? "1.1.8 的补充资源指标" : "Additional 1.1.8 resource metrics")}${resourceGroups()}${successfulDuration()}
` ); } function candidateReproductionSection() { diff --git a/scripts/moli_report/build.py b/scripts/moli_report/build.py index c4073462e..b87266ddf 100644 --- a/scripts/moli_report/build.py +++ b/scripts/moli_report/build.py @@ -18,7 +18,7 @@ ) sys.path.insert(0, str(BENCH_ROOT)) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from plot_moli_version_resources import render_chart # noqa: E402 +from plot_moli_version_resources import combine_comparisons, render_chart # noqa: E402 from runner.resources import duration_calibration # noqa: E402 RUNS = ROOT / "runs/moli-1.1.8-failures-linux" @@ -723,6 +723,9 @@ def timestamp(value): "extra_physical_calls": 0, }, ] +for method in functional_methods: + method["moli_sha256"] = version_protocol["configs"][method["id"]]["sha256"] + method["physical_calls"] = 3 if method["id"] == "114_off" else 1116 fixed_candidates = {} fixed_case_data = {c["id"]: {"id": c["id"], "title": c["title"], "methods": {}} for c in cases} public_candidate_files = {} @@ -964,7 +967,9 @@ def timestamp(value): "calls_per_task": 5, }, } +combined_comparison = combine_comparisons(functional_methods, version_comparison, macos_comparison) public = { + "combined_comparison": combined_comparison, "fixed_case_outcomes": [ { "id": c["id"], @@ -1075,6 +1080,16 @@ def timestamp(value): json.dumps(version_comparison, ensure_ascii=False, indent=2) + "\n" ) (OUT / "assets").mkdir() +(OUT / "data/combined-comparison.json").write_text( + json.dumps(combined_comparison, ensure_ascii=False, indent=2) + "\n" +) +for language in ("zh", "en"): + render_chart( + combined_comparison, + OUT / f"assets/moli-all-success-resources-{language}.svg", + ("memory", "cpu"), + language, + ) if macos_comparison: for language in ("zh", "en"): render_chart( diff --git a/scripts/moli_report/style.css b/scripts/moli_report/style.css index 04dcb7e9c..0447c3f1c 100644 --- a/scripts/moli_report/style.css +++ b/scripts/moli_report/style.css @@ -222,6 +222,22 @@ main { margin: 0.35rem 0 1rem; overflow-wrap: anywhere; } +.resource-disclosure { + margin: 2rem 0; + padding: 1rem 1.25rem; + border: 1px solid var(--line); + border-radius: 12px; + background: var(--surface); +} +.resource-disclosure > summary { + cursor: pointer; + font-weight: 650; +} +.method-number { + display: inline-block; + font-variant-numeric: tabular-nums; + color: var(--muted); +} .grid { display: grid; gap: 1rem; diff --git a/scripts/moli_report/ui_check.js b/scripts/moli_report/ui_check.js index eab59105b..24edb565d 100644 --- a/scripts/moli_report/ui_check.js +++ b/scripts/moli_report/ui_check.js @@ -61,88 +61,58 @@ for (const id of new Set([fixedPass, fixedFail].filter(Boolean))) routes.push("fixed/" + id); async function metrics(page) { return page.evaluate(() => { - let groups = new Map(); - for (let cell of document.querySelectorAll("[data-metric]")) { - let key = cell.getAttribute("data-metric"), - list = groups.get(key) || []; - list.push(cell); - groups.set(key, list); + const groups = new Map(); + for (const cell of document.querySelectorAll("[data-combined-metric]")) { + const key = cell.dataset.combinedMetric + ":" + cell.dataset.platform; + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(cell); } - for (let [key, cells] of groups) { - if (cells.length !== 2) throw Error("metric pair " + key); - let values = cells.map((c) => Number(c.dataset.sort)); - if (values.some((v) => !Number.isFinite(v))) - throw Error("numeric value " + key); - let direction = cells[0].dataset.metricDirection; - let expected = - values[0] === values[1] - ? -1 - : direction === "max" - ? values[0] > values[1] - ? 0 - : 1 - : values[0] < values[1] - ? 0 - : 1; - let marked = cells - .map((c, i) => (c.classList.contains("winner") ? i : -1)) - .filter((i) => i >= 0); - if (expected < 0 && marked.length) - throw Error("tied metric highlighted " + key); - if (expected >= 0 && (marked.length !== 1 || marked[0] !== expected)) - throw Error("wrong or missing highlight " + key); + for (const [key, cells] of groups) { + const values = cells.map((c) => Number(c.dataset.value)); + const min = Math.min(...values); + const unique = values.filter((v) => v === min).length === 1; + for (const cell of cells) + if ( + cell.classList.contains("winner") !== + (unique && Number(cell.dataset.value) === min) + ) + throw Error("resource highlight " + key); } return groups.size; }); } async function caseMetric(page) { - let cells = await page - .locator(".core-table tbody tr") - .first() - .locator("[data-metric]") - .evaluateAll((xs) => - xs.map((x) => ({ value: Number(x.dataset.sort), text: x.textContent })), + const cells = await page + .locator("[data-functional-method]") + .evaluateAll((rows) => + rows.map((row) => ({ + id: row.dataset.functionalMethod, + value: Number( + row.querySelector("[data-functional-final]").dataset.functionalFinal, + ), + text: row.querySelector("[data-functional-final]").textContent, + winner: row + .querySelector("[data-functional-final]") + .classList.contains("winner"), + })), ); + const max = Math.max( + ...model.functional_methods.map((m) => m.final_passed_cases), + ); + const unique = + model.functional_methods.filter((m) => m.final_passed_cases === max) + .length === 1; if ( - cells.length !== 2 || + cells.length !== model.functional_methods.length || cells.some( (c, i) => - c.value !== model.case_outcomes[i ? "on" : "off"] || - !c.text.includes("/" + model.task_count + " "), + c.id !== model.functional_methods[i].id || + c.value !== model.functional_methods[i].final_passed_cases || + !c.text.includes("/" + model.task_count + " ") || + c.winner !== (unique && c.value === max), ) ) - throw Error("primary metric must count cases"); -} -async function versionMetrics(page) { - let groups = await page - .locator("[data-version-metric]") - .evaluateAll((cells) => { - let out = {}; - for (let cell of cells) { - let key = cell.dataset.versionMetric; - (out[key] ??= []).push({ - value: Number(cell.dataset.value), - direction: cell.dataset.direction, - winner: cell.classList.contains("winner"), - }); - } - return out; - }); - for (let [key, cells] of Object.entries(groups)) { - if (cells.length !== 3) throw Error("version metric cardinality " + key); - let values = cells.map((cell) => cell.value), - target = - cells[0].direction === "max" - ? Math.max(...values) - : Math.min(...values), - unique = values.filter((value) => value === target).length === 1, - winners = cells.filter((cell) => cell.winner); - if (unique && (winners.length !== 1 || winners[0].value !== target)) - throw Error("version metric highlight " + key); - if (!unique && winners.length) - throw Error("tied version metric highlighted " + key); - } - return Object.keys(groups).length; + throw Error("functional registry or verdict mismatch"); } async function fixedMetrics(page) { let groups = await page @@ -231,18 +201,10 @@ async function run() { if (route === "home") { await caseMetric(page); let n = await metrics(page); - if (n < 8) throw Error("missing comparison metrics"); - if ((await versionMetrics(page)) !== 3) - throw Error("missing version summary metrics"); - if ( - (await page - .locator(".version-summary-table tbody tr") - .count()) !== 3 - ) - throw Error("version summary rows"); + if (n !== 4) throw Error("missing grouped resource metrics"); let chart = page.locator(".summary-chart img"); if ( - (await chart.count()) !== (model.macos_resource ? 2 : 1) || + (await chart.count()) !== 1 || !(await chart.evaluateAll((imgs) => imgs.every((img) => img.complete && img.naturalWidth > 0), )) @@ -327,10 +289,10 @@ async function run() { await ready(page); await caseMetric(page); await page - .locator(".core-table [data-metric]") + .locator("[data-functional-final]") .first() .evaluate((el) => { - el.dataset.sort = "580"; + el.dataset.functionalFinal = "580"; el.textContent = "580/750"; }); let caseRejected = false; @@ -343,8 +305,8 @@ async function run() { await page.reload(); await ready(page); let baseline = await metrics(page); - if (baseline < 8) throw Error("metric coverage"); - let cell = page.locator(".winner[data-metric]").first(); + if (baseline !== 4) throw Error("metric coverage"); + let cell = page.locator(".winner[data-combined-metric]").first(); await cell.evaluate((el) => el.classList.remove("winner")); let wrongRejected = false; try { @@ -356,9 +318,12 @@ async function run() { await page.reload(); await ready(page); await page.evaluate(() => { - let old = document.querySelector(".winner[data-metric]"); - let other = [...document.querySelectorAll("[data-metric]")].find( - (x) => x !== old && x.dataset.metric === old.dataset.metric, + let old = document.querySelector(".winner[data-combined-metric]"); + let other = [...document.querySelectorAll("[data-combined-metric]")].find( + (x) => + x !== old && + x.dataset.combinedMetric === old.dataset.combinedMetric && + x.dataset.platform === old.dataset.platform, ); old.classList.remove("winner"); other.classList.add("winner"); @@ -372,12 +337,15 @@ async function run() { if (!shiftedRejected) throw Error("wrong-highlight negative control"); await page.reload(); await ready(page); - let tied = page.locator("[data-metric]").first(); + let tied = page.locator("[data-combined-metric]").first(); await tied.evaluate((el) => { - let other = [...document.querySelectorAll("[data-metric]")].find( - (x) => x !== el && x.dataset.metric === el.dataset.metric, + let other = [...document.querySelectorAll("[data-combined-metric]")].find( + (x) => + x !== el && + x.dataset.combinedMetric === el.dataset.combinedMetric && + x.dataset.platform === el.dataset.platform, ); - other.dataset.sort = el.dataset.sort; + other.dataset.value = el.dataset.value; }); let tieRejected = false; try { @@ -388,12 +356,12 @@ async function run() { if (!tieRejected) throw Error("tie-highlight negative control"); await page.reload(); await ready(page); - await versionMetrics(page); - let versionWinner = page.locator(".winner[data-version-metric]").first(); + await caseMetric(page); + let versionWinner = page.locator(".winner[data-functional-final]").first(); await versionWinner.evaluate((el) => el.classList.remove("winner")); let versionRejected = false; try { - await versionMetrics(page); + await caseMetric(page); } catch { versionRejected = true; } diff --git a/scripts/moli_report/verify.py b/scripts/moli_report/verify.py index 71353c16a..3ad5d2172 100644 --- a/scripts/moli_report/verify.py +++ b/scripts/moli_report/verify.py @@ -10,8 +10,12 @@ import shutil import statistics import subprocess +import sys import tempfile +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from plot_moli_version_resources import combine_comparisons, render_chart # noqa: E402 + parser = argparse.ArgumentParser() parser.add_argument( "--site", @@ -141,6 +145,20 @@ def validate(model, site, check_files=True): if not near(row["cpu_change_pct"], (row["cpu_ms"] / baseline["cpu_ms"] - 1) * 100): fail("version CPU change") functional_methods = model.get("functional_methods") or [] + combined = model.get("combined_comparison") + if combined != combine_comparisons( + functional_methods, comparison, model.get("macos_comparison") + ): + fail("combined chart registry, baseline or measurement mismatch") + if json.loads((site / "data/combined-comparison.json").read_text()) != combined: + fail("combined chart data target") + with tempfile.TemporaryDirectory() as directory: + for language in ("zh", "en"): + expected = pathlib.Path(directory) / f"{language}.svg" + render_chart(combined, expected, ("memory", "cpu"), language) + actual = site / f"assets/moli-all-success-resources-{language}.svg" + if not actual.is_file() or actual.read_bytes() != expected.read_bytes(): + fail("combined chart does not match measured registry") candidates = model.get("fixed_candidates") or {} expected_ids = ["114_off", "118_off", "118_on"] + list(candidates) if [row.get("id") for row in functional_methods] != expected_ids: @@ -701,6 +719,9 @@ def rejected(change): rejected(lambda m: m["task_cost"][0].update(off_duration_ms=0)) rejected(lambda m: m["version_comparison"]["configurations"][1].update(pss_change_pct=99)) rejected(lambda m: m["version_comparison"]["configurations"][2].update(success_rate_pct=0)) +rejected(lambda m: m["combined_comparison"].update(baseline="119_official_on")) +rejected(lambda m: m["combined_comparison"]["configurations"].reverse()) +rejected(lambda m: m["combined_comparison"]["configurations"][-1].update(cpu_change_pct=0)) rejected(lambda m: m["functional_contract_correction"].update(calls=17)) rejected(lambda m: m["functional_contract_correction"].update(success_rates_changed=True)) if model.get("fixed_candidates"): diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py index 5db4d161a..ca065823a 100644 --- a/scripts/plot_moli_version_resources.py +++ b/scripts/plot_moli_version_resources.py @@ -18,6 +18,38 @@ COLOR_RE = re.compile(r"#[0-9a-fA-F]{6}") +def combine_comparisons(methods: list[dict], historical: dict, macos: dict | None) -> dict: + """Keep registry order and baseline while separating unlike resource measurements.""" + sources = {row["id"]: (row, "Linux", "PSS") for row in historical["configurations"]} + sources.update( + {row["id"]: (row, "macOS", "RSS") for row in (macos or {}).get("configurations", [])} + ) + baseline = sources[historical["baseline"]][0] + rows = [] + for index, method in enumerate(methods): + source, platform, memory_kind = sources[method["id"]] + row = dict(source) + row.update( + label=method["label"], + label_en=method["label_en"], + passed_cases=method["final_passed_cases"], + success_rate_pct=method["final_passed_cases"] / source["total_cases"] * 100, + platform=platform, + memory_kind=memory_kind, + memory_mib=source[f"{memory_kind.lower()}_mib"], + memory_change_pct=source["pss_change_pct"] if platform == "Linux" else None, + cpu_change_pct=source["cpu_change_pct"] if platform == "Linux" else None, + color=COLORS[index % len(COLORS)], + ) + row["success_change_pp"] = row["success_rate_pct"] - baseline["success_rate_pct"] + rows.append(row) + return { + "baseline": historical["baseline"], + "configurations": rows, + "resource_population": historical["resource_population"], + } + + def _scale(value: float, lower: float, upper: float, start: float, end: float) -> float: if upper == lower: return (start + end) / 2 @@ -30,9 +62,9 @@ def render_chart( if ( not metrics or len(metrics) > 2 - or any(metric not in {"pss", "rss", "cpu"} for metric in metrics) + or any(metric not in {"pss", "rss", "memory", "cpu"} for metric in metrics) ): - raise ValueError("metrics must contain one or two of pss, rss and cpu") + raise ValueError("metrics must contain one or two of pss, rss, memory and cpu") if len(set(metrics)) != len(metrics): raise ValueError("metrics must not contain duplicates") if language not in {"zh", "en"}: @@ -48,6 +80,7 @@ def render_chart( "pss": {"pss_mib", "pss_change_pct"}, "rss": {"rss_mib", "rss_change_pct"}, "cpu": {"cpu_ms", "cpu_change_pct"}, + "memory": {"memory_mib", "memory_change_pct"}, } for metric in metrics: required_row_fields.update(metric_fields[metric]) @@ -68,6 +101,12 @@ def render_chart( for metric in metrics: numeric_fields.update(metric_fields[metric]) for field in sorted(numeric_fields): + if ( + row.get("platform") == "macOS" + and field.endswith("_change_pct") + and row[field] is None + ): + continue try: number = float(row[field]) except (TypeError, ValueError) as exc: @@ -110,6 +149,7 @@ def render_chart( "y": f"{total_cases} 题通过率(每题 3 次全部通过)", "pss": "峰值进程树 PSS 中位数(MiB)", "rss": "峰值进程树 RSS 中位数(MiB)", + "memory": "峰值内存中位数(MiB;Linux PSS / macOS RSS)", "cpu": "单次执行平均 CPU 时间(ms)", "off": "关闭", "on": "开启", @@ -125,17 +165,25 @@ def render_chart( "y": f"Success rate on {total_cases} cases (all 3 attempts pass)", "pss": "Median peak process-tree PSS (MiB)", "rss": "Median peak process-tree RSS (MiB)", + "memory": "Median peak memory (MiB; Linux PSS / macOS RSS)", "cpu": "Mean CPU time per execution (ms)", "off": "off", "on": "on", }, }[language] + if "memory" in metrics: + text["subtitle"] = ( + text["subtitle"] + .replace("越靠左资源消耗越低", "不同平台资源分别解释") + .replace("farther left is lower", "platform-specific resources") + ) width = 1420 if len(metrics) == 2 else 820 - height = 700 + 30 * len(rows) + mixed = any(row.get("platform") for row in rows) + height = 700 + 30 * len(rows) + (48 if mixed else 0) left, right, top, bottom = 105, 55, 145, 115 + 30 * len(rows) gap = 90 panel_width = (width - left - right - gap * (len(metrics) - 1)) / len(metrics) - chart_bottom = height - bottom + chart_bottom = height - bottom - (48 if mixed else 0) max_success_rate = max(float(row["success_rate_pct"]) for row in rows) y_max = max(20, math.ceil(max_success_rate / 20) * 20) described_metrics = { @@ -158,10 +206,10 @@ def render_chart( '', '', + ".grid{stroke:#dfe5eb;stroke-width:1}.axis{stroke:#8b98a6;stroke-width:1.2}" + ".label{font-size:17px}.tick{font-size:14px}" + ".point-label{font-size:15px;font-weight:650}.title{font-size:29px;font-weight:760}" + ".subtitle{font-size:16px}.legend{font-size:14px}", f'{html.escape(text["title"])}', f'{html.escape(text["subtitle"])}', ] @@ -182,12 +230,13 @@ def render_chart( "pss": (text["pss"], "pss_mib", "pss_change_pct", "MiB"), "rss": (text["rss"], "rss_mib", "rss_change_pct", "MiB"), "cpu": (text["cpu"], "cpu_ms", "cpu_change_pct", "ms"), + "memory": (text["memory"], "memory_mib", "memory_change_pct", "MiB"), } row_colors = { row["id"]: str(row.get("color") or COLORS[index % len(COLORS)]) for index, row in enumerate(rows) } - offsets = ((0, 0), (-18, -18), (18, 18), (-18, 18), (18, -18), (0, -24), (0, 24)) + offsets = ((0, 0), (-24, -24), (24, 24), (-24, 24), (24, -24), (0, -32), (0, 32)) for panel, metric in enumerate(metrics): title, key, change_key, unit = specs[metric] x0 = left + panel * (panel_width + gap) @@ -217,6 +266,7 @@ def render_chart( f'text-anchor="middle">{value:.1f}' ) plotted: list[tuple[float, float]] = [] + markers = [] for row_index, row in enumerate(rows, 1): exact_x = _scale(float(row[key]), low, high, x0, x1) exact_y = _scale(float(row["success_rate_pct"]), 0, y_max, chart_bottom, top) @@ -239,14 +289,18 @@ def render_chart( parts.append( f'' ) - parts.append( - f'' + shape = ( + f'') + markers.append( f'{number}' ) + parts.extend(markers) legend_y = chart_bottom + 82 for index, row in enumerate(rows): color = row_colors[row["id"]] @@ -258,9 +312,16 @@ def render_chart( f"{int(float(row['passed_cases']))}/{total_cases} " f"({float(row['success_rate_pct']):.1f}%)" ] + if mixed: + fields.append( + f"{row['success_change_pp']:+.2f} " + ("百分点" if language == "zh" else "pp") + ) for metric in metrics: _, key, change_key, unit = specs[metric] - fields.append(f"{float(row[key]):.2f} {unit} ({float(row[change_key]):+.2f}%)") + change = row[change_key] + delta = f"{float(change):+.2f}%" if change is not None else "—" + prefix = f"{row['platform']} {row['memory_kind']} " if metric == "memory" else "" + fields.append(f"{prefix}{float(row[key]):.2f} {unit} ({delta})") y = legend_y + index * 30 parts.append(f'') parts.append( @@ -269,8 +330,27 @@ def render_chart( ) parts.append( f'' - f'{html.escape(row_label + ": " + " · ".join(fields))}' + f"{html.escape(row_label + ': ' + ' · '.join(fields))}" ) + if mixed: + notes = ( + [ + "基线:1.1.4 关闭 layout;成功率变化用百分点表示。圆形:Linux;菱形:macOS。", + "PSS 与 RSS、不同平台 CPU 不直接比较;跨平台资源变化不计算(—)。", + ] + if language == "zh" + else [ + "Baseline: 1.1.4 layout off; success changes in pp. " + "Circles: Linux; diamonds: macOS.", + "PSS vs. RSS and cross-platform CPU are not directly comparable; " + "resource changes: —.", + ] + ) + for i, note in enumerate(notes): + parts.append( + f'' + f"{html.escape(note)}" + ) parts.append("") output.parent.mkdir(parents=True, exist_ok=True) output.write_text("\n".join(parts) + "\n") diff --git a/tests/moli_report_render_contract.cjs b/tests/moli_report_render_contract.cjs index 8282e9b92..bb78b60cf 100644 --- a/tests/moli_report_render_contract.cjs +++ b/tests/moli_report_render_contract.cjs @@ -139,11 +139,27 @@ if (site) { fs.readFileSync(path.join(site, "data/model.json"), "utf8"), ); for (let lang of ["zh", "en"]) { + for (let page of ["home()", "guidePage()", "methodPage()", "reviewPage()"]) { + const html = render(measured, lang, page); + const prose = html.replace(/<[^>]+>/g, " "); + assert.ok(!/历史|补测|Historical|historical|Corrected-contract/.test(prose), page); + assert.ok(!html.includes("undefined")); + } if (measured.macos_resource) { for (let page of ["home()", "guidePage()"]) { const html = render(measured, lang, page); resourceHighlights(html); - assert.ok(html.includes("moli-macos-success-resources-")); + assert.ok(html.includes("moli-all-success-resources-")); + assert.equal((html.match(/data-combined-chart/g) || []).length, 1); + assert.equal( + (html.match(/data-functional-method=/g) || []).length, + measured.functional_methods.length, + ); + if (page === "home()") { + assert.ok(!html.includes("version-summary-table")); + assert.ok(!html.includes("core-table")); + assert.ok(html.includes('class="resource-disclosure"')); + } } } for (let relation of render(measured, lang, "fixedRelations()")) diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index a557e4fd4..8c02892b8 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -1,4 +1,5 @@ import importlib.util +import math import re import tempfile import unittest @@ -13,6 +14,51 @@ class MoliVersionResourceChartTests(unittest.TestCase): + def test_near_identical_methods_keep_both_numbered_markers_visible(self): + self.data["configurations"][1]["pss_mib"] = self.data["configurations"][0]["pss_mib"] + self.data["configurations"][1]["success_rate_pct"] = 0.01 + svg = self.render(("pss",)) + points = re.findall(r' Date: Mon, 21 Sep 2026 11:23:56 +0800 Subject: [PATCH 22/29] Bind the published six-configuration report and cover single-metric charts --- evaluation/moli/current-report.json | 2 +- research/report-changes.json | 51 +++++++++++++++++++++++ tests/test_moli_version_resource_chart.py | 12 ++++++ 3 files changed, 64 insertions(+), 1 deletion(-) diff --git a/evaluation/moli/current-report.json b/evaluation/moli/current-report.json index 99aa19a85..4f7c3d381 100644 --- a/evaluation/moli/current-report.json +++ b/evaluation/moli/current-report.json @@ -28,7 +28,7 @@ "base_url": "https://artifact-site.lexmount.cn", "slug": "gdwtSGOel0va", "kind": "folder", - "expected_version": "ver_4d7cfe448a8e4ac98287607dc6a2266a", + "expected_version": "ver_faf65d03d9394f83be59555df833bd65", "share_url": "https://artifact-site.lexmount.cn/v/w1vgSkFJjvmCL6kPaHmj4K8sUZ8iTI8t" } } diff --git a/research/report-changes.json b/research/report-changes.json index c0763b3c9..5ce7e717c 100644 --- a/research/report-changes.json +++ b/research/report-changes.json @@ -1252,6 +1252,57 @@ } ], "releases": [ + { + "id": "2026-09-21-moli-six-configuration-report", + "date": "2026-09-21", + "date_timezone": "Asia/Shanghai", + "comparison_kinds": [ + "moli_historical_failure_retest", + "moli_process_tree_resource_profile" + ], + "title": "统一六配置图表与正式报告结构", + "summary": "六种固定配置按同一顺序呈现在总表和一张汇总图中,以 1.1.4 关闭布局为成功率基线。首页保留核心结果和可展开的资源明细;方法、解读与证据页面统一描述完整评测。通过率与资源测量值不变。", + "publication": { + "service": "Artifact Site", + "site_slug": "gdwtSGOel0va", + "share_url": "https://artifact-site.lexmount.cn/v/w1vgSkFJjvmCL6kPaHmj4K8sUZ8iTI8t", + "version": "ver_faf65d03d9394f83be59555df833bd65" + }, + "changes": [ + [ + "六配置图表", + "分开的版本图与六配置总表不对应。", + "图表使用同一配置注册表、顺序和编号,统一显示成功率、内存与 CPU;重叠标记用引线区分。", + "成功率变化用百分点;Linux PSS 与 macOS RSS 分别标注,跨平台资源变化不计算。" + ], + [ + "报告结构", + "首页存在重复汇总,解释分散在版本分块中。", + "总览、方法、解读和证据页面按读者问题组织;移除过程性叙述,资源明细可展开。", + "结果和分母不变。1.1.4 的直接验证与继承范围保留在方法和覆盖说明中。" + ] + ], + "i18n": { + "en": { + "title": "Unify the six-configuration chart and reader-facing report", + "summary": "The same six fixed configurations appear in registry order in one summary table and chart, using 1.1.4 layout off as the success baseline. The home page keeps core results and expandable resources; method, interpretation and evidence pages describe the complete evaluation. Success and resource measurements are unchanged.", + "changes": [ + [ + "Six-configuration chart", + "Separate version charts did not align with the six-method table.", + "Use the same registry, order and numbering for success, memory and CPU; leader lines separate overlapping markers.", + "Success changes use percentage points. Linux PSS and macOS RSS stay explicitly labeled; cross-platform resource changes are not calculated." + ], + [ + "Report structure", + "The home page repeated summaries and split interpretation into version additions.", + "Organize overview, method, interpretation and evidence by reader questions, remove execution narration and make resources expandable.", + "Results and denominators are unchanged. The method and coverage sections retain 1.1.4 direct and inherited evidence scope." + ] + ] + } + } + }, { "id": "2026-09-21-moli-119-fixed-layout-comparison", "date_timezone": "Asia/Shanghai", diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index 8c02892b8..0dc8e34f1 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -58,6 +58,13 @@ def test_combined_chart_keeps_registry_order_and_baseline_without_cross_platform self.assertIn("+96.77", text) self.assertIn("(—)", text) self.assertEqual(text.count(' Date: Mon, 21 Sep 2026 11:31:33 +0800 Subject: [PATCH 23/29] Preserve report language during hosted hash navigation --- scripts/moli_report/app.js | 20 ++++++++++++++++++++ scripts/moli_report/ui_check.js | 19 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/scripts/moli_report/app.js b/scripts/moli_report/app.js index 9a070da01..2424603c3 100644 --- a/scripts/moli_report/app.js +++ b/scripts/moli_report/app.js @@ -1619,4 +1619,24 @@ document.getElementById("menu-toggle").addEventListener("click", (e) => { e.currentTarget.setAttribute("aria-expanded", String(open)); }); window.addEventListener("hashchange", render); +// Preview hosts may inject a base URL pointing at the Chinese entry. +// Keep report routes in the current document, including its language. +document.addEventListener("click", (event) => { + const anchor = event.target.closest("a[href]"); + const href = anchor?.getAttribute("href"); + if ( + !href?.startsWith("#page=") || + event.defaultPrevented || + event.button !== 0 || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey || + anchor.target || + anchor.hasAttribute("download") + ) + return; + event.preventDefault(); + window.location.hash = href; +}); render(); diff --git a/scripts/moli_report/ui_check.js b/scripts/moli_report/ui_check.js index 24edb565d..96ecfdc23 100644 --- a/scripts/moli_report/ui_check.js +++ b/scripts/moli_report/ui_check.js @@ -285,6 +285,25 @@ async function run() { await page.close(); } let page = await browser.newPage(); + // Tokenized preview hosts inject a root base URL even on English entries. + for (const entry of ["/en.html", "/en/index.html"]) { + await page.goto(origin + entry + "#page=home"); + await ready(page); + await page.evaluate((url) => { + const base = document.createElement("base"); + base.href = url + "/"; + document.head.prepend(base); + }, origin); + for (const route of ["guide", "method", "home"]) { + await page.locator(`nav a[href="#page=${route}"]`).click(); + await page.locator(`main[data-route="${route}"] h1`).waitFor(); + if ( + (await page.locator("html").getAttribute("lang")) !== "en" || + new URL(page.url()).pathname !== entry + ) + throw Error("preview navigation changed the language entry"); + } + } await page.goto(origin + "/#page=home"); await ready(page); await caseMetric(page); From 074fe6ad2abf936ae8605a96df4da55e671689a1 Mon Sep 17 00:00:00 2001 From: kevin Date: Mon, 21 Sep 2026 11:43:30 +0800 Subject: [PATCH 24/29] Bind the verified hosted-navigation report release --- evaluation/moli/current-report.json | 2 +- research/report-changes.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/evaluation/moli/current-report.json b/evaluation/moli/current-report.json index 4f7c3d381..4ae2b601c 100644 --- a/evaluation/moli/current-report.json +++ b/evaluation/moli/current-report.json @@ -28,7 +28,7 @@ "base_url": "https://artifact-site.lexmount.cn", "slug": "gdwtSGOel0va", "kind": "folder", - "expected_version": "ver_faf65d03d9394f83be59555df833bd65", + "expected_version": "ver_297e78e469d84077a0e95c813b34df91", "share_url": "https://artifact-site.lexmount.cn/v/w1vgSkFJjvmCL6kPaHmj4K8sUZ8iTI8t" } } diff --git a/research/report-changes.json b/research/report-changes.json index 5ce7e717c..906e77f7d 100644 --- a/research/report-changes.json +++ b/research/report-changes.json @@ -1266,7 +1266,7 @@ "service": "Artifact Site", "site_slug": "gdwtSGOel0va", "share_url": "https://artifact-site.lexmount.cn/v/w1vgSkFJjvmCL6kPaHmj4K8sUZ8iTI8t", - "version": "ver_faf65d03d9394f83be59555df833bd65" + "version": "ver_297e78e469d84077a0e95c813b34df91" }, "changes": [ [ From b103a638501b20153dfd59cf51cb5f5eccbad2c7 Mon Sep 17 00:00:00 2001 From: kevin Date: Mon, 21 Sep 2026 13:53:31 +0800 Subject: [PATCH 25/29] Calibrate Moli release resources and publish seven configurations --- evaluation/moli/current-report.json | 38 ++- research/report-changes.json | 64 +++++ scripts/moli_report/BUILD.md | 10 +- scripts/moli_report/app.js | 99 ++++--- scripts/moli_report/build.py | 62 ++++- scripts/moli_report/resource_evidence.py | 192 ++++++++++++++ scripts/moli_report/run_resource_matrix.py | 294 +++++++++++++++++++++ scripts/moli_report/ui_check.js | 44 ++- scripts/moli_report/verify.py | 75 +++++- scripts/plot_moli_version_resources.py | 34 ++- tests/moli_report_render_contract.cjs | 64 ++++- tests/test_moli_resource_evidence.py | 163 ++++++++++++ tests/test_moli_resource_matrix.py | 134 ++++++++++ tests/test_moli_version_resource_chart.py | 22 +- 14 files changed, 1211 insertions(+), 84 deletions(-) create mode 100644 scripts/moli_report/resource_evidence.py create mode 100644 scripts/moli_report/run_resource_matrix.py create mode 100644 tests/test_moli_resource_evidence.py create mode 100644 tests/test_moli_resource_matrix.py diff --git a/evaluation/moli/current-report.json b/evaluation/moli/current-report.json index 4ae2b601c..203e09713 100644 --- a/evaluation/moli/current-report.json +++ b/evaluation/moli/current-report.json @@ -15,20 +15,48 @@ "114_off", "118_off", "118_on", + "119_official_off", + "119_official_on", "119_off", - "119_on", - "119_official_on" + "119_on" ], "macos_method_ids": [ + "119_official_off", + "119_official_on", "119_off", - "119_on", - "119_official_on" + "119_on" ], "publication": { "base_url": "https://artifact-site.lexmount.cn", "slug": "gdwtSGOel0va", "kind": "folder", - "expected_version": "ver_297e78e469d84077a0e95c813b34df91", + "expected_version": "ver_2f4844c0550241b78f7c80d8614bca87", "share_url": "https://artifact-site.lexmount.cn/v/w1vgSkFJjvmCL6kPaHmj4K8sUZ8iTI8t" + }, + "resource_builds": { + "119_official_off": { + "sha256": "79699e50476118a7a5d1a36775f52d4106801fd5bc803727fd317501faa840cd", + "source_commit": "47512623315aa9b57edc2ef721a033b6b8d91063", + "profile": "official_release", + "target": "aarch64-apple-darwin" + }, + "119_official_on": { + "sha256": "79699e50476118a7a5d1a36775f52d4106801fd5bc803727fd317501faa840cd", + "source_commit": "47512623315aa9b57edc2ef721a033b6b8d91063", + "profile": "official_release", + "target": "aarch64-apple-darwin" + }, + "119_off": { + "sha256": "9b3f3dd6e550a71cddfb93ec3490317b0dfa5db407ebc2d5fb0a9748f58dd226", + "source_commit": "f315ff26ed6222603d382b8f7a4648157da3ebf9", + "profile": "release", + "target": "aarch64-apple-darwin" + }, + "119_on": { + "sha256": "9b3f3dd6e550a71cddfb93ec3490317b0dfa5db407ebc2d5fb0a9748f58dd226", + "source_commit": "f315ff26ed6222603d382b8f7a4648157da3ebf9", + "profile": "release", + "target": "aarch64-apple-darwin" + } } } diff --git a/research/report-changes.json b/research/report-changes.json index 906e77f7d..97cfe116a 100644 --- a/research/report-changes.json +++ b/research/report-changes.json @@ -1252,6 +1252,69 @@ } ], "releases": [ + { + "id": "2026-09-21-moli-seven-method-release-resource-calibration", + "date": "2026-09-21", + "date_timezone": "Asia/Shanghai", + "comparison_kinds": [ + "moli_historical_failure_retest", + "moli_process_tree_resource_profile" + ], + "publication": { + "service": "Artifact Site", + "site_slug": "gdwtSGOel0va", + "share_url": "https://artifact-site.lexmount.cn/v/w1vgSkFJjvmCL6kPaHmj4K8sUZ8iTI8t", + "version": "ver_2f4844c0550241b78f7c80d8614bca87" + }, + "title": "发布七种 Moli 配置与 Release 资源对照", + "summary": "七种配置统一展示 372 题成功率。1.1.9 与修复版的四组 Release 资源数据覆盖每组 557 题 × 5 次;修复版相对同布局 1.1.9 的峰值 RSS 中位数变化为 +0.54% / +2.69%,平均 CPU 时间变化为 −1.62% / −0.82%。", + "changes": [ + [ + "配置与成绩", + "比较需要统一配置顺序,并区分功能构建和资源构建。", + "表格与图按版本及布局排序,共七种配置;保留已有功能结果,增加已经完成的 1.1.9 关闭布局结果 1/372。", + "修复版准确率对应 87c87e95 构建,资源对应 f315ff26 Release;不将已有准确率归为新构建的实测。" + ], + [ + "资源口径", + "Debug 与 Release、Linux PSS 与 macOS RSS 不可混用为直接涨幅。", + "四组 Release 在同一主机按任务轮换顺序、串行调用,每组 2,785 次;全量表使用 557 题,汇总图使用预先冻结的 209 题。", + "资源百分比以相同布局的 1.1.9 Release 为参照;PSS 与 RSS 分开标注,不计算跨平台变化。" + ], + [ + "公开证据", + "资源汇总需要能够回溯并独立重算。", + "公开完整调用顺序、逐次资源值、二进制哈希、冻结协议和实际执行脚本;缺失、部分或不一致的资源证据阻止发布。", + "站点保留原链接;成功与失败详情均可打开原始证据,并通过键盘关闭后返回。" + ] + ], + "i18n": { + "en": { + "title": "Publish seven Moli configurations and Release resource comparisons", + "summary": "Seven configurations share the 372-task success comparison. Four Release resource configurations cover 557 tasks × 5 calls each. Relative to matching-layout Moli 1.1.9, the patched build changes median peak RSS by +0.54% / +2.69% and mean CPU time by −1.62% / −0.82%.", + "changes": [ + [ + "Configurations and scores", + "Comparisons require consistent ordering and distinct functional and resource build identities.", + "Tables and charts list seven configurations by version and layout. Existing functional results are retained, with the completed 1.1.9 layout-off result of 1/372 added.", + "Patched success results belong to build 87c87e95; resources belong to f315ff26 Release. Existing accuracy is not attributed to a new-build measurement." + ], + [ + "Resource scope", + "Debug and Release builds, or Linux PSS and macOS RSS, cannot supply directly comparable growth percentages.", + "Four Release configurations run serially on one host with task-level rotating order, 2,785 calls each. Full tables cover 557 tasks; the summary chart uses the 209 tasks frozen before execution.", + "Resource percentages use matching-layout Moli 1.1.9 Release as the reference. PSS and RSS are labeled separately without cross-platform percentage changes." + ], + [ + "Public evidence", + "Resource aggregates must be traceable and independently reproducible.", + "Publish complete call order, per-call measurements, binary hashes, frozen protocol and the exact executed script. Missing, partial or inconsistent resource evidence blocks release.", + "The share link is unchanged. Success and failure details expose raw evidence with keyboard dismissal and return navigation." + ] + ] + } + } + }, { "id": "2026-09-21-moli-six-configuration-report", "date": "2026-09-21", @@ -1368,6 +1431,7 @@ }, { "id": "2026-09-20-moli-version-layout-resource-summary", + "date_timezone": "Asia/Shanghai", "publication": { "service": "Artifact Site", "site_slug": "gdwtSGOel0va", diff --git a/scripts/moli_report/BUILD.md b/scripts/moli_report/BUILD.md index d314e6765..d8401b350 100644 --- a/scripts/moli_report/BUILD.md +++ b/scripts/moli_report/BUILD.md @@ -13,18 +13,24 @@ uv run --frozen python scripts/moli_report/build.py \ --output /tmp/moli-report-release \ --fixed-summary 119_off /path/to/patched-off-summary.json \ --fixed-summary 119_on /path/to/patched-on-summary.json \ + --fixed-summary 119_official_off /path/to/official-off-summary.json \ --fixed-summary 119_official_on /path/to/official-on-summary.json \ --macos-resource-summary /path/to/patched-resource-summary.json \ - --official-resource-summary /path/to/official-resource-summary.json + --official-resource-summary /path/to/official-resource-summary.json \ + --resource-matrix /path/to/certified-resource-matrix uv run --frozen python scripts/moli_report/verify.py --site /tmp/moli-report-release --release ``` Choose a new output directory for each build; the builder does not delete existing output. `--vendor-dir` selects the retained Mermaid distribution and license. Their hashes are checked before copying. The default location is the original report asset directory under the data home; no vendored executable or measured output is committed here. +The four macOS resource configurations are release builds bound by `resource_builds` in `evaluation/moli/current-report.json`. Their functional evidence binds its own binary identity: the patched functional results and resource measurements use different builds. Do not relabel retained functional outcomes as a new build's measured accuracy. + +`run_resource_matrix.py --protocol /path/to/frozen-protocol.json --output /path/to/new-evidence-directory` executes the unchanged Lexbench driver and sampler. Freeze the 557 task definitions, fixtures, runner files, four binary hashes, five attempts, sampling interval and selected round before execution. It grants one call globally at a time, rotates method order for each task attempt, and retains the complete physical-call sequence. Summarize each pair of layouts with the Lexbench resource summarizer. The report builder requires the protocol, physical calls and completion receipt, checks all 11,140 calls against saved result rows, and rejects partial or unrelated summaries. Keep these files outside Git. + The static verifier checks score/evidence bindings, resource populations and percentages, fixed-case log links, charts, bilingual rendering, unique resource extrema and negative controls. It invokes the same JavaScript rendering checks used by `tests/test_moli_report_render_contract.py`. For full release verification, serve the build with a static HTTP server and run `ui_check.js` with `MOLI_REPORT_SITE`, `MOLI_REPORT_ORIGIN`, and `MOLI_REPORT_SHOTS`. `LEXBENCH_NODE_MODULES` selects the provisioned Playwright installation. The browser check covers route classes, themes, widths, evidence dialogs and keyboard navigation. Run it after resource measurement to avoid contaminating the measurement host. Publish only after the complete requested method matrix and release checks pass, using the existing bound Artifact Site target and its freshly read remote version. Preserve binary identity, raw trials and previous report versions. -Package the validated tree with `uv run --frozen python scripts/moli_report/pack.py --source /tmp/moli-report-release --output /tmp/moli-report-package`. The packer retains both English entry paths and checks bytes through the bundle manifest; it refuses symlinks, hidden paths, and existing destinations. Run the browser release check against this packaged directory before uploading. +Package the validated tree with `uv run --frozen python scripts/moli_report/pack.py --source /tmp/moli-report-release --output /tmp/moli-report-package`. The packer retains both English entry paths and checks bytes through the bundle manifest; it refuses symlinks, hidden paths, and existing destinations. Run the browser release check against this packaged directory before uploading: serve the package at `MOLI_REPORT_ORIGIN`, while `MOLI_REPORT_SITE` points to the validated unpacked tree that supplies the reference model. The browser checks include the complete resource matrix and frozen measurement-script evidence in both languages. diff --git a/scripts/moli_report/app.js b/scripts/moli_report/app.js index 2424603c3..3b60a03c3 100644 --- a/scripts/moli_report/app.js +++ b/scripts/moli_report/app.js @@ -68,7 +68,7 @@ const D = { observed: "观测到的采样最大值", filterFail: "涉及失败或变化", methodIntro: - "题目与验收预先冻结,两种浏览器配置只相差是否启用 --layout。默认模式使用低成本模拟几何;--layout 启用按需真实布局,并非持续绘制。可选图片等资源抓取由另一开关控制,未改变。1.1.9 的每个固定配置各测一轮资源,557 题各五次;372 题成功率另测,每题三次。", + "题目与验收预先冻结,同一构建的两种布局配置只相差是否启用 --layout。默认模式使用低成本模拟几何;--layout 启用按需真实布局,并非持续绘制。可选图片等资源抓取由另一开关控制,未改变。1.1.9 的每个固定配置各测一轮资源,557 题各五次;372 题成功率另测,每题三次。", analysisIntro: "按相同任务与执行次数配对。成功变化和资源代价分开解读。", guideIntro: "从 Agent 使用者角度,先看能否完成,再看失败等待和完成任务的资源。", @@ -143,7 +143,7 @@ const D = { observed: "Observed sampled maximum", filterFail: "Failures or changes", methodIntro: - "Task contracts were frozen in advance. The browser configurations differ only in Moli's --layout flag. The default uses low-cost mock geometry; --layout enables real geometry on demand rather than continuous painting. Optional image and media fetching is a separate control and was unchanged. Each fixed 1.1.9 configuration has one 557-task resource run with five calls per task. Success is measured separately on 372 cases with three calls per task.", + "Task contracts were frozen in advance. Within each build, the two layout configurations differ only in Moli's --layout flag. The default uses low-cost mock geometry; --layout enables real geometry on demand rather than continuous painting. Optional image and media fetching is a separate control and was unchanged. Each fixed 1.1.9 configuration has one 557-task resource run with five calls per task. Success is measured separately on 372 cases with three calls per task.", analysisIntro: "Pair the same task and attempt. Outcome changes and resource costs are interpreted separately.", guideIntro: @@ -246,8 +246,8 @@ const datasetIntro = () => : `All 372 cases selected from Moli 0.1.1 failures are included across 15 driver types, without selection based on current outcomes.`; const reproduceIntro = () => zh - ? `所选用例测试和独立的 557 题资源实验均为诊断实验,不计入完整 1,928 题正式分数。1.1.8 直接覆盖 372 题;1.1.4 使用唯一差异候选题验证。三种固定配置使用 Moli 1.1.4 / 1.1.8 Linux aarch64 发行版;1.1.9 修复版使用固定的 macOS arm64 debug 二进制,官方版使用发布资产;每个版本的功能与资源实验绑定同一 SHA-256。` - : `The selected-case evaluation and separate 557-task resource experiment are diagnostic and excluded from the formal 1,928-case score. Moli 1.1.8 directly covers all 372 cases; Moli 1.1.4 uses the sole differential candidate. The three fixed configurations use Moli 1.1.4 / 1.1.8 Linux aarch64 releases. Patched Moli 1.1.9 uses the frozen macOS arm64 debug binary; official 1.1.9 uses the release asset. Functional and resource runs are bound to the same binary hash for each build.`; + ? `所选用例测试和独立的 557 题资源实验均为诊断实验,不计入完整 1,928 题正式分数。1.1.8 直接覆盖 372 题;1.1.4 使用唯一差异候选题验证。三种固定配置使用 Moli 1.1.4 / 1.1.8 Linux aarch64 发行版;1.1.9 的资源实验均使用 macOS arm64 release 构建。修复版成功率沿用 87c87e95 构建,资源使用 f315ff26 release;两类实验分别绑定二进制 SHA-256。` + : `The selected-case evaluation and separate 557-task resource experiment are diagnostic and excluded from the formal 1,928-case score. Moli 1.1.8 directly covers all 372 cases; Moli 1.1.4 uses the sole differential candidate. The three fixed configurations use Moli 1.1.4 / 1.1.8 Linux aarch64 releases. All 1.1.9 resource configurations use macOS arm64 release builds. Patched functional outcomes retain build 87c87e95; resources use release build f315ff26. The two experiments bind their binary hashes separately.`; const ms = (v) => v === null || v === undefined ? "—" @@ -349,27 +349,24 @@ function functionalMethodSummary() { } function combinedSummaryChart() { const chart = `moli-all-success-resources-${zh ? "zh" : "en"}.svg`; - return `
${esc(zh ?
${esc(zh ? "成功率:372 个所选用例,每题 3 次全部通过;资源:独立的 557 题 × 5 次实验,图中使用预先冻结的 209 题、1,045 次样本。成功率变化以 1.1.4 为基线;内存和 CPU 仅在同一平台内计算相对基线的变化。" : "Success: 372 selected cases, all three attempts must pass. Resources: a separate 557-task × 5-call experiment; the plot uses the pre-frozen 209-task / 1,045-call sample. Success changes use 1.1.4 as baseline; memory and CPU changes are calculated only within the baseline platform.")}
`; + return `
${esc(zh ? `${M.functional_methods.length} 种固定配置的成功率与资源,顺序与总表一致,以 1.1.4 关闭布局为基线` : `${M.functional_methods.length} fixed configurations, aligned with the summary table; baseline: 1.1.4 layout off`)}
${esc(zh ? "成功率:372 个所选用例,每题 3 次全部通过;资源:独立的 557 题 × 5 次实验,图中使用预先冻结的 209 题、1,045 次样本。成功率变化以 1.1.4 为基线;内存和 CPU 仅在同一平台内计算相对基线的变化。" : "Success: 372 selected cases, all three attempts must pass. Resources: a separate 557-task × 5-call experiment; the plot uses the pre-frozen 209-task / 1,045-call sample. Success changes use 1.1.4 as baseline; memory and CPU changes are calculated only within the baseline platform.")}
`; } function macosResourceMethods() { let result = []; - for (let [key, layouts] of [ - ["macos_resource", ["off", "on"]], - ["official_resource", ["on"]], - ]) { + for (let method of M.functional_methods) { + if (!method.id.startsWith("119_")) continue; + const key = method.id.startsWith("119_official_") + ? "official_resource" + : "macos_resource"; + const layout = method.policy === "fixed_off" ? "off" : "on"; let resource = M[key]; - if (!resource) continue; - for (let layout of layouts) { - let id = - key === "official_resource" ? "119_official_on" : `119_${layout}`, - method = M.functional_methods.find((row) => row.id === id); - result.push({ - id, - label: zh ? method.label : method.label_en, - config: resource.summary.configurations[layout], - resource, - }); - } + if (!resource?.summary.configurations[layout]) continue; + result.push({ + id: method.id, + label: zh ? method.label : method.label_en, + config: resource.summary.configurations[layout], + resource, + }); } return result; } @@ -411,8 +408,13 @@ function candidateResourceSection() { return winners.length === 1 ? winners[0].label : zh ? "并列" : "Tie"; }; let rows = methods.map((item) => { + const reference = + methods.find( + (x) => + x.id === `119_official_${item.id.endsWith("_off") ? "off" : "on"}`, + ) || baseline; let m = item.config.metrics[scope], - b = baseline.config.metrics[scope]; + b = reference.config.metrics[scope]; return `${esc(item.label)}${fmt(calls)}${specs.map(([metric, stat, label, unit]) => `${fmt(m[metric][stat], 2)} ${unit}`).join("")}${signed((m.rss_peak_mib.p50 / b.rss_peak_mib.p50 - 1) * 100, 2)}${signed((m.cpu_time_ms.mean / b.cpu_time_ms.mean - 1) * 100, 2)}`; }); return ( @@ -430,21 +432,30 @@ function candidateResourceSection() { ) ); }); + const referenceLabel = methods.some((x) => x.id === "119_official_off") + ? zh + ? "相同 layout 设置的 Moli 1.1.9" + : "Moli 1.1.9 with the same layout setting" + : baseline.label; let intro = zh - ? `资源实验与 372 题成功率测试分开:每个配置固定 layout,557 题各执行 5 次。P50 是中位数,P95 是第 95 百分位;每组统计包含同一批成功与失败调用。变化基准:${baseline.label}。macOS 测量进程树 RSS;Linux PSS 另表展示。` - : `Resources are measured separately from success on 372 cases: each configuration fixes layout and runs 557 tasks five times. P50 is the median and P95 the 95th percentile; every metric in a scope includes the same passing and failing calls. Change baseline: ${baseline.label}. macOS measures process-tree RSS; Linux PSS is shown separately.`; + ? `资源实验与 372 题成功率测试分开:每个配置固定 layout,557 题各执行 5 次。P50 是中位数,P95 是第 95 百分位;每组统计包含同一批成功与失败调用。变化基准:${referenceLabel}。macOS 测量进程树 RSS;Linux PSS 另表展示。` + : `Resources are measured separately from success on 372 cases: each configuration fixes layout and runs 557 tasks five times. P50 is the median and P95 the 95th percentile; every metric in a scope includes the same passing and failing calls. Change baseline: ${referenceLabel}. macOS measures process-tree RSS; Linux PSS is shown separately.`; let evidence = methods .filter((x, i, a) => a.findIndex((y) => y.resource === x.resource) === i) .map( (x) => - ``, + ``, ) .join(" "); + if (M.resource_matrix) { + const item = M.resource_matrix.evidence; + evidence += ` `; + } return section( zh ? "Moli 1.1.9 资源统计" : "Moli 1.1.9 resource statistics", intro, tables.join("") + - `

${esc(zh ? "修复版使用 debug 构建,官方版使用发布资产。两者资源差异同时包含代码与构建配置差异。CPU 指进程树用户态与内核态时间之和。" : "The patched binary is a debug build; the official build uses the release asset. Their resource differences include both code and build configuration. CPU is the sum of process-tree user and system time.")}

${evidence}
`, + `

${esc(zh ? "四组均使用 release 构建,共享同一主机,各自保留独立浏览器进程和采样。任务调用按配置轮换、串行执行,只统计当前配置的进程树。CPU 为用户态与内核态时间之和。" : "All four release configurations share one host and retain separate browser processes and samplers. Task calls run serially in rotating order; each measurement covers only its own process tree. CPU is user plus system time.")}

${evidence}
`, ); } function resourceGroups() { @@ -606,7 +617,7 @@ function home() { section( zh ? "如何查看结果" : "Explore the results", "", - `

${esc(zh ? "修复版为 debug 构建,官方版为发布资产。macOS 与 Linux 的资源数值分别解释,不能把跨平台差异归因于代码修复。" : "The patched binary is a debug build; the official binary is a release asset. Interpret macOS and Linux resources separately; cross-platform differences cannot be attributed to the code changes.")}

${esc(zh ? "比较新增通过与仍然失败的用例" : "Compare gained passes and remaining failures")} · ${esc(T.nav.guide)} · ${esc(T.nav.reproduce)}`, + `

${esc(zh ? "资源均为 release 构建;macOS RSS 与 Linux PSS 分开比较。修复版成功率来自 87c87e95,资源来自 f315ff26,构建身份见评测方法。" : "Resources use release builds; macOS RSS and Linux PSS are compared separately. Patched success uses 87c87e95 and resources use f315ff26; see the method page for build identities.")}

${esc(zh ? "比较新增通过与仍然失败的用例" : "Compare gained passes and remaining failures")} · ${esc(T.nav.guide)} · ${esc(T.nav.reproduce)}`, ) ); } @@ -954,13 +965,13 @@ B --> C["${zh ? "功能:372 题,每题 3 次" : "Functional: 372 cases, thre B --> D["${zh ? "资源:557 题,每题 5 次" : "Resources: 557 tasks, five calls each"}"] C --> E["${zh ? "三次全部通过才算通过" : "A case passes only when all three attempts pass"}"] D --> F["${zh ? "全部调用统计与固定 209 题图表样本" : "All-call statistics and fixed 209-task chart sample"}"] -E --> G["${zh ? "六配置总表与总图" : "Six-configuration table and chart"}"] +E --> G["${zh ? "配置总表与总图" : "Configuration table and chart"}"] F --> G`, ) + section( zh ? "功能评分与基线" : "Functional scoring and baseline", "", - `

${esc(zh ? "六种配置共用 372 题分母。每题三次执行全部通过运行与验收检查,才记为一个通过用例。1.1.8 的两种布局、修复版 1.1.9 的两种布局和官方 1.1.9 开启布局均覆盖全部 372 题。" : "All six configurations use the same 372-case denominator. A case passes only when execution and acceptance checks pass in all three attempts. Both 1.1.8 layouts, both patched 1.1.9 layouts and official 1.1.9 layout on directly cover all 372 cases.")}

${esc(zh ? "1.1.4 关闭布局为基线:对 1.1.8 关闭布局唯一通过的候选题实测三次,均失败;其余 371 题沿用共同失败关系。因此表中的 0/372 包含 1 题直接验证和 371 题继承结果,并非对 1.1.4 的完整重测。基线通过率为 0%,通过率变化用百分点表示。" : "Layout-off 1.1.4 is the baseline: the sole candidate passed by layout-off 1.1.8 failed all three direct checks; the other 371 retain the shared-failure relation. Its 0/372 consists of one directly checked case and 371 inherited outcomes, not a complete 1.1.4 rerun. Because baseline success is zero, success changes are expressed in percentage points.")}

`, + `

${esc(zh ? "所有配置共用 372 题分母。每题三次执行全部通过运行与验收检查,才记为一个通过用例。1.1.8 的两种布局、修复版 1.1.9 的两种布局和 1.1.9 的两种布局均覆盖全部 372 题。" : "All configurations use the same 372-case denominator. A case passes only when execution and acceptance checks pass in all three attempts. Both 1.1.8 layouts, both patched 1.1.9 layouts and both 1.1.9 layouts directly cover all 372 cases.")}

${esc(zh ? "1.1.4 关闭布局为基线:对 1.1.8 关闭布局唯一通过的候选题实测三次,均失败;其余 371 题沿用共同失败关系。因此表中的 0/372 包含 1 题直接验证和 371 题继承结果,并非对 1.1.4 的完整重测。基线通过率为 0%,通过率变化用百分点表示。" : "Layout-off 1.1.4 is the baseline: the sole candidate passed by layout-off 1.1.8 failed all three direct checks; the other 371 retain the shared-failure relation. Its 0/372 consists of one directly checked case and 371 inherited outcomes, not a complete 1.1.4 rerun. Because baseline success is zero, success changes are expressed in percentage points.")}

`, ) + section( zh ? "任务来源与适用范围" : "Task selection and scope", @@ -970,12 +981,12 @@ F --> G`, section( zh ? "资源测量与可比范围" : "Resource measurement and comparability", "", - `

${esc(zh ? "资源实验单独执行 557 题,每题五次,每种配置共 2,785 次调用。图和总表使用运行前固定的 209 题、1,045 次样本;完整资源表另列全部 557 题。P50 是中位数,P95 是第 95 百分位。" : "Resources use a separate 557-task experiment with five calls per task, or 2,785 calls per configuration. The chart and overview table use 1,045 calls on 209 tasks fixed before execution; detailed resource tables also show all 557 tasks. P50 is the median and P95 the 95th percentile.")}

${esc(zh ? "1.1.4 / 1.1.8 的资源来自 Linux PSS;1.1.9 来自 macOS RSS。CPU 为进程树用户态与内核态时间之和。跨平台的内存和 CPU 不计算相对 1.1.4 的百分比变化;同平台百分比是样本数值对照。修复版为 debug 构建,官方版为发布资产。" : "Moli 1.1.4 / 1.1.8 resources use Linux PSS; 1.1.9 uses macOS RSS. CPU is process-tree user plus system time. Cross-platform memory and CPU changes relative to 1.1.4 are not calculated; same-platform percentages describe the measured sample. The patched binary is a debug build and the official binary is a release asset.")}

`, + `

${esc(zh ? "资源实验单独执行 557 题,每题五次,每种配置共 2,785 次调用。图和总表使用运行前固定的 209 题、1,045 次样本;完整资源表另列全部 557 题。P50 是中位数,P95 是第 95 百分位。" : "Resources use a separate 557-task experiment with five calls per task, or 2,785 calls per configuration. The chart and overview table use 1,045 calls on 209 tasks fixed before execution; detailed resource tables also show all 557 tasks. P50 is the median and P95 the 95th percentile.")}

${esc(zh ? "1.1.4 / 1.1.8 的资源来自 Linux PSS;1.1.9 来自 macOS RSS。CPU 为进程树用户态与内核态时间之和。跨平台的内存和 CPU 不计算相对 1.1.4 的百分比变化;同平台百分比是样本数值对照。四组 macOS 资源配置均为 release 构建,使用同一冻结调用矩阵,逐次轮换顺序并串行执行。" : "Moli 1.1.4 / 1.1.8 resources use Linux PSS; 1.1.9 uses macOS RSS. CPU is process-tree user plus system time. Cross-platform memory and CPU changes relative to 1.1.4 are not calculated; same-platform percentages describe the measured sample. All four macOS resource configurations use release builds and one frozen call matrix, executed serially with rotating order.")}

`, ) + section( zh ? "执行与证据" : "Execution and evidence", "", - `

${esc(zh ? "使用冻结脚本和单工作进程执行。每个版本的功能与资源调用绑定同一二进制哈希;任务定义、程序判定、标准输出与错误日志可从逐题详情检查。未进行独立人工逐次复核。" : "Frozen scripts run with one worker. Functional and resource calls for each build bind the same binary hash. Task definitions, program verdicts, stdout and error logs are available in task details. No independent per-call human review was performed.")}

${esc(T.nav.reproduce)}`, + `

${esc(zh ? "资源实验全局同时只执行一次任务调用。修复版功能结果来自 87c87e95 debug 构建,资源来自 f315ff26 release 构建;成功率仅适用于对应的功能构建。任务定义、程序判定、标准输出与错误日志可从逐题详情检查。未进行独立人工逐次复核。" : "The resource experiment executes one task call globally at a time. Patched functional outcomes use the 87c87e95 debug build; resources use the f315ff26 release build. Success applies to the functional build only. Task definitions, program verdicts, stdout and error logs are available in task details. No independent per-call human review was performed.")}

${esc(T.nav.reproduce)}`, ) ); } @@ -1026,9 +1037,12 @@ function fixedRelations() { [ "119_official_on", "119_on", - zh - ? "同为开启 layout:修复版与官方版" - : "Layout on: patched vs. official", + zh ? "同为开启 layout:修复版与 1.1.9" : "Layout on: patched vs. 1.1.9", + ], + [ + "119_official_off", + "119_official_on", + zh ? "1.1.9:开启 layout 的变化" : "1.1.9: enabling layout", ], ]; return pairs @@ -1053,8 +1067,8 @@ function fixedComparisonSection() { return section( zh ? "布局变化与版本变化" : "Layout changes and version changes", zh - ? "同一修复版的开关对照用于判断布局变化;固定开启 layout 的官方版与修复版对照用于定位版本间变化。下表保留新增通过和退步,不能只看净增加。" - : "Compare layout off/on within the patched build to measure layout changes. Compare the official and patched builds with layout on to locate version differences. Gains and losses are both retained.", + ? "同一修复版的开关对照用于判断布局变化;固定开启 layout 的 1.1.9 与修复版对照用于定位版本间变化。下表保留新增通过和退步,不能只看净增加。" + : "Compare layout off/on within the patched build to measure layout changes. Compare 1.1.9 and patched 1.1.9 with layout on to locate version differences. Gains and losses are both retained.", table( [ zh ? "对照" : "Comparison", @@ -1266,8 +1280,8 @@ function guidePage() { hero( T.nav.guide, zh - ? `修复版开启布局通过 ${patched.final_passed_cases}/${M.task_count} 题,官方版开启布局通过 ${official.final_passed_cases}/${M.task_count} 题。` - : `Patched layout on passes ${patched.final_passed_cases}/${M.task_count} cases; official layout on passes ${official.final_passed_cases}/${M.task_count}.`, + ? `修复版开启布局通过 ${patched.final_passed_cases}/${M.task_count} 题,1.1.9 开启布局通过 ${official.final_passed_cases}/${M.task_count} 题。` + : `Patched layout on passes ${patched.final_passed_cases}/${M.task_count} cases; 1.1.9 layout on passes ${official.final_passed_cases}/${M.task_count}.`, ) + functionalMethodSummary() + combinedSummaryChart() + @@ -1280,13 +1294,13 @@ function guidePage() { section( zh ? "如何理解一个通过结果" : "What a passed case means", "", - `

${esc(zh ? "每个任务定义固定操作和验收条件。单次工具返回成功不足以判为用例通过;每次执行必须满足评分器检查,而且三次执行全部通过。" : "Each task defines fixed actions and acceptance conditions. A successful tool response alone is insufficient: the evaluator must accept every execution, and all three attempts must pass.")}

${example ? `

${esc(example.id)} · ${esc(zh ? `官方开启布局 ${example.passes["119_official_on"]}/3,修复版开启布局 ${example.passes["119_on"]}/3。` : `Official layout on: ${example.passes["119_official_on"]}/3; patched layout on: ${example.passes["119_on"]}/3.`)} ${esc(zh ? "检查任务要求、实际输出和评分证据" : "Inspect requirements, actual output and evaluator evidence")}

` : ""}`, + `

${esc(zh ? "每个任务定义固定操作和验收条件。单次工具返回成功不足以判为用例通过;每次执行必须满足评分器检查,而且三次执行全部通过。" : "Each task defines fixed actions and acceptance conditions. A successful tool response alone is insufficient: the evaluator must accept every execution, and all three attempts must pass.")}

${example ? `

${esc(example.id)} · ${esc(zh ? `1.1.9 开启布局 ${example.passes["119_official_on"]}/3,修复版开启布局 ${example.passes["119_on"]}/3。` : `1.1.9 layout on: ${example.passes["119_official_on"]}/3; patched layout on: ${example.passes["119_on"]}/3.`)} ${esc(zh ? "检查任务要求、实际输出和评分证据" : "Inspect requirements, actual output and evaluator evidence")}

` : ""}`, ) + candidateResourceSection() + section( zh ? "结论与适用范围" : "Conclusions and scope", "", - `

${esc(zh ? "固定开启布局显著扩大了修复版在这组任务上的通过范围;在相同开启布局设置下,修复版比官方版通过更多任务。资源消耗与任务成功分别判断:修复版 debug 构建的 CPU 和 RSS 更高,不能把这一差异单独归因于代码修复。1.1.4 的验证范围及任务选择条件见评测方法。" : "Fixed layout on substantially expands the patched build's passing coverage on this cohort. Under layout on, the patched build passes more tasks than the official build. Evaluate resources separately from success: the patched debug build uses more CPU and RSS, and that difference cannot be attributed solely to code changes. The method page defines task selection and 1.1.4 coverage.")}

${esc(T.nav.method)}`, + `

${esc(zh ? "固定开启布局显著扩大了修复版在这组任务上的通过范围;在相同开启布局设置下,修复版比 1.1.9 通过更多任务。资源比较采用 release 构建的同环境测量;修复版功能与资源来自不同构建,两类结论分别适用于对应构建。1.1.4 的验证范围及任务选择条件见评测方法。" : "Fixed layout on substantially expands the patched build's passing coverage on this cohort. Under layout on, the patched build passes more tasks than Moli 1.1.9. The resource comparison uses release builds measured in the same environment. Patched functional and resource results come from different builds, and each conclusion applies to its corresponding build. The method page defines task selection and 1.1.4 coverage.")}

${esc(T.nav.method)}`, ) + `
${esc(zh ? "1.1.8 的补充资源指标" : "Additional 1.1.8 resource metrics")}${resourceGroups()}${successfulDuration()}
` ); @@ -1312,7 +1326,10 @@ function candidateReproductionSection() { zh ? "二进制 SHA-256" : "Binary SHA-256", ], rows, - ), + ) + + (M.resource_matrix + ? `

` + : ""), ); } function reproducePage() { diff --git a/scripts/moli_report/build.py b/scripts/moli_report/build.py index b87266ddf..816cf90fd 100644 --- a/scripts/moli_report/build.py +++ b/scripts/moli_report/build.py @@ -18,6 +18,7 @@ ) sys.path.insert(0, str(BENCH_ROOT)) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from moli_report.resource_evidence import load_matrix # noqa: E402 from plot_moli_version_resources import combine_comparisons, render_chart # noqa: E402 from runner.resources import duration_calibration # noqa: E402 @@ -40,7 +41,14 @@ ) parser.add_argument("--macos-resource-summary", type=pathlib.Path) parser.add_argument("--official-resource-summary", type=pathlib.Path) +parser.add_argument("--resource-matrix", type=pathlib.Path) args = parser.parse_args() +report_profile = json.loads( + ( + pathlib.Path(__file__).resolve().parents[2] / "evaluation/moli/current-report.json" + ).read_text() +) +resource_builds = report_profile.get("resource_builds", {}) SRC = args.source.resolve() OUT = args.output.resolve() FUNCTIONAL_CORRECTION = args.functional_correction.resolve() @@ -730,12 +738,17 @@ def timestamp(value): fixed_case_data = {c["id"]: {"id": c["id"], "title": c["title"], "methods": {}} for c in cases} public_candidate_files = {} labels = { + "119_official_off": ("Moli 1.1.9 · 关闭 layout", "Moli 1.1.9 · layout off", "off"), + "119_official_on": ("Moli 1.1.9 · 开启 layout", "Moli 1.1.9 · layout on", "on"), "119_off": ("Moli 1.1.9 修复版 · 关闭 layout", "Moli 1.1.9 patched · layout off", "off"), "119_on": ("Moli 1.1.9 修复版 · 开启 layout", "Moli 1.1.9 patched · layout on", "on"), - "119_official_on": ("Moli 1.1.9 官方版 · 开启 layout", "Moli 1.1.9 official · layout on", "on"), } functional_task_ids_sha256 = sha("".join(task_id + "\n" for task_id in sorted(selected)).encode()) -for method_id, summary_path in args.fixed_summary: +assert len(dict(args.fixed_summary)) == len(args.fixed_summary) +assert set(dict(args.fixed_summary)).issubset(labels) +for method_id, summary_path in sorted( + args.fixed_summary, key=lambda item: list(labels).index(item[0]) +): assert method_id in labels and method_id not in fixed_candidates source_bytes = pathlib.Path(summary_path).read_bytes() candidate = json.loads(source_bytes) @@ -848,7 +861,11 @@ def timestamp(value): continue resource = json.loads(resource_path.read_text()) assert resource["schema"] == "lexbench_moli_macos_fixed_resource_summary/1" - expected_layouts = ["layout_on"] if is_official else ["layout_off", "layout_on"] + expected_layouts = [ + f"layout_{layout}" + for layout in ("off", "on") + if (f"119_official_{layout}" if is_official else f"119_{layout}") in fixed_candidates + ] assert ( resource["method"]["configurations"] == expected_layouts and resource["method"]["layout_retry"] is False @@ -867,11 +884,8 @@ def timestamp(value): and resource["quality"]["publishable"] is True ) for layout, config in resource["configurations"].items(): - method_id = "119_official_on" if is_official else f"119_{layout}" - assert ( - resource["candidate"]["binary_sha256"] - == fixed_candidates[method_id]["binary"]["moli_sha256"] - ) + method_id = f"119_official_{layout}" if is_official else f"119_{layout}" + assert resource["candidate"]["binary_sha256"] == resource_builds[method_id]["sha256"] for population_name, n in [ ("all_predeclared_calls", 2785), ("frozen_historical_common_pass_calls", 1045), @@ -896,6 +910,27 @@ def timestamp(value): official_resource = entry else: macos_resource = entry +resource_matrix = None +if macos_resource or official_resource: + assert args.resource_matrix is not None, "a complete matched resource receipt is required" + bundle = load_matrix( + args.resource_matrix, + resource_builds, + { + "patched": macos_resource["summary"], + "official": official_resource["summary"], + }, + ) + public_bytes = (clean(json.dumps(bundle, ensure_ascii=False, indent=2)) + "\n").encode() + url = "data/candidates/resource-matrix.json" + public_candidate_files[url] = public_bytes + resource_matrix = { + "evidence": {"url": url, "sha256": sha(public_bytes), "bytes": len(public_bytes)}, + "receipt": bundle["receipt"], + } + public_candidate_files["reproduction/run_resource_matrix.py"] = ( + args.resource_matrix / "orchestrator.py" + ).read_bytes() functional_correction = json.loads((FUNCTIONAL_CORRECTION / "receipt.json").read_text()) assert functional_correction["schema"] == "moli_functional_contract_correction/1" assert functional_correction["effect"]["report_success_rates_changed"] is False @@ -929,11 +964,12 @@ def timestamp(value): if macos_resource: mac_rows = [] for method_id, resource, layout in [ + ("119_official_off", official_resource, "off"), + ("119_official_on", official_resource, "on"), ("119_off", macos_resource, "off"), ("119_on", macos_resource, "on"), - ("119_official_on", official_resource, "on"), ]: - if resource is None: + if resource is None or method_id not in fixed_candidates: continue metric = resource["summary"]["configurations"][layout]["metrics"][ "frozen_historical_common_pass_calls" @@ -946,6 +982,8 @@ def timestamp(value): "label_en": method["label_en"], "short_label": method["label"].replace("Moli ", ""), "short_label_en": method["label_en"].replace("Moli ", ""), + "functional_binary_sha256": method["moli_sha256"], + "resource_binary_sha256": resource["summary"]["candidate"]["binary_sha256"], "passed_cases": method["final_passed_cases"], "total_cases": 372, "success_rate_pct": method["final_passed_cases"] / 372 * 100, @@ -983,6 +1021,8 @@ def timestamp(value): "fixed_candidates": fixed_candidates, "macos_resource": macos_resource, "official_resource": official_resource, + "resource_builds": resource_builds, + "resource_matrix": resource_matrix, "case_outcomes": case_outcomes, "schema": "moli_layout_report/2", "functional_contract_correction": functional_correction_public, @@ -1128,7 +1168,7 @@ def timestamp(value): asset = args.vendor_dir / name assert not asset.is_symlink() and sha(asset.read_bytes()) == digest shutil.copy2(asset, OUT / name) -(OUT / "reproduction").mkdir() +(OUT / "reproduction").mkdir(exist_ok=True) (OUT / "reproduction/cohort.json").write_text(clean(args.cohort.read_text())) shutil.copy2(SRC / "run.py", OUT / "reproduction/run.py") shutil.copy2( diff --git a/scripts/moli_report/resource_evidence.py b/scripts/moli_report/resource_evidence.py new file mode 100644 index 000000000..0f4d9a160 --- /dev/null +++ b/scripts/moli_report/resource_evidence.py @@ -0,0 +1,192 @@ +"""Bind a complete serialized resource matrix to report summary provenance.""" + +from __future__ import annotations + +import hashlib +import json +import math +import re +import statistics +from pathlib import Path + +from .run_resource_matrix import verify_calls + + +def digest(path: Path) -> str: + if path.is_symlink() or not path.is_file(): + raise ValueError("resource evidence must be a regular file") + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def validate_measurements(rows: list[dict], protocol: dict, metrics: dict) -> None: + by_key = {(r["task_id"], r["attempt"]): r for r in rows} + expected = {(task, attempt) for task in protocol["task_ids"] for attempt in range(1, 6)} + chart = {(r["task_id"], r["attempt"]) for r in protocol["chart_keys"]} + chart_tasks = {task for task, _ in chart} + if ( + len(rows) != len(by_key) + or set(by_key) != expected + or len(chart) != 1045 + or len(chart_tasks) != 209 + or chart != {(task, attempt) for task in chart_tasks for attempt in range(1, 6)} + or not chart.issubset(expected) + ): + raise ValueError("resource measurement population mismatch") + for row in rows: + if row["memory_backend"] != "darwin_ps_process_tree_rss": + raise ValueError("resource measurement backend mismatch") + for key in ("rss_peak_bytes", "cpu_total_ms"): + value = row[key] + if ( + isinstance(value, bool) + or not isinstance(value, (float, int)) + or not math.isfinite(value) + or value < 0 + ): + raise ValueError("invalid resource measurement") + for scope, keys in ( + ("all_predeclared_calls", expected), + ("frozen_historical_common_pass_calls", chart), + ): + for name, field, scale in ( + ("rss_peak_mib", "rss_peak_bytes", 1024**2), + ("cpu_time_ms", "cpu_total_ms", 1), + ): + values = [by_key[key][field] / scale for key in sorted(keys)] + actual = { + "n": len(values), + "sum": math.fsum(values), + "mean": statistics.mean(values), + "p50": statistics.median(values), + "p95": statistics.quantiles(values, n=20, method="inclusive")[18], + "min": min(values), + "max": max(values), + } + if any( + not math.isclose(value, metrics[scope][name][key], rel_tol=1e-9, abs_tol=1e-6) + for key, value in actual.items() + ): + raise ValueError("resource aggregate differs from the physical measurements") + + +def validate_matrix(bundle: dict, builds: dict, summaries: dict) -> None: + protocol, receipt, calls = (bundle[k] for k in ("protocol", "receipt", "calls")) + if ( + protocol["schema"] != "moli_resource_matrix_protocol/1" + or receipt["schema"] != "moli_resource_matrix_receipt/1" + or protocol["selected_round"] != 1 + or receipt["selected_round"] != 1 + or len(protocol["task_ids"]) != 557 + or protocol["attempts"] != 5 + or protocol["sampler_interval_ms"] != 250 + or receipt["physical_calls"] != 11140 + or list(protocol["methods"]) != list(builds) + or len(builds) != 4 + or set(receipt["results"]) != set(builds) + or protocol["orchestrator_sha256"] != receipt["orchestrator_sha256"] + ): + raise ValueError("incomplete or unbound resource matrix") + verify_calls(protocol, calls) + for method, build in builds.items(): + source = protocol["methods"][method] + if any(source[k] != v for k, v in build.items()): + raise ValueError("resource build differs from the declared identity") + summary = summaries["official" if "official" in method else "patched"] + if ( + summary["provenance"]["comparison_protocol_sha256"] + != protocol["reference_protocol_sha256"] + ): + raise ValueError("resource comparison population binding mismatch") + candidate = summary["candidate"] + for key in ("source_commit", "profile", "target"): + if candidate[key] != build[key]: + raise ValueError("resource summary build mismatch") + if candidate["binary_sha256"] != build["sha256"]: + raise ValueError("resource summary binary mismatch") + provenance = summary["configurations"][source["layout"]]["provenance"]["profiled"] + if provenance["run_id"] != source["run_id"]: + raise ValueError("resource run identity mismatch") + for file, key in ( + ("run_manifest.json", "manifest_sha256"), + ("results.jsonl", "results_sha256"), + ("host_summary.json", "host_summary_sha256"), + ): + if receipt["results"][method][file] != provenance[key]: + raise ValueError("resource summary is not from the matched matrix") + validate_measurements( + bundle["measurements"][method], + protocol, + summary["configurations"][source["layout"]]["metrics"], + ) + + +def load_matrix(directory: Path, builds: dict, summaries: dict) -> dict: + if directory.is_symlink(): + raise ValueError("resource matrix directory must not be a symlink") + protocol_path = directory / "protocol.json" + calls_path = directory / "physical-calls.jsonl" + receipt_path = directory / "receipt.json" + for path in (protocol_path, calls_path, receipt_path): + digest(path) + protocol = json.loads(protocol_path.read_text()) + receipt = json.loads(receipt_path.read_text()) + calls = [json.loads(line) for line in calls_path.read_text().splitlines()] + if receipt["protocol_sha256"] != digest(protocol_path) or receipt[ + "physical_calls_sha256" + ] != digest(calls_path): + raise ValueError("resource matrix evidence changed") + if receipt["orchestrator_sha256"] != digest(directory / "orchestrator.py"): + raise ValueError("resource orchestrator source changed") + root = Path(protocol["runner_root"]) + measurements = {} + for method, identity in protocol["methods"].items(): + if not re.fullmatch(r"[A-Za-z0-9_-]+", identity["run_id"]): + raise ValueError("invalid resource run identifier") + run = root / "runs" / identity["run_id"] + if run.is_symlink(): + raise ValueError("resource run must not be a symlink") + for filename, expected in receipt["results"][method].items(): + if digest(run / filename) != expected: + raise ValueError("resource run changed after certification") + rows = [json.loads(line) for line in (run / "results.jsonl").read_text().splitlines()] + hashes = { + (r["task_id"], r["attempt"]): hashlib.sha256( + json.dumps(r, sort_keys=True).encode() + ).hexdigest() + for r in rows + } + if ( + len(rows) != 2785 + or len(hashes) != 2785 + or any( + hashes.get((c["task_id"], c["attempt"])) != c["row_sha256"] + for c in calls + if c["method"] == method + ) + ): + raise ValueError("physical resource calls differ from saved results") + measurements[method] = [ + { + "task_id": row["task_id"], + "attempt": row["attempt"], + "rss_peak_bytes": row["resource"]["rss_peak_bytes"], + "cpu_total_ms": row["resource"]["cpu_total_ms"], + "memory_backend": row["resource"]["measurement_backend"]["memory_rss"], + "root_pid": row["engine_provenance"]["pid"], + "process_count_peak": row["resource"]["process_count_peak"], + } + for row in rows + ] + bundle = { + "measurements": measurements, + "protocol": protocol, + "receipt": receipt, + "calls": calls, + } + validate_matrix(bundle, builds, summaries) + # Public evidence retains identities and calls, excluding local filesystem paths. + protocol.pop("runner_root") + for identity in protocol["methods"].values(): + identity.pop("binary") + bundle["public_protocol_redactions"] = ["runner_root", "methods.*.binary"] + return bundle diff --git a/scripts/moli_report/run_resource_matrix.py b/scripts/moli_report/run_resource_matrix.py new file mode 100644 index 000000000..55733e9ab --- /dev/null +++ b/scripts/moli_report/run_resource_matrix.py @@ -0,0 +1,294 @@ +"""Serialize frozen Lexbench configurations in rotating order for every task attempt. + +Uses the unchanged Lexbench driver, sampler, grader and manifests. Each child +owns its browser and output directory; the coordinator grants one call at a time. +The protocol and every physical call are retained outside Git. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import multiprocessing +import os +import sys +import time +import traceback +from pathlib import Path + + +def sha(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def schedule(task_ids: list[str], attempts: int, methods: list[str]): + if not task_ids or len(set(task_ids)) != len(task_ids) or attempts < 1: + raise ValueError("invalid task population") + if len(methods) < 2 or len(set(methods)) != len(methods): + raise ValueError("need distinct comparison methods") + for task_index, task_id in enumerate(task_ids): + for attempt in range(1, attempts + 1): + offset = (task_index * attempts + attempt - 1) % len(methods) + for method in methods[offset:] + methods[:offset]: + yield method, task_id, attempt + + +def verify_calls(protocol: dict, calls: list[dict]) -> None: + expected = list(schedule(protocol["task_ids"], protocol["attempts"], list(protocol["methods"]))) + if [(c["method"], c["task_id"], c["attempt"]) for c in calls] != expected: + raise ValueError("physical calls differ from the predeclared complete order") + previous_end = 0 + for call in calls: + if call["started_ns"] < previous_end or call["ended_ns"] < call["started_ns"]: + raise ValueError("overlapping or invalid physical call intervals") + previous_end = call["ended_ns"] + if call["binary_sha256"] != protocol["methods"][call["method"]]["sha256"]: + raise ValueError("binary identity mismatch") + + +def worker(channel, protocol: dict, method_id: str, output: str) -> None: + root = Path(protocol["runner_root"]) + out = Path(output) + method = protocol["methods"][method_id] + try: + with (out / f"{method_id}.log").open("w") as log: + os.dup2(log.fileno(), 1) + os.dup2(log.fileno(), 2) + os.chdir(root) + sys.path.insert(0, str(root)) + from runner import run + + meta = run.ENGINE_DEFS["moli"] + meta.update( + binary=Path(method["binary"]), + version=method["version"], + sha256=method["sha256"], + sha256_12=method["sha256"][:12], + cdp_port=run.find_free_port(), + ) + run.ACTIVE_ENGINE_SET = { + "name": protocol["id"], + "engines": { + "moli": { + key: str(value) if isinstance(value, Path) else value + for key, value in meta.items() + if key in {"binary", "version", "sha256", "sha256_12"} + } + }, + } + original_launch = run.BrowserManager.launch + original_attempt = run.run_driver_attempt + launch_count = 0 + call_count = 0 + total = len(protocol["task_ids"]) * protocol["attempts"] + + def launch(manager, *args, **kwargs): + nonlocal launch_count + if launch_count: + channel.send({"kind": "ready", "index": call_count}) + if channel.recv() != {"grant": call_count}: + raise ValueError("invalid call grant") + launch_count += 1 + return original_launch(manager, *args, **kwargs) + + def attempt(*args, **kwargs): + nonlocal call_count + task, ordinal = args[3], args[5] + expected = ( + protocol["task_ids"][call_count // protocol["attempts"]], + call_count % protocol["attempts"] + 1, + ) + if (task.task_id, ordinal) != expected: + raise ValueError("resolved task order changed") + started = time.monotonic_ns() + row = original_attempt(*args, **kwargs) + event = { + "kind": "done", + "method": method_id, + "task_id": task.task_id, + "attempt": ordinal, + "started_ns": started, + "ended_ns": time.monotonic_ns(), + "binary_sha256": method["sha256"], + "row_sha256": hashlib.sha256( + json.dumps(row, sort_keys=True).encode() + ).hexdigest(), + } + call_count += 1 + channel.send(event) + if call_count == total and channel.recv() != {"finish": True}: + raise ValueError("invalid completion grant") + return row + + run.BrowserManager.launch = launch + run.run_driver_attempt = attempt + argv = [ + "run", + *(value for task in protocol["task_ids"] for value in ("--task", task)), + "--engines", + "moli", + "--moli-layout", + method["layout"], + "--chrome-baseline", + "off", + "--score-mode", + "independent", + "--seed", + protocol["seed"], + "--k", + str(protocol["attempts"]), + "--jobs", + "1", + "--host-telemetry", + "on", + "--host-sample-interval-s", + "0.5", + "--resource-profile", + "engine", + "--resource-sample-interval-ms", + "250", + "--provenance-level", + "full", + "--run-id-conflict", + "error", + "--no-progress", + "--run-id", + method["run_id"], + ] + if run.main(argv) != 0: + raise RuntimeError("Lexbench resource run failed") + channel.send({"kind": "finished"}) + except BaseException: + channel.send({"kind": "error", "message": traceback.format_exc()}) + raise + finally: + channel.close() + + +def receive(connection, expected: str) -> dict: + if not connection.poll(600): + raise TimeoutError(f"waiting for resource worker {expected}") + message = connection.recv() + if message.get("kind") != expected: + raise RuntimeError(f"expected {expected}: {message}") + return message + + +def execute(protocol_path: Path, output: Path) -> None: + protocol = json.loads(protocol_path.read_text()) + planned = list(schedule(protocol["task_ids"], protocol["attempts"], list(protocol["methods"]))) + if protocol["selected_round"] != 1: + raise ValueError("this protocol selects exactly one round before execution") + if sha(Path(__file__)) != protocol["orchestrator_sha256"]: + raise ValueError("orchestrator differs from the frozen protocol") + runner_root = Path(protocol["runner_root"]) + for relative, digest in protocol["input_files"].items(): + path = runner_root / relative + if not path.resolve().is_relative_to(runner_root.resolve()) or sha(path) != digest: + raise ValueError(f"frozen input changed: {relative}") + for method in protocol["methods"].values(): + if sha(Path(method["binary"])) != method["sha256"]: + raise ValueError("binary changed before execution") + output.mkdir(parents=True, exist_ok=False) + (output / "protocol.json").write_bytes(protocol_path.read_bytes()) + (output / "orchestrator.py").write_bytes(Path(__file__).read_bytes()) + context = multiprocessing.get_context("spawn") + workers = {} + calls = [] + try: + for method in protocol["methods"]: + parent, child = context.Pipe() + process = context.Process(target=worker, args=(child, protocol, method, str(output))) + process.start() + child.close() + workers[method] = (parent, process) + ready = {method: receive(channel, "ready") for method, (channel, _) in workers.items()} + with (output / "physical-calls.jsonl").open("w") as log: + for index, (method, task, ordinal) in enumerate(planned): + channel, _ = workers[method] + grant = ready.pop(method) if method in ready else receive(channel, "ready") + channel.send({"grant": grant["index"]}) + event = receive(channel, "done") + if (event["method"], event["task_id"], event["attempt"]) != (method, task, ordinal): + raise ValueError("worker executed a different physical call") + log.write(json.dumps(event) + "\n") + log.flush() + calls.append(event) + if (index + 1) % (protocol["attempts"] * len(workers)) == 0: + completed = (index + 1) // (protocol["attempts"] * len(workers)) + print( + f"Completed {completed}/{len(protocol['task_ids'])} tasks", + flush=True, + ) + for channel, _ in workers.values(): + channel.send({"finish": True}) + for channel, process in workers.values(): + receive(channel, "finished") + process.join(30) + if process.exitcode != 0: + raise RuntimeError("resource worker did not finish cleanly") + verify_calls(protocol, calls) + for relative, digest in protocol["input_files"].items(): + if sha(runner_root / relative) != digest: + raise ValueError(f"input changed during execution: {relative}") + results = {} + for method_id, method in protocol["methods"].items(): + if sha(Path(method["binary"])) != method["sha256"]: + raise ValueError("binary changed during execution") + run_dir = Path(protocol["runner_root"]) / "runs" / method["run_id"] + manifest = json.loads((run_dir / "run_manifest.json").read_text()) + if ( + manifest["completion_status"] != "completed" + or manifest["completed_result_rows"] + != len(protocol["task_ids"]) * protocol["attempts"] + ): + raise ValueError("incomplete run manifest") + rows = [ + json.loads(line) for line in (run_dir / "results.jsonl").read_text().splitlines() + ] + row_hashes = { + (row["task_id"], row["attempt"]): hashlib.sha256( + json.dumps(row, sort_keys=True).encode() + ).hexdigest() + for row in rows + } + method_calls = [call for call in calls if call["method"] == method_id] + if ( + len(row_hashes) != len(rows) + or len(rows) != len(method_calls) + or any( + row_hashes.get((call["task_id"], call["attempt"])) != call["row_sha256"] + for call in method_calls + ) + ): + raise ValueError("physical call receipt does not match saved results") + results[method_id] = { + name: sha(run_dir / name) + for name in ("run_manifest.json", "results.jsonl", "host_summary.json") + } + receipt = { + "schema": "moli_resource_matrix_receipt/1", + "protocol_sha256": sha(protocol_path), + "orchestrator_sha256": sha(Path(__file__)), + "selected_round": 1, + "physical_calls": len(calls), + "physical_calls_sha256": sha(output / "physical-calls.jsonl"), + "results": results, + } + (output / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n") + print(json.dumps(receipt), flush=True) + finally: + for channel, process in workers.values(): + if process.is_alive(): + process.terminate() + process.join(30) + channel.close() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--protocol", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + options = parser.parse_args() + execute(options.protocol, options.output) diff --git a/scripts/moli_report/ui_check.js b/scripts/moli_report/ui_check.js index 96ecfdc23..e12679be1 100644 --- a/scripts/moli_report/ui_check.js +++ b/scripts/moli_report/ui_check.js @@ -523,12 +523,54 @@ async function run() { ) throw Error("fixed case explorer coverage"); } + if (model.resource_matrix) { + for (const entry of urls) { + for (const [route, target] of [ + ["guide", model.resource_matrix.evidence.url], + ["reproduce", "reproduction/run_resource_matrix.py"], + ]) { + await page.goto(entry + "#page=" + route); + await ready(page); + const button = page.locator(`[data-evidence="${target}"]`); + const expected = await button.getAttribute("data-sha"); + await button.click(); + const evidence = page.locator("dialog[open] #evidence-text"); + await evidence.waitFor(); + const raw = await evidence.textContent(); + if ( + require("node:crypto") + .createHash("sha256") + .update(raw) + .digest("hex") !== expected + ) + throw Error("resource evidence payload hash mismatch"); + if (route === "guide") { + const matrix = JSON.parse(raw); + if ( + matrix.calls.length !== + model.resource_matrix.receipt.physical_calls + ) + throw Error("resource matrix call coverage"); + for (const id of Object.keys(model.resource_builds)) + if (matrix.measurements[id].length !== 2785) + throw Error("resource measurement coverage"); + } + await page.keyboard.press("Escape"); + if ( + (await page.locator("dialog[open]").count()) || + !(await button.evaluate((el) => document.activeElement === el)) + ) + throw Error("resource evidence keyboard/focus flow"); + } + } + } await page.close(); console.log( JSON.stringify({ route_theme_viewport_checks: checked, negative_controls: 6, - evidence_flows: fixedPass && fixedFail ? 6 : 4, + evidence_flows: + (fixedPass && fixedFail ? 6 : 4) + (model.resource_matrix ? 4 : 0), result: "pass", }), ); diff --git a/scripts/moli_report/verify.py b/scripts/moli_report/verify.py index 3ad5d2172..eb3c2e7fc 100644 --- a/scripts/moli_report/verify.py +++ b/scripts/moli_report/verify.py @@ -14,6 +14,7 @@ import tempfile sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from moli_report.resource_evidence import validate_matrix # noqa: E402 from plot_moli_version_resources import combine_comparisons, render_chart # noqa: E402 parser = argparse.ArgumentParser() @@ -169,7 +170,7 @@ def validate(model, site, check_files=True): ] != [(0, 1, 371), (1, 372, 0), (255, 372, 0)]: fail("fixed functional methods") for method_id, candidate in candidates.items(): - if method_id not in {"119_off", "119_on", "119_official_on"}: + if method_id not in {"119_off", "119_on", "119_official_off", "119_official_on"}: fail("unknown fixed method") info = candidate.get("evidence") or {} path = site / info.get("url", "") @@ -185,7 +186,7 @@ def validate(model, site, check_files=True): summary = json.loads(path.read_text()) if summary.get("schema") != "lexbench_moli_fixed_layout_summary/1": fail("fixed summary schema") - layout = "off" if method_id == "119_off" else "on" + layout = "off" if method_id.endswith("_off") else "on" if summary.get("layout") != layout: fail("fixed layout identity") for field in ("population", "outcomes", "binary", "sources"): @@ -297,7 +298,11 @@ def validate(model, site, check_files=True): or quality.get("publishable") is not True ): fail("resource quality") - layouts = ["on"] if official else ["off", "on"] + layouts = [ + layout + for layout in ("off", "on") + if (f"119_official_{layout}" if official else f"119_{layout}") in candidates + ] method = summary.get("method") or {} if ( method.get("configurations") != [f"layout_{x}" for x in layouts] @@ -311,11 +316,10 @@ def validate(model, site, check_files=True): if set(configs) != set(layouts): fail("resource configurations") for layout, config in configs.items(): - method_id = "119_official_on" if official else f"119_{layout}" - if ( - summary["candidate"]["binary_sha256"] - != candidates[method_id]["binary"]["moli_sha256"] - ): + method_id = f"119_official_{layout}" if official else f"119_{layout}" + if summary["candidate"]["binary_sha256"] != model.get("resource_builds", {}).get( + method_id, {} + ).get("sha256"): fail("resource binary") if ( config.get("layout") != layout @@ -338,7 +342,7 @@ def validate(model, site, check_files=True): fail("metric finite values") if not near(stats["sum"], stats["mean"] * n): fail("metric mean/sum agreement") - if not official: + if set(configs) == {"off", "on"}: for name in ("all_predeclared_calls", "frozen_historical_common_pass_calls"): change_values = summary["comparisons"][name] for metric, stat, key in [ @@ -352,6 +356,42 @@ def validate(model, site, check_files=True): ) * 100 if not near(change_values[key], expected): fail("resource percentage change") + if model.get("macos_resource") or model.get("official_resource"): + matrix = model.get("resource_matrix") or {} + info = matrix.get("evidence") or {} + relative = pathlib.PurePosixPath(info.get("url", "")) + if ( + relative.is_absolute() + or ".." in relative.parts + or not str(relative).startswith("data/candidates/") + ): + fail("unsafe resource matrix evidence") + path = site / relative + if ( + path.is_symlink() + or not path.is_file() + or digest(path) != info.get("sha256") + or path.stat().st_size != info.get("bytes") + ): + fail("resource matrix evidence integrity") + bundle = json.loads(path.read_text()) + if bundle["receipt"] != matrix.get("receipt"): + fail("resource matrix receipt identity") + source = site / "reproduction/run_resource_matrix.py" + if ( + source.is_symlink() + or not source.is_file() + or digest(source) != bundle["receipt"]["orchestrator_sha256"] + ): + fail("resource orchestrator source identity") + validate_matrix( + bundle, + model["resource_builds"], + { + "official": model["official_resource"]["summary"], + "patched": model["macos_resource"]["summary"], + }, + ) chart = model.get("macos_comparison") if model.get("macos_resource"): if not chart or {r["id"] for r in chart["configurations"]} != set(candidates): @@ -360,10 +400,17 @@ def validate(model, site, check_files=True): for row in chart["configurations"]: resource = ( model["official_resource"] - if row["id"] == "119_official_on" + if row["id"].startswith("119_official_") else model["macos_resource"] ) - layout = "off" if row["id"] == "119_off" else "on" + layout = "off" if row["id"].endswith("_off") else "on" + if ( + row.get("functional_binary_sha256") + != candidates[row["id"]]["binary"]["moli_sha256"] + or row.get("resource_binary_sha256") + != resource["summary"]["candidate"]["binary_sha256"] + ): + fail("chart functional/resource build identity") metrics = resource["summary"]["configurations"][layout]["metrics"][ "frozen_historical_common_pass_calls" ] @@ -676,6 +723,8 @@ def validate(model, site, check_files=True): pathlib.Path(__file__).resolve().parents[2] / "evaluation/moli/current-report.json" ) profile = json.loads(profile_path.read_text()) + if model.get("resource_builds") != profile.get("resource_builds"): + fail("release resource binaries differ from the bound identities") if [row["id"] for row in model["functional_methods"]] != profile["method_ids"]: fail("release requires the complete bound functional method matrix") if ( @@ -724,6 +773,10 @@ def rejected(change): rejected(lambda m: m["combined_comparison"]["configurations"][-1].update(cpu_change_pct=0)) rejected(lambda m: m["functional_contract_correction"].update(calls=17)) rejected(lambda m: m["functional_contract_correction"].update(success_rates_changed=True)) +if model.get("resource_matrix"): + rejected(lambda m: m.pop("resource_matrix")) + rejected(lambda m: m["resource_matrix"]["receipt"].update(physical_calls=11139)) + rejected(lambda m: m["resource_builds"]["119_on"].update(sha256="0" * 64)) if model.get("fixed_candidates"): rejected( lambda m: m["functional_methods"][-1].update( diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py index ca065823a..3e9ccb6db 100644 --- a/scripts/plot_moli_version_resources.py +++ b/scripts/plot_moli_version_resources.py @@ -14,7 +14,7 @@ import re from pathlib import Path -COLORS = ("#239b68", "#d1841e", "#7652c7", "#2775c9", "#c54f79", "#4c8793") +COLORS = ("#239b68", "#d1841e", "#7652c7", "#2775c9", "#c54f79", "#4c8793", "#9a653c") COLOR_RE = re.compile(r"#[0-9a-fA-F]{6}") @@ -179,11 +179,19 @@ def render_chart( ) width = 1420 if len(metrics) == 2 else 820 mixed = any(row.get("platform") for row in rows) - height = 700 + 30 * len(rows) + (48 if mixed else 0) + separate_builds = { + row["id"] + for row in rows + if row.get("functional_binary_sha256") + and row.get("resource_binary_sha256") + and row["functional_binary_sha256"] != row["resource_binary_sha256"] + } + note_height = (48 if mixed else 0) + (24 if separate_builds else 0) + height = 700 + 30 * len(rows) + note_height left, right, top, bottom = 105, 55, 145, 115 + 30 * len(rows) gap = 90 panel_width = (width - left - right - gap * (len(metrics) - 1)) / len(metrics) - chart_bottom = height - bottom - (48 if mixed else 0) + chart_bottom = height - bottom - note_height max_success_rate = max(float(row["success_rate_pct"]) for row in rows) y_max = max(20, math.ceil(max_success_rate / 20) * 20) described_metrics = { @@ -308,6 +316,8 @@ def render_chart( if language == "en": label_key += "_en" row_label = row[label_key] + if row["id"] in separate_builds: + row_label += " †" fields = [ f"{int(float(row['passed_cases']))}/{total_cases} " f"({float(row['success_rate_pct']):.1f}%)" @@ -332,6 +342,7 @@ def render_chart( f'' f"{html.escape(row_label + ': ' + ' · '.join(fields))}" ) + notes = [] if mixed: notes = ( [ @@ -346,11 +357,18 @@ def render_chart( "resource changes: —.", ] ) - for i, note in enumerate(notes): - parts.append( - f'' - f"{html.escape(note)}" - ) + if separate_builds: + notes.append( + "† 功能与资源使用不同构建;成功率仅适用于功能构建,身份见报告。" + if language == "zh" + else "† Success and resources use different builds; " + "success applies to the functional build only." + ) + for i, note in enumerate(notes): + parts.append( + f'' + f"{html.escape(note)}" + ) parts.append("") output.parent.mkdir(parents=True, exist_ok=True) output.write_text("\n".join(parts) + "\n") diff --git a/tests/moli_report_render_contract.cjs b/tests/moli_report_render_contract.cjs index bb78b60cf..051110d3d 100644 --- a/tests/moli_report_render_contract.cjs +++ b/tests/moli_report_render_contract.cjs @@ -134,15 +134,75 @@ console.log( "PASS: bilingual fixed methods, gains/losses, resource extrema, ties, percentages and negative controls", ); +// Adding layout-off 1.1.9 must preserve registry order everywhere and retain +// both release resource configurations alongside the patched configurations. +const sevenIds = [ + "114_off", + "118_off", + "118_on", + "119_official_off", + "119_official_on", + "119_off", + "119_on", +]; +const sevenModel = { + ...model, + functional_methods: sevenIds.map((id) => ({ + ...(methods.find((row) => row.id === id) || methods[0]), + id, + label: id, + label_en: id, + policy: id.endsWith("_off") ? "fixed_off" : "fixed_on", + })), + official_resource: resource( + { off: config(90, 9), on: config(120, 15) }, + "official_release", + ), +}; +for (const lang of ["zh", "en"]) { + const ids = Array.from( + render(sevenModel, lang, "macosResourceMethods().map(row => row.id)"), + ); + assert.deepEqual(ids, sevenIds.slice(3)); + const html = render(sevenModel, lang, "functionalMethodSummary()"); + assert.deepEqual( + [...html.matchAll(/data-functional-method="([^"]+)"/g)].map( + (match) => match[1], + ), + sevenIds, + ); + const resources = render(sevenModel, lang, "candidateResourceSection()"); + resourceHighlights(resources); + assert.ok(resources.includes("+11.11%")); // patched off vs. release off + assert.ok( + resources.includes( + lang === "zh" ? "相同 layout 设置" : "same layout setting", + ), + ); + assert.ok( + render(sevenModel, lang, "combinedSummaryChart()").includes( + lang === "zh" ? "7 种固定配置" : "7 fixed configurations", + ), + ); +} + if (site) { const measured = JSON.parse( fs.readFileSync(path.join(site, "data/model.json"), "utf8"), ); for (let lang of ["zh", "en"]) { - for (let page of ["home()", "guidePage()", "methodPage()", "reviewPage()"]) { + for (let page of [ + "home()", + "guidePage()", + "methodPage()", + "reviewPage()", + ]) { const html = render(measured, lang, page); const prose = html.replace(/<[^>]+>/g, " "); - assert.ok(!/历史|补测|Historical|historical|Corrected-contract/.test(prose), page); + assert.ok( + !/历史|补测|Historical|historical|Corrected-contract/.test(prose), + page, + ); assert.ok(!html.includes("undefined")); } if (measured.macos_resource) { diff --git a/tests/test_moli_resource_evidence.py b/tests/test_moli_resource_evidence.py new file mode 100644 index 000000000..e9b2192e7 --- /dev/null +++ b/tests/test_moli_resource_evidence.py @@ -0,0 +1,163 @@ +"""Resource publication must use the complete declared release comparison.""" + +import copy +import unittest + +from scripts.moli_report.resource_evidence import validate_matrix +from scripts.moli_report.run_resource_matrix import schedule + + +class ResourceEvidenceTests(unittest.TestCase): + def setUp(self): + methods = ["119_official_off", "119_official_on", "119_off", "119_on"] + self.builds = { + name: { + "sha256": ("a" if "official" in name else "b") * 64, + "source_commit": "source", + "profile": "release", + "target": "arm64", + } + for name in methods + } + protocol = { + "schema": "moli_resource_matrix_protocol/1", + "selected_round": 1, + "task_ids": [f"case_{i}" for i in range(557)], + "attempts": 5, + "sampler_interval_ms": 250, + "orchestrator_sha256": "c" * 64, + "reference_protocol_sha256": "e" * 64, + "chart_keys": [ + {"task_id": f"case_{i}", "attempt": a} for i in range(209) for a in range(1, 6) + ], + "methods": { + m: {**self.builds[m], "layout": m.rsplit("_", 1)[1], "run_id": m} for m in methods + }, + } + calls = [ + { + "method": m, + "task_id": t, + "attempt": a, + "started_ns": i * 2, + "ended_ns": i * 2 + 1, + "binary_sha256": self.builds[m]["sha256"], + } + for i, (m, t, a) in enumerate(schedule(protocol["task_ids"], 5, methods)) + ] + results = { + m: {k: "d" * 64 for k in ("run_manifest.json", "results.jsonl", "host_summary.json")} + for m in methods + } + self.bundle = { + "protocol": protocol, + "calls": calls, + "measurements": { + m: [ + { + "task_id": task, + "attempt": a, + "rss_peak_bytes": 100 * 1024**2, + "cpu_total_ms": 10, + "memory_backend": "darwin_ps_process_tree_rss", + } + for task in protocol["task_ids"] + for a in range(1, 6) + ] + for m in methods + }, + "receipt": { + "schema": "moli_resource_matrix_receipt/1", + "selected_round": 1, + "physical_calls": 11140, + "orchestrator_sha256": "c" * 64, + "results": results, + }, + } + self.summaries = {} + for group in ("official", "patched"): + ids = methods[:2] if group == "official" else methods[2:] + build = self.builds[ids[0]] + self.summaries[group] = { + "provenance": {"comparison_protocol_sha256": "e" * 64}, + "candidate": {**build, "binary_sha256": build["sha256"]}, + "configurations": { + m.rsplit("_", 1)[1]: { + "metrics": { + scope: { + metric: { + "n": n, + "sum": n * value, + "mean": value, + "p50": value, + "p95": value, + "min": value, + "max": value, + } + for metric, value in (("rss_peak_mib", 100), ("cpu_time_ms", 10)) + } + for scope, n in ( + ("all_predeclared_calls", 2785), + ("frozen_historical_common_pass_calls", 1045), + ) + }, + "provenance": { + "profiled": { + "run_id": m, + "manifest_sha256": "d" * 64, + "results_sha256": "d" * 64, + "host_summary_sha256": "d" * 64, + } + }, + } + for m in ids + }, + } + + def test_complete_release_matrix_can_retain_separate_functional_evidence(self): + validate_matrix(self.bundle, self.builds, self.summaries) + + def test_partial_reordered_overlapping_or_different_build_calls_cannot_publish(self): + mutations = [ + lambda b: b["calls"].pop(), + lambda b: b["calls"].reverse(), + lambda b: b["calls"][1].update(started_ns=0), + lambda b: b["protocol"]["methods"]["119_on"].update(profile="debug"), + lambda b: b["receipt"].update(selected_round=2), + ] + for mutate in mutations: + bundle = copy.deepcopy(self.bundle) + mutate(bundle) + with self.assertRaises(ValueError): + validate_matrix(bundle, self.builds, self.summaries) + + def test_unrelated_measurements_cannot_be_substituted_into_summary(self): + for key in ("run_id", "results_sha256", "manifest_sha256", "host_summary_sha256"): + summaries = copy.deepcopy(self.summaries) + summaries["patched"]["configurations"]["on"]["provenance"]["profiled"][key] = "other" + with self.subTest(key=key), self.assertRaises(ValueError): + validate_matrix(self.bundle, self.builds, summaries) + + def test_internally_consistent_but_wrong_statistics_cannot_publish(self): + stats = self.summaries["patched"]["configurations"]["on"]["metrics"][ + "all_predeclared_calls" + ]["cpu_time_ms"] + stats.update(mean=20, sum=20 * 2785, p50=20, p95=20, min=20, max=20) + with self.assertRaisesRegex(ValueError, "physical measurements"): + validate_matrix(self.bundle, self.builds, self.summaries) + + def test_missing_measurement_or_changed_chart_population_cannot_publish(self): + for mutate in ( + lambda b: b["measurements"]["119_on"].pop(), + lambda b: b["protocol"]["chart_keys"].pop(), + lambda b: b["measurements"]["119_on"][0].update(cpu_total_ms=float("nan")), + lambda b: b["measurements"]["119_on"][0].update(memory_backend="different"), + ): + bundle = copy.deepcopy(self.bundle) + mutate(bundle) + with self.assertRaises(ValueError): + validate_matrix(bundle, self.builds, self.summaries) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_moli_resource_matrix.py b/tests/test_moli_resource_matrix.py new file mode 100644 index 000000000..18e950ee4 --- /dev/null +++ b/tests/test_moli_resource_matrix.py @@ -0,0 +1,134 @@ +import copy +import json +import tempfile +import unittest +from pathlib import Path + +from scripts.moli_report import run_resource_matrix as matrix +from scripts.moli_report.run_resource_matrix import schedule, verify_calls + + +class ResourceMatrixTests(unittest.TestCase): + def setUp(self): + self.protocol = { + "task_ids": ["first", "second"], + "attempts": 3, + "methods": {name: {"sha256": name * 64} for name in ("a", "b", "c")}, + } + self.calls = [ + { + "method": m, + "task_id": t, + "attempt": a, + "started_ns": i * 10, + "ended_ns": i * 10 + 5, + "binary_sha256": m * 64, + } + for i, (m, t, a) in enumerate(schedule(["first", "second"], 3, ["a", "b", "c"])) + ] + + def test_every_method_gets_every_position_and_every_task_attempt(self): + for task in self.protocol["task_ids"]: + groups = [ + [c["method"] for c in self.calls if c["task_id"] == task and c["attempt"] == a] + for a in range(1, 4) + ] + self.assertEqual(groups, [["a", "b", "c"], ["b", "c", "a"], ["c", "a", "b"]]) + verify_calls(self.protocol, self.calls) + + def test_partial_duplicate_and_reordered_results_are_rejected(self): + variants = [self.calls[:-1], self.calls + self.calls[-1:], list(reversed(self.calls))] + for rows in variants: + with self.subTest(rows=len(rows)), self.assertRaises(ValueError): + verify_calls(self.protocol, rows) + + def test_overlapping_execution_and_wrong_binary_are_rejected(self): + for field, value in [("started_ns", 0), ("binary_sha256", "other")]: + rows = copy.deepcopy(self.calls) + rows[1][field] = value + with self.subTest(field=field), self.assertRaises(ValueError): + verify_calls(self.protocol, rows) + + def test_duplicate_task_or_method_cannot_expand_the_population(self): + for tasks, methods in [(["x", "x"], ["a", "b"]), (["x"], ["a", "a"])]: + with self.assertRaises(ValueError): + list(schedule(tasks, 3, methods)) + + def test_workers_run_the_complete_serial_matrix_and_bind_saved_rows(self): + # A small stand-in driver exposes the same lifecycle, without browsers + # or provider calls. The real coordinator and child processes execute. + source = """ +import json +from pathlib import Path +from types import SimpleNamespace +ENGINE_DEFS = {"moli": {}} +def find_free_port(): return 0 +class BrowserManager: + def launch(self, *args, **kwargs): return None +def run_driver_attempt(run_dir, result_path, run_id, task, engine, attempt, *args): + row = {"task_id": task.task_id, "attempt": attempt, "status": "pass"} + with result_path.open("a") as file: file.write(json.dumps(row) + "\\n") + return row +def main(argv): + task_ids = [argv[i+1] for i, item in enumerate(argv) if item == "--task"] + k = int(argv[argv.index("--k")+1]) + run_id = argv[argv.index("--run-id")+1] + directory = Path("runs") / run_id + directory.mkdir(parents=True) + manager = BrowserManager() + manager.launch("moli") + for task in task_ids: + for attempt in range(1,k+1): + manager.launch("moli") + run_driver_attempt(directory, directory / "results.jsonl", run_id, + SimpleNamespace(task_id=task), "moli", attempt) + (directory / "run_manifest.json").write_text(json.dumps({ + "completion_status": "completed", "completed_result_rows":len(task_ids)*k})) + (directory / "host_summary.json").write_text('{"polluted":false}') + return 0 +""" + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + (root / "runner").mkdir() + (root / "runner/__init__.py").write_text("") + (root / "runner/run.py").write_text(source) + binary = root / "binary" + binary.write_bytes(b"fixed test binary") + protocol = { + **self.protocol, + "runner_root": str(root), + "id": "test", + "selected_round": 1, + "seed": "fixed", + "orchestrator_sha256": matrix.sha(Path(matrix.__file__)), + "input_files": {"runner/run.py": matrix.sha(root / "runner/run.py")}, + "methods": { + name: { + "binary": str(binary), + "sha256": matrix.sha(binary), + "version": "test", + "layout": "off", + "run_id": name, + } + for name in ("a", "b", "c") + }, + } + path = root / "protocol.json" + path.write_text(json.dumps(protocol)) + matrix.execute(path, root / "output") + calls = [ + json.loads(line) + for line in (root / "output/physical-calls.jsonl").read_text().splitlines() + ] + verify_calls(protocol, calls) + receipt = json.loads((root / "output/receipt.json").read_text()) + self.assertEqual(receipt["physical_calls"], 18) + self.assertEqual(set(receipt["results"]), {"a", "b", "c"}) + protocol["input_files"]["runner/run.py"] = "wrong" + path.write_text(json.dumps(protocol)) + with self.assertRaisesRegex(ValueError, "frozen input changed"): + matrix.execute(path, root / "rejected") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index 0dc8e34f1..8064f6720 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -14,6 +14,21 @@ class MoliVersionResourceChartTests(unittest.TestCase): + def test_chart_marks_retained_success_from_a_different_resource_build(self): + row = self.data["configurations"][1] + row.update(functional_binary_sha256="a" * 64, resource_binary_sha256="b" * 64) + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "builds.svg" + for language in ("zh", "en"): + for metrics in (("pss",), ("pss", "cpu")): + MODULE.render_chart(self.data, output, metrics, language) + rendered = output.read_text() + self.assertIn(" †:", rendered) + self.assertIn("不同构建" if language == "zh" else "different builds", rendered) + row["resource_binary_sha256"] = row["functional_binary_sha256"] + MODULE.render_chart(self.data, output) + self.assertNotIn("†", output.read_text()) + def test_near_identical_methods_keep_both_numbered_markers_visible(self): self.data["configurations"][1]["pss_mib"] = self.data["configurations"][0]["pss_mib"] self.data["configurations"][1]["success_rate_pct"] = 0.01 @@ -27,7 +42,7 @@ def test_near_identical_methods_keep_both_numbered_markers_visible(self): def test_combined_chart_keeps_registry_order_and_baseline_without_cross_platform_deltas(self): historical = {**self.data, "baseline": "114_off"} mac = {"configurations": []} - for i, passed in enumerate((1, 360, 255)): + for i, passed in enumerate((1, 360, 255, 1)): row = dict(self.data["configurations"][0]) row.update( id=f"mac_{i}", @@ -41,6 +56,7 @@ def test_combined_chart_keeps_registry_order_and_baseline_without_cross_platform methods = [{**r, "final_passed_cases": r["passed_cases"]} for r in sources] combined = MODULE.combine_comparisons(methods, historical, mac) self.assertEqual(combined["baseline"], "114_off") + self.assertEqual(len({r["color"] for r in combined["configurations"]}), 7) self.assertEqual([r["id"] for r in combined["configurations"]], [r["id"] for r in methods]) for row in combined["configurations"][3:]: self.assertIsNone(row["memory_change_pct"]) @@ -57,12 +73,12 @@ def test_combined_chart_keeps_registry_order_and_baseline_without_cross_platform self.assertIn("360/372", text) self.assertIn("+96.77", text) self.assertIn("(—)", text) - self.assertEqual(text.count(' Date: Mon, 21 Sep 2026 19:40:18 +0800 Subject: [PATCH 26/29] Align Moli release resource measurements and seven-method report --- evaluation/moli/current-report.json | 24 +- research/report-changes.json | 51 ++++ scripts/moli_report/BUILD.md | 12 +- scripts/moli_report/README.md | 8 +- scripts/moli_report/app.js | 268 ++++++++++++++++- scripts/moli_report/build.py | 83 +++++- .../run_linux_resource_profiles.py | 259 +++++++++++++++++ .../summarize_linux_resource_profiles.py | 271 ++++++++++++++++++ scripts/moli_report/ui_check.js | 45 ++- scripts/moli_report/verify.py | 116 +++++++- scripts/plot_moli_version_resources.py | 132 +++++++-- tests/moli_report_render_contract.cjs | 54 +++- tests/test_moli_linux_resource_profiles.py | 66 +++++ tests/test_moli_linux_resource_summary.py | 97 +++++++ tests/test_moli_version_resource_chart.py | 36 ++- 15 files changed, 1438 insertions(+), 84 deletions(-) create mode 100644 scripts/moli_report/run_linux_resource_profiles.py create mode 100644 scripts/moli_report/summarize_linux_resource_profiles.py create mode 100644 tests/test_moli_linux_resource_profiles.py create mode 100644 tests/test_moli_linux_resource_summary.py diff --git a/evaluation/moli/current-report.json b/evaluation/moli/current-report.json index 203e09713..e02761f17 100644 --- a/evaluation/moli/current-report.json +++ b/evaluation/moli/current-report.json @@ -20,7 +20,7 @@ "119_off", "119_on" ], - "macos_method_ids": [ + "resource_method_ids": [ "119_official_off", "119_official_on", "119_off", @@ -30,33 +30,33 @@ "base_url": "https://artifact-site.lexmount.cn", "slug": "gdwtSGOel0va", "kind": "folder", - "expected_version": "ver_2f4844c0550241b78f7c80d8614bca87", + "expected_version": "ver_460f324bc0c04d53a866517db54edd13", "share_url": "https://artifact-site.lexmount.cn/v/w1vgSkFJjvmCL6kPaHmj4K8sUZ8iTI8t" }, "resource_builds": { "119_official_off": { - "sha256": "79699e50476118a7a5d1a36775f52d4106801fd5bc803727fd317501faa840cd", + "sha256": "4a10cfab1d743ff327d6e1d5e1a7a8702bed5d869544089ef7df231b0e3b453a", "source_commit": "47512623315aa9b57edc2ef721a033b6b8d91063", - "profile": "official_release", - "target": "aarch64-apple-darwin" + "profile": "release", + "target": "aarch64-unknown-linux-gnu" }, "119_official_on": { - "sha256": "79699e50476118a7a5d1a36775f52d4106801fd5bc803727fd317501faa840cd", + "sha256": "4a10cfab1d743ff327d6e1d5e1a7a8702bed5d869544089ef7df231b0e3b453a", "source_commit": "47512623315aa9b57edc2ef721a033b6b8d91063", - "profile": "official_release", - "target": "aarch64-apple-darwin" + "profile": "release", + "target": "aarch64-unknown-linux-gnu" }, "119_off": { - "sha256": "9b3f3dd6e550a71cddfb93ec3490317b0dfa5db407ebc2d5fb0a9748f58dd226", + "sha256": "568874d3f943957e003e6c7ca34163372c1d3df8823431377037dfae86d99cbd", "source_commit": "f315ff26ed6222603d382b8f7a4648157da3ebf9", "profile": "release", - "target": "aarch64-apple-darwin" + "target": "aarch64-unknown-linux-gnu" }, "119_on": { - "sha256": "9b3f3dd6e550a71cddfb93ec3490317b0dfa5db407ebc2d5fb0a9748f58dd226", + "sha256": "568874d3f943957e003e6c7ca34163372c1d3df8823431377037dfae86d99cbd", "source_commit": "f315ff26ed6222603d382b8f7a4648157da3ebf9", "profile": "release", - "target": "aarch64-apple-darwin" + "target": "aarch64-unknown-linux-gnu" } } } diff --git a/research/report-changes.json b/research/report-changes.json index 97cfe116a..0d4bff962 100644 --- a/research/report-changes.json +++ b/research/report-changes.json @@ -1252,6 +1252,57 @@ } ], "releases": [ + { + "id": "2026-09-21-moli-seven-linux-release-resources", + "date": "2026-09-21", + "date_timezone": "Asia/Shanghai", + "comparison_kinds": [ + "moli_historical_failure_retest", + "moli_process_tree_resource_profile" + ], + "publication": { + "service": "Artifact Site", + "site_slug": "gdwtSGOel0va", + "share_url": "https://artifact-site.lexmount.cn/v/w1vgSkFJjvmCL6kPaHmj4K8sUZ8iTI8t", + "version": "ver_460f324bc0c04d53a866517db54edd13" + }, + "title": "七种 Moli 配置统一采用 Linux Release 资源口径", + "summary": "四组 1.1.9 Release 资源结果与前三组对齐,统一使用 Mac 主机上 Docker Linux 的进程树 PSS 和 CPU。修复版开启 layout 为 80.83 MiB、21.48 ms,相对 1.1.4 为 +4.68%、+0.36%;372 题功能结果保持不变。", + "changes": [ + [ + "资源比较", + "不同平台内存指标与构建模式不能直接比较。", + "四组各测量 557 题 × 5 次,并通过官方 profiler-off 校准;七组以 1.1.4 关闭 layout 为共同基线。", + "汇总图使用预先冻结的 209 题 / 1,045 次,完整表保留 557 题;准确率未重测。" + ], + [ + "图表与证据", + "汇总需要同时清晰展示变化和具体值。", + "点旁显示方法及成功率、资源变化;✦ 标识开启 layout,图例集中列出具体值。公开逐次测量与构建身份。", + "保留原分享链接,功能构建与资源构建分别绑定。" + ] + ], + "i18n": { + "en": { + "title": "Align all seven Moli resource configurations to Linux Release measurements", + "summary": "Four 1.1.9 Release resource configurations now align with the original three using process-tree PSS and CPU in Docker Linux on the Mac host. Patched layout on measures 80.83 MiB and 21.48 ms, +4.68% and +0.36% relative to 1.1.4. Existing 372-task functional results are unchanged.", + "changes": [ + [ + "Resource comparison", + "Different memory metrics and build profiles do not form a direct comparison.", + "Measure 557 tasks × 5 calls for each of four configurations with the official profiler-off calibration. Use 1.1.4 layout off as the common baseline for all seven.", + "The chart retains the predeclared 209-task / 1,045-call population; full tables retain 557 tasks. Accuracy was not rerun." + ], + [ + "Chart and evidence", + "Readers need both changes and exact values.", + "Point labels show method and success/resource changes; ✦ identifies layout on. Legends list exact values. Publish individual measurements and build identities.", + "The existing share link is retained. Functional and resource builds are identified separately." + ] + ] + } + } + }, { "id": "2026-09-21-moli-seven-method-release-resource-calibration", "date": "2026-09-21", diff --git a/scripts/moli_report/BUILD.md b/scripts/moli_report/BUILD.md index d8401b350..78e44268d 100644 --- a/scripts/moli_report/BUILD.md +++ b/scripts/moli_report/BUILD.md @@ -2,11 +2,11 @@ This directory owns the Moli comparison report renderer. Measured evidence stays outside Git under `BROWSER_EVAL_DATA_HOME` (default: `~/.browser-eval`). It does not use the Web Fetch publication target. -The historical Linux source checkout is read from `LEXBENCH_REPORT_RUNNER_ROOT` (default: `$BROWSER_EVAL_DATA_HOME/work/moli-1.1.8-failures-linux`). Its recorded resource-calibration helper remains necessary to validate the historical measurements. Current macOS resource configurations each use one sampled run. +The frozen Linux runner is read from `LEXBENCH_REPORT_RUNNER_ROOT` (default: `$BROWSER_EVAL_DATA_HOME/work/moli-1.1.8-failures-linux`). Its recorded resource-calibration helper verifies the profiler-off and profiler-on pairs. All seven resource configurations use Linux ARM64 release binaries, PSS and process-tree CPU measurements in Docker on the Mac host. The report profile and chart payload have separate schemas. In `moli_report_profile/1`, resource `tasks` and `attempts_per_task` map to the chart's `total_tasks` and `calls_per_task`; `chart_tasks` and `chart_calls` retain their names. The builder validates the measured populations before constructing the chart payload. Do not pass the profile directly to the plotting API. -Build from validated fixed-layout summaries generated by Lexbench's `tools/summarize_moli_fixed_layout.py` and `tools/summarize_moli_macos_resources.py`: +Build from validated fixed-layout functional summaries and the complete resource profile directory: ```sh uv run --frozen python scripts/moli_report/build.py \ @@ -15,17 +15,15 @@ uv run --frozen python scripts/moli_report/build.py \ --fixed-summary 119_on /path/to/patched-on-summary.json \ --fixed-summary 119_official_off /path/to/official-off-summary.json \ --fixed-summary 119_official_on /path/to/official-on-summary.json \ - --macos-resource-summary /path/to/patched-resource-summary.json \ - --official-resource-summary /path/to/official-resource-summary.json \ - --resource-matrix /path/to/certified-resource-matrix + --linux-resource-profiles /path/to/completed-linux-resource-profiles uv run --frozen python scripts/moli_report/verify.py --site /tmp/moli-report-release --release ``` Choose a new output directory for each build; the builder does not delete existing output. `--vendor-dir` selects the retained Mermaid distribution and license. Their hashes are checked before copying. The default location is the original report asset directory under the data home; no vendored executable or measured output is committed here. -The four macOS resource configurations are release builds bound by `resource_builds` in `evaluation/moli/current-report.json`. Their functional evidence binds its own binary identity: the patched functional results and resource measurements use different builds. Do not relabel retained functional outcomes as a new build's measured accuracy. +The four 1.1.9 resource configurations are release builds bound by `resource_builds` in `evaluation/moli/current-report.json`. Functional evidence binds its own binary identity. Do not relabel retained functional outcomes as a new build's measured accuracy. -`run_resource_matrix.py --protocol /path/to/frozen-protocol.json --output /path/to/new-evidence-directory` executes the unchanged Lexbench driver and sampler. Freeze the 557 task definitions, fixtures, runner files, four binary hashes, five attempts, sampling interval and selected round before execution. It grants one call globally at a time, rotates method order for each task attempt, and retains the complete physical-call sequence. Summarize each pair of layouts with the Lexbench resource summarizer. The report builder requires the protocol, physical calls and completion receipt, checks all 11,140 calls against saved result rows, and rejects partial or unrelated summaries. Keep these files outside Git. +`uv run --frozen python -m scripts.moli_report.run_linux_resource_profiles --protocol /path/to/frozen-protocol.json --output /path/to/new-evidence-directory` executes the unchanged Lexbench driver and resource collector. Freeze 557 task definitions, fixtures, runner files, four binary hashes, five attempts, jobs=1, the seed and the 250 ms interval before execution. Each configuration has an independent container; all runs execute serially. The official profiler-off calibration precedes the profiler-on measurement. Resource values come from the latter. The builder verifies all 11,140 measured calls and their calibration pairs, checks the frozen 1,045-call chart population, recomputes aggregates and rejects missing or changed evidence. Keep all measured files outside Git. The static verifier checks score/evidence bindings, resource populations and percentages, fixed-case log links, charts, bilingual rendering, unique resource extrema and negative controls. It invokes the same JavaScript rendering checks used by `tests/test_moli_report_render_contract.py`. diff --git a/scripts/moli_report/README.md b/scripts/moli_report/README.md index eb44c2956..2182d0043 100644 --- a/scripts/moli_report/README.md +++ b/scripts/moli_report/README.md @@ -1,9 +1,9 @@ # Moli compatibility and resource comparison -Success rates use the same 372 historical Moli 0.1.1 failures. A case passes only when all three attempts pass. Moli 1.1.8 and the supplied patched Moli 1.1.9 binary are compared with layout fixed off and on. Official Moli 1.1.9 is evaluated with layout on. Moli 1.1.4 layout off uses a differential check of the sole candidate, with inherited failures explicitly identified. +The report compares seven fixed configurations: Moli 1.1.4 with layout off, Moli 1.1.8 with layout off and on, Moli 1.1.9 with layout off and on, and patched Moli 1.1.9 with layout off and on. Success rates use the same 372 cases failed by Moli 0.1.1. A case passes only when all three attempts pass. Moli 1.1.4 uses a direct check of the sole candidate and 371 inherited failures, explicitly identified in the report. -Resources use a separate 557-task experiment, five calls per task. Each patched 1.1.9 layout configuration has one measured run (2,785 calls each); the official layout-on configuration has one measured run. The chart additionally uses the pre-frozen 1,045-call, 209-task population aligned with the historical resource comparison. Results from every task, including failures, remain in the declared population. +Resources use a separate 557-task experiment, five calls per task. Each configuration has 2,785 measured calls, paired with the official profiler-off calibration. The chart and overview table use the 1,045-call, 209-task population frozen before execution; the detailed tables also report all 557 tasks. Passing and failing calls remain in both declared populations. -Historical Linux measurements report process-tree PSS; macOS measurements report process-tree RSS. These memory metrics are shown separately. Historical percentage changes use 1.1.4 layout off as baseline. The macOS comparison uses official 1.1.9 layout on as baseline when available. The patched debug binary and official release asset differ in build configuration as well as code. +All seven resource configurations run in Docker Linux on the Mac host, using Linux ARM64 release binaries and process-tree PSS and CPU measurements. Resource changes use Moli 1.1.4 with layout off as the baseline. Success-rate changes use percentage points. Functional results retain their own binary identities; patched functional outcomes use commit 87c87e95, while patched resource measurements use the f315ff26 release build. The report does not treat these resource runs as new accuracy measurements. -Open index.html through a static HTTP server. Chinese and English routes share the same report model and evidence. Charts are rendered by the included Python script; RSS/PSS and CPU axes can be selected independently. Per-task results retain the exact program errors and sanitized grader, output, and protocol logs. +Open index.html through a static HTTP server. Chinese and English routes share the same report model and evidence. Charts are rendered by the included Python script; memory and CPU panels can be selected independently. Per-task results retain exact program errors and sanitized grader, output, and protocol logs. diff --git a/scripts/moli_report/app.js b/scripts/moli_report/app.js index 3b60a03c3..b1c90cd7c 100644 --- a/scripts/moli_report/app.js +++ b/scripts/moli_report/app.js @@ -298,7 +298,7 @@ function functionalMethodSummary() { peers.filter((r) => r[key] === minimum).length === 1; let unit = metric === "memory" ? resource.memory_kind + " MiB" : "ms"; - return `${fmt(resource[key], 2)} ${unit}
${delta === null ? esc(zh ? "跨平台 · 不计算变化" : "Cross-platform · no delta") : signed(delta, 2)}
`; + return `${fmt(resource[key], 2)} ${unit}
${delta === null ? esc(zh ? "—" : "—") : signed(delta, 2)}
`; }) .join("") : ""; @@ -316,15 +316,19 @@ function functionalMethodSummary() { let evidence = row.evidence ? `
` : ""; - return `${index + 1} ${esc(zh ? row.label : row.label_en)}${resource ? `
${esc(resource.platform)}${row.id === "114_off" ? (zh ? " · 基线" : " · baseline") : ""}
` : ""}${evidence}${esc(policy)}${esc(scope)}${fmt(row.final_passed_cases)}/${total} (${fmt((row.final_passed_cases / total) * 100, 1)}%)${signed(((row.final_passed_cases - rows[0].final_passed_cases) / total) * 100, 2, zh ? " 个百分点" : " pp")}${fmt(row.physical_calls || (row.id === "114_off" ? 3 : total * 3))}${resourceCells}`; + return `${index + 1} ${esc(zh ? row.label : row.label_en)}${resource ? `
${esc(resource.platform === "Linux" ? "Docker · Linux" : "macOS")}${row.id === "114_off" ? (zh ? " · 基线" : " · baseline") : ""}
` : ""}${evidence}${esc(policy)}${esc(scope)}${fmt(row.final_passed_cases)}/${total} (${fmt((row.final_passed_cases / total) * 100, 1)}%)${signed(((row.final_passed_cases - rows[0].final_passed_cases) / total) * 100, 2, zh ? " 个百分点" : " pp")}${fmt(row.physical_calls || (row.id === "114_off" ? 3 : total * 3))}${resourceCells}`; }); return section( zh ? `${rows.length} 种固定配置的成功率` : `Success rates for ${rows.length} fixed configurations`, - zh - ? `同一 ${total} 题分母,每题三次全部通过才算成功。开启和关闭 layout 分别统计各自的实际结果;资源使用独立的 557 题实验。变化以 1.1.4 关闭 layout 为基准;资源列为图中的 209 题样本。PSS 与 RSS 不直接比较,绿色标识同平台内唯一最低资源值。` - : `The same ${total}-case denominator is used; all three attempts must pass. Layout on and off use their own observed results. Resources come from a separate 557-task experiment. Changes are relative to 1.1.4 layout off; resource columns use the plotted 209-task sample. PSS and RSS are not directly comparable. Green marks the unique resource minimum within each platform.`, + M.resource_metrics + ? zh + ? `${total} 题,每题 3/3 通过才算成功;资源列使用固定 209 题样本,统一为 Linux 进程树 PSS 与 CPU 时间。基线:1.1.4 关闭 layout;绿色为唯一最优值。` + : `${total} cases; all 3 attempts must pass. Resources use the fixed 209-task sample and Linux process-tree PSS and CPU time. Baseline: 1.1.4 layout off; green marks each unique optimum.` + : zh + ? `${total} 题,每题 3/3 通过才算成功;资源列使用固定 209 题样本。基线:1.1.4 关闭 layout。— 表示执行环境不同,不计算资源涨幅;绿色为同环境唯一最优值。` + : `${total} cases; all 3 attempts must pass. Resources use the fixed 209-task sample. Baseline: 1.1.4 layout off. — denotes incompatible execution environments; green marks the unique optimum within each environment.`, table( [ zh ? "方法" : "Method", @@ -349,7 +353,22 @@ function functionalMethodSummary() { } function combinedSummaryChart() { const chart = `moli-all-success-resources-${zh ? "zh" : "en"}.svg`; - return `
${esc(zh ? `${M.functional_methods.length} 种固定配置的成功率与资源,顺序与总表一致,以 1.1.4 关闭布局为基线` : `${M.functional_methods.length} fixed configurations, aligned with the summary table; baseline: 1.1.4 layout off`)}
${esc(zh ? "成功率:372 个所选用例,每题 3 次全部通过;资源:独立的 557 题 × 5 次实验,图中使用预先冻结的 209 题、1,045 次样本。成功率变化以 1.1.4 为基线;内存和 CPU 仅在同一平台内计算相对基线的变化。" : "Success: 372 selected cases, all three attempts must pass. Resources: a separate 557-task × 5-call experiment; the plot uses the pre-frozen 209-task / 1,045-call sample. Success changes use 1.1.4 as baseline; memory and CPU changes are calculated only within the baseline platform.")}
`; + return `
${esc(zh ? `${M.functional_methods.length} 种固定配置的成功率与资源,顺序与总表一致,以 1.1.4 关闭布局为基线` : `${M.functional_methods.length} fixed configurations, aligned with the summary table; baseline: 1.1.4 layout off`)}
`; +} +function resourceBuildNote() { + const measurement = M.linux_resource_profiles + ? zh + ? "资源均使用 Linux ARM64 release 构建,统一测量 PSS 与 CPU。" + : "Resources use Linux ARM64 release builds with consistent PSS and CPU measurements. " + : zh + ? "资源均为 release 构建;macOS RSS 与 Linux PSS 分开比较。" + : "Resources use release builds; macOS RSS and Linux PSS are compared separately. "; + return ( + measurement + + (zh + ? "修复版成功率来自 87c87e95,资源来自 f315ff26;构建身份见评测方法。" + : "Patched success uses 87c87e95 and resources use f315ff26; see the method page for build identities.") + ); } function macosResourceMethods() { let result = []; @@ -371,6 +390,7 @@ function macosResourceMethods() { return result; } function candidateResourceSection() { + if (M.resource_metrics) return unifiedResourceSection(); let methods = macosResourceMethods(); if (!methods.length) return ""; let baseline = methods.find((x) => x.id === M.macos_comparison.baseline), @@ -458,6 +478,111 @@ function candidateResourceSection() { `

${esc(zh ? "四组均使用 release 构建,共享同一主机,各自保留独立浏览器进程和采样。任务调用按配置轮换、串行执行,只统计当前配置的进程树。CPU 为用户态与内核态时间之和。" : "All four release configurations share one host and retain separate browser processes and samplers. Task calls run serially in rotating order; each measurement covers only its own process tree. CPU is user plus system time.")}

${evidence}
`, ); } +function unifiedResourceSection() { + const methods = M.functional_methods; + const specs = [ + ["pss_peak_mib", "mean", zh ? "峰值 PSS 均值" : "Peak PSS mean", "MiB"], + ["pss_peak_mib", "p50", zh ? "峰值 PSS P50" : "Peak PSS P50", "MiB"], + ["pss_peak_mib", "p95", zh ? "峰值 PSS P95" : "Peak PSS P95", "MiB"], + ["cpu_time_ms", "mean", zh ? "CPU 均值" : "CPU mean", "ms"], + ["cpu_time_ms", "p50", zh ? "CPU P50" : "CPU P50", "ms"], + ["cpu_time_ms", "p95", zh ? "CPU P95" : "CPU P95", "ms"], + ]; + let content = [ + ["all_predeclared_calls", zh ? "557 题全部调用" : "All calls on 557 tasks"], + [ + "frozen_historical_common_pass_calls", + zh ? "图表样本:209 题" : "Chart sample: 209 tasks", + ], + ] + .map(([scope, title]) => { + const metric = (id, name, stat) => + M.resource_metrics[id][scope][name][stat]; + const winners = (name, stat) => { + const minimum = Math.min( + ...methods.map((m) => metric(m.id, name, stat)), + ); + return methods.filter((m) => metric(m.id, name, stat) === minimum); + }; + const winnerName = (name, stat) => { + const found = winners(name, stat); + return found.length === 1 + ? zh + ? found[0].label + : found[0].label_en + : zh + ? "并列" + : "Tie"; + }; + const baseline = M.resource_metrics["114_off"][scope]; + const rows = methods.map((method) => { + const values = M.resource_metrics[method.id][scope]; + const cells = specs + .map(([name, stat, label, unit]) => { + const best = winners(name, stat); + const winner = best.length === 1 && best[0].id === method.id; + return `${fmt(values[name][stat], 2)} ${unit}`; + }) + .join(""); + return `${esc(zh ? method.label : method.label_en)}${fmt(values.pss_peak_mib.n)}${cells}${signed((values.pss_peak_mib.p50 / baseline.pss_peak_mib.p50 - 1) * 100, 2)}${signed((values.cpu_time_ms.mean / baseline.cpu_time_ms.mean - 1) * 100, 2)}`; + }); + return ( + `

${esc(title)}

${esc(zh ? `峰值 PSS P50 最低:${winnerName("pss_peak_mib", "p50")};单次 CPU 均值最低:${winnerName("cpu_time_ms", "mean")}。资源消耗与通过率分别比较。` : `Lowest peak PSS P50: ${winnerName("pss_peak_mib", "p50")}; lowest mean CPU per call: ${winnerName("cpu_time_ms", "mean")}. Resource consumption and success are compared separately.`)}

` + + table( + [ + zh ? "方法" : "Method", + zh ? "调用数" : "Calls", + ...specs.map((s) => s[2]), + zh ? "PSS P50 变化" : "PSS P50 change", + zh ? "CPU 均值变化" : "Mean CPU change", + ], + rows, + "unified-resource-table", + ) + ); + }) + .join(""); + content += `

${[ + [ + M.resource_metrics_source, + zh ? "1.1.4 / 1.1.8 资源证据" : "1.1.4 / 1.1.8 resource evidence", + ], + [ + M.linux_resource_profiles.evidence, + zh ? "1.1.9 测量与校准证据" : "1.1.9 measurements and calibration", + ], + ] + .map( + ([evidence, label]) => + ``, + ) + .join(" ")}

`; + return section( + zh ? "七种配置的资源统计" : "Resource statistics for seven configurations", + zh + ? "各指标使用同一批成功与失败调用;P50 为中位数,P95 为第 95 百分位。全部变化以 1.1.4 关闭 layout 为基准。" + : "All metrics include the same passing and failing calls. P50 is the median and P95 the 95th percentile. Every change uses 1.1.4 with layout off as its baseline.", + content, + ); +} +function unifiedResourceMethodology() { + const paragraphs = zh + ? [ + "资源测试独立使用 557 题,每题执行五次,每种配置共 2,785 次调用。图和总表使用事先固定的 209 题、1,045 次调用;完整资源表另列全部 557 题。每个统计范围都保留成功与失败调用。", + "七种配置都在 Mac 主机上的 Docker Linux 环境中测量,使用 Linux ARM64 release 二进制和同一资源采集方法。PSS 通过 /proc/PID/smaps_rollup 采集并按进程树求和,CPU 为该进程树的用户态与内核态 CPU 时间之和。250 ms 采集间隔,jobs=1,各配置串行执行。", + "官方流程先执行 profiler-off 校准,再执行 profiler-on 测量;报告资源值来自后者,校准用于检查采集器影响。P50 是中位数,P95 是第 95 百分位。全部资源变化以 1.1.4 关闭 layout 为基线,表示对应样本统计值的差异。官网 71 MiB 不参与这七组计算。", + ] + : [ + "Resources use a separate 557-task experiment with five attempts per task, or 2,785 calls per configuration. The chart and overview table use 1,045 calls on 209 tasks fixed before execution; the detailed resource tables also show all 557 tasks. Each scope retains passing and failing calls.", + "All seven configurations are measured in Docker Linux on the Mac host, using Linux ARM64 release binaries and the same resource collection method. PSS is read from /proc/PID/smaps_rollup and summed over the process tree; CPU is the tree's user plus system CPU time. Sampling uses a 250 ms interval and jobs=1, with configurations executed serially.", + "The official procedure runs profiler-off calibration followed by profiler-on measurement. Reported resources come from the latter; calibration checks observer effect. P50 is the median and P95 the 95th percentile. Every resource change uses 1.1.4 with layout off as the baseline and describes the corresponding sample statistic. The website's 71 MiB value is excluded from these seven configurations.", + ]; + return section( + zh ? "资源测量与可比范围" : "Resource measurement and comparability", + "", + paragraphs.map((p) => `

${esc(p)}

`).join(""), + ); +} function resourceGroups() { let off = M.metrics.off.profile, on = M.metrics.on.profile, @@ -613,11 +738,11 @@ function home() { ) + functionalMethodSummary() + combinedSummaryChart() + - `
${esc(zh ? "查看完整资源统计与测量范围" : "Inspect resource statistics and measurement scope")}${candidateResourceSection()}

${esc(zh ? "Linux PSS 与 CPU 数值见总表。全部资源统计包含成功与失败调用;图表样本在运行前固定。" : "Linux PSS and CPU values appear in the summary table. Resource statistics include successful and failed calls; the chart sample is fixed before execution.")}

${esc(zh ? "下载 Linux 资源数据" : "Download Linux resource data")}
` + + `
${esc(zh ? "查看完整资源统计与测量范围" : "Inspect resource statistics and measurement scope")}${candidateResourceSection()}
` + section( zh ? "如何查看结果" : "Explore the results", "", - `

${esc(zh ? "资源均为 release 构建;macOS RSS 与 Linux PSS 分开比较。修复版成功率来自 87c87e95,资源来自 f315ff26,构建身份见评测方法。" : "Resources use release builds; macOS RSS and Linux PSS are compared separately. Patched success uses 87c87e95 and resources use f315ff26; see the method page for build identities.")}

${esc(zh ? "比较新增通过与仍然失败的用例" : "Compare gained passes and remaining failures")} · ${esc(T.nav.guide)} · ${esc(T.nav.reproduce)}`, + `

${esc(resourceBuildNote())}

${esc(zh ? "比较新增通过与仍然失败的用例" : "Compare gained passes and remaining failures")} · ${esc(T.nav.guide)} · ${esc(T.nav.reproduce)}`, ) ); } @@ -978,10 +1103,77 @@ F --> G`, "", `

${esc(zh ? "372 题选自 Moli 0.1.1 在 1,928 题中未达到三次全部通过的全部用例,覆盖 15 类驱动。Chrome 结果不影响入选。其余 1,556 题不在评测范围内,这里的通过率不代表完整 1,928 题的通过率。" : "The 372 cases are all cases from the 1,928-case suite that Moli 0.1.1 did not pass in all three attempts, spanning 15 driver types. Chrome outcomes do not affect selection. The other 1,556 cases are outside this evaluation, so these rates do not describe the full suite.")}

${esc(T.nav.dataset)}`, ) + + (M.linux_resource_profiles + ? unifiedResourceMethodology() + : section( + zh ? "资源测量与可比范围" : "Resource measurement and comparability", + "", + `

${esc(zh ? "资源实验单独执行 557 题,每题五次,每种配置共 2,785 次调用。图和总表使用运行前固定的 209 题、1,045 次样本;完整资源表另列全部 557 题。P50 是中位数,P95 是第 95 百分位。" : "Resources use a separate 557-task experiment with five calls per task, or 2,785 calls per configuration. The chart and overview table use 1,045 calls on 209 tasks fixed before execution; detailed resource tables also show all 557 tasks. P50 is the median and P95 the 95th percentile.")}

${esc(zh ? "1.1.4 / 1.1.8 在 Mac 发起的 Docker Linux 容器中执行,使用 Linux ARM64 二进制并采集 PSS;1.1.9 在 macOS 原生执行,使用 Mach-O ARM64 二进制并采集 RSS。七组均为本次系列的复测数据,非官网 71 MiB 数据;同一宿主机不等于相同执行环境。CPU 为进程树用户态与内核态时间之和。跨平台的内存和 CPU 不计算相对 1.1.4 的百分比变化;同平台百分比是样本数值对照。四组 macOS 资源配置均为 release 构建,使用同一冻结调用矩阵,逐次轮换顺序并串行执行。" : "Moli 1.1.4 / 1.1.8 run in Docker Linux containers launched from the Mac, using Linux ARM64 binaries and PSS sampling. Moli 1.1.9 runs natively on macOS with Mach-O ARM64 binaries and RSS sampling. All seven configurations are reruns in this series, not the website’s 71 MiB result. Sharing a host does not imply an identical execution environment. CPU is process-tree user plus system time. Cross-platform memory and CPU changes relative to 1.1.4 are not calculated; same-platform percentages describe the measured sample. All four macOS resource configurations use release builds and one frozen call matrix, executed serially with rotating order.")}

`, + )) + section( - zh ? "资源测量与可比范围" : "Resource measurement and comparability", - "", - `

${esc(zh ? "资源实验单独执行 557 题,每题五次,每种配置共 2,785 次调用。图和总表使用运行前固定的 209 题、1,045 次样本;完整资源表另列全部 557 题。P50 是中位数,P95 是第 95 百分位。" : "Resources use a separate 557-task experiment with five calls per task, or 2,785 calls per configuration. The chart and overview table use 1,045 calls on 209 tasks fixed before execution; detailed resource tables also show all 557 tasks. P50 is the median and P95 the 95th percentile.")}

${esc(zh ? "1.1.4 / 1.1.8 的资源来自 Linux PSS;1.1.9 来自 macOS RSS。CPU 为进程树用户态与内核态时间之和。跨平台的内存和 CPU 不计算相对 1.1.4 的百分比变化;同平台百分比是样本数值对照。四组 macOS 资源配置均为 release 构建,使用同一冻结调用矩阵,逐次轮换顺序并串行执行。" : "Moli 1.1.4 / 1.1.8 resources use Linux PSS; 1.1.9 uses macOS RSS. CPU is process-tree user plus system time. Cross-platform memory and CPU changes relative to 1.1.4 are not calculated; same-platform percentages describe the measured sample. All four macOS resource configurations use release builds and one frozen call matrix, executed serially with rotating order.")}

`, + zh ? "RSS 与 PSS:指标口径" : "RSS and PSS: memory definitions", + zh + ? "两者均以 MiB 展示,但共享内存的计数方式不同,不能互换或按固定比例换算。" + : "Both use MiB, but account for shared memory differently and cannot be interchanged or converted by a fixed ratio.", + table( + [zh ? "对比项" : "Property", "RSS", "PSS"], + [ + [ + zh ? "统计内容" : "What is counted", + zh + ? "进程当前驻留物理内存中的页" + : "Pages currently resident in physical memory for the process", + zh + ? "私有驻留页,加上按共享进程数分摊的共享驻留页" + : "Private resident pages plus a proportional share of shared resident pages", + ], + [ + zh ? "共享页" : "Shared pages", + zh + ? "每个映射进程都计入;进程树求和会重复计入共享页" + : "Counted for each mapping process; process-tree sums can count shared pages multiple times", + zh + ? "按共享份额计入,减少进程间重复计算" + : "Counted proportionally, reducing double counting across processes", + ], + [ + zh ? "示例" : "Example", + zh + ? "20 MiB 私有页+与另一进程共享的 10 MiB:RSS=30 MiB" + : "20 MiB private plus 10 MiB shared equally with one other process: RSS = 30 MiB", + zh + ? "同例:PSS=20+10÷2=25 MiB" + : "Same example: PSS = 20 + 10 / 2 = 25 MiB", + ], + [ + zh ? "本报告采集" : "Collection in this report", + M.linux_resource_profiles + ? zh + ? "本报告资源对比统一使用 PSS" + : "This report consistently compares PSS" + : zh + ? "macOS:ps 的 rss 字段,按进程树求和" + : "macOS: ps rss field, summed over the process tree", + zh + ? "Linux:/proc/PID/smaps_rollup 的 Pss 字段,按进程树求和" + : "Linux: Pss in /proc/PID/smaps_rollup, summed over the process tree", + ], + [ + zh ? "比较条件" : "Comparison conditions", + zh + ? "相同执行环境、采样与任务范围;CPU 时间也须采用一致条件" + : "Matching execution environment, sampling and task scope; CPU comparisons also require consistent conditions", + zh + ? "相同条件,且保持共享进程环境一致;PSS 不等于 RSS" + : "Matching conditions and shared-process environment; PSS is not RSS", + ], + ].map( + (cells) => + `${cells.map((cell) => `${esc(cell)}`).join("")}`, + ), + "memory-definition-table", + ) + + `

${esc(zh ? "Linux 内核:RSS 与 PSS 定义" : "Linux kernel: RSS and PSS definitions")} · ${esc(zh ? "Apple:驻留内存与共享映射" : "Apple: resident memory and shared mappings")}

`, ) + section( zh ? "执行与证据" : "Execution and evidence", @@ -1007,7 +1199,7 @@ function costSection() { return section( zh ? "耗时下降来自哪些任务" : "Where the time reduction came from", zh - ? `以下三题贡献净耗时变化的 ${share}%。正值表示开启布局后耗时下降;负值表示增加。CPU 差值来自资源采样轮,耗时差值来自无采样轮。` + ? `以下三题贡献净耗时变化的 ${share}%。正值表示开启布局后耗时下降;负值表示增加。CPU 差值来自开启资源采集的调用,耗时差值来自关闭资源采集的调用。` : `These three tasks account for ${share}% of the net duration change. Positive differences mean lower duration with layout; negative values mean higher duration. CPU differences use profiled calls and duration differences use unprofiled calls.`, table( [ @@ -1206,6 +1398,30 @@ function analysisPage() { ); } function candidateResourceQuality() { + if (M.linux_resource_profiles) { + const rows = M.functional_methods + .filter((m) => M.linux_resource_profiles.configurations[m.id]) + .map((method) => { + const config = M.linux_resource_profiles.configurations[method.id]; + return `${esc(zh ? method.label : method.label_en)}${fmt(config.metrics.all_predeclared_calls.pss_peak_mib.n)}/2,785${fmt(config.metrics.all_predeclared_calls.cpu_time_ms.n)}/2,785${esc(config.calibration.acceptable ? (zh ? "通过" : "Pass") : zh ? "失败" : "Fail")}${esc(Object.values(config.host).every((h) => !h.polluted) ? (zh ? "通过" : "Pass") : zh ? "失败" : "Fail")}`; + }); + return section( + zh ? "1.1.9 资源测量质量" : "1.1.9 resource measurement quality", + zh + ? "按官方流程执行 profiler-off 校准和 profiler-on 测量;核验完整题目范围、构建身份、PSS/CPU 覆盖、采集器影响和宿主机负载。" + : "The official procedure pairs profiler-off calibration with profiler-on measurement and checks task coverage, build identity, PSS/CPU availability, observer effect and host load.", + table( + [ + zh ? "配置" : "Configuration", + zh ? "PSS 覆盖" : "PSS coverage", + zh ? "CPU 覆盖" : "CPU coverage", + zh ? "采集器校准" : "Profiler calibration", + zh ? "宿主机检查" : "Host check", + ], + rows, + ), + ); + } let methods = macosResourceMethods(); if (!methods.length) return ""; let rows = methods.map((item) => { @@ -1306,6 +1522,34 @@ function guidePage() { ); } function candidateReproductionSection() { + if (M.linux_resource_profiles) { + const profiles = M.linux_resource_profiles; + const rows = M.functional_methods + .filter((m) => profiles.configurations[m.id]) + .map((method) => { + const build = profiles.configurations[method.id].build; + const run = profiles.receipt.results[`${method.id}:engine`]; + return `${esc(zh ? method.label : method.label_en)}${esc(run.run_id)}${fmt(run.rows)}/2,785${esc(build.sha256)}`; + }); + return section( + zh + ? "1.1.9 Linux release 资源复现" + : "Reproduce 1.1.9 Linux release resources", + zh + ? "Mac 主机上的固定 Docker Linux 镜像;557 题、每题五次、jobs=1,250 ms PSS 采集间隔。测量前冻结任务、依赖和二进制哈希;各配置独立容器、串行执行。" + : "A fixed Docker Linux image on the Mac host; 557 tasks, five attempts each, jobs=1 and a 250 ms PSS interval. Tasks, dependencies and binary hashes are frozen before execution. Configurations run serially in independent containers.", + table( + [ + zh ? "配置" : "Configuration", + zh ? "测量 ID" : "Measurement ID", + zh ? "调用数" : "Calls", + zh ? "资源二进制 SHA-256" : "Resource binary SHA-256", + ], + rows, + ) + + `

`, + ); + } let methods = macosResourceMethods(); if (!methods.length) return ""; let rows = methods.map((item) => { diff --git a/scripts/moli_report/build.py b/scripts/moli_report/build.py index 816cf90fd..b19713a2c 100644 --- a/scripts/moli_report/build.py +++ b/scripts/moli_report/build.py @@ -19,6 +19,12 @@ sys.path.insert(0, str(BENCH_ROOT)) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from moli_report.resource_evidence import load_matrix # noqa: E402 +from moli_report.summarize_linux_resource_profiles import ( # noqa: E402 + summarize as summarize_linux_profiles, +) +from moli_report.summarize_linux_resource_profiles import ( # noqa: E402 + validate_summary as validate_linux_summary, +) from plot_moli_version_resources import combine_comparisons, render_chart # noqa: E402 from runner.resources import duration_calibration # noqa: E402 @@ -42,6 +48,7 @@ parser.add_argument("--macos-resource-summary", type=pathlib.Path) parser.add_argument("--official-resource-summary", type=pathlib.Path) parser.add_argument("--resource-matrix", type=pathlib.Path) +parser.add_argument("--linux-resource-profiles", type=pathlib.Path) args = parser.parse_args() report_profile = json.loads( ( @@ -1005,8 +1012,82 @@ def timestamp(value): "calls_per_task": 5, }, } -combined_comparison = combine_comparisons(functional_methods, version_comparison, macos_comparison) +linux_resource_profiles = None +linux_comparison = None +resource_metrics = None +resource_metrics_source = None +if args.linux_resource_profiles: + assert not macos_resource and not official_resource, "use one current resource cohort" + linux_summary = summarize_linux_profiles(args.linux_resource_profiles) + validate_linux_summary(linux_summary, resource_builds) + public_bytes = (clean(json.dumps(linux_summary, ensure_ascii=False, indent=2)) + "\n").encode() + url = "data/candidates/linux-resource-profiles.json" + public_candidate_files[url] = public_bytes + linux_public_summary = json.loads(public_bytes) + linux_resource_profiles = { + "configurations": linux_public_summary["configurations"], + "receipt": linux_public_summary["receipt"], + "evidence": {"url": url, "sha256": sha(public_bytes), "bytes": len(public_bytes)}, + } + public_candidate_files["reproduction/run_linux_resource_profiles.py"] = ( + args.linux_resource_profiles / "orchestrator.py" + ).read_bytes() + original_bytes = (clean(json.dumps(resource_comparison, indent=2)) + "\n").encode() + original_url = "data/candidates/version-resource-measurements.json" + public_candidate_files[original_url] = original_bytes + resource_metrics_source = { + "url": original_url, + "sha256": sha(original_bytes), + "bytes": len(original_bytes), + } + resource_metrics = {} + for method in functional_methods: + method_id = method["id"] + if method_id in linux_summary["configurations"]: + resource_metrics[method_id] = linux_summary["configurations"][method_id]["metrics"] + else: + resource_metrics[method_id] = { + scope: { + metric: {**stat, "p50": stat["median"], "sum": stat["mean"] * stat["n"]} + for metric, stat in resource_comparison["memory"][method_id][scope].items() + if metric in {"pss_peak_mib", "cpu_time_ms"} + } + for scope in ("all_predeclared_calls", "frozen_historical_common_pass_calls") + } + linux_rows = [] + for method in functional_methods: + method_id = method["id"] + if method_id not in linux_summary["configurations"]: + continue + config = linux_summary["configurations"][method_id] + metric = config["metrics"]["frozen_historical_common_pass_calls"] + linux_rows.append( + { + "id": method_id, + "label": method["label"], + "label_en": method["label_en"], + "short_label": method["label"].removeprefix("Moli "), + "short_label_en": method["label_en"].removeprefix("Moli "), + "functional_binary_sha256": method["moli_sha256"], + "resource_binary_sha256": config["build"]["sha256"], + "passed_cases": method["final_passed_cases"], + "total_cases": 372, + "success_rate_pct": method["final_passed_cases"] / 372 * 100, + "pss_mib": metric["pss_peak_mib"]["p50"], + "cpu_ms": metric["cpu_time_ms"]["mean"], + "platform": "Linux", + "memory_kind": "PSS", + } + ) + linux_comparison = {"configurations": linux_rows} +combined_comparison = combine_comparisons( + functional_methods, version_comparison, linux_comparison or macos_comparison +) public = { + "linux_resource_profiles": linux_resource_profiles, + "linux_comparison": linux_comparison, + "resource_metrics": resource_metrics, + "resource_metrics_source": resource_metrics_source, "combined_comparison": combined_comparison, "fixed_case_outcomes": [ { diff --git a/scripts/moli_report/run_linux_resource_profiles.py b/scripts/moli_report/run_linux_resource_profiles.py new file mode 100644 index 000000000..c766b3dd8 --- /dev/null +++ b/scripts/moli_report/run_linux_resource_profiles.py @@ -0,0 +1,259 @@ +"""Run independent Linux PSS/CPU profiles from a frozen Moli protocol. + +Each configuration owns one container and one complete official resource run. +Containers execute strictly serially, so no comparison Moli process is resident +while another configuration is measured. The official profiler-off calibration +is retained only to verify observer effect; published PSS/CPU values come from +the single engine profile for each configuration. +""" + +from __future__ import annotations + +import argparse +import collections +import hashlib +import json +import re +import subprocess +from pathlib import Path + + +def sha256(path: Path) -> str: + if path.is_symlink() or not path.is_file(): + raise ValueError(f"expected regular file: {path}") + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def validate_protocol(protocol: dict, source: Path) -> None: + configs = protocol.get("configs") + tasks = protocol.get("task_ids") + order = protocol.get("order") + if ( + protocol.get("schema") != "moli_linux_resource_profiles/1" + or not isinstance(configs, dict) + or len(configs) != 4 + or not isinstance(tasks, list) + or len(tasks) != 557 + or len(set(tasks)) != len(tasks) + or protocol.get("attempts") != 5 + or protocol.get("jobs") != 1 + or protocol.get("sample_interval_ms") != 250 + or protocol.get("memory_metric") != "process_tree_pss" + or protocol.get("orchestrator_sha256") != sha256(source) + ): + raise ValueError("invalid or incomplete Linux resource protocol") + expected = [ + *[(method, "baseline") for method in configs], + *[(method, "engine") for method in reversed(configs)], + ] + if order != [list(item) for item in expected]: + raise ValueError("resource order must pair forward baselines with reverse profiles") + for method, config in configs.items(): + if ( + not re.fullmatch(r"[a-z0-9_]{1,55}", method) + or config.get("layout") not in {"off", "on"} + or config.get("target") != "aarch64-unknown-linux-gnu" + or config.get("profile") != "release" + or len(config.get("sha256", "")) != 64 + ): + raise ValueError(f"invalid configuration: {method}") + + +def verify_inputs(protocol: dict, runner: Path) -> None: + for relative, digest in protocol["input_files"].items(): + if sha256(runner / relative) != digest: + raise ValueError(f"runner input changed: {relative}") + for config in protocol["configs"].values(): + if sha256(Path(config["binary"])) != config["sha256"]: + raise ValueError("Moli binary changed") + if sha256(Path(protocol["node_modules_lock"])) != protocol["node_modules_lock_sha256"]: + raise ValueError("Node dependency lock changed") + if sha256(Path(protocol["agent_browser_binary"])) != protocol["agent_browser_sha256"]: + raise ValueError("agent-browser binary changed") + + +def active_set(method: str, config: dict) -> dict: + return { + "name": f"moli-linux-resource-{method}", + "engines": { + "moli": { + "binary": "build_artifacts/moli/bin/moli", + "version": config["version"], + "sha256": config["sha256"], + "sha256_12": config["sha256"][:12], + } + }, + } + + +def run_one(protocol: dict, output: Path, method: str, phase: str) -> dict: + config = protocol["configs"][method] + run_id = f"{method}_{phase}" + run_dir = output / run_id + if run_dir.exists(): + raise ValueError(f"run already exists: {run_dir}") + active_path = output / f"{method}-active-set.json" + payload = active_set(method, config) + if active_path.exists() and json.loads(active_path.read_text()) != payload: + raise ValueError("active set changed") + active_path.write_text(json.dumps(payload, indent=2) + "\n") + runner = Path(protocol["runner_root"]) + command = [ + "docker", + "run", + "--rm", + "--init", + "--name", + f"{protocol['id']}-{method}-{phase}", + "--mount", + f"type=bind,src={runner},dst=/work,readonly", + "--mount", + f"type=bind,src={protocol['node_modules']},dst=/work/node_modules,readonly", + "--mount", + ( + f"type=bind,src={protocol['agent_browser_binary']}," + "dst=/work/node_modules/agent-browser/bin/agent-browser-linux-arm64,readonly" + ), + "--mount", + f"type=bind,src={output},dst=/results", + "--mount", + f"type=bind,src={active_path},dst=/work/build_artifacts/active-set.json,readonly", + "--mount", + (f"type=bind,src={config['binary']},dst=/work/build_artifacts/moli/bin/moli,readonly"), + "-w", + "/work", + "-e", + "NODE_PATH=/work/node_modules", + "-e", + "PATH=/work/node_modules/.bin:/home/evaluator/.cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin", + "-e", + "AGENT_BROWSER_SOCKET_DIR=/tmp/ab", + "-e", + "HTTP_PROXY=", + "-e", + "HTTPS_PROXY=", + "-e", + "http_proxy=", + "-e", + "https_proxy=", + "-e", + "ALL_PROXY=", + "-e", + "NO_PROXY=*", + "--entrypoint", + "python3", + protocol["image"], + "runner/run.py", + "run", + "--engines", + "moli", + "--moli-layout", + config["layout"], + "--k", + str(protocol["attempts"]), + "--jobs", + str(protocol["jobs"]), + "--seed", + protocol["seed"], + "--chrome-baseline", + "off", + "--score-mode", + "independent", + "--resource-profile", + phase, + "--resource-sample-interval-ms", + str(protocol["sample_interval_ms"]), + "--host-telemetry", + "on", + "--host-sample-interval-s", + "0.5", + "--run-id", + run_id, + "--run-id-conflict", + "error", + "--out", + "/results", + "--no-report", + "--no-progress", + "--provenance-level", + "minimal", + ] + if phase == "engine": + command.extend( + [ + "--resource-calibration-baseline", + f"/results/{method}_baseline", + "--resource-max-observer-effect-pct", + str(protocol["max_observer_effect_pct"]), + ] + ) + for task in protocol["task_ids"]: + command.extend(["--task", task]) + (output / f"{run_id}-command.json").write_text(json.dumps(command, indent=2) + "\n") + with (output / f"{run_id}.log").open("w") as log: + subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=True) + manifest = json.loads((run_dir / "run_manifest.json").read_text()) + rows = [json.loads(line) for line in (run_dir / "results.jsonl").read_text().splitlines()] + expected = collections.Counter( + (task, attempt) + for task in protocol["task_ids"] + for attempt in range(1, protocol["attempts"] + 1) + ) + if ( + manifest["completion_status"] != "completed" + or collections.Counter((row["task_id"], row["attempt"]) for row in rows) != expected + or any(row["engine_provenance"]["binary_sha256"] != config["sha256"] for row in rows) + or any( + row["engine_provenance"]["layout_enabled"] != (config["layout"] == "on") for row in rows + ) + ): + raise ValueError("completed run does not match the protocol") + if phase == "engine" and any( + row["resource"].get("pss_peak_bytes") is None + or row["resource"].get("sample_interval_ms") != protocol["sample_interval_ms"] + for row in rows + ): + raise ValueError("engine profile is missing PSS measurements") + return { + "run_id": run_id, + "rows": len(rows), + "run_manifest_sha256": sha256(run_dir / "run_manifest.json"), + "results_sha256": sha256(run_dir / "results.jsonl"), + "host_summary_sha256": sha256(run_dir / "host_summary.json"), + } + + +def execute(protocol_path: Path, output: Path) -> None: + protocol = json.loads(protocol_path.read_text()) + validate_protocol(protocol, Path(__file__)) + verify_inputs(protocol, Path(protocol["runner_root"])) + output.mkdir(parents=True, exist_ok=False) + (output / "protocol.json").write_bytes(protocol_path.read_bytes()) + (output / "orchestrator.py").write_bytes(Path(__file__).read_bytes()) + results = {} + for method, phase in protocol["order"]: + if sha256(Path(__file__)) != protocol["orchestrator_sha256"]: + raise ValueError("resource orchestrator changed during execution") + print(f"START {method} {phase}", flush=True) + results[f"{method}:{phase}"] = run_one(protocol, output, method, phase) + verify_inputs(protocol, Path(protocol["runner_root"])) + (output / "completed-profiles.json").write_text(json.dumps(results, indent=2) + "\n") + print(f"VERIFIED {method} {phase}", flush=True) + if sha256(Path(__file__)) != protocol["orchestrator_sha256"]: + raise ValueError("resource orchestrator changed during execution") + receipt = { + "schema": "moli_linux_resource_profiles_receipt/1", + "protocol_sha256": sha256(protocol_path), + "orchestrator_sha256": sha256(Path(__file__)), + "results": results, + } + (output / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n") + print(json.dumps(receipt), flush=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--protocol", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + options = parser.parse_args() + execute(options.protocol, options.output) diff --git a/scripts/moli_report/summarize_linux_resource_profiles.py b/scripts/moli_report/summarize_linux_resource_profiles.py new file mode 100644 index 000000000..7e4f88ad2 --- /dev/null +++ b/scripts/moli_report/summarize_linux_resource_profiles.py @@ -0,0 +1,271 @@ +"""Verify complete Linux profiles and aggregate the frozen resource populations.""" + +from __future__ import annotations + +import argparse +import collections +import importlib +import json +import math +import statistics +import sys +from pathlib import Path + +from .run_linux_resource_profiles import sha256 + + +def stats(values: list[float]) -> dict: + if not values or any(not math.isfinite(v) or v < 0 for v in values): + raise ValueError("missing or invalid resource measurement") + return { + "n": len(values), + "sum": math.fsum(values), + "mean": statistics.mean(values), + "p50": statistics.median(values), + "p95": statistics.quantiles(values, n=20, method="inclusive")[18], + "min": min(values), + "max": max(values), + } + + +def summarize(directory: Path) -> dict: + protocol_path, receipt_path = directory / "protocol.json", directory / "receipt.json" + protocol = json.loads(protocol_path.read_text()) + receipt = json.loads(receipt_path.read_text()) + if ( + protocol["schema"] != "moli_linux_resource_profiles/1" + or receipt["schema"] != "moli_linux_resource_profiles_receipt/1" + or receipt["protocol_sha256"] != sha256(protocol_path) + or receipt["orchestrator_sha256"] != sha256(directory / "orchestrator.py") + or protocol["orchestrator_sha256"] != receipt["orchestrator_sha256"] + or protocol["memory_metric"] != "process_tree_pss" + or protocol["attempts"] != 5 + or protocol["jobs"] != 1 + or len(protocol["task_ids"]) != 557 + or len(protocol["configs"]) != 4 + or set(receipt["results"]) + != { + f"{method}:{phase}" + for method in protocol["configs"] + for phase in ("baseline", "engine") + } + ): + raise ValueError("incomplete or changed resource protocol") + runner = Path(protocol["runner_root"]) + for name, expected_hash in protocol["input_files"].items(): + if sha256(runner / name) != expected_hash: + raise ValueError(f"resource runner changed: {name}") + sys.path.insert(0, str(runner)) + calibrate = importlib.import_module("runner.resources").duration_calibration + expected = {(task, attempt) for task in protocol["task_ids"] for attempt in range(1, 6)} + chart = {(item["task_id"], item["attempt"]) for item in protocol["chart_keys"]} + chart_tasks = {task for task, _ in chart} + if ( + len(expected) != 2785 + or len(chart) != len(protocol["chart_keys"]) + or len(chart) != 1045 + or len(chart_tasks) != 209 + or chart != {(task, attempt) for task in chart_tasks for attempt in range(1, 6)} + or not chart.issubset(expected) + ): + raise ValueError("resource population mismatch") + configurations = {} + measurements = {} + for method, config in protocol["configs"].items(): + rows_by_phase, manifests, hosts = {}, {}, {} + for phase in ("baseline", "engine"): + binding = receipt["results"][f"{method}:{phase}"] + run = directory / binding["run_id"] + if run.resolve().parent != directory.resolve() or run.is_symlink(): + raise ValueError("invalid resource run directory") + for filename, key in ( + ("run_manifest.json", "run_manifest_sha256"), + ("results.jsonl", "results_sha256"), + ("host_summary.json", "host_summary_sha256"), + ): + if sha256(run / filename) != binding[key]: + raise ValueError("resource run changed after completion") + manifest = json.loads((run / "run_manifest.json").read_text()) + rows = [json.loads(line) for line in (run / "results.jsonl").read_text().splitlines()] + if ( + manifest["completion_status"] != "completed" + or manifest["resource_profile"]["mode"] != phase + or manifest["k_runs"] != 5 + or manifest["runner"]["jobs"] != 1 + or collections.Counter((r["task_id"], r["attempt"]) for r in rows) + != collections.Counter(expected) + ): + raise ValueError("resource run does not match the frozen scope") + for row in rows: + identity = row["engine_provenance"] + if ( + identity["binary_sha256"] != config["sha256"] + or identity["layout_enabled"] != (config["layout"] == "on") + or ("--layout" in identity["launch_command"]) != (config["layout"] == "on") + ): + raise ValueError("resource build or layout mismatch") + rows_by_phase[phase] = rows + manifests[phase] = manifest + hosts[phase] = json.loads((run / "host_summary.json").read_text()) + rows = rows_by_phase["engine"] + by_key = {(r["task_id"], r["attempt"]): r for r in rows} + if any( + row["resource"].get("pss_peak_bytes") is None + or row["resource"].get("sample_interval_ms") != 250 + or row["resource"].get("measurement_backend", {}).get("memory_pss") + != "proc_smaps_rollup" + or row["resource"].get("measurement_backend", {}).get("cpu") != "proc_tree" + for row in rows + ): + raise ValueError("missing PSS or changed sampling interval") + metrics = {} + for population, keys in ( + ("all_predeclared_calls", expected), + ("frozen_historical_common_pass_calls", chart), + ): + metrics[population] = { + name: stats([by_key[key]["resource"][field] / scale for key in sorted(keys)]) + for name, field, scale in ( + ("pss_peak_mib", "pss_peak_bytes", 1024**2), + ("cpu_time_ms", "cpu_total_ms", 1), + ) + } + calibration = calibrate( + rows, + rows_by_phase["baseline"], + protocol["max_observer_effect_pct"], + profiled_manifest=manifests["engine"], + baseline_manifest=manifests["baseline"], + ) + configurations[method] = { + "build": {key: value for key, value in config.items() if key != "binary"}, + "metrics": metrics, + "calibration": calibration, + "host": hosts, + "publishable": bool(calibration["acceptable"]) + and all(not h.get("polluted", True) for h in hosts.values()), + } + measurements[method] = [ + { + "task_id": row["task_id"], + "attempt": row["attempt"], + "status": row["status"], + "resource": { + key: row["resource"][key] + for key in ( + "pss_peak_bytes", + "cpu_total_ms", + "measurement_backend", + "sample_interval_ms", + "samples_seen", + "quality_flags", + ) + }, + } + for row in rows + ] + return { + "schema": "moli_linux_resource_summary/1", + "protocol_sha256": sha256(protocol_path), + "receipt_sha256": sha256(receipt_path), + "protocol": protocol, + "receipt": receipt, + "population": { + "task_ids": protocol["task_ids"], + "chart_keys": protocol["chart_keys"], + "attempts_per_task": 5, + }, + "configurations": configurations, + "measurements": measurements, + "publishable": all(c["publishable"] for c in configurations.values()), + } + + +def validate_summary(summary: dict, builds: dict) -> None: + """Verify the public values against every retained call, without local files.""" + population = summary["population"] + expected = {(task, attempt) for task in population["task_ids"] for attempt in range(1, 6)} + chart = {(r["task_id"], r["attempt"]) for r in population["chart_keys"]} + receipt = summary["receipt"] + if ( + summary["schema"] != "moli_linux_resource_summary/1" + or summary["publishable"] is not True + or population["attempts_per_task"] != 5 + or len(population["task_ids"]) != 557 + or len(expected) != 2785 + or len(chart) != len(population["chart_keys"]) + or len(chart) != 1045 + or len({task for task, _ in chart}) != 209 + or not chart.issubset(expected) + or list(summary["configurations"]) != list(builds) + or len(builds) != 4 + or set(summary["measurements"]) != set(builds) + or receipt["schema"] != "moli_linux_resource_profiles_receipt/1" + or receipt["protocol_sha256"] != summary["protocol_sha256"] + or set(receipt["results"]) + != {f"{method}:{phase}" for method in builds for phase in ("baseline", "engine")} + or any(run["rows"] != 2785 for run in receipt["results"].values()) + ): + raise ValueError("incomplete Linux resource summary") + for method, build in builds.items(): + config = summary["configurations"][method] + if ( + any(config["build"].get(key) != value for key, value in build.items()) + or config["build"]["target"] != "aarch64-unknown-linux-gnu" + or config["build"]["profile"] != "release" + or config["publishable"] is not True + or config["calibration"]["acceptable"] is not True + or config["calibration"]["complete_pairing"] is not True + or set(config["host"]) != {"baseline", "engine"} + or any(host.get("polluted", True) for host in config["host"].values()) + ): + raise ValueError("Linux resource identity or calibration mismatch") + rows = summary["measurements"][method] + by_key = {(r["task_id"], r["attempt"]): r for r in rows} + if len(rows) != len(by_key) or set(by_key) != expected: + raise ValueError("partial or duplicated Linux resource calls") + for row in rows: + resource = row["resource"] + if ( + resource["measurement_backend"]["memory_pss"] != "proc_smaps_rollup" + or resource["measurement_backend"]["cpu"] != "proc_tree" + or resource["sample_interval_ms"] != 250 + or any( + isinstance(resource[key], bool) + or not isinstance(resource[key], (int, float)) + or not math.isfinite(resource[key]) + or resource[key] < 0 + for key in ("pss_peak_bytes", "cpu_total_ms") + ) + ): + raise ValueError("invalid Linux resource measurement") + for scope, keys in ( + ("all_predeclared_calls", expected), + ("frozen_historical_common_pass_calls", chart), + ): + for metric, field, scale in ( + ("pss_peak_mib", "pss_peak_bytes", 1024**2), + ("cpu_time_ms", "cpu_total_ms", 1), + ): + measured = stats([by_key[key]["resource"][field] / scale for key in sorted(keys)]) + reported = config["metrics"][scope][metric] + if any( + not math.isclose(value, reported[key], rel_tol=1e-9, abs_tol=1e-6) + for key, value in measured.items() + ): + raise ValueError("Linux resource aggregate differs from the recorded calls") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--directory", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + result = summarize(args.directory) + with args.output.open("x") as output: + output.write(json.dumps(result, indent=2) + "\n") + print( + json.dumps( + {"publishable": result["publishable"], "methods": list(result["configurations"])} + ) + ) diff --git a/scripts/moli_report/ui_check.js b/scripts/moli_report/ui_check.js index e12679be1..e16a2ed7f 100644 --- a/scripts/moli_report/ui_check.js +++ b/scripts/moli_report/ui_check.js @@ -19,6 +19,9 @@ const fs = require("fs"); const model = JSON.parse( fs.readFileSync(path.join(site, "data/model.json"), "utf8"), ); +const expectedMetricGroups = + new Set(model.combined_comparison.configurations.map((row) => row.platform)) + .size * 2; const successId = model.cases.find( (c) => c.on_passes === model.protocol.k_runs, ).id; @@ -128,10 +131,16 @@ async function fixedMetrics(page) { } return groups; }); - if (Object.keys(groups).length !== 12) throw Error("macOS metric coverage"); + if (Object.keys(groups).length !== 12) + throw Error("resource metric coverage"); for (let cells of Object.values(groups)) { - if (cells.length !== fixedIds.length) - throw Error("macOS participant coverage"); + if ( + cells.length !== + (model.resource_metrics + ? model.functional_methods.length + : fixedIds.length) + ) + throw Error("resource participant coverage"); let min = Math.min(...cells.map((x) => x.value)), unique = cells.filter((x) => x.value === min).length === 1; for (let cell of cells) @@ -196,12 +205,16 @@ async function run() { if (route === "method") { await page.locator(".mermaid svg").waitFor({ timeout: 10000 }); } - if (["home", "guide"].includes(route) && model.macos_resource) + if ( + ["home", "guide"].includes(route) && + (model.macos_resource || model.linux_resource_profiles) + ) await fixedMetrics(page); if (route === "home") { await caseMetric(page); let n = await metrics(page); - if (n !== 4) throw Error("missing grouped resource metrics"); + if (n !== expectedMetricGroups) + throw Error("missing grouped resource metrics"); let chart = page.locator(".summary-chart img"); if ( (await chart.count()) !== 1 || @@ -324,7 +337,7 @@ async function run() { await page.reload(); await ready(page); let baseline = await metrics(page); - if (baseline !== 4) throw Error("metric coverage"); + if (baseline !== expectedMetricGroups) throw Error("metric coverage"); let cell = page.locator(".winner[data-combined-metric]").first(); await cell.evaluate((el) => el.classList.remove("winner")); let wrongRejected = false; @@ -356,7 +369,7 @@ async function run() { if (!shiftedRejected) throw Error("wrong-highlight negative control"); await page.reload(); await ready(page); - let tied = page.locator("[data-combined-metric]").first(); + let tied = page.locator(".winner[data-combined-metric]").first(); await tied.evaluate((el) => { let other = [...document.querySelectorAll("[data-combined-metric]")].find( (x) => @@ -523,11 +536,18 @@ async function run() { ) throw Error("fixed case explorer coverage"); } - if (model.resource_matrix) { + const resourceEvidence = + model.linux_resource_profiles || model.resource_matrix; + if (resourceEvidence) { for (const entry of urls) { for (const [route, target] of [ - ["guide", model.resource_matrix.evidence.url], - ["reproduce", "reproduction/run_resource_matrix.py"], + ["guide", resourceEvidence.evidence.url], + [ + "reproduce", + model.linux_resource_profiles + ? "reproduction/run_linux_resource_profiles.py" + : "reproduction/run_resource_matrix.py", + ], ]) { await page.goto(entry + "#page=" + route); await ready(page); @@ -547,8 +567,9 @@ async function run() { if (route === "guide") { const matrix = JSON.parse(raw); if ( + !model.linux_resource_profiles && matrix.calls.length !== - model.resource_matrix.receipt.physical_calls + model.resource_matrix.receipt.physical_calls ) throw Error("resource matrix call coverage"); for (const id of Object.keys(model.resource_builds)) @@ -570,7 +591,7 @@ async function run() { route_theme_viewport_checks: checked, negative_controls: 6, evidence_flows: - (fixedPass && fixedFail ? 6 : 4) + (model.resource_matrix ? 4 : 0), + (fixedPass && fixedFail ? 6 : 4) + (resourceEvidence ? 4 : 0), result: "pass", }), ); diff --git a/scripts/moli_report/verify.py b/scripts/moli_report/verify.py index eb3c2e7fc..0ea11329a 100644 --- a/scripts/moli_report/verify.py +++ b/scripts/moli_report/verify.py @@ -15,6 +15,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from moli_report.resource_evidence import validate_matrix # noqa: E402 +from moli_report.summarize_linux_resource_profiles import validate_summary # noqa: E402 from plot_moli_version_resources import combine_comparisons, render_chart # noqa: E402 parser = argparse.ArgumentParser() @@ -45,6 +46,17 @@ def fail(message): def validate(model, site, check_files=True): if model.get("schema") != "moli_layout_report/2": fail("schema") + if any( + model.get(key) for key in ("linux_resource_profiles", "macos_resource", "official_resource") + ): + if not isinstance(model.get("resource_builds"), dict): + fail("resource_builds missing") + if model.get("macos_resource") or model.get("official_resource"): + for key in ("macos_resource", "official_resource"): + if not isinstance(model.get(key), dict) or not isinstance( + model[key].get("summary"), dict + ): + fail(f"{key} summary missing") count = model.get("task_count") calls_per_mode = model.get("attempts_per_mode") if not isinstance(count, int) or count != 372 or calls_per_mode != count * 3: @@ -148,7 +160,9 @@ def validate(model, site, check_files=True): functional_methods = model.get("functional_methods") or [] combined = model.get("combined_comparison") if combined != combine_comparisons( - functional_methods, comparison, model.get("macos_comparison") + functional_methods, + comparison, + model.get("linux_comparison") or model.get("macos_comparison"), ): fail("combined chart registry, baseline or measurement mismatch") if json.loads((site / "data/combined-comparison.json").read_text()) != combined: @@ -260,6 +274,77 @@ def validate(model, site, check_files=True): or target.stat().st_size != evidence["bytes"] ): fail("fixed log integrity") + if model.get("linux_comparison") and not model.get("linux_resource_profiles"): + fail("Linux resource evidence is required") + if model.get("linux_resource_profiles"): + profiles = model["linux_resource_profiles"] + + def resource_document(info): + path = site / info["url"] + if ( + not path.resolve().is_relative_to(site.resolve()) + or path.is_symlink() + or not path.is_file() + or digest(path) != info["sha256"] + or path.stat().st_size != info["bytes"] + ): + fail("Linux resource evidence integrity") + return json.loads(path.read_text()) + + summary = resource_document(profiles["evidence"]) + validate_summary(summary, model["resource_builds"]) + if ( + summary["protocol"]["reference_protocol_sha256"] + != comparison["bindings"]["resource_protocol_sha256"] + or summary["protocol"]["task_ids"] != summary["population"]["task_ids"] + or summary["protocol"]["chart_keys"] != summary["population"]["chart_keys"] + or summary["protocol"]["orchestrator_sha256"] + != profiles["receipt"]["orchestrator_sha256"] + ): + fail("Linux resource protocol or comparison population binding") + if ( + profiles["configurations"] != summary["configurations"] + or profiles["receipt"] != summary["receipt"] + ): + fail("Linux resource summary binding") + script = site / "reproduction/run_linux_resource_profiles.py" + if script.is_symlink() or digest(script) != profiles["receipt"]["orchestrator_sha256"]: + fail("Linux resource script binding") + original = resource_document(model["resource_metrics_source"]) + metrics = model["resource_metrics"] + if list(metrics) != [m["id"] for m in functional_methods]: + fail("unified resource method registry") + for method, scopes in metrics.items(): + if set(scopes) != {"all_predeclared_calls", "frozen_historical_common_pass_calls"}: + fail("unified resource population coverage") + for scope, values in scopes.items(): + expected = ( + summary["configurations"][method]["metrics"][scope] + if method in summary["configurations"] + else original["memory"][method][scope] + ) + for metric in ("pss_peak_mib", "cpu_time_ms"): + for stat in ("n", "mean", "p50", "p95"): + key = "median" if stat == "p50" and "median" in expected[metric] else stat + if not near(values[metric][stat], expected[metric][key]): + fail("unified resource table differs from measurements") + rows = model["linux_comparison"]["configurations"] + if [r["id"] for r in rows] != list(model["resource_builds"]): + fail("Linux resource chart registry") + for row in rows: + candidate = candidates[row["id"]] + measured = summary["configurations"][row["id"]] + values = measured["metrics"]["frozen_historical_common_pass_calls"] + if ( + row["platform"] != "Linux" + or row["memory_kind"] != "PSS" + or row["passed_cases"] != candidate["outcomes"]["passed_cases"] + or row["functional_binary_sha256"] != candidate["binary"]["moli_sha256"] + or row["resource_binary_sha256"] != measured["build"]["sha256"] + or not near(row["pss_mib"], values["pss_peak_mib"]["p50"]) + or not near(row["cpu_ms"], values["cpu_time_ms"]["mean"]) + ): + fail("Linux resource chart values or build identity") for resource_key in ("macos_resource", "official_resource"): resource = model.get(resource_key) if not resource: @@ -396,6 +481,8 @@ def validate(model, site, check_files=True): if model.get("macos_resource"): if not chart or {r["id"] for r in chart["configurations"]} != set(candidates): fail("macOS chart registry") + if chart.get("baseline") not in {r["id"] for r in chart["configurations"]}: + fail("macOS chart baseline not in configurations") baseline = next(r for r in chart["configurations"] if r["id"] == chart["baseline"]) for row in chart["configurations"]: resource = ( @@ -728,11 +815,12 @@ def validate(model, site, check_files=True): if [row["id"] for row in model["functional_methods"]] != profile["method_ids"]: fail("release requires the complete bound functional method matrix") if ( - not model.get("macos_comparison") - or [row["id"] for row in model["macos_comparison"]["configurations"]] - != profile["macos_method_ids"] + not model.get("linux_comparison") + or [row["id"] for row in model["linux_comparison"]["configurations"]] + != profile["resource_method_ids"] + or not model.get("linux_resource_profiles") ): - fail("release requires all bound macOS resource configurations") + fail("release requires all bound Linux resource configurations") validate(model, SITE) # Semantic negative controls must fail through the same validator. negative_controls = 0 @@ -774,9 +862,27 @@ def rejected(change): rejected(lambda m: m["functional_contract_correction"].update(calls=17)) rejected(lambda m: m["functional_contract_correction"].update(success_rates_changed=True)) if model.get("resource_matrix"): + rejected(lambda m: m.pop("resource_builds")) + rejected(lambda m: m["official_resource"].pop("summary")) + rejected(lambda m: m["macos_comparison"].update(baseline="absent")) rejected(lambda m: m.pop("resource_matrix")) rejected(lambda m: m["resource_matrix"]["receipt"].update(physical_calls=11139)) rejected(lambda m: m["resource_builds"]["119_on"].update(sha256="0" * 64)) +if model.get("linux_resource_profiles"): + rejected(lambda m: m.pop("resource_builds")) + rejected(lambda m: m.pop("linux_resource_profiles")) + rejected(lambda m: m["resource_builds"]["119_on"].update(sha256="0" * 64)) + rejected(lambda m: m["resource_metrics"].pop("114_off")) + rejected( + lambda m: m["resource_metrics"]["119_on"]["all_predeclared_calls"]["pss_peak_mib"].update( + mean=0 + ) + ) + rejected( + lambda m: m["linux_resource_profiles"]["configurations"]["119_on"]["calibration"].update( + acceptable=False + ) + ) if model.get("fixed_candidates"): rejected( lambda m: m["functional_methods"][-1].update( diff --git a/scripts/plot_moli_version_resources.py b/scripts/plot_moli_version_resources.py index 3e9ccb6db..588b23211 100644 --- a/scripts/plot_moli_version_resources.py +++ b/scripts/plot_moli_version_resources.py @@ -18,11 +18,18 @@ COLOR_RE = re.compile(r"#[0-9a-fA-F]{6}") -def combine_comparisons(methods: list[dict], historical: dict, macos: dict | None) -> dict: +def combine_comparisons(methods: list[dict], historical: dict, current: dict | None) -> dict: """Keep registry order and baseline while separating unlike resource measurements.""" sources = {row["id"]: (row, "Linux", "PSS") for row in historical["configurations"]} sources.update( - {row["id"]: (row, "macOS", "RSS") for row in (macos or {}).get("configurations", [])} + { + row["id"]: ( + row, + row.get("platform", "macOS"), + row.get("memory_kind", "RSS"), + ) + for row in (current or {}).get("configurations", []) + } ) baseline = sources[historical["baseline"]][0] rows = [] @@ -37,10 +44,16 @@ def combine_comparisons(methods: list[dict], historical: dict, macos: dict | Non platform=platform, memory_kind=memory_kind, memory_mib=source[f"{memory_kind.lower()}_mib"], - memory_change_pct=source["pss_change_pct"] if platform == "Linux" else None, - cpu_change_pct=source["cpu_change_pct"] if platform == "Linux" else None, + memory_change_pct=(source["pss_mib"] / baseline["pss_mib"] - 1) * 100 + if platform == "Linux" and memory_kind == "PSS" + else None, + cpu_change_pct=(source["cpu_ms"] / baseline["cpu_ms"] - 1) * 100 + if platform == "Linux" + else None, color=COLORS[index % len(COLORS)], ) + if memory_kind == "PSS": + row["pss_change_pct"] = row["memory_change_pct"] row["success_change_pp"] = row["success_rate_pct"] - baseline["success_rate_pct"] rows.append(row) return { @@ -171,14 +184,17 @@ def render_chart( "on": "on", }, }[language] - if "memory" in metrics: + mixed = len({(row.get("platform"), row.get("memory_kind")) for row in rows}) > 1 + labelled = all("success_change_pp" in row for row in rows) + if "memory" in metrics and not mixed: + text["memory"] = text[rows[0].get("memory_kind", "PSS").lower()] + if "memory" in metrics and mixed: text["subtitle"] = ( text["subtitle"] .replace("越靠左资源消耗越低", "不同平台资源分别解释") .replace("farther left is lower", "platform-specific resources") ) width = 1420 if len(metrics) == 2 else 820 - mixed = any(row.get("platform") for row in rows) separate_builds = { row["id"] for row in rows @@ -186,7 +202,7 @@ def render_chart( and row.get("resource_binary_sha256") and row["functional_binary_sha256"] != row["resource_binary_sha256"] } - note_height = (48 if mixed else 0) + (24 if separate_builds else 0) + note_height = (24 if labelled else 0) + (24 if mixed else 0) + (24 if separate_builds else 0) height = 700 + 30 * len(rows) + note_height left, right, top, bottom = 105, 55, 145, 115 + 30 * len(rows) gap = 90 @@ -274,19 +290,21 @@ def render_chart( f'text-anchor="middle">{value:.1f}' ) plotted: list[tuple[float, float]] = [] + for row in rows: + px = _scale(float(row[key]), low, high, x0, x1) + py = _scale(float(row["success_rate_pct"]), 0, y_max, chart_bottom, top) + for dx, dy in offsets: + candidate = (px + dx, py + dy) + if all(math.hypot(candidate[0] - x, candidate[1] - y) >= 27 for x, y in plotted): + break + plotted.append(candidate) markers = [] + annotations = [] + label_boxes = [] for row_index, row in enumerate(rows, 1): exact_x = _scale(float(row[key]), low, high, x0, x1) exact_y = _scale(float(row["success_rate_pct"]), 0, y_max, chart_bottom, top) - x, y = exact_x, exact_y - for dx, dy in offsets: - candidate = (exact_x + dx, exact_y + dy) - if all( - math.hypot(candidate[0] - px, candidate[1] - py) >= 27 for px, py in plotted - ): - x, y = candidate - break - plotted.append((x, y)) + x, y = plotted[row_index - 1] color = row_colors[row["id"]] number = row_index if (x, y) != (exact_x, exact_y): @@ -308,6 +326,51 @@ def render_chart( f'{number}' ) + if labelled: + name = ( + row["label" if language == "zh" else "label_en"] + .removeprefix("Moli ") + .split(" · ")[0] + ) + if row["id"].endswith("_on"): + name += " ✦" + if row["id"] in separate_builds: + name += " †" + delta = row[change_key] + change = "—" if delta is None else f"{float(delta):+.2f}%" + detail = f"{row['success_change_pp']:+.2f} pp / {change}" + box_w, box_h = 182, 46 + # Place readable labels near the true data point, avoiding previous labels. + candidates = [] + for dy in (-58, -112, -166, 22, 76, 130): + for dx in (-box_w / 2, 18, -box_w - 18): + bx = min(max(exact_x + dx, x0 + 4), x1 - box_w - 4) + by = min(max(exact_y + dy, top + 6), chart_bottom - box_h - 6) + overlap = sum( + max(0, min(bx + box_w + 8, px + pw) - max(bx - 8, px)) + * max(0, min(by + box_h + 8, py + ph) - max(by - 8, py)) + for px, py, pw, ph in label_boxes + + [(x - 20, y - 20, 40, 40) for x, y in plotted] + ) + distance = math.hypot(bx + box_w / 2 - exact_x, by + box_h / 2 - exact_y) + candidates.append((overlap * 1000 + distance, bx, by)) + _, bx, by = min(candidates) + label_boxes.append((bx, by, box_w, box_h)) + anchor_x = min(max(exact_x, bx), bx + box_w) + anchor_y = min(max(exact_y, by), by + box_h) + annotations.append( + f'' + f'' + f'' + f'' + f"{html.escape(name)}" + f'{html.escape(detail)}' + ) + parts.extend(annotations) parts.extend(markers) legend_y = chart_bottom + 82 for index, row in enumerate(rows): @@ -316,22 +379,28 @@ def render_chart( if language == "en": label_key += "_en" row_label = row[label_key] + if labelled: + row_label = row_label.removeprefix("Moli ").split(" · ")[0] + if row["id"].endswith("_on"): + row_label += " ✦" if row["id"] in separate_builds: row_label += " †" fields = [ f"{int(float(row['passed_cases']))}/{total_cases} " f"({float(row['success_rate_pct']):.1f}%)" ] - if mixed: - fields.append( - f"{row['success_change_pp']:+.2f} " + ("百分点" if language == "zh" else "pp") - ) for metric in metrics: _, key, change_key, unit = specs[metric] change = row[change_key] delta = f"{float(change):+.2f}%" if change is not None else "—" - prefix = f"{row['platform']} {row['memory_kind']} " if metric == "memory" else "" - fields.append(f"{prefix}{float(row[key]):.2f} {unit} ({delta})") + prefix = ( + f"{row['platform']} {row['memory_kind']} " + if mixed and metric == "memory" + else "" + ) + fields.append( + f"{prefix}{float(row[key]):.2f} {unit}" + ("" if labelled else f" ({delta})") + ) y = legend_y + index * 30 parts.append(f'') parts.append( @@ -343,20 +412,25 @@ def render_chart( f"{html.escape(row_label + ': ' + ' · '.join(fields))}" ) notes = [] - if mixed: + if labelled: notes = ( [ - "基线:1.1.4 关闭 layout;成功率变化用百分点表示。圆形:Linux;菱形:macOS。", - "PSS 与 RSS、不同平台 CPU 不直接比较;跨平台资源变化不计算(—)。", + "点旁:方法名;通过率变化(pp)/ 资源变化(%)。" + "✦ 开启 layout;其余关闭。基线:1.1.4 关闭。", ] if language == "zh" else [ - "Baseline: 1.1.4 layout off; success changes in pp. " - "Circles: Linux; diamonds: macOS.", - "PSS vs. RSS and cross-platform CPU are not directly comparable; " - "resource changes: —.", + "Labels: method; success change (pp) / resource change (%). " + "✦ Layout on; otherwise off. Baseline: 1.1.4 off.", ] ) + if mixed: + notes.append( + "圆形:Docker Linux(PSS);菱形:原生 macOS(RSS)。不同执行环境不计算资源涨幅(—)。" + if language == "zh" + else "Circles: Docker Linux (PSS); diamonds: native macOS (RSS). " + "Resource changes across environments: —." + ) if separate_builds: notes.append( "† 功能与资源使用不同构建;成功率仅适用于功能构建,身份见报告。" diff --git a/tests/moli_report_render_contract.cjs b/tests/moli_report_render_contract.cjs index 051110d3d..bcd368f54 100644 --- a/tests/moli_report_render_contract.cjs +++ b/tests/moli_report_render_contract.cjs @@ -186,6 +186,58 @@ for (const lang of ["zh", "en"]) { ); } +const linuxModel = { + ...sevenModel, + resource_metrics_source: { + url: "data/earlier-versions.json", + sha256: "b".repeat(64), + }, + resource_metrics: Object.fromEntries( + sevenIds.map((id, i) => [ + id, + Object.fromEntries( + [ + ["all_predeclared_calls", 2785], + ["frozen_historical_common_pass_calls", 1045], + ].map(([scope, n]) => [ + scope, + { pss_peak_mib: stat(n, 100 + i * 10), cpu_time_ms: stat(n, 50 - i) }, + ]), + ), + ]), + ), + linux_resource_profiles: { + evidence: { url: "data/linux.json", sha256: "a".repeat(64) }, + }, +}; +for (const lang of ["zh", "en"]) { + const html = render(linuxModel, lang, "candidateResourceSection()"); + resourceHighlights(html); + assert.deepEqual( + [...html.matchAll(/data-resource-method="([^"]+)"/g)].map((m) => m[1]), + [...sevenIds, ...sevenIds], + ); + assert.ok(html.includes("+60.00%")); + assert.ok(html.includes("-12.00%")); + assert.ok(!html.includes("RSS")); + assert.ok(html.includes("PSS")); + assert.throws(() => resourceHighlights(html.replace("num winner", "num"))); + assert.throws(() => + resourceHighlights( + html.replace( + 'class="num " data-resource-metric', + 'class="num winner" data-resource-metric', + ), + ), + ); + const summary = render(linuxModel, lang, "functionalMethodSummary()"); + assert.ok( + !summary.includes( + lang === "zh" ? "执行环境不同" : "incompatible execution", + ), + ); +} + if (site) { const measured = JSON.parse( fs.readFileSync(path.join(site, "data/model.json"), "utf8"), @@ -205,7 +257,7 @@ if (site) { ); assert.ok(!html.includes("undefined")); } - if (measured.macos_resource) { + if (measured.macos_resource || measured.linux_resource_profiles) { for (let page of ["home()", "guidePage()"]) { const html = render(measured, lang, page); resourceHighlights(html); diff --git a/tests/test_moli_linux_resource_profiles.py b/tests/test_moli_linux_resource_profiles.py new file mode 100644 index 000000000..e86b76883 --- /dev/null +++ b/tests/test_moli_linux_resource_profiles.py @@ -0,0 +1,66 @@ +import copy +import unittest +from pathlib import Path + +from scripts.moli_report import run_linux_resource_profiles as profiles + + +class LinuxResourceProfileTests(unittest.TestCase): + def setUp(self): + self.source = Path(profiles.__file__) + configs = { + name: { + "layout": layout, + "target": "aarch64-unknown-linux-gnu", + "profile": "release", + "sha256": "a" * 64, + } + for name, layout in ( + ("official_off", "off"), + ("official_on", "on"), + ("fixed_off", "off"), + ("fixed_on", "on"), + ) + } + self.protocol = { + "schema": "moli_linux_resource_profiles/1", + "configs": configs, + "task_ids": [f"task_{i}" for i in range(557)], + "attempts": 5, + "jobs": 1, + "sample_interval_ms": 250, + "memory_metric": "process_tree_pss", + "orchestrator_sha256": profiles.sha256(self.source), + "order": [ + *[[name, "baseline"] for name in configs], + *[[name, "engine"] for name in reversed(configs)], + ], + } + + def test_complete_official_resource_scope_is_accepted(self): + profiles.validate_protocol(self.protocol, self.source) + + def test_partial_scope_parallel_execution_and_changed_collector_are_rejected(self): + for field, value in ( + ("task_ids", self.protocol["task_ids"][:-1]), + ("task_ids", ["duplicate"] * 557), + ("attempts", 3), + ("jobs", 2), + ("memory_metric", "process_tree_rss"), + ("sample_interval_ms", 500), + ("orchestrator_sha256", "b" * 64), + ): + candidate = {**self.protocol, field: value} + with self.subTest(field=field), self.assertRaises(ValueError): + profiles.validate_protocol(candidate, self.source) + + def test_missing_calibration_or_native_macos_build_is_rejected(self): + candidate = copy.deepcopy(self.protocol) + candidate["order"] = candidate["order"][1:] + with self.assertRaises(ValueError): + profiles.validate_protocol(candidate, self.source) + for field, value in (("target", "aarch64-apple-darwin"), ("profile", "debug")): + candidate = copy.deepcopy(self.protocol) + candidate["configs"]["fixed_on"][field] = value + with self.subTest(field=field), self.assertRaises(ValueError): + profiles.validate_protocol(candidate, self.source) diff --git a/tests/test_moli_linux_resource_summary.py b/tests/test_moli_linux_resource_summary.py new file mode 100644 index 000000000..fe59709cd --- /dev/null +++ b/tests/test_moli_linux_resource_summary.py @@ -0,0 +1,97 @@ +import copy +import unittest + +from scripts.moli_report.summarize_linux_resource_profiles import validate_summary + + +class LinuxResourceSummaryTests(unittest.TestCase): + def setUp(self): + tasks = [f"task_{i}" for i in range(557)] + chart = [{"task_id": t, "attempt": a} for t in tasks[:209] for a in range(1, 6)] + self.builds = { + name: { + "sha256": str(i) * 64, + "target": "aarch64-unknown-linux-gnu", + "profile": "release", + } + for i, name in enumerate(("official_off", "official_on", "fixed_off", "fixed_on")) + } + configurations, measurements = {}, {} + for i, (name, build) in enumerate(self.builds.items()): + measurements[name] = [ + { + "task_id": t, + "attempt": a, + "resource": { + "pss_peak_bytes": (100 + i) * 1024**2, + "cpu_total_ms": 10 + i, + "measurement_backend": { + "memory_pss": "proc_smaps_rollup", + "cpu": "proc_tree", + }, + "sample_interval_ms": 250, + }, + } + for t in tasks + for a in range(1, 6) + ] + configurations[name] = { + "build": build, + "publishable": True, + "calibration": {"acceptable": True, "complete_pairing": True}, + "host": {"baseline": {"polluted": False}, "engine": {"polluted": False}}, + "metrics": { + scope: { + metric: { + "n": n, + "sum": n * value, + "mean": value, + "p50": value, + "p95": value, + "min": value, + "max": value, + } + for metric, value in (("pss_peak_mib", 100 + i), ("cpu_time_ms", 10 + i)) + } + for scope, n in ( + ("all_predeclared_calls", 2785), + ("frozen_historical_common_pass_calls", 1045), + ) + }, + } + self.summary = { + "schema": "moli_linux_resource_summary/1", + "publishable": True, + "protocol_sha256": "a" * 64, + "population": {"task_ids": tasks, "chart_keys": chart, "attempts_per_task": 5}, + "configurations": configurations, + "measurements": measurements, + "receipt": { + "schema": "moli_linux_resource_profiles_receipt/1", + "protocol_sha256": "a" * 64, + "results": { + f"{m}:{p}": {"rows": 2785} for m in self.builds for p in ("baseline", "engine") + }, + }, + } + + def test_complete_measurements_reproduce_both_population_statistics(self): + validate_summary(self.summary, self.builds) + + def test_missing_duplicate_or_changed_measurements_are_rejected(self): + for mutation in ( + lambda s: s["measurements"]["fixed_on"].pop(), + lambda s: s["measurements"]["fixed_on"].append(s["measurements"]["fixed_on"][0]), + lambda s: s["measurements"]["fixed_on"][0]["resource"].update(cpu_total_ms=99999), + lambda s: s["measurements"]["fixed_on"][0]["resource"]["measurement_backend"].update( + memory_pss="darwin_ps_process_tree_rss" + ), + lambda s: s["configurations"]["fixed_on"]["calibration"].update(acceptable=False), + lambda s: s["configurations"]["fixed_on"]["host"].clear(), + lambda s: s["configurations"]["fixed_on"]["build"].update(profile="debug"), + lambda s: s["receipt"]["results"].pop("fixed_on:baseline"), + ): + changed = copy.deepcopy(self.summary) + mutation(changed) + with self.assertRaises(ValueError): + validate_summary(changed, self.builds) diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index 8064f6720..8c170c2c2 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -14,6 +14,37 @@ class MoliVersionResourceChartTests(unittest.TestCase): + def test_linux_release_results_use_one_baseline_and_keep_point_labels(self): + historical = {**self.data, "baseline": "114_off"} + row = { + **self.data["configurations"][0], + "id": "119_on", + "label": "Moli 1.1.9 修复版 · 开启 layout", + "label_en": "Moli 1.1.9 patched · Layout on", + "platform": "Linux", + "memory_kind": "PSS", + "pss_mib": self.data["configurations"][0]["pss_mib"] * 1.1, + "cpu_ms": self.data["configurations"][0]["cpu_ms"] * 0.8, + "passed_cases": 360, + } + methods = [ + {**item, "final_passed_cases": item["passed_cases"]} + for item in historical["configurations"] + [row] + ] + combined = MODULE.combine_comparisons(methods, historical, {"configurations": [row]}) + self.assertAlmostEqual(combined["configurations"][-1]["memory_change_pct"], 10) + self.assertAlmostEqual(combined["configurations"][-1]["cpu_change_pct"], -20) + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "linux.svg" + MODULE.render_chart(combined, output, ("memory", "cpu")) + chart = output.read_text() + self.assertEqual(chart.count("data-point-label="), 8) + self.assertIn("pp / +10.00%", chart) + self.assertIn("pp / -20.00%", chart) + self.assertIn("1.1.9 修复版 ✦", chart) + self.assertNotIn("RSS", chart) + self.assertNotIn("不同执行环境", chart) + def test_chart_marks_retained_success_from_a_different_resource_build(self): row = self.data["configurations"][1] row.update(functional_binary_sha256="a" * 64, resource_binary_sha256="b" * 64) @@ -72,7 +103,10 @@ def test_combined_chart_keeps_registry_order_and_baseline_without_cross_platform self.assertIn("macOS RSS", text) self.assertIn("360/372", text) self.assertIn("+96.77", text) - self.assertIn("(—)", text) + self.assertIn("pp / —", text) + self.assertEqual(text.count("data-point-label="), 14) + self.assertIn("1.1.8 ✦", text) + self.assertNotIn("MiB (+", text) self.assertEqual(text.count(' Date: Mon, 21 Sep 2026 21:19:58 +0800 Subject: [PATCH 27/29] Document fixed-only Moli runs and remove retry chart example --- scripts/moli_report/README.md | 2 ++ tests/test_moli_version_resource_chart.py | 12 ++++++------ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/scripts/moli_report/README.md b/scripts/moli_report/README.md index 2182d0043..ad1e6a53a 100644 --- a/scripts/moli_report/README.md +++ b/scripts/moli_report/README.md @@ -7,3 +7,5 @@ Resources use a separate 557-task experiment, five calls per task. Each configur All seven resource configurations run in Docker Linux on the Mac host, using Linux ARM64 release binaries and process-tree PSS and CPU measurements. Resource changes use Moli 1.1.4 with layout off as the baseline. Success-rate changes use percentage points. Functional results retain their own binary identities; patched functional outcomes use commit 87c87e95, while patched resource measurements use the f315ff26 release build. The report does not treat these resource runs as new accuracy measurements. Open index.html through a static HTTP server. Chinese and English routes share the same report model and evidence. Charts are rendered by the included Python script; memory and CPU panels can be selected independently. Per-task results retain exact program errors and sanitized grader, output, and protocol logs. + +New benchmark runs select a fixed `--moli-layout off` (default) or `--moli-layout on` for every attempt. Failed cases keep the selected layout and repetition count. The harness does not schedule layout recovery or replace results from a second batch. diff --git a/tests/test_moli_version_resource_chart.py b/tests/test_moli_version_resource_chart.py index 8c170c2c2..d6108a6e5 100644 --- a/tests/test_moli_version_resource_chart.py +++ b/tests/test_moli_version_resource_chart.py @@ -255,11 +255,11 @@ def test_future_configuration_is_rendered_without_code_changes(self): future = dict(self.data["configurations"][2]) future.update( { - "id": "pr640_try_layout", - "label": "Moli PR #640 · 失败后尝试 layout", - "label_en": "Moli PR #640 · try layout after failure", - "short_label": "PR #640 尝试布局", - "short_label_en": "PR #640 try layout", + "id": "120_on", + "label": "Moli 1.2.0 · 开启 layout", + "label_en": "Moli 1.2.0 · layout on", + "short_label": "1.2.0 开启布局", + "short_label_en": "1.2.0 layout on", "passed_cases": 300, "success_rate_pct": 300 / 372 * 100, "color": "#2775c9", @@ -268,7 +268,7 @@ def test_future_configuration_is_rendered_without_code_changes(self): self.data["configurations"].append(future) svg = self.render() self.assertIn("4 种配置", svg) - self.assertIn("Moli PR #640 · 失败后尝试 layout", svg) + self.assertIn("Moli 1.2.0 · 开启 layout", svg) self.assertIn("300/372 (80.6%)", svg) def test_mismatched_denominators_have_clear_error(self): From fda4695658513a93905ff829b64a49dcf299ded2 Mon Sep 17 00:00:00 2001 From: kevin Date: Mon, 21 Sep 2026 21:40:27 +0800 Subject: [PATCH 28/29] Share report byte packing and clarify chart schema mapping --- harness/reporting/packs.py | 55 +++++++++++++++++++++++++++++++ scripts/moli_report/BUILD.md | 6 ++++ scripts/moli_report/build.py | 21 ++++++------ scripts/moli_report/pack.py | 49 +++++++++++++-------------- scripts/package_artifact_hub.py | 17 +++------- tests/test_publication_privacy.py | 2 +- tests/test_report_packs.py | 42 +++++++++++++++++++++++ 7 files changed, 141 insertions(+), 51 deletions(-) create mode 100644 harness/reporting/packs.py create mode 100644 tests/test_report_packs.py diff --git a/harness/reporting/packs.py b/harness/reporting/packs.py new file mode 100644 index 000000000..cd3aa1412 --- /dev/null +++ b/harness/reporting/packs.py @@ -0,0 +1,55 @@ +"""Deterministic byte packs shared by static report publishers. + +Adapters own routes, privacy projection and MIME metadata. This layer only stores +ordered byte blocks and returns byte-exact locations for their existing loaders. +""" +from __future__ import annotations + +import gzip +from collections.abc import Iterable +from pathlib import Path + + +def write_packs( + blocks: Iterable[tuple[str, bytes]], + destination: Path, + *, + limit: int, + pattern: str, + compresslevel: int, +) -> tuple[dict[str, dict], int]: + if limit <= 0: + raise ValueError("pack limit must be positive") + catalog: dict[str, dict] = {} + payload = bytearray() + pending: list[str] = [] + index = 0 + + def flush(): + nonlocal index, payload, pending + if not pending: + return + relative = Path(pattern.format(index=index)) + if relative.is_absolute() or ".." in relative.parts: + raise ValueError("pack path must stay inside the destination") + path = destination / relative + path.parent.mkdir(parents=True, exist_ok=True) + # Refuse accidental replacement if a naming pattern repeats. + with path.open("xb") as stream: + stream.write(gzip.compress(bytes(payload), compresslevel=compresslevel, mtime=0)) + for key in pending: + catalog[key] = {"pack": relative.as_posix(), **catalog[key]} + index += 1 + payload = bytearray() + pending = [] + + for key, data in blocks: + if key in catalog: + raise ValueError(f"duplicate block: {key}") + if pending and len(payload) + len(data) > limit: + flush() + catalog[key] = {"offset": len(payload), "size": len(data)} + payload.extend(data) + pending.append(key) + flush() + return catalog, index diff --git a/scripts/moli_report/BUILD.md b/scripts/moli_report/BUILD.md index 78e44268d..d2245f4f3 100644 --- a/scripts/moli_report/BUILD.md +++ b/scripts/moli_report/BUILD.md @@ -32,3 +32,9 @@ For full release verification, serve the build with a static HTTP server and run Publish only after the complete requested method matrix and release checks pass, using the existing bound Artifact Site target and its freshly read remote version. Preserve binary identity, raw trials and previous report versions. Package the validated tree with `uv run --frozen python scripts/moli_report/pack.py --source /tmp/moli-report-release --output /tmp/moli-report-package`. The packer retains both English entry paths and checks bytes through the bundle manifest; it refuses symlinks, hidden paths, and existing destinations. Run the browser release check against this packaged directory before uploading: serve the package at `MOLI_REPORT_ORIGIN`, while `MOLI_REPORT_SITE` points to the validated unpacked tree that supplies the reference model. The browser checks include the complete resource matrix and frozen measurement-script evidence in both languages. + +## Shared implementation boundary + +Moli and Web Fetch publishers use `harness/reporting/packs.py` for deterministic gzip packing and byte offsets. Their adapters retain different entry points and catalogs: Moli serves case evidence through fetch, while Web Fetch packs virtual HTML routes and applies its own privacy projection. The shared packer accepts ordered bytes and neither selects evidence nor changes it. Round-trip tests cover both filename/compression formats, binary and Unicode content, empty files and pack boundaries; publisher tests verify their public catalogs independently. + +Moli's scorer bindings, 372-case matrix and source manifests remain in this adapter because they are specific to this benchmark. The renderer is not a second Web Fetch scorer. Common code is extracted where both reports actually use the same operation, rather than introducing a generic renderer with benchmark-specific branches. diff --git a/scripts/moli_report/build.py b/scripts/moli_report/build.py index b19713a2c..76d286fba 100644 --- a/scripts/moli_report/build.py +++ b/scripts/moli_report/build.py @@ -56,6 +56,15 @@ ).read_text() ) resource_builds = report_profile.get("resource_builds", {}) +# The report profile names the experiment; the chart schema names plotted calls. +# Convert once at this boundary instead of passing the profile to render_chart. +resource_scope = report_profile["resource_population"] +chart_population = { + "total_tasks": resource_scope["tasks"], + "calls_per_task": resource_scope["attempts_per_task"], + "chart_tasks": resource_scope["chart_tasks"], + "chart_calls": resource_scope["chart_calls"], +} SRC = args.source.resolve() OUT = args.output.resolve() FUNCTIONAL_CORRECTION = args.functional_correction.resolve() @@ -679,10 +688,7 @@ def timestamp(value): "resource_population": { "experiment_cases": 557, "attempts_per_case": 5, - "total_tasks": 557, - "calls_per_task": 5, - "chart_calls": resource_comparison["resource_populations"][population]["calls"], - "chart_tasks": resource_comparison["resource_populations"][population]["tasks"], + **chart_population, "selection": population, "sample_interval_ms": 250, }, @@ -1005,12 +1011,7 @@ def timestamp(value): macos_comparison = { "baseline": mac_baseline["id"], "configurations": mac_rows, - "resource_population": { - "chart_calls": 1045, - "chart_tasks": 209, - "total_tasks": 557, - "calls_per_task": 5, - }, + "resource_population": dict(chart_population), } linux_resource_profiles = None linux_comparison = None diff --git a/scripts/moli_report/pack.py b/scripts/moli_report/pack.py index 5ec497082..6b8c6ec36 100644 --- a/scripts/moli_report/pack.py +++ b/scripts/moli_report/pack.py @@ -3,13 +3,16 @@ from __future__ import annotations import argparse -import gzip import hashlib import json import mimetypes import shutil +import sys from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness.reporting.packs import write_packs # noqa: E402 + def package(source: Path, destination: Path, pack_limit: int = 8 * 1024 * 1024) -> dict: source = source.resolve() @@ -59,34 +62,26 @@ def package(source: Path, destination: Path, pack_limit: int = 8 * 1024 * 1024) else: shutil.copy2(source / name, target) shutil.copy2(Path(__file__).with_name("bundle-loader.js"), destination / "bundle-loader.js") - index, payload, catalog = 0, bytearray(), {} + metadata = {} - def flush(): - nonlocal index, payload - if not payload: - return - (destination / f"evidence-{index:02d}.bin.gz").write_bytes( - gzip.compress(bytes(payload), compresslevel=6, mtime=0) - ) - index += 1 - payload = bytearray() + def evidence(): + for path in files: + name = path.relative_to(source).as_posix() + if name in physical: + continue + data = path.read_bytes() + metadata[name] = { + "sha256": hashlib.sha256(data).hexdigest(), + "mime": mimetypes.guess_type(name)[0] or "application/octet-stream", + } + yield name, data - for path in files: - name = path.relative_to(source).as_posix() - if name in physical: - continue - data = path.read_bytes() - if payload and len(payload) + len(data) > pack_limit: - flush() - catalog[name] = { - "pack": f"evidence-{index:02d}.bin.gz", - "offset": len(payload), - "size": len(data), - "sha256": hashlib.sha256(data).hexdigest(), - "mime": mimetypes.guess_type(name)[0] or "application/octet-stream", - } - payload.extend(data) - flush() + catalog, index = write_packs( + evidence(), destination, limit=pack_limit, + pattern="evidence-{index:02d}.bin.gz", compresslevel=6, + ) + for name, entry in catalog.items(): + entry.update(metadata[name]) (destination / "bundle-manifest.json").write_text( json.dumps({"files": catalog}, separators=(",", ":")) + "\n" ) diff --git a/scripts/package_artifact_hub.py b/scripts/package_artifact_hub.py index 089d525e7..2fb6f1e4d 100644 --- a/scripts/package_artifact_hub.py +++ b/scripts/package_artifact_hub.py @@ -20,6 +20,7 @@ ROOT=Path(__file__).resolve().parents[1] sys.path.insert(0,str(ROOT)) +from harness.reporting.packs import write_packs from harness.web_fetch.publication_privacy import project_file from harness.web_fetch.publication_target import HUB SOURCE=Path(sys.argv[1]).resolve() if len(sys.argv)>1 else ROOT/'reports/webfetch' @@ -265,19 +266,9 @@ def add(path,data): 'detection_limits':'Pattern-based scan; not a guarantee of detecting every secret. Key validity is not tested.', 'files':redactions} add('publication-privacy.json',(json.dumps(privacy,ensure_ascii=False,indent=2)+'\n').encode()) - # Pack raw blocks together then gzip, keeping requests small and all bytes intact. - batch=bytearray();batch_keys=[];index=0 - def flush(): - nonlocal batch,batch_keys,index - if not batch:return - name=f'data/{index:03d}.gz';compressed=gzip.compress(bytes(batch),compresslevel=9,mtime=0) - (DEST/name).write_bytes(compressed) - for key,offset,size in batch_keys:blocks[key]={'pack':name,'offset':offset,'size':size} - batch=bytearray();batch_keys=[];index+=1 - for key,data in raw_blocks.items(): - if len(batch)+len(data)>4*1024*1024:flush() - batch_keys.append((key,len(batch),len(data)));batch.extend(data) - flush() + # Privacy projection and block deduplication remain report-specific. + blocks,index=write_packs(raw_blocks.items(),DEST,limit=4*1024*1024, + pattern='data/{index:03d}.gz',compresslevel=9) manifest={'schema_version':2, 'architecture':{'kind':'single_html_shell_with_lazy_virtual_routes', 'logical_routes':logical_route_count,'source_files':source_file_count, diff --git a/tests/test_publication_privacy.py b/tests/test_publication_privacy.py index 0b1c2119d..819c66f72 100644 --- a/tests/test_publication_privacy.py +++ b/tests/test_publication_privacy.py @@ -97,7 +97,7 @@ def test_packaged_downloads_and_disclosure(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) for relative in ('scripts/package_artifact_hub.py', 'harness/web_fetch/publication_privacy.py', - 'harness/web_fetch/publication_target.py'): + 'harness/web_fetch/publication_target.py', 'harness/reporting/packs.py'): target = root / relative target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(repository / relative, target) diff --git a/tests/test_report_packs.py b/tests/test_report_packs.py new file mode 100644 index 000000000..c66dab201 --- /dev/null +++ b/tests/test_report_packs.py @@ -0,0 +1,42 @@ +"""Public byte blocks survive both report pack formats without loss or mutation.""" +import gzip +import tempfile +import unittest +from pathlib import Path + +from harness.reporting.packs import write_packs + + +class ReportPacksTests(unittest.TestCase): + def test_roundtrip_and_determinism_for_both_public_formats(self): + source = [('empty', b''), ('unicode', '中文'.encode()), ('binary', bytes(range(256))), + ('tail', b'end'), ('empty-tail', b'')] + for pattern, level in [('data/{index:03d}.gz', 9), ('evidence-{index:02d}.bin.gz', 6)]: + with self.subTest(pattern=pattern), tempfile.TemporaryDirectory() as temp: + first, second = Path(temp) / 'first', Path(temp) / 'second' + a, count = write_packs(source, first, limit=8, pattern=pattern, compresslevel=level) + b, other_count = write_packs(source, second, limit=8, pattern=pattern, + compresslevel=level) + self.assertEqual((a, count), (b, other_count)) + self.assertGreater(count, 1) + for key, expected in source: + entry = a[key] + self.assertEqual((first / entry['pack']).read_bytes(), + (second / entry['pack']).read_bytes()) + raw = gzip.decompress((first / entry['pack']).read_bytes()) + self.assertEqual(raw[entry['offset']:entry['offset'] + entry['size']], expected) + + def test_empty_only_evidence_still_has_a_real_pack(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + entries, count = write_packs([('empty', b'')], root, limit=8, + pattern='{index}.gz', compresslevel=6) + self.assertEqual(count, 1) + self.assertEqual(gzip.decompress((root / entries['empty']['pack']).read_bytes()), b'') + + def test_rejects_duplicate_keys_and_unsafe_pack_paths(self): + for blocks, pattern in [([('x', b'a'), ('x', b'b')], '{index}.gz'), + ([('x', b'a')], '../{index}.gz')]: + with self.subTest(pattern=pattern), tempfile.TemporaryDirectory() as temp: + with self.assertRaises(ValueError): + write_packs(blocks, Path(temp), limit=8, pattern=pattern, compresslevel=6) From c2c599ecbea85005487ddf583796aa1409722cc5 Mon Sep 17 00:00:00 2001 From: kevin Date: Mon, 21 Sep 2026 21:44:23 +0800 Subject: [PATCH 29/29] Declare the shared reporting package explicitly --- harness/reporting/__init__.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 harness/reporting/__init__.py diff --git a/harness/reporting/__init__.py b/harness/reporting/__init__.py new file mode 100644 index 000000000..90684f23c --- /dev/null +++ b/harness/reporting/__init__.py @@ -0,0 +1 @@ +"""Shared, benchmark-independent report infrastructure."""