From 3fa23cc20bc6faf2495ce6333d6d91fb94a97f7a Mon Sep 17 00:00:00 2001 From: Maisiqi <324751762+Maisiqi@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:11:36 +0800 Subject: [PATCH 1/4] feat(webfetch): retain separate proxy configuration comparisons --- .agents/skills/benchmark-report/SKILL.md | 5 + src/harness/web_fetch/README.md | 19 + src/harness/web_fetch/providers/lexmount.py | 10 +- src/harness/web_fetch/report.py | 12 +- src/harness/web_fetch/report_model.py | 6 +- src/harness/web_fetch/report_package.py | 44 ++- .../web_fetch/report_saved_composition.py | 343 +++++++++++++++++- src/harness/web_fetch/report_saved_matrix.py | 24 +- tests/fixtures/native-route-baseline.json | 8 +- tests/test_configuration_comparisons.py | 218 +++++++++++ tests/test_providers.py | 19 + 11 files changed, 664 insertions(+), 44 deletions(-) create mode 100644 tests/test_configuration_comparisons.py diff --git a/.agents/skills/benchmark-report/SKILL.md b/.agents/skills/benchmark-report/SKILL.md index 21eb85634..abf2d6ee8 100644 --- a/.agents/skills/benchmark-report/SKILL.md +++ b/.agents/skills/benchmark-report/SKILL.md @@ -72,6 +72,11 @@ For an explicitly requested full review, set `independent_result_review_scope: a ## Frozen report extensions +For a separate configuration experiment, use the saved publication owner's +`configuration_comparisons` instead of adding participants to its leaderboard. +Bind a complete saved comparison and retain its original task contracts, scores, +languages and evidence. The Web Fetch guide documents its build and check contract. + When adding saved methods to an existing publication, inspect both frozen task contracts and scorer identities before combining ranks. Different editions retain their own saved values and evidence. Default to unranked presentation; when the user diff --git a/src/harness/web_fetch/README.md b/src/harness/web_fetch/README.md index 381a64793..81610f600 100644 --- a/src/harness/web_fetch/README.md +++ b/src/harness/web_fetch/README.md @@ -1696,6 +1696,25 @@ language must show the same comparison population and valid evidence links; evidence uses its frozen English edition when available, otherwise its original language. +Optional `configuration_comparisons` adds separately frozen saved reports to the +home page without changing leaderboard participants, ranks or result inventories. +Each entry declares an `id`, report `root`, path/hash `audit` binding, and English +and Chinese `title` and `description`. The complete comparison remains available +under `comparisons//`; the home table retains its saved values and evidence +links. Every generated parent language requires the same comparison language. +Build, refresh and portable checks verify these sources and displayed tables. +To retain an already extended publication byte for byte, bind its +`saved-extension.json` as `published_base.audit` and omit `additional_report`. +This appends the separate comparisons and retains every original page and result; +it does not rebuild the leaderboard with a newer renderer. Packaging resolves +lazy evidence against each frozen report's own file inventory, including nested +source reports. +When composing frozen reports with different task ID namespaces, +`saved_reports[].case_id_mapping` maps every `suite--source_id` to a unique target +ID within that suite. This requires `retain_source_task_contracts`; task names, +URLs and deliverable kinds must still match, and original cases and records stay +unchanged. + Use `scripts/build_report.py --variant saved-matrix --input SPEC --output NEW_REPORT` and `scripts/check_report.py NEW_REPORT --variant saved-matrix --source-spec SPEC`. Package with `uv run --frozen python -m harness.web_fetch site-package NEW_REPORT ARCHIVE diff --git a/src/harness/web_fetch/providers/lexmount.py b/src/harness/web_fetch/providers/lexmount.py index 71e20b987..d674cd7f0 100644 --- a/src/harness/web_fetch/providers/lexmount.py +++ b/src/harness/web_fetch/providers/lexmount.py @@ -36,7 +36,7 @@ def normalize_native_http_body(self, body, case): return True return False native_configuration_fields = Provider.native_configuration_fields + ( - 'engine', 'trace_include_steps') + 'engine', 'trace_include_steps', 'use_proxy') @staticmethod def native_answer_selection(selection): @@ -121,12 +121,19 @@ def native_http_arguments(self, case, timeout): 'options': {'engine_preference': engine}}} if trace: body['trace'] = {'include_steps': True} + self._configure_proxy(body) return (str(self.config.get('base_url', 'https://api.lexmount.com')).rstrip('/') + '/v1/extract', self.native_http_options(body, { 'X-API-Key': str(self.config.get('api_key', '')), 'X-Project-Id': str(self.config.get('project_id', '')), }, timeout)) + def _configure_proxy(self, body): + if 'use_proxy' in self.config: + if type(self.config['use_proxy']) is not bool: + raise ValueError('Lexmount use_proxy must be boolean') + body['use_proxy'] = self.config['use_proxy'] + def validate(self) -> list[str]: missing = [] if not self.config.get("api_key"): @@ -224,6 +231,7 @@ def fetch(self, case: EvalCase, timeout: float, *, native_route_ledger=None) -> "X-API-Key": str(self.config.get("api_key", "")), "X-Project-Id": str(self.config.get("project_id", "")), }, json_body={"extract": extract}) + self._configure_proxy(arguments['json_body']) response = self.native_http_request(case, request, endpoint, native_route_ledger=native_route_ledger, **arguments) try: diff --git a/src/harness/web_fetch/report.py b/src/harness/web_fetch/report.py index ceaaedcce..59d402f79 100644 --- a/src/harness/web_fetch/report.py +++ b/src/harness/web_fetch/report.py @@ -13,6 +13,7 @@ import statistics from collections import Counter, defaultdict from dataclasses import replace +from functools import lru_cache from math import ceil from pathlib import Path from urllib.parse import urlsplit @@ -832,9 +833,16 @@ def result_view(record, *, ctx): views=ctx.result_views return views.get((record['provider'],record['case_id']),{}) if views else {} +@lru_cache(maxsize=8192) +def _saved_source_case(path): + return json.loads(Path(path).read_bytes()) + def result_case(record,fallback, *, ctx): """Keep each saved result's own rules separate from its comparison identity.""" - return result_view(record, ctx=ctx).get('case',fallback) + selected=result_view(record, ctx=ctx).get('case') + if selected is not None:return selected + source=record.get('report_source_case_path') + return _saved_source_case(str(contained_path(ctx.source_root,source,reject_symlinks=True))) if source and ctx.source_root is not None else record.get('report_source_case') or fallback def result_href(record,kind,base='', *, ctx): """Resolve a retained evidence route relative to the report root.""" @@ -2055,7 +2063,7 @@ def _write_uncalled_participants(out,model, *, ctx): @with_measured_method_labels def _render_model(out,dataset,records,manifests,*,model,scope): - ctx=model_render_context(model,methods=scope) + ctx=model_render_context(model,methods=scope,source_root=out) options=model.options include_english,authored_interpretation,presentation_only=options.include_english,options.authored_interpretation,options.presentation_only show_local_status_banners,detail_attempt_ids,dataset_case_ids=options.show_local_status_banners,options.detail_attempt_ids,options.dataset_case_ids diff --git a/src/harness/web_fetch/report_model.py b/src/harness/web_fetch/report_model.py index fddb739ac..733017273 100644 --- a/src/harness/web_fetch/report_model.py +++ b/src/harness/web_fetch/report_model.py @@ -9,6 +9,7 @@ from collections.abc import Mapping, Sequence from dataclasses import dataclass, field, fields +from pathlib import Path from harness.record_io import canonical_json_sha256 from harness.web_fetch.models import report_family @@ -157,11 +158,12 @@ class RenderContext: scope_presentation: dict | None = None descriptive_ranks: bool = False result_views: dict | None = None + source_root: Path | None = None methods: MethodScope = field(default_factory=MethodScope) -def model_render_context(model=None, *, methods, descriptive_ranks=False, result_views=None): +def model_render_context(model=None, *, methods, descriptive_ranks=False, result_views=None, source_root=None): """The render context of ``model``'s participants and suites; shared views may opt into descriptive ranks.""" return RenderContext( labels=model.labels if model else {}, suites=model.suites if model else (), - descriptive_ranks=descriptive_ranks, result_views=result_views, methods=methods) + descriptive_ranks=descriptive_ranks, result_views=result_views, methods=methods, source_root=source_root) diff --git a/src/harness/web_fetch/report_package.py b/src/harness/web_fetch/report_package.py index 2421107c9..2693fda6e 100644 --- a/src/harness/web_fetch/report_package.py +++ b/src/harness/web_fetch/report_package.py @@ -972,9 +972,33 @@ def _save_wire_manifest(content, manifest): (content/'manifest.json').write_bytes(raw) -def _extension_file_bytes(name, path, originals): +def _extension_namespace_sources(source): + """Locate each frozen report that owns a separate comparison's lazy files.""" + proof = json.loads((source/'saved-extension.json').read_bytes()) + namespaces = {} + for entry in proof.get('configuration_comparisons', []): + root = contained_path(source, entry['path'], reject_symlinks=True) + for audit in root.rglob('saved-matrix-audit.json'): + prefix = audit.parent.relative_to(source).as_posix() + '/' + namespaces[prefix] = json.loads(audit.read_bytes())['files'] + return namespaces + + +def _extension_file_bytes(name, path, originals, *, namespaces=None): """Namespace packed lazy evidence while preserving standalone source pages.""" data = path.read_bytes() + if name.startswith('comparisons/') and name.endswith('.html'): + text = data.decode('utf-8') + _namespace_extension_evidence(text, prefix='') + keys = re.findall(r'\b(?:data-file|data-evidence-file)="([^"]+)"', text) + if not keys: + return data + for prefix in sorted(namespaces or {}, key=len, reverse=True): + files = namespaces[prefix] + if (name.startswith(prefix) and name[len(prefix):] in files + and all(key in files for key in keys)): + return _namespace_extension_evidence(text, prefix=prefix).encode('utf-8') + raise ValueError('Nested comparison evidence has no owning frozen report: ' + name) if name.startswith('additional/') and name.endswith('.html'): text = data.decode('utf-8') expected = originals[name.removeprefix('additional/')] @@ -986,9 +1010,9 @@ def _extension_file_bytes(name, path, originals): return data -def _extension_file_identity(name, path, originals): - if name.startswith('additional/') and name.endswith('.html'): - data = _extension_file_bytes(name, path, originals) +def _extension_file_identity(name, path, originals, *, namespaces=None): + if name.startswith(('additional/', 'comparisons/')) and name.endswith('.html'): + data = _extension_file_bytes(name, path, originals, namespaces=namespaces) return hashlib.sha256(data).hexdigest(), len(data) return _archive_identity(path), path.stat().st_size @@ -1015,6 +1039,7 @@ def extend_published_content(source, baseline, destination, *, replace_site=None raise ValueError('Extension content must be outside its immutable inputs') check_published_extension(source) originals = json.loads((source/'additional/saved-matrix-audit.json').read_bytes())['files'] + namespaces = _extension_namespace_sources(source) original = _wire_manifest(baseline) _require(original['schema_version'] == 3, 'Published extension requires a compact baseline') retire_packs = frozenset(retire_packs) @@ -1054,7 +1079,7 @@ def append(name, metadata, ids): for path in sorted(p for p in source.rglob('*') if p.is_file()): name = path.relative_to(source).as_posix() - digest, size = _extension_file_identity(name, path, originals) + digest, size = _extension_file_identity(name, path, originals, namespaces=namespaces) old = normalized['files'].get(name) if old is None and name == 'extension-base-home.txt': old = normalized['files'].get('index.html') @@ -1062,7 +1087,7 @@ def append(name, metadata, ids): (not retire_packs or not any(normalized['blocks'][i]['pack'] in retire_packs for i in old['parts']))): append(name, {k:v for k,v in old.items() if k != 'parts'}, old['parts']) continue - data = _extension_file_bytes(name, path, originals) + data = _extension_file_bytes(name, path, originals, namespaces=namespaces) _require(not publication_file_risk(name, data), 'Private content in extension: '+name) ids = [] for offset in range(0, len(data), 32768): @@ -1114,6 +1139,7 @@ def append(name, metadata, ids): def check_extended_content(source, baseline, content, *, replace_site=None, rehydrated=(), retire_packs=()): """Verify reused ranges and every appended byte against the report tree.""" originals = json.loads((source/'additional/saved-matrix-audit.json').read_bytes())['files'] + namespaces = _extension_namespace_sources(source) original = read_packed_manifest(lambda name:(baseline/name).read_bytes()) current = read_packed_manifest(lambda name:(content/name).read_bytes()) retire_packs = frozenset(retire_packs) @@ -1156,7 +1182,7 @@ def check_extended_content(source, baseline, content, *, replace_site=None, rehy _require(len(cache(name)) == expected_size, kind+' pack has undeclared bytes: '+name) for name, path in paths.items(): entry = current['files'][name] - digest, size = _extension_file_identity(name, path, originals) + digest, size = _extension_file_identity(name, path, originals, namespaces=namespaces) _require(entry['sha256'] == digest and entry['size'] == size, 'Extension package file differs: '+name) old = original['files'].get(name) @@ -1165,7 +1191,7 @@ def check_extended_content(source, baseline, content, *, replace_site=None, rehy if old and old['sha256'] == digest and list(entry['parts']) == list(old['parts']): blocks = [current['blocks'][i] for i in entry['parts']] if any(block['pack'] in reused_physical_packs for block in blocks): - data = _extension_file_bytes(name, path, originals) + data = _extension_file_bytes(name, path, originals, namespaces=namespaces) _require(not publication_file_risk(name, data), 'Private content in re-uploaded pack: '+name) offset = 0 for block in blocks: @@ -1177,7 +1203,7 @@ def check_extended_content(source, baseline, content, *, replace_site=None, rehy _require(offset == len(data), 'Reused file ranges differ from the frozen size: '+name) reused += 1 else: - data = _extension_file_bytes(name, path, originals) + data = _extension_file_bytes(name, path, originals, namespaces=namespaces) _require(not publication_file_risk(name, data), 'Private content in extension: '+name) _require(all(i >= count for i in entry['parts']), 'Appended file uses undeclared old ranges') _require(reconstruct_packed_file(current, name, cache) == data, diff --git a/src/harness/web_fetch/report_saved_composition.py b/src/harness/web_fetch/report_saved_composition.py index bb2b5209e..bedf42960 100644 --- a/src/harness/web_fetch/report_saved_composition.py +++ b/src/harness/web_fetch/report_saved_composition.py @@ -12,34 +12,42 @@ from harness.web_fetch.report_i18n import saved_matrix_text as _text -def _frozen_report(root, binding): +def _frozen_files(root, binding, audit_name): """Verify a published tree without reinterpreting its historical verdicts.""" - audit = root / 'saved-matrix-audit.json' + audit = root / audit_name if _hash(audit) != binding['sha256']: raise ValueError('Frozen report audit changed') - files = _read(audit)['files'] + authority = _read(audit) + files = authority['files'] inventory = list(root.rglob('*')) if root.is_symlink() or any(p.is_symlink() for p in inventory): raise ValueError('Frozen reports reject symlinks') actual = {p.relative_to(root).as_posix() for p in inventory if p.is_file()} - if actual != set(files) | {'saved-matrix-audit.json'}: + if actual != set(files) | {audit_name}: raise ValueError('Frozen report file inventory changed') for name, digest in files.items(): if _hash(root / name) != digest: raise ValueError('Frozen report file changed: ' + name) + return authority + + +def _frozen_report(root, binding): + _frozen_files(root, binding, 'saved-matrix-audit.json') return _read(root / 'matrix.json') -def _namespace_extension_evidence(text): +def _namespace_extension_evidence(text, prefix='additional/'): """Qualify lazy sources only in views rendered beneath the outer report root.""" if re.search(r'\bdata-record=', text): raise ValueError('Nested report requires explicit evidence-file bindings') - return re.sub(r'\bdata-file="([^"]+)"', r'data-file="additional/\1"', text) + return re.sub(r'\b(data-file|data-evidence-file)="([^"]+)"', + lambda match: match[1] + '="' + prefix + match[2] + '"', text) -def _restore_extension_evidence(text): +def _restore_extension_evidence(text, prefix='additional/'): """Recover only the namespace projection used by frozen older extensions.""" - return re.sub(r'\bdata-file="additional/([^"]+)"', r'data-file="\1"', text) + return re.sub(r'\b(data-file|data-evidence-file)="' + re.escape(prefix) + r'([^"]+)"', + lambda match: match[1] + '="' + match[2] + '"', text) def _extended_home(base, addition, base_model, added_model, overview, note, *, ranked=False, presentation=None): @@ -278,7 +286,9 @@ def _joined_presentation(output, *, ctx): key = record['provider'], comparison_id if key in views: raise ValueError('Joined presentation repeats a saved task result') - views[key] = {'case': source_cases[source_id], + case = (_read(contained_path(output, record['report_source_case_path'], reject_symlinks=True)) + if record.get('report_source_case_path') else record.get('report_source_case') or source_cases[source_id]) + views[key] = {'case': case, 'task_href': prefix+'datasets/'+source_id+'.html', 'attempt_href': prefix+'attempts/'+record['attempt_id']+'.html'} record['case_id'] = comparison_id @@ -798,10 +808,130 @@ def _selected_method_prices(spec_path, spec): return prices +def _configuration_comparisons(content, output, comparisons, *, language): + """Embed complete saved comparisons without adding leaderboard participants.""" + if not comparisons: + return content + from bs4 import BeautifulSoup + from harness.report_languages import generated_languages + from urllib.parse import urlsplit + page = BeautifulSoup(content, 'html.parser') + for old in page.select('[data-configuration-comparison]'): + old.decompose() + container = page.find('main') or page.body + anchor = page.find(id='configuration-comparisons') + for entry in comparisons: + identifier = safe_identifier(entry['id']) + for field in ('title', 'description'): + if (not isinstance(entry[field], dict) or any( + not isinstance(entry[field].get(key), str) or not entry[field][key].strip() + for key in ('en', 'zh'))): + raise ValueError('Configuration comparisons require English and Chinese text') + root = output / entry['path'] + if language not in generated_languages(root): + raise ValueError('Configuration comparison is missing the generated language: ' + language) + edition = 'en/' if language == 'en' else '' + source = BeautifulSoup((root / edition / 'index.html').read_text(encoding='utf-8'), 'html.parser') + table = source.select_one('#ranking-overall') + model = _read(root / 'matrix.json') + if table is None or len(table.select('tbody > tr')) != len(model['providers']): + raise ValueError('Configuration comparison omitted saved participants') + section = page.new_tag('section', attrs={ + 'id': 'configuration-' + identifier, 'data-configuration-comparison': identifier}) + heading = page.new_tag('h2') + heading.string = entry['title'][language] + section.append(heading) + paragraph = page.new_tag('p') + paragraph.string = entry['description'][language] + section.append(paragraph) + prefix = ('../' if language == 'en' else '') + entry['path'] + '/' + edition + link = page.new_tag('a', href=prefix + 'index.html') + link.string = ('Open task results, settings and evidence →' if language == 'en' + else '查看逐题结果、配置与证据 →') + section.append(link) + table = deepcopy(table) + original_id = table['id'] + table['id'] = 'configuration-' + identifier + '-overall' + for button in table.select('[onclick]'): + button['onclick'] = re.sub(r'(\bsortTable\([\'\"])' + re.escape(original_id) + r'([\'\"])', + lambda match, table_id=table['id']: match[1] + table_id + match[2], button['onclick']) + for table_link in table.select('a[href]'): + href = table_link['href'] + parsed = urlsplit(href) + if not parsed.scheme and not parsed.netloc and not href.startswith(('#', '/')): + table_link['href'] = prefix + href + wrapper = page.new_tag('div', attrs={'class': 'table-wrap'}) + wrapper.append(table) + section.append(wrapper) + if anchor is not None: + anchor.insert_after(section) + anchor = section + else: + container.append(section) + return str(page) + + +def _copy_configuration_comparisons(spec_path, output, entries, existing=()): + from harness.web_fetch.report_saved_matrix import _path + comparisons = deepcopy(list(existing)) + for entry in entries: + identifier = safe_identifier(entry['id']) + if any(row['id'] == identifier for row in comparisons): + raise ValueError('Duplicate configuration comparison') + source = _path(spec_path.parent, entry['root']) + _frozen_report(source, entry['audit']) + path = 'comparisons/' + identifier + shutil.copytree(source, output / path) + comparisons.append({key: deepcopy(entry[key]) for key in ('id', 'title', 'description')} | { + 'path': path, 'audit_sha256': _hash(source / 'saved-matrix-audit.json')}) + return comparisons + + +def _build_frozen_configuration_extension(spec_path, output, spec): + """Add comparisons to an existing publication without rebuilding its views.""" + from harness.web_fetch.report_saved_matrix import _path + from harness.record_io import json_bytes + from harness.reporting.publication import atomic_write + from harness.report_languages import generated_languages, language_metadata_path + source = _path(spec_path.parent, spec['published_base']['root']) + base = _frozen_files(source, spec['published_base']['audit'], 'saved-extension.json') + if not spec.get('configuration_comparisons'): + raise ValueError('A frozen publication extension requires configuration comparisons') + shutil.copytree(source, output) + comparisons = _copy_configuration_comparisons(spec_path, output, + spec['configuration_comparisons'], base.get('configuration_comparisons', [])) + retained = 'configuration-sources/' + _hash(source/'saved-extension.json') + (output/retained).mkdir(parents=True) + shutil.copyfile(source/'saved-extension.json', output/retained/'saved-extension.json') + routes = [('index.html', 'zh')] + if 'en' in generated_languages(source) and (language_metadata_path(source).is_file() or (source/'en/index.html').is_file()): + routes.append(('en/index.html', 'en')) + homes = {} + for route, language in routes: + original = source/route + target = output/retained/(route+'.txt') + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(original, target) + homes[route] = target.relative_to(output).as_posix() + (output/route).write_text(_configuration_comparisons(original.read_text(encoding='utf-8'), + output, comparisons, language=language), encoding='utf-8') + proof = deepcopy(base) + proof.update(spec_sha256=_hash(spec_path), configuration_comparisons=comparisons, + configuration_base={'path': retained+'/saved-extension.json', + 'sha256': _hash(source/'saved-extension.json'), 'homes': homes}) + proof['files'] = {p.relative_to(output).as_posix(): _hash(p) for p in output.rglob('*') + if p.is_file() and p != output/'saved-extension.json'} + atomic_write(output/'saved-extension.json', json_bytes(proof)) + check_published_extension(output) + return output/'index.html' + + def build_published_extension(spec_path, output): """Extend a frozen publication while retaining each scoring edition verbatim.""" from harness.web_fetch.report_saved_matrix import _path, _write spec = _read(spec_path) + if 'additional_report' not in spec: + return _build_frozen_configuration_extension(spec_path, output, spec) base_root = _path(spec_path.parent, spec['published_base']['root']) added_root = _path(spec_path.parent, spec['additional_report']['root']) base = _frozen_report(base_root, spec['published_base']['audit']) @@ -825,6 +955,7 @@ def build_published_extension(spec_path, output): shutil.copytree(base_root, output) shutil.copytree(added_root, output / 'additional') shutil.copyfile(base_root / 'index.html', output / 'extension-base-home.txt') + comparisons = _copy_configuration_comparisons(spec_path, output, spec.get('configuration_comparisons', [])) if 'method_prices' in spec: _write(output/'extension-prices.json', _selected_method_prices(spec_path, spec)) ranked = spec.get('presentation') == 'ranked' @@ -839,6 +970,11 @@ def build_published_extension(spec_path, output): shutil.copyfile(output / route, retained) (output/route).parent.mkdir(parents=True, exist_ok=True) (output / route).write_text(content, encoding='utf-8') + for route, language in [('index.html', 'zh'), ('en/index.html', 'en')]: + if route == 'index.html' or route in pages: + path = output / route + path.write_text(_configuration_comparisons(path.read_text(encoding='utf-8'), + output, comparisons, language=language), encoding='utf-8') _write(output / 'extension-methods.json', overview) _write(output / 'saved-extension.json', { 'schema_version': 1, 'spec_sha256': _hash(spec_path), @@ -847,14 +983,60 @@ def build_published_extension(spec_path, output): 'comparison_note': spec['comparison_note'], 'provider_calls_added': 0, 'presentation': spec.get('presentation', 'audit'), 'presentation_pages': list(pages), 'providers': base['providers'] + added['providers'], + 'configuration_comparisons': comparisons, 'files': {p.relative_to(output).as_posix(): _hash(p) for p in output.rglob('*') if p.is_file()}}) check_published_extension(output) return output / 'index.html' +def _check_frozen_configuration_extension(output, proof): + from bs4 import BeautifulSoup + from urllib.parse import urljoin, urlsplit, unquote + binding = proof['configuration_base'] + path = contained_path(output, binding['path'], reject_symlinks=True) + if _hash(path) != binding['sha256']: + raise ValueError('Frozen publication source changed') + prefix = 'configuration-sources/' + binding['sha256'] + '/' + if (binding['path'] != prefix + 'saved-extension.json' or 'index.html' not in binding['homes'] + or not set(binding['homes']) <= {'index.html', 'en/index.html'} + or any(name != prefix + route + '.txt' for route, name in binding['homes'].items())): + raise ValueError('Invalid frozen publication home binding') + base = _read(path) + if proof['providers'] != base['providers']: + raise ValueError('Configuration comparison changed leaderboard participants') + for entry in base.get('configuration_comparisons', []): + if entry not in proof.get('configuration_comparisons', []): + raise ValueError('Frozen configuration comparison changed') + for name, digest in base['files'].items(): + retained = binding['homes'].get(name, name) + if _hash(contained_path(output, retained, reject_symlinks=True)) != digest: + raise ValueError('Configuration comparison changed original evidence: ' + name) + for route, retained in binding['homes'].items(): + original = contained_path(output, retained, reject_symlinks=True).read_text(encoding='utf-8') + expected = _configuration_comparisons(original, output, proof['configuration_comparisons'], + language='en' if route.startswith('en/') else 'zh') + if (output/route).read_text(encoding='utf-8') != expected: + raise ValueError('Configuration comparison differs from frozen sources') + page = BeautifulSoup(expected, 'html.parser') + if len(page.select('#ranking-overall > tbody > tr')) != len(base['providers']): + raise ValueError('Configuration comparison changed leaderboard population') + for link in page.select('[data-configuration-comparison] a[href]'): + url = urlsplit(urljoin('https://extension.invalid/' + route, link['href'])) + if url.netloc == 'extension.invalid' and url.path != '/': + if not contained_path(output, unquote(url.path.lstrip('/')), reject_symlinks=True).is_file(): + raise ValueError('Configuration comparison has a broken evidence link') + return {'valid': True, 'files_verified': len(proof['files']), + 'providers': len(proof['providers']), 'provider_calls_added': 0, 'frozen_base': True} + + def check_published_extension(output): from bs4 import BeautifulSoup proof = _read(output / 'saved-extension.json') + comparisons = proof.get('configuration_comparisons', []) + for entry in comparisons: + if entry['path'] != 'comparisons/' + safe_identifier(entry['id']): + raise ValueError('Invalid configuration comparison path') + _frozen_report(output / entry['path'], {'sha256': entry['audit_sha256']}) inventory = list(output.rglob('*')) if output.is_symlink() or any(p.is_symlink() for p in inventory): raise ValueError('Published extensions reject symlinks') @@ -864,6 +1046,8 @@ def check_published_extension(output): for name, digest in proof['files'].items(): if _hash(output / name) != digest: raise ValueError('Published extension bytes changed: ' + name) + if proof.get('configuration_base'): + return _check_frozen_configuration_extension(output, proof) baseline = _read(output / 'saved-matrix-audit.json') if (_hash(output / 'saved-matrix-audit.json') != proof['base_audit_sha256'] or _hash(output / 'additional/saved-matrix-audit.json') != proof['additional_audit_sha256'] @@ -887,11 +1071,17 @@ def check_published_extension(output): _read(output / 'additional/matrix.json'), _read(output / 'extension-methods.json'), proof['comparison_note'], ranked=proof.get('presentation') == 'ranked', presentation=_shared_presentations(output) if proof.get('presentation') == 'ranked' else None) + expected = _configuration_comparisons(expected, output, comparisons, language='zh') if (output / 'index.html').read_text(encoding='utf-8') != expected: raise ValueError('Published extension comparison differs from source metrics') views = _extension_views(output, _read(output / 'matrix.json'), _read(output / 'additional/matrix.json'), _read(output / 'extension-methods.json'), proof['comparison_note'], ranked=proof.get('presentation') == 'ranked') + # The shared localizer receives the retained main comparison. Each separate + # configuration report supplies its own generated language and evidence. + for route in ('en/index.html',): + if route in views: + views[route] = _configuration_comparisons(views[route], output, comparisons, language='en') if set(views) != set(proof.get('presentation_pages', [])): raise ValueError('Published extension omitted comparison pages') for route, content in views.items(): @@ -965,10 +1155,30 @@ def _refresh_published_extension(output, *, spec_path=None): from harness.record_io import json_bytes import hashlib proof = _read(output / 'saved-extension.json') + if proof.get('configuration_base'): + if spec_path is not None and _hash(spec_path) != proof['spec_sha256']: + raise ValueError('Frozen comparison sources require a new build') + for name, digest in proof['files'].items(): + if _hash(contained_path(output, name, reject_symlinks=True)) != digest: + raise ValueError('Cannot refresh changed frozen evidence: ' + name) + for route, retained in proof['configuration_base']['homes'].items(): + original = (output/retained).read_text(encoding='utf-8') + content = _configuration_comparisons(original, output, proof['configuration_comparisons'], + language='en' if route.startswith('en/') else 'zh') + atomic_write(output/route, content.encode()) + proof['files'][route] = _hash(output/route) + atomic_write(output/'saved-extension.json', json_bytes(proof)) + return check_published_extension(output) overview = _read(output / 'extension-methods.json') prices = _read(output/'extension-prices.json') if (output/'extension-prices.json').is_file() else {} if spec_path is not None: spec = _read(spec_path) + comparisons = [{key: deepcopy(entry[key]) for key in ('id', 'title', 'description')} | { + 'path': 'comparisons/' + safe_identifier(entry['id']), + 'audit_sha256': entry['audit']['sha256']} + for entry in spec.get('configuration_comparisons', [])] + if comparisons != proof.get('configuration_comparisons', []): + raise ValueError('Refresh cannot replace configuration comparison sources') if (spec['published_base']['audit']['sha256'] != proof['base_audit_sha256'] or spec['additional_report']['audit']['sha256'] != proof['additional_audit_sha256']): raise ValueError('Refresh cannot replace frozen report sources') @@ -990,6 +1200,7 @@ def _refresh_published_extension(output, *, spec_path=None): (output / 'additional/index.html').read_text(encoding='utf-8'), _read(output / 'matrix.json'), _read(output / 'additional/matrix.json'), overview, note, ranked=ranked, presentation=presentation) + home = _configuration_comparisons(home, output, proof.get('configuration_comparisons', []), language='zh') for name, digest in proof['files'].items(): actual = _hash(contained_path(output, name, reject_symlinks=True)) if actual != digest and not (name == 'index.html' and actual == hashlib.sha256(home.encode()).hexdigest()): @@ -1003,6 +1214,9 @@ def _refresh_published_extension(output, *, spec_path=None): proof['files']['extension-prices.json'] = _hash(output/'extension-prices.json') pages = _extension_views(output, _read(output / 'matrix.json'), _read(output / 'additional/matrix.json'), overview, note, ranked=ranked) + if 'en/index.html' in pages: + pages['en/index.html'] = _configuration_comparisons(pages['en/index.html'], output, + proof.get('configuration_comparisons', []), language='en') for route, content in pages.items(): retained = output / 'extension-base-pages' / route if route in baseline['files'] and not retained.exists(): @@ -1045,7 +1259,7 @@ def _project(value, paths): def _public_spec(spec): - result = {k: deepcopy(spec[k]) for k in ('title', 'limitations', 'presentation', 'combined_ranking') if k in spec} + result = {k: deepcopy(spec[k]) for k in ('title', 'limitations', 'presentation', 'combined_ranking', 'retain_source_reviews', 'frozen_sources', 'retain_source_task_contracts') if k in spec} if spec.get('native_policy_registry'): result['native_policy_registry'] = True return result @@ -1061,8 +1275,12 @@ def composition_model(output, spec, snapshots): root = contained_path(output, snapshot['path'], reject_symlinks=True) if _hash(root / 'saved-matrix-audit.json') != snapshot['sha256']: raise ValueError('Saved composition source audit changed') - check_saved_matrix(root) - audit, model = _read(root / 'saved-matrix-audit.json'), _read(root / 'matrix.json') + if spec.get('frozen_sources'): + model = _frozen_report(root, {'sha256': snapshot['sha256']}) + else: + check_saved_matrix(root) + model = _read(root / 'matrix.json') + audit = _read(root / 'saved-matrix-audit.json') if 'providers' in snapshot: selected = snapshot['providers'] available = {p['id'] for p in model['providers']} @@ -1072,6 +1290,18 @@ def composition_model(output, spec, snapshots): raise ValueError('Invalid saved report provider selection') model['providers'] = [p for p in model['providers'] if p['id'] in selected] model['rows'] = [r for r in model['rows'] if r['provider'] in selected] + mapping = snapshot.get('case_id_mapping', {}) + if 'case_id_mapping' in snapshot: + source_ids = {row['suite'] + '--' + row['case_id'] for row in model['rows']} + if (not spec.get('retain_source_task_contracts') or not isinstance(mapping, dict) + or set(mapping) != source_ids + or any(not isinstance(value, str) for value in mapping.values())): + raise ValueError('Case identity mapping must cover the complete frozen population') + targets = {(row['suite'], mapping[row['suite'] + '--' + row['case_id']]) for row in model['rows']} + if len(targets) != len(mapping): + raise ValueError('Case identity mapping repeats a target within a suite') + for row in model['rows']: + row['case_id'] = safe_identifier(mapping[row['suite'] + '--' + row['case_id']]) if suites is None: suites, families = model['suites'], model.get('report_families') if suites != model['suites'] or families != model.get('report_families'): @@ -1085,13 +1315,20 @@ def composition_model(output, spec, snapshots): key = row['suite'], row['case_id'] case = _case_identity(_read(root / row['case_path'])) if key in cases and cases[key] != case: - raise ValueError('Saved comparisons have different frozen tasks') - cases[key] = case + same_identity = (cases[key].url, cases[key].name, cases[key].task_kind) == (case.url, case.name, case.task_kind) + if not spec.get('retain_source_task_contracts') or not same_identity: + raise ValueError('Saved comparisons have different frozen tasks') + cases.setdefault(key, case) population.add(key) if expected_population is not None and population != expected_population: raise ValueError('Saved comparisons have different case populations') expected_population = population - rows.extend(_project(model['rows'], paths)) + projected = _project(model['rows'], paths) + if spec.get('frozen_sources'): + for row in projected: + if 'score_revision' in row: + row['source_score_revision'] = row.pop('score_revision') + rows.extend(projected) if not rows: raise ValueError('Saved composition requires reports') result = dict(title=spec['title'], providers=providers, suites=suites, rows=rows, @@ -1099,21 +1336,83 @@ def composition_model(output, spec, snapshots): presentation=spec.get('presentation', 'audit'), combined_ranking=spec.get('combined_ranking', True), source_bindings=[{'name': s['id'], 'sha256': s['sha256']} for s in snapshots], - scores_changed=any(row.get('score_revision') for row in rows)) + scores_changed=any(row.get('score_revision') or row.get('source_score_revision') for row in rows)) if families is not None: result['report_families'] = families if spec.get('native_policy_registry'): result['native_policy_registry'] = {'path': 'native-policy-registry.json', 'sha256': _hash(output / 'native-policy-registry.json')} + if spec.get('retain_source_reviews'): + result['source_review_pages'] = [ + {'path': snapshot['path'] + '/review/index.html', + 'providers': _read(output/snapshot['path']/'matrix.json')['providers']} + for snapshot in snapshots] + if spec.get('retain_source_task_contracts'): + result['retain_source_task_contracts'] = True + if spec.get('frozen_sources'): + result['frozen_source_prefixes'] = [snapshot['path'] for snapshot in snapshots] return result +def render_source_reviews(output, model): + """Retain frozen review scopes beneath the composition's own navigation.""" + from bs4 import BeautifulSoup + from urllib.parse import urljoin, urlsplit + sources = model.get('source_review_pages') + if not sources: + return + path = output/'review/index.html' + page = BeautifulSoup(path.read_text(encoding='utf-8'), 'html.parser') + main = page.find('main') + for child in list(main.children): + if not isinstance(child, str) and (child.name == 'h1' or child.find('h1')): + continue + child.extract() + for index, source in enumerate(sources): + original = BeautifulSoup((output/source['path']).read_text(encoding='utf-8'), 'html.parser') + content = original.find('main') + identifiers = {} + for node in content.select('[id]'): + old = node['id'] + identifiers[old] = node['id'] = f'source-review-{index}-' + old + for node in content.find_all(True): + for attribute in ('for', 'aria-controls', 'aria-labelledby', 'aria-describedby'): + if node.has_attr(attribute): + node[attribute] = ' '.join(identifiers.get(value, value) for value in node[attribute].split()) + for node in content.select('a[href]'): + href = node['href'] + if href.startswith('#'): + node['href'] = '#' + identifiers.get(href[1:], href[1:]) + elif not urlsplit(href).scheme and not urlsplit(href).netloc: + target = urlsplit(urljoin('https://report.invalid/' + source['path'], href)) + node['href'] = '../' + target.path.lstrip('/') + ('#' + target.fragment if target.fragment else '') + section = page.new_tag('section', attrs={'data-source-review': source['path']}) + heading = page.new_tag('h2') + heading.string = ', '.join(p.get('label', p['id']) for p in source['providers']) + section.append(heading) + for title in content.find_all('h1'): + title.decompose() + for child in list(content.children): + section.append(child) + main.append(section) + path.write_text(str(page), encoding='utf-8') + + + def build_composition(spec_path, output): from harness.web_fetch.report_saved_matrix import generate_saved_matrix from harness.web_fetch.report_saved_matrix import _path, _write, check_saved_matrix spec = _read(spec_path) if spec.get('schema_version') != 1 or not isinstance(spec.get('saved_reports'), list): raise ValueError('Unsupported saved composition specification') + if 'retain_source_reviews' in spec and type(spec['retain_source_reviews']) is not bool: + raise ValueError('Source review retention must be explicitly enabled or disabled') + if 'frozen_sources' in spec and type(spec['frozen_sources']) is not bool: + raise ValueError('Frozen source selection must be explicitly enabled or disabled') + if spec.get('frozen_sources') and spec.get('presentation', 'audit') != 'audit': + raise ValueError('Frozen source composition retains historical scores without final certification') + if spec.get('retain_source_task_contracts') and not spec.get('frozen_sources'): + raise ValueError('Historical task contracts require frozen source imports') snapshots, identifiers = [], set() output.mkdir() for item in spec['saved_reports']: @@ -1127,18 +1426,23 @@ def build_composition(spec_path, output): audit_path = root / 'saved-matrix-audit.json' if _hash(audit_path) != item['audit']['sha256']: raise ValueError('Saved report audit differs from binding') - check_saved_matrix(root) + if spec.get('frozen_sources'): + _frozen_report(root, item['audit']) + else: + check_saved_matrix(root) relative = 'evidence/saved-reports/' + identifier shutil.copytree(root, output / relative) snapshot = {'id': identifier, 'path': relative, 'sha256': _hash(audit_path)} if 'providers' in item: snapshot['providers'] = item['providers'] + if 'case_id_mapping' in item: + snapshot['case_id_mapping'] = item['case_id_mapping'] snapshots.append(snapshot) # Revision receipts use report-root review attachment links. Preserve # those exact bytes, rejecting ambiguous collisions across sources. model = _read(root / 'matrix.json') - receipt_paths = {row['score_revision']['receipt_path'] for row in model['rows'] - if row.get('score_revision')} + receipt_paths = ({row['score_revision']['receipt_path'] for row in model['rows'] + if row.get('score_revision')} if not spec.get('frozen_sources') else set()) for receipt_path in sorted(receipt_paths): receipt = _read(root / receipt_path) for name in receipt.get('review_files', {}).values(): @@ -1157,6 +1461,7 @@ def build_composition(spec_path, output): _write(output / 'matrix.json', model) _write(output / 'saved-composition.json', {'spec': _public_spec(spec), 'snapshots': snapshots}) entry = generate_saved_matrix(output, model) + render_source_reviews(output, model) files = {p.relative_to(output).as_posix(): _hash(p) for p in output.rglob('*') if p.is_file()} _write(output / 'saved-matrix-audit.json', dict(schema_version=1, spec_sha256=_hash(spec_path), sources=model['source_bindings'], files=files, totals=model['totals'], diff --git a/src/harness/web_fetch/report_saved_matrix.py b/src/harness/web_fetch/report_saved_matrix.py index 781a9aea4..bc93e5e44 100644 --- a/src/harness/web_fetch/report_saved_matrix.py +++ b/src/harness/web_fetch/report_saved_matrix.py @@ -2745,13 +2745,14 @@ def record_paths(value): for row in model['rows']: identity = row['suite'], row['provider'], row['case_id'] case = _json(contained_path(output, row['case_path'], reject_symlinks=True)) - if case['id'] != row['case_id']: + if case['id'] != row['case_id'] and not model.get('retain_source_task_contracts'): raise ValueError('Saved case identity differs from matrix') if row.get('url') != case['url'] or row.get('name') != case.get('name', row['case_id']): raise ValueError('Saved case metadata differs from matrix') if row.get('record_path'): record = _json(contained_path(output, row['record_path'], reject_symlinks=True)) - if (record['provider'], record['case_id']) != identity[1:]: + source_identity = (row['provider'], case['id']) if model.get('retain_source_task_contracts') else identity[1:] + if (record['provider'], record['case_id']) != source_identity: raise ValueError('Saved record identity differs from matrix') values = _saved_row_values(record, case) if row.get('retry_continuation'): @@ -2794,7 +2795,11 @@ def record_paths(value): _validate_record_links(output, row) for relative in set(record_paths(row)): path = contained_path(output, relative, reject_symlinks=True) - _validate_record_artifacts(path) + # Published snapshots can contain post-score public views whose + # bytes deliberately differ from private acquisition hashes. Their + # complete file inventory is verified by the frozen-source owner. + if not any(relative.startswith(prefix + '/') for prefix in model.get('frozen_source_prefixes', [])): + _validate_record_artifacts(path) if row.get('score_revision'): receipt = _json(contained_path(output, row['score_revision']['receipt_path'], reject_symlinks=True)) for target in receipt.get('review_files', {}).values(): @@ -2831,7 +2836,8 @@ def record_paths(value): saved_records = [json.loads(line) for line in (output/'results.jsonl').read_bytes().splitlines() if line.strip()] execution = _json(output/'execution.json') scores_changed = (bool(inputs['revision']) or any(adoptions[key]['revision'] for key in keys if key in adoptions) - if inputs is not None else bool(model.get('offline_revision')) or any(row.get('score_revision') for row in model['rows'])) + if inputs is not None else bool(model.get('offline_revision')) or any( + row.get('score_revision') or row.get('source_score_revision') for row in model['rows'])) scores_changed = bool(scores_changed) if any(value.get('scores_changed') is not scores_changed for value in (audit, model, execution)): raise ValueError('Saved scoring-change flags differ from revision evidence') @@ -2915,7 +2921,8 @@ def _saved_renderer_projection(output, model, admission=None): before = _json(contained_path(output, proof['before_case_path'], reject_symlinks=True)) if not _same_task_rules(before, case): raise ValueError('Changed task contracts cannot enter a portable final report') - if case['id'] != row['case_id']: + source_case_id = case['id'] + if case['id'] != row['case_id'] and not model.get('retain_source_task_contracts'): raise ValueError('Saved case identity differs from matrix') if row.get('url') != case['url'] or row.get('name') != case.get('name', row['case_id']): raise ValueError('Saved case metadata differs from matrix') @@ -2923,12 +2930,13 @@ def _saved_renderer_projection(output, model, admission=None): family = _presentation_family(case, row['suite'], groups) if 'report_families' in model else row['suite'] case['report_family'] = family case['report_family_label'] = labels[family] - if cases.setdefault(route, case) != case: + if cases.setdefault(route, case) != case and not model.get('retain_source_task_contracts'): raise ValueError(f"Conflicting saved case definitions for {route}") if not row.get('record_path'): continue raw = _json(contained_path(output, row['record_path'])) - if raw['case_id'] != row['case_id'] or raw['provider'] != row['provider']: + expected_case_id = source_case_id if model.get('retain_source_task_contracts') else row['case_id'] + if raw['case_id'] != expected_case_id or raw['provider'] != row['provider']: raise ValueError('Saved record identity differs from matrix') if _saved_row_values(raw, case)['passed'] != row['passed']: raise ValueError('Saved verdict differs from matrix') @@ -2944,6 +2952,8 @@ def project(value, key='', prefix=prefix): return candidate return value record = project(raw) + if model.get('retain_source_task_contracts'): + record['report_source_case_path'] = row['case_path'] if model.get('public_evidence_views'): from harness.reporting.publication_privacy import public_render_views, read_evidence_binding from harness.web_fetch.failure_diagnosis import diagnose diff --git a/tests/fixtures/native-route-baseline.json b/tests/fixtures/native-route-baseline.json index 8e13c7cfc..9c240415c 100644 --- a/tests/fixtures/native-route-baseline.json +++ b/tests/fixtures/native-route-baseline.json @@ -105,19 +105,19 @@ }, "lexmount:defaults": { "cells": 192, - "sha256": "60682051fb2ac45134e1c112f66dda8c22931c705388f6161d29070b9abe0940" + "sha256": "c66bd5850cfcc925bbfa0759c21d25b6b2ce5aa3a022a0c737f5cc8915cef514" }, "lexmount:configured": { "cells": 192, - "sha256": "6c13091b78dc93b940443404081b87bc7ec37c9e3d303d14797a2aac0a087862" + "sha256": "5ea6d4b80238dbd5067f6265fa4680e7a56558313e05276512aa54a11256726f" }, "lexmount_cn:defaults": { "cells": 192, - "sha256": "b84f349a5d52fee4ab28c7c3f000a6c09e8bab4a61d619f67c90c28885d7b9f0" + "sha256": "e4d9be5dc134a2f8afa9899c549a1d6fa1eb05d378c38a8f1bb400f504bcebf6" }, "lexmount_cn:configured": { "cells": 192, - "sha256": "ac5d273cb6fc423cdbc2161a777daccd1a4709becf823936da54c9403af7676a" + "sha256": "9ea7cd71de04dc6162788902f730111dfcfdb1ae73501c78fc6703a6a794dd98" }, "moli_webfetch:defaults": { "cells": 192, diff --git a/tests/test_configuration_comparisons.py b/tests/test_configuration_comparisons.py new file mode 100644 index 000000000..e53a4895f --- /dev/null +++ b/tests/test_configuration_comparisons.py @@ -0,0 +1,218 @@ +"""Keep configuration experiments separate from the published leaderboard.""" +import hashlib +import json +from pathlib import Path + +import pytest + +from harness.web_fetch.report_saved_matrix import build_saved_matrix, check_saved_matrix +from tests.test_saved_matrix_composition import reports, _published_extension +from tests.test_saved_matrix_evidence import write + + +def test_configuration_comparison_keeps_leaderboard_population_and_checks_evidence(tmp_path): + from bs4 import BeautifulSoup + from harness.web_fetch.report_saved_composition import refresh_published_extension + (tmp_path / 'baseline').mkdir() + _, packed, _, _ = _published_extension(tmp_path / 'baseline') + spec_path = tmp_path / 'baseline/extension.json' + comparison_spec, _ = reports(tmp_path / 'comparison') + comparison = build_saved_matrix(comparison_spec, tmp_path / 'comparison-report').parent + # Frozen publications can defer logs at both their root and nested source + # report roots. These fixtures must retain their own lazy-file namespaces. + nested = comparison / 'evidence/saved-reports/source-0' + for owner, name in [(nested, 'method-0'), (comparison, 'method-1')]: + log = owner / 'lazy-log.txt' + log.write_text('Complete diagnostic for ' + name, encoding='utf-8') + page_path = owner / 'providers' / (name + '.html') + source_page = page_path.read_text(encoding='utf-8') + page_path.write_text(source_page.replace('', '
'), encoding='utf-8')
+        owner_audit = owner / 'saved-matrix-audit.json'
+        authority = json.loads(owner_audit.read_bytes())
+        authority['files'] = {str(p.relative_to(owner)): hashlib.sha256(p.read_bytes()).hexdigest()
+                              for p in owner.rglob('*') if p.is_file() and p != owner_audit}
+        write(owner_audit, authority)
+    audit = comparison / 'saved-matrix-audit.json'
+    spec = json.loads(spec_path.read_bytes())
+    spec['configuration_comparisons'] = [{
+        'id': 'proxy', 'root': str(comparison),
+        'audit': {'path': str(audit), 'sha256': hashlib.sha256(audit.read_bytes()).hexdigest()},
+        'title': {'en': 'Proxy comparison', 'zh': '代理配置对照'},
+        'description': {'en': 'Separate saved configurations.', 'zh': '单独展示保存的配置结果。'}}]
+    write(spec_path, spec)
+    output = build_saved_matrix(spec_path, tmp_path / 'with-comparison').parent
+    assert check_saved_matrix(output, spec_path=spec_path)['providers'] == 2
+    page = BeautifulSoup((output / 'index.html').read_text(encoding='utf-8'), 'html.parser')
+    assert len(page.select('#ranking-overall tbody > tr')) == 2
+    assert len(page.select('#configuration-proxy-overall tbody > tr')) == 2
+    controls = page.select('#configuration-proxy-overall button[onclick]')
+    assert controls and all('configuration-proxy-overall' in button['onclick'] for button in controls)
+    assert page.select_one('[data-configuration-comparison="proxy"] a')['href'] == 'comparisons/proxy/index.html'
+    assert refresh_published_extension(output, spec_path=spec_path)['valid']
+    from harness.web_fetch.report_package import extend_published_content, _write_archive, check_extension_archive
+    from harness.reporting.packs import read_packed_file
+    content = tmp_path / 'packed-comparison'
+    manifest = extend_published_content(output, packed, content)
+    archive = tmp_path / 'comparison.zip'
+    _write_archive(content, archive)
+    assert check_extension_archive(archive, output, baseline=packed)['valid']
+    import zipfile
+    checked = 0
+    with zipfile.ZipFile(archive) as bundle:
+        for name in manifest['files']:
+            if not name.startswith('comparisons/') or not name.endswith('.html'):
+                continue
+            delivered = BeautifulSoup(read_packed_file(bundle, name), 'html.parser')
+            for pre in delivered.select('pre[data-file], pre[data-evidence-file]'):
+                key = pre.get('data-file') or pre['data-evidence-file']
+                assert key.startswith('comparisons/proxy/') and key in manifest['files']
+                if key.endswith('/lazy-log.txt'):
+                    prefix = ('comparisons/proxy/evidence/saved-reports/source-0/'
+                              if '/source-0/' in name else 'comparisons/proxy/')
+                    assert key == prefix + 'lazy-log.txt'
+                assert read_packed_file(bundle, key) == (output / key).read_bytes()
+                checked += 1
+    assert checked >= 2
+    frozen_spec = tmp_path / 'frozen-extension.json'
+    previous = tmp_path / 'baseline/extended'
+    source_proof = previous / 'saved-extension.json'
+    write(frozen_spec, {'published_base': {'root': str(previous), 'audit': {
+        'path': str(source_proof), 'sha256': hashlib.sha256(source_proof.read_bytes()).hexdigest()}},
+        'configuration_comparisons': spec['configuration_comparisons']})
+    frozen = build_saved_matrix(frozen_spec, tmp_path / 'frozen-added').parent
+    checked_frozen = check_saved_matrix(frozen, spec_path=frozen_spec)
+    assert checked_frozen['frozen_base'] and checked_frozen['providers'] == 2
+    previous_page = BeautifulSoup((previous/'index.html').read_text(encoding='utf-8'), 'html.parser')
+    frozen_page = BeautifulSoup((frozen/'index.html').read_text(encoding='utf-8'), 'html.parser')
+    for table in previous_page.select('table[id]'):
+        assert str(frozen_page.find('table', id=table['id'])) == str(table)
+    old_files = json.loads(source_proof.read_bytes())['files']
+    for name in old_files:
+        if name != 'index.html':
+            assert (frozen / name).read_bytes() == (previous / name).read_bytes()
+    assert refresh_published_extension(frozen, spec_path=frozen_spec)['valid']
+    frozen_content = tmp_path / 'packed-frozen'
+    extend_published_content(frozen, packed, frozen_content)
+    frozen_archive = tmp_path / 'frozen.zip'
+    _write_archive(frozen_content, frozen_archive)
+    assert check_extension_archive(frozen_archive, frozen, baseline=packed)['valid']
+    # Updating an inventory cannot conceal changes to the original publication.
+    original_file = next(name for name in old_files if name.endswith('.html') and name != 'index.html')
+    (frozen/original_file).write_text('changed historical evidence', encoding='utf-8')
+    frozen_proof = json.loads((frozen/'saved-extension.json').read_bytes())
+    frozen_proof['files'][original_file] = hashlib.sha256((frozen/original_file).read_bytes()).hexdigest()
+    write(frozen/'saved-extension.json', frozen_proof)
+    with pytest.raises(ValueError, match='changed original evidence'):
+        check_saved_matrix(frozen)
+    # Even a refreshed inventory cannot authorize a wrong displayed value.
+    page = BeautifulSoup((output / 'index.html').read_text(encoding='utf-8'), 'html.parser')
+    page.select_one('#configuration-proxy-overall tbody td').string = 'wrong'
+    (output / 'index.html').write_text(str(page), encoding='utf-8')
+    proof_path = output / 'saved-extension.json'
+    proof = json.loads(proof_path.read_bytes())
+    proof['files']['index.html'] = hashlib.sha256((output / 'index.html').read_bytes()).hexdigest()
+    write(proof_path, proof)
+    with pytest.raises(ValueError, match='comparison differs from source metrics'):
+        check_saved_matrix(output)
+
+
+
+def test_frozen_composition_maps_case_ids_without_changing_source_records(tmp_path):
+    spec_path, entries = reports(tmp_path)
+    spec = json.loads(spec_path.read_bytes())
+    spec.update(frozen_sources=True, retain_source_task_contracts=True)
+    for entry in spec['saved_reports']:
+        model = json.loads((Path(entry['root']) / 'matrix.json').read_bytes())
+        row = model['rows'][0]
+        entry['case_id_mapping'] = {row['suite'] + '--' + row['case_id']: 'canonical-task'}
+    write(spec_path, spec)
+    output = build_saved_matrix(spec_path, tmp_path / 'mapped').parent
+    assert check_saved_matrix(output, spec_path=spec_path)['valid']
+    rows = json.loads((output / 'matrix.json').read_bytes())['rows']
+    assert {row['case_id'] for row in rows} == {'canonical-task'}
+    assert all(json.loads((output / row['record_path']).read_bytes())['case_id'] != 'canonical-task' for row in rows)
+    spec['saved_reports'][0]['case_id_mapping']['unknown'] = 'another-task'
+    write(spec_path, spec)
+    with pytest.raises(ValueError, match='complete frozen population'):
+        build_saved_matrix(spec_path, tmp_path / 'invalid-mapping')
+
+
+
+def test_frozen_source_composition_accepts_published_audit_and_rejects_changed_bytes(tmp_path):
+    spec_path, entries = reports(tmp_path)
+    source = Path(entries[0]['root'])
+    audit = source/'saved-matrix-audit.json'
+    original = json.loads(audit.read_bytes())
+    binding = write(audit, {'files': original['files']})
+    spec = json.loads(spec_path.read_bytes())
+    spec['saved_reports'][0]['audit'] = binding
+    spec['frozen_sources'] = True
+    write(spec_path, spec)
+    output = build_saved_matrix(spec_path, tmp_path/'combined').parent
+    assert check_saved_matrix(output, spec_path=spec_path)['valid']
+    (source/'index.html').write_text('changed frozen source', encoding='utf-8')
+    with pytest.raises(ValueError, match='Frozen report file changed'):
+        build_saved_matrix(spec_path, tmp_path/'changed')
+
+
+
+def test_composition_retains_source_review_pages_under_shared_navigation(tmp_path):
+    from bs4 import BeautifulSoup
+    spec_path, entries = reports(tmp_path)
+    spec = json.loads(spec_path.read_bytes())
+    spec['retain_source_reviews'] = True
+    write(spec_path, spec)
+    output = build_saved_matrix(spec_path, tmp_path/'combined').parent
+    assert check_saved_matrix(output, spec_path=spec_path)['valid']
+    page = BeautifulSoup((output/'review/index.html').read_text(encoding='utf-8'), 'html.parser')
+    sections = page.select('[data-source-review]')
+    assert len(sections) == 2
+    for index, (section, entry) in enumerate(zip(sections, entries, strict=True)):
+        original = BeautifulSoup((Path(entry['root'])/'review/index.html').read_text(encoding='utf-8'), 'html.parser')
+        assert f'method-{index}' in section.h2.get_text()
+        for paragraph in original.select('main p'):
+            assert paragraph.get_text(' ', strip=True) in section.get_text(' ', strip=True)
+    (output/'review/index.html').write_text('
Missing source review scopes
', encoding='utf-8') + with pytest.raises(ValueError): + check_saved_matrix(output) + + + +def test_frozen_revision_stays_source_history_without_inventing_private_attachments(tmp_path): + spec_path, entries = reports(tmp_path) + source = Path(entries[0]['root']) + model = json.loads((source/'matrix.json').read_bytes()) + model['rows'][0]['score_revision'] = {'receipt_path': 'historical-revision.json'} + matrix = write(source/'matrix.json', model) + revision = write(source/'historical-revision.json', {'review_files': {'private': 'private-unpublished.json'}}) + audit = json.loads((source/'saved-matrix-audit.json').read_bytes()) + audit['files']['matrix.json'] = matrix['sha256'] + audit['files']['historical-revision.json'] = revision['sha256'] + audit_binding = write(source/'saved-matrix-audit.json', {'files': audit['files']}) + spec = json.loads(spec_path.read_bytes()) + spec['saved_reports'][0]['audit'] = audit_binding + spec['frozen_sources'] = True + write(spec_path, spec) + output = build_saved_matrix(spec_path, tmp_path/'combined').parent + assert check_saved_matrix(output, spec_path=spec_path)['valid'] + current = json.loads((output/'matrix.json').read_bytes()) + row = current['rows'][0] + assert row['source_score_revision']['receipt_path'].endswith('/historical-revision.json') + assert 'score_revision' not in row and current['scores_changed'] is True + assert not (output/'private-unpublished.json').exists() + + + +def test_frozen_comparison_keeps_each_saved_task_contract(tmp_path): + spec_path, entries = reports(tmp_path, different_task=True) + spec = json.loads(spec_path.read_bytes()) + spec.update(frozen_sources=True, retain_source_task_contracts=True) + write(spec_path, spec) + output = build_saved_matrix(spec_path, tmp_path/'combined').parent + assert check_saved_matrix(output, spec_path=spec_path)['valid'] + records = [json.loads(line) for line in (output/'results.jsonl').read_text(encoding='utf-8').splitlines()] + assert json.loads((output/records[1]['report_source_case_path']).read_bytes())['expected_any'] == ['different'] + assert json.loads((output/records[0]['report_source_case_path']).read_bytes())['expected_any'] != ['different'] + assert all('report_source_case' not in record for record in records) + assert all(row['passed'] for row in json.loads((output/'matrix.json').read_bytes())['rows']) + diff --git a/tests/test_providers.py b/tests/test_providers.py index 438a97d42..f77a5db47 100644 --- a/tests/test_providers.py +++ b/tests/test_providers.py @@ -107,6 +107,25 @@ def test_lexmount_engine_uses_nested_extract_options(self, mock_request) -> None }) self.assertNotIn("engine", mock_request.call_args.kwargs["json_body"]["extract"]) + @patch("harness.web_fetch.providers.lexmount.request") + def test_lexmount_proxy_preserves_existing_native_request(self, mock_request) -> None: + mock_request.return_value = HttpResponse( + 200, "u", {}, b'{"result":{"main_text":"Example"}}') + for engine, trace in [('lightmount_domstable', True), ('auto', False)]: + for native in (True, False): + config = {'api_key': 'x', 'project_id': 'p', 'engine': engine, + 'trace_include_steps': trace, 'uniform_native_parameters': native} + LexmountProvider('lexmount', config).fetch(self.case, 30) + original = mock_request.call_args.kwargs['json_body'] + for use_proxy in (True, False): + provider = LexmountProvider('lexmount', {**config, 'use_proxy': use_proxy}) + provider.fetch(self.case, 30) + self.assertEqual(mock_request.call_args.kwargs['json_body'], + {**original, 'use_proxy': use_proxy}) + self.assertEqual(provider.native_configured_parameters()['use_proxy'], use_proxy) + with self.assertRaisesRegex(ValueError, 'use_proxy must be boolean'): + LexmountProvider('lexmount', {**config, 'use_proxy': 'true'}).fetch(self.case, 30) + @patch("harness.web_fetch.providers.lexmount.request") def test_lexmount_never_uses_api_envelope_as_page_content(self, mock_request) -> None: mock_request.return_value = HttpResponse( From 35eaf2beca219982299ca8eb0237ef5f5cfc3c29 Mon Sep 17 00:00:00 2001 From: Maisiqi <324751762+Maisiqi@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:35:59 +0800 Subject: [PATCH 2/4] fix(webfetch): verify public native retry evidence views --- src/harness/reporting/publication_privacy.py | 32 +++++++++-- src/harness/web_fetch/README.md | 1 + .../web_fetch/report_saved_composition.py | 13 +++-- src/harness/web_fetch/report_saved_matrix.py | 48 ++++++++++++---- tests/test_publication_privacy.py | 47 ++++++++++++++++ tests/test_saved_matrix_evidence.py | 56 ++++++++++++++----- 6 files changed, 163 insertions(+), 34 deletions(-) diff --git a/src/harness/reporting/publication_privacy.py b/src/harness/reporting/publication_privacy.py index 7dadc2ec8..a394cd918 100644 --- a/src/harness/reporting/publication_privacy.py +++ b/src/harness/reporting/publication_privacy.py @@ -1181,20 +1181,23 @@ def project(value, *, secret=False): 'original_bytes': len(data), 'published_bytes': len(projected)} -def project_result_diagnostics(name, data): +def project_result_diagnostics(name, data, *, case=None, answer=None): """Redact quoted output diagnostics without changing result authority. - Only passage quotations and resource-URL diagnostics may differ. Original - records stay at source; callers must bind this separate presentation receipt - and verify its projection against those originals at the report boundary. + Passage quotations and resource-URL diagnostics may differ. Native answer + fields additionally require their bound scorer and unchanged task acceptance. + Original records stay at source; callers bind this separate presentation + receipt and verify its projection at the report boundary. """ public, receipt = project_file(name, data) if receipt is None: return data, None before, after = json.loads(data), json.loads(public) changed = [] + acceptance_context_changed = False def compare(left, right, path=()): + nonlocal acceptance_context_changed if left == right: return if isinstance(left, dict) and isinstance(right, dict) and left.keys() == right.keys(): @@ -1210,10 +1213,31 @@ def compare(left, right, path=()): ('metrics', 'resource_candidates', '*', 'url'), ('metrics', 'unexpected_resource_urls', '*')}: changed.append('/'.join(map(str, path))) + elif (case is not None and answer is not None + and isinstance(left, str) and isinstance(right, str) + and tuple('*' if isinstance(part, int) else part for part in path) in { + ('provider_metadata', 'links', '*'), + ('provider_metadata', 'links', '*', 'href'), + ('provider_metadata', 'images', '*', 'src'), + ('provider_metadata', 'page_information', 'paragraphs', '*'), + ('final_url',)}): + acceptance_context_changed = True + changed.append('/'.join(map(str, path))) else: raise ValueError('Public result diagnostics would change non-diagnostic authority') compare(before, after) + if acceptance_context_changed: + from lexbench_webfetch.metrics import task_passed + from lexbench_webfetch.scoring import SCORING_SOURCE_SHA256, score_attempt + if before['metrics'].get('scoring_source_sha256') != SCORING_SOURCE_SHA256: + raise ValueError('Changed native view requires its bound scoring version') + metrics = score_attempt(case, answer, ok=before['ok'], status_code=before.get('status_code'), + metadata=after.get('provider_metadata'), previous_metrics=before['metrics'], + title=after.get('title'), final_url=after.get('final_url')) + if task_passed(before['ok'], metrics, case.get('task_kind', 'body')) != task_passed( + before['ok'], before['metrics'], case.get('task_kind', 'body')): + raise ValueError('Public native projection changes task acceptance') return public, {**receipt, 'kind': 'post_score_result_diagnostics_view', 'changed_fields': changed, 'measurements_unchanged': True, 'original_retained_privately': True, 'provider_calls_added': 0} diff --git a/src/harness/web_fetch/README.md b/src/harness/web_fetch/README.md index 81610f600..7670addcf 100644 --- a/src/harness/web_fetch/README.md +++ b/src/harness/web_fetch/README.md @@ -1657,6 +1657,7 @@ tables use final-call latency; accumulated retry cost stays in the evidence. - The hash-bound specification declares datasets, providers, selected results and evidenced missing outcomes. Suite-qualified identities preserve original cases and scores. No provider calls, rescoring or certification are added. - This mode uses the existing Web Fetch renderer, including datasets, method pages and result/reference comparisons. Missing outcomes have a separate inventory. Keep the HTML pages and evidence directories together. - Set `public_evidence_views: true` for a fixed text-output selection when native responses or diagnostic logs need inspectable public copies. The shared privacy owner creates separately hash-bound post-score views; original result records, source artifacts and scores remain immutable. A changed displayed answer must preserve task acceptance. Each evidence scope retains its view inventory and original/public identities, including declared split retries. The source-spec check reproduces these views from originals and rejects altered or missing copies. Scoring-only revisions with unchanged task contracts, call inputs and answer bytes are supported: the public predecessor is an explicitly labeled historical score summary bound to the original record hash, not a historical scorer replay. Original predecessor records remain in private evidence. Parameter candidates, adoptions, changed answer fields and superseded histories are excluded; this option does not weaken acquisition checks or add provider calls. + Native link, image, paragraph and redirect views require the acquisition scorer and unchanged task acceptance. Direct Lexmount retry replay verifies the retained native response and hash-bound API call log, including the logging owner's URL redaction. Missing events, inconsistent status, changed redirect targets or acceptance changes fail before publication. - When quoted output passages or resource-URL diagnostics contain sensitive values, the same public-view mode projects only those diagnostic strings in the report copy of `record.json`. A separate `result-diagnostics-view.json` binds its original/public hashes and exact changed fields. All scores, counts, timings, verdicts and other result authority must remain identical; source-backed checks reproduce the projection and reject unrelated changes. Result pages disclose the projection and link its receipt. Original source records remain private and immutable. - Optional `pricing` binds an external public price catalog by path and SHA-256. It must cover every selected participant. The report copies it to `report-assets/provider-pricing.json`, renders prices and registered interfaces for the measured cohort, and checks the source bytes again during rebuild validation. Without this binding, historical saved reports retain their explicit unavailable-price state. - Optional `report_families` lists ordered `{id, label}` entries for every observed task family. It groups the presentation by task content (including embedded media versus direct files), while preserving suite-qualified evidence identities and all saved scores. diff --git a/src/harness/web_fetch/report_saved_composition.py b/src/harness/web_fetch/report_saved_composition.py index bedf42960..0da83662b 100644 --- a/src/harness/web_fetch/report_saved_composition.py +++ b/src/harness/web_fetch/report_saved_composition.py @@ -837,18 +837,21 @@ def _configuration_comparisons(content, output, comparisons, *, language): if table is None or len(table.select('tbody > tr')) != len(model['providers']): raise ValueError('Configuration comparison omitted saved participants') section = page.new_tag('section', attrs={ - 'id': 'configuration-' + identifier, 'data-configuration-comparison': identifier}) + 'id': 'configuration-' + identifier, 'class': 'section', + 'data-configuration-comparison': identifier}) + body = page.new_tag('div', attrs={'class': 'wrap'}) + section.append(body) heading = page.new_tag('h2') heading.string = entry['title'][language] - section.append(heading) + body.append(heading) paragraph = page.new_tag('p') paragraph.string = entry['description'][language] - section.append(paragraph) + body.append(paragraph) prefix = ('../' if language == 'en' else '') + entry['path'] + '/' + edition link = page.new_tag('a', href=prefix + 'index.html') link.string = ('Open task results, settings and evidence →' if language == 'en' else '查看逐题结果、配置与证据 →') - section.append(link) + body.append(link) table = deepcopy(table) original_id = table['id'] table['id'] = 'configuration-' + identifier + '-overall' @@ -862,7 +865,7 @@ def _configuration_comparisons(content, output, comparisons, *, language): table_link['href'] = prefix + href wrapper = page.new_tag('div', attrs={'class': 'table-wrap'}) wrapper.append(table) - section.append(wrapper) + body.append(wrapper) if anchor is not None: anchor.insert_after(section) anchor = section diff --git a/src/harness/web_fetch/report_saved_matrix.py b/src/harness/web_fetch/report_saved_matrix.py index bc93e5e44..d651ec3de 100644 --- a/src/harness/web_fetch/report_saved_matrix.py +++ b/src/harness/web_fetch/report_saved_matrix.py @@ -1657,7 +1657,7 @@ def reject(): private = call.get('private_artifacts', []) responses = [item for item in private if item['path'].endswith('.response.bin')] logs = [item for item in private if item['path'].endswith('.stderr.log')] - if len(responses) != 1 or len(logs) != 1 or not call.get('call_log'): + if len(responses) != 1 or len(logs) > 1 or not call.get('call_log'): reject() def read(binding): raw = contained_path(source, binding['path'], reject_symlinks=True).read_bytes() @@ -1665,15 +1665,31 @@ def read(binding): reject() return raw native = read(responses[0]) + log = json.loads(read(call['call_log'])) events = [] - for line in read(logs[0]).splitlines(): + for line in read(logs[0]).splitlines() if logs else []: try: event = json.loads(line) except (ValueError, UnicodeError): continue if isinstance(event, dict) and str(event.get('event', '')).endswith('http_response_received'): events.append(event) - log = json.loads(read(call['call_log'])) + if not logs: + signature = receipt['requests'][0]['signature'] + # The direct Lexmount adapter records the API HTTP status as its result + # status. It has a hash-bound call log instead of worker stderr. + if (record['provider_type'] != 'lexmount' + or signature.get('transport') != 'http' + or signature.get('interface') != '/v1/extract' + or signature.get('parameters', {}).get('method') != 'POST' + or log.get('request', {}).get('route') != 'v1_extract_native' + or log.get('capture', {}).get('diagnostic_log') != 'not_retained'): + reject() + events = [{'status': event.get('status_code')} for event in log.get('events', []) + if event.get('stage') == 'response_received'] + if (len(events) != 1 or events[0]['status'] != call.get('status_code') + or events[0]['status'] != log.get('response', {}).get('status_code')): + reject() if (len(events) != 1 or type(events[0].get('status')) is not int or log.get('output', {}).get('sha256') != call['content_sha256'] or log.get('timing', {}).get('elapsed_ms') != call['elapsed_ms'] @@ -1691,7 +1707,8 @@ def read(binding): if content.encode('utf-8') != answer: reject() fields = project_native_result_fields(payload, declaration, request_url=case['url']) - if fields['final_url'] != log.get('response', {}).get('final_url'): + from harness.web_fetch.runner import _public_url + if log.get('response', {}).get('final_url') not in (fields['final_url'], _public_url(fields['final_url'])): reject() metadata.update(native_answer_projection=declaration, native_route_receipt=receipt, raw_response_sha256=responses[0]['sha256']) @@ -1783,11 +1800,14 @@ def _record_public_views(source, record, case, approved_policies=None): return views -def _display_record_bytes(settings, name, raw): +def _display_record_bytes(settings, name, raw, *, case=None, root=None): if not settings.get('public_evidence_views'): return raw from harness.reporting.publication_privacy import project_result_diagnostics - return project_result_diagnostics(name, raw)[0] + record = json.loads(raw) + answer = (contained_path(root, record['artifact_path'], reject_symlinks=True).read_bytes() + if root is not None and record.get('artifact_path') else None) + return project_result_diagnostics(name, raw, case=case, answer=answer)[0] def _require_public_fixed_selection(inputs, candidates, adoptions): @@ -1846,7 +1866,8 @@ def _materialize_record_public_views(source, destination, record, case, original _write(destination / 'presentation-binding.json', {'publication_evidence_views': {'path': index.name, 'sha256': _sha(index)}}) from harness.reporting.publication_privacy import project_result_diagnostics - public_record, receipt = project_result_diagnostics(record_name, original_record) + public_record, receipt = project_result_diagnostics(record_name, original_record, + case=case, answer=(destination/record['artifact_path']).read_bytes()) if receipt: target = destination/record_name if target.read_bytes() != original_record: @@ -1885,7 +1906,8 @@ def _validate_record_public_views(source, destination, record, case, original_re if index != {'kind': 'post_score_public_evidence_view_inventory', 'provider_calls_added': 0, 'files': expected}: raise ValueError('Public evidence view inventory differs from original sources') from harness.reporting.publication_privacy import project_result_diagnostics - public_record, receipt = project_result_diagnostics(record_name, original_record) + public_record, receipt = project_result_diagnostics(record_name, original_record, + case=case, answer=(destination/record['artifact_path']).read_bytes()) path = destination/'result-diagnostics-view.json' if ((destination/record_name).read_bytes() != public_record or bool(receipt) != path.is_file() @@ -2420,7 +2442,8 @@ def _validate_revision_and_authority_proofs(output, row, inputs, candidates, dec if (row.get('receipt_path') != prefix+'/receipt.json' or _json(output/row['receipt_path']) != json.loads(json.dumps(expected_receipt)) or (output/row['record_path']).read_bytes() != _display_record_bytes( - inputs['spec'], Path(row['record_path']).name, raw)): + inputs['spec'], Path(row['record_path']).name, raw, + case=inputs['cases'][key[0]][key[2]], root=(output/row['record_path']).parent)): raise ValueError('Saved result receipt differs from validated source') if key in inputs['historical']: @@ -2784,7 +2807,8 @@ def record_paths(value): expected_record = adoptions[identity]['selected'][1] if expected_record is not None: if not row.get('record_path') or record != json.loads(_display_record_bytes( - model, Path(row['record_path']).name, json_bytes(expected_record))): + model, Path(row['record_path']).name, json_bytes(expected_record), + case=case, root=(output/row['record_path']).parent)): raise ValueError('Saved record differs from validated source selection') elif (row.get('record_path') or row['status'] != inputs['missing'][identity][0]['status'] or receipt != _json(inputs['missing'][identity][1]) @@ -2828,7 +2852,9 @@ def record_paths(value): approved_policies) for relative, expected_record in _source_record_inventory(inputs, candidates, decisions, adoptions, keys).items(): path = contained_path(output, relative, reject_symlinks=True) - if not path.is_file() or path.read_bytes() != _display_record_bytes(model, path.name, expected_record): + suite, _, case_id = Path(relative).parts[1:4] + if not path.is_file() or path.read_bytes() != _display_record_bytes(model, path.name, expected_record, + case=inputs['cases'][suite][case_id], root=path.parent): raise ValueError('Published provenance record differs from validated source: '+relative) _validate_record_artifacts(path) projected_dataset, projected_records, projected_identities, projected_scope = _saved_renderer_projection( diff --git a/tests/test_publication_privacy.py b/tests/test_publication_privacy.py index 68dda7210..d916f2b13 100644 --- a/tests/test_publication_privacy.py +++ b/tests/test_publication_privacy.py @@ -81,6 +81,53 @@ def test_result_diagnostic_views_reject_changes_outside_quoted_output(): project_result_diagnostics('record.json',json.dumps({'error_message':'Authorization: Bearer synthetic-secret'}).encode()) +@pytest.mark.parametrize('field', ['links', 'link_objects', 'images', 'paragraphs']) +def test_native_metadata_public_views_require_bound_answer_and_unchanged_verdict(field): + from harness.reporting.publication_privacy import project_result_diagnostics + from lexbench_webfetch.models import EvalCase + from lexbench_webfetch.scoring import score_attempt + case = vars(EvalCase(id='native', name='Native output', url='https://example.test/', + category='synthetic', expected_any=['Expected body'])) + answer = b'Expected body' + url = 'https://example.test/file?token=synthetic-secret' + metadata = {'links': {'links':[url], 'link_objects':[{'href':url}]}[field]} if field in { + 'links', 'link_objects'} else ({'images':[{'src':url}]} if field == 'images' else { + 'page_information':{'paragraphs':['meta-csrf-token: synthetic-secret']}}) + metrics = score_attempt(case, answer, ok=True, metadata=metadata) + row = {'ok':True, 'status_code':200, 'metrics':metrics, 'provider_metadata':metadata} + raw = json.dumps(row).encode() + with pytest.raises(ValueError, match='non-diagnostic authority'): + project_result_diagnostics('record.json', raw) + public, receipt = project_result_diagnostics('record.json', raw, case=case, answer=answer) + assert b'synthetic-secret' not in public + assert receipt['measurements_unchanged'] and receipt['changed_fields'] + assert json.loads(public)['metrics']['content_pass'] == metrics['content_pass'] + with pytest.raises(ValueError, match='changes task acceptance'): + project_result_diagnostics('record.json', raw, case=case, answer=b'Unrelated body') + row['metrics']['scoring_source_sha256'] = '0'*64 + with pytest.raises(ValueError, match='bound scoring version'): + project_result_diagnostics('record.json', json.dumps(row).encode(), case=case, answer=answer) + + +def test_public_redirect_cannot_change_required_page_identity(): + from harness.reporting.publication_privacy import project_result_diagnostics + from lexbench_webfetch.models import EvalCase + from lexbench_webfetch.scoring import score_attempt + url = 'https://example.test/article?token=synthetic-secret' + case = vars(EvalCase(id='redirect', name='Redirect', url='https://example.test/', + category='synthetic', expected_any=['Expected body'])) + for required in (False, True): + selected = {**case, 'page_identity_required':required, 'expected_final_url':url} + metrics = score_attempt(selected, b'Expected body', ok=True, final_url=url) + raw = json.dumps({'ok':True, 'final_url':url, 'metrics':metrics, 'provider_metadata':{}}).encode() + if required: + with pytest.raises(ValueError, match='changes task acceptance'): + project_result_diagnostics('record.json', raw, case=selected, answer=b'Expected body') + else: + public, receipt = project_result_diagnostics('record.json', raw, case=selected, answer=b'Expected body') + assert json.loads(public)['metrics'] == metrics and 'final_url' in receipt['changed_fields'] + + def test_mixed_native_diagnostic_views_preserve_text_and_decoded_events(): from harness.reporting.publication_privacy import project_evidence_view, publication_file_risk event = json.dumps({'event':'native_response','body':json.dumps({'token':'synthetic-secret', diff --git a/tests/test_saved_matrix_evidence.py b/tests/test_saved_matrix_evidence.py index 217a89b43..91ac0d108 100644 --- a/tests/test_saved_matrix_evidence.py +++ b/tests/test_saved_matrix_evidence.py @@ -372,8 +372,11 @@ def test_changed_final_public_answer_requires_current_scoring_version(tmp_path): _record_public_views(source, record, case) -@pytest.mark.parametrize('mode', ['unchanged', 'changed', 'language_invariant', 'language_ambiguous', 'tampered']) -def test_native_retry_public_views_require_bound_verdict_invariant_inputs(tmp_path, mode): +@pytest.mark.parametrize('mode', ['unchanged', 'changed', 'language_invariant', 'language_ambiguous', + 'tampered', 'missing_events', 'status_mismatch', + 'redacted_redirect', 'wrong_redirect']) +@pytest.mark.parametrize('transport', ['worker', 'direct']) +def test_native_retry_public_views_require_bound_verdict_invariant_inputs(tmp_path, mode, transport): from harness.web_fetch.native_projection import native_projection_policy, native_projection_source from harness.web_fetch.report_saved_matrix import _record_public_views from lexbench_webfetch.scoring import SCORING_SOURCE_SHA256 @@ -389,38 +392,63 @@ def test_native_retry_public_views_require_bound_verdict_invariant_inputs(tmp_pa answer = ('meta-csrf-token: '+secret+'\nanswer').encode() early = source/'artifacts/early.txt' early.write_bytes(answer) - record.update(provider_type='kimi_fetch') + provider_type = 'lexmount' if transport == 'direct' else 'kimi_fetch' + record.update(provider_type=provider_type) record['metrics']['scoring_source_sha256'] = SCORING_SOURCE_SHA256 - policy = native_projection_policy('kimi_fetch') + policy = native_projection_policy(provider_type) policy_path = source/policy['source_path'] policy_path.parent.mkdir() - policy_path.write_bytes(native_projection_source('kimi_fetch')) + policy_path.write_bytes(native_projection_source(provider_type)) + payload = ({'result':{'main_text':answer.decode(),'title':'Example','url':case['url']}} + if transport == 'direct' else {'markdown':answer.decode(),'title':'Example','url':case['url']}) + if mode == 'redacted_redirect': + (payload['result'] if transport == 'direct' else payload)['url'] += '?token=synthetic-secret' raw = write(source/'private_artifacts/early.response.bin', - {'markdown':answer.decode(),'title':'Example','url':case['url']}) + payload) events = write(source/'private_artifacts/early.stderr.log', - {'event':'http_response_received','status':200}) + {'event':'other' if mode == 'missing_events' else 'http_response_received', + 'status':200.0 if mode == 'status_mismatch' else 200}) digest = hashlib.sha256(answer).hexdigest() - log = write(source/'call-logs/early.json', {'output':{'sha256':digest}, + call_log = {'output':{'sha256':digest}, 'timing':{'elapsed_ms':1,'deadline_budget_ms':30000,'deadline_overrun':False}, - 'response':{'final_url':case['url']}}) + 'response':{'final_url':case['url']}} + if mode == 'redacted_redirect': + from harness.web_fetch.runner import _public_url + call_log['response']['final_url'] = _public_url(case['url']+'?token=synthetic-secret') + elif mode == 'wrong_redirect': + call_log['response']['final_url'] = 'https://unrelated.test/' + if transport == 'direct': + call_log.update(capture={'diagnostic_log':'not_retained'}, request={'route':'v1_extract_native'}, + events=[{'stage':'response_received','status_code':200}]) + call_log['response']['status_code'] = 200 + if mode == 'missing_events': + call_log['events'] = [] + elif mode == 'status_mismatch': + call_log['events'][0]['status_code'] = 201 + log = write(source/'call-logs/early.json', call_log) for binding in (raw,events,log): binding['bytes'] = Path(binding['path']).stat().st_size binding['path'] = Path(binding['path']).relative_to(source).as_posix() call = {'artifact_path':'artifacts/early.txt','content_sha256':digest, 'artifact_paths':['artifacts/early.txt'],'artifact_sha256':{'artifacts/early.txt':digest}, - 'elapsed_ms':1,'task_pass':False,'ok':True,'status_code':None,'private_artifacts':[raw,events], + 'elapsed_ms':1,'task_pass':False,'ok':True,'status_code':200 if transport == 'direct' else None, + 'private_artifacts':[raw] if transport == 'direct' else [raw,events], 'call_log':log,'native_route_receipt':{'answer_selection_policy':policy, - 'answer_fields':['markdown','title','url'], - 'requests':[{'signature':{'interface':'fetch'}}]}} + 'answer_fields':(['result.main_text','result.final_url','result.url','result.title', + 'result.links','result.images','result.extra','result.author','result.publish_time'] + if transport == 'direct' else ['markdown','title','url']), + 'requests':[{'signature':({'interface':'/v1/extract','transport':'http','parameters':{'method':'POST'}} + if transport == 'direct' else {'interface':'fetch'})}]}} record['provider_metadata']['retry'] = {'attempts':[call]} if mode == 'tampered': (source/raw['path']).write_bytes(b'altered response') - if mode in {'unchanged', 'language_invariant'}: + if mode in {'unchanged', 'language_invariant', 'redacted_redirect'}: views = _record_public_views(source,record,case) assert secret.encode() not in next(public for binding,public,_ in views if binding['path']==call['artifact_path']) else: reason = {'changed':'changes task acceptance','language_ambiguous':'unretained language', - 'tampered':'original scoring inputs'}[mode] + 'tampered':'original scoring inputs','missing_events':'original scoring inputs', + 'status_mismatch':'original scoring inputs','wrong_redirect':'original scoring inputs'}[mode] with pytest.raises(ValueError,match=reason): _record_public_views(source,record,case) assert early.read_bytes() == answer From 4d8ad385c22e8f45f886f81689db8ef60b3d3be3 Mon Sep 17 00:00:00 2001 From: Maisiqi <324751762+Maisiqi@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:54:23 +0800 Subject: [PATCH 3/4] fix(webfetch): distinguish web routes from evidence paths --- src/harness/web_fetch/report_saved_matrix.py | 15 +++++++++++---- tests/test_saved_matrix_evidence.py | 19 +++++++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/harness/web_fetch/report_saved_matrix.py b/src/harness/web_fetch/report_saved_matrix.py index d651ec3de..61f7ff885 100644 --- a/src/harness/web_fetch/report_saved_matrix.py +++ b/src/harness/web_fetch/report_saved_matrix.py @@ -61,8 +61,8 @@ def _write(path, value): _write_bytes(path, json_bytes(value)) -def _require_public_json(receipt, *, label="Missing receipt"): - """Reject private values and absolute path fields in distributable JSON.""" +def _require_public_json(receipt, *, label="Missing receipt", native_response=False): + """Reject private values and local evidence paths; native page_path is a web route.""" from harness.reporting.publication_privacy import publication_risk risk = publication_risk(json_bytes(receipt)) @@ -73,7 +73,13 @@ def local_path(value): # scan above still rejects actual home paths and secrets there. web_route = (isinstance(value.get('hosts'), list) and bool(value['hosts']) and all(isinstance(host, str) and host for host in value['hosts'])) - return any((key.endswith('path') and not (key == 'entry_path' and web_route) and isinstance(item, str) + api_route = (isinstance(value.get('method'), str) and value['method'].upper() in { + 'GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'TRACE'}) + return any((key.endswith('path') and not (key == 'entry_path' and web_route) + and not (key == 'path' and api_route and isinstance(item, str) + and item.startswith('/') and not item.startswith('//')) + and not (key == 'page_path' and native_response and isinstance(item, str) + and item.startswith('/') and not item.startswith('//')) and isinstance(item, str) and (item.startswith(('/', '~', '\\')) or re.match(r'^[A-Za-z]:', item))) or local_path(item) for key, item in value.items()) if isinstance(value, list): @@ -2700,7 +2706,8 @@ def _check_saved_matrix(output: Path, *, spec_path: Path | None = None, approved values = [] for value in values: try: - _require_public_json(value, label='Saved report file') + _require_public_json(value, label='Saved report file', + native_response='/public-evidence/native-responses/' in '/' + relative) except ValueError as exc: raise ValueError(str(exc)+': '+relative) from exc model = _json(output / 'matrix.json') diff --git a/tests/test_saved_matrix_evidence.py b/tests/test_saved_matrix_evidence.py index 91ac0d108..6fdc6e75a 100644 --- a/tests/test_saved_matrix_evidence.py +++ b/tests/test_saved_matrix_evidence.py @@ -454,6 +454,25 @@ def test_native_retry_public_views_require_bound_verdict_invariant_inputs(tmp_pa assert early.read_bytes() == answer +def test_native_page_path_is_a_web_route_without_relaxing_evidence_path_or_secret_checks(): + from harness.web_fetch.report_saved_matrix import _require_public_json + response = {'result':{'url':'https://example.test/zh/docs', 'extra':{'page_path':'/zh/docs'}}} + _require_public_json(response, native_response=True) + _require_public_json({'method':'GET', 'path':'/pet/{petId}', 'summary':'Get pet'}) + _require_public_json({'schema':{'method':{'type':'string'}, 'path':{'type':'string'}}}) + with pytest.raises(ValueError, match='private content'): + _require_public_json(response) + for value in ({'artifact_path':'/tmp/record.json'}, + {'method':'GET', 'artifact_path':'/tmp/record.json'}, + {'method':'GET', 'path':'C:\\private\\record.json'}, + {'method':'download', 'path':'/tmp/record.json'}, + {'result':{'extra':{'page_path':'C:\\private\\record.json'}}}, + {'result':{'extra':{'page_path':'/Users/fixture/private.txt'}}}, + {'authorization':'Bearer synthetic-secret'}): + with pytest.raises(ValueError, match='private content'): + _require_public_json(value, native_response=True) + + def test_public_views_keep_binary_attachments_and_native_stderr(tmp_path): spec, source, record, _ = fixture(tmp_path) spec['public_evidence_views'] = True From 267c7a66bcd33b48413a45b36e1bb7cf1879f697 Mon Sep 17 00:00:00 2001 From: Maisiqi <324751762+Maisiqi@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:57:29 +0800 Subject: [PATCH 4/4] fix(webfetch): retain source context in frozen report views --- .agents/skills/benchmark-report/SKILL.md | 3 + src/harness/reporting/release_check.py | 8 ++- src/harness/web_fetch/README.md | 3 + .../web_fetch/data/report-methods.json | 1 + src/harness/web_fetch/methods.py | 6 +- src/harness/web_fetch/report.py | 5 +- src/harness/web_fetch/report_explainer.py | 8 +-- src/harness/web_fetch/report_model.py | 3 +- src/harness/web_fetch/report_package.py | 9 ++- .../web_fetch/report_saved_composition.py | 72 +++++++++++++++++-- src/harness/web_fetch/report_saved_matrix.py | 2 +- tests/test_configuration_comparisons.py | 52 ++++++++++++++ tests/test_report_method_registry.py | 8 +++ tests/test_saved_report_explainer.py | 17 +++++ 14 files changed, 180 insertions(+), 17 deletions(-) diff --git a/.agents/skills/benchmark-report/SKILL.md b/.agents/skills/benchmark-report/SKILL.md index abf2d6ee8..eae671be7 100644 --- a/.agents/skills/benchmark-report/SKILL.md +++ b/.agents/skills/benchmark-report/SKILL.md @@ -76,6 +76,9 @@ For a separate configuration experiment, use the saved publication owner's `configuration_comparisons` instead of adding participants to its leaderboard. Bind a complete saved comparison and retain its original task contracts, scores, languages and evidence. The Web Fetch guide documents its build and check contract. +Retain each selected source's execution settings. Presentation gates verify the +hash-bound predecessor HTML and apply current semantic checks to new projections, +including embedded comparisons; diagnostic views do not introduce winner styling. When adding saved methods to an existing publication, inspect both frozen task contracts and scorer identities before combining ranks. Different editions retain diff --git a/src/harness/reporting/release_check.py b/src/harness/reporting/release_check.py index b2b3ae4e5..0ba3b8322 100644 --- a/src/harness/reporting/release_check.py +++ b/src/harness/reporting/release_check.py @@ -124,6 +124,8 @@ class ReleaseRules: ``identity`` and ``evidence`` are the track's own rules. ``languages`` and ``links`` default to the shared checks; a track replaces one only when its layout differs, and names the replacement's reason where it declares it. + Presentation defaults to the shared checker. A frozen-template adapter may + retain verified predecessor markup while checking every current view. """ identity: Callable[[Path], object] @@ -131,13 +133,15 @@ class ReleaseRules: languages: Callable[[Path], object] | None = check_language_editions links: Callable[[Path], object] | None = check_links visual: VisualReceipt | None = None + presentation: Callable[[Path], object] | None = None def validate_release(report, rules: ReleaseRules) -> dict[str, object]: """Run the release gate in its fixed order and return each stage's result. Order: identity, languages, links, presentation, evidence bindings, visual - receipt. The presentation stage is shared and always runs. + receipt. Presentation always runs; frozen-source adapters retain old HTML + identities while applying the shared checker to current views. """ root = open_report(report) results: dict[str, object] = {"identity": rules.identity(root)} @@ -145,7 +149,7 @@ def validate_release(report, rules: ReleaseRules) -> dict[str, object]: results["languages"] = rules.languages(root) if rules.links is not None: results["links"] = rules.links(root) - results["presentation"] = check_report_presentation(root) + results["presentation"] = (rules.presentation or check_report_presentation)(root) if rules.evidence is not None: results["evidence"] = rules.evidence(root) if rules.visual is not None: diff --git a/src/harness/web_fetch/README.md b/src/harness/web_fetch/README.md index 7670addcf..30f4ec780 100644 --- a/src/harness/web_fetch/README.md +++ b/src/harness/web_fetch/README.md @@ -1710,6 +1710,9 @@ This appends the separate comparisons and retains every original page and result it does not rebuild the leaderboard with a newer renderer. Packaging resolves lazy evidence against each frozen report's own file inventory, including nested source reports. +Selected sources retain their verified execution settings. The release gate keeps +hash-bound predecessor HTML under its original renderer and checks all current +views and embedded comparisons with the shared semantic presentation rules. When composing frozen reports with different task ID namespaces, `saved_reports[].case_id_mapping` maps every `suite--source_id` to a unique target ID within that suite. This requires `retain_source_task_contracts`; task names, diff --git a/src/harness/web_fetch/data/report-methods.json b/src/harness/web_fetch/data/report-methods.json index 3b6519ffd..22d010505 100644 --- a/src/harness/web_fetch/data/report-methods.json +++ b/src/harness/web_fetch/data/report-methods.json @@ -157,6 +157,7 @@ } }, "lexmount": { + "engine_is_method": false, "endpoint": "POST https://api.lexmount.com/v1/extract", "contract": { "zh": "已知 URL → 主正文 + 元数据", diff --git a/src/harness/web_fetch/methods.py b/src/harness/web_fetch/methods.py index 6645856f2..a04e186c1 100644 --- a/src/harness/web_fetch/methods.py +++ b/src/harness/web_fetch/methods.py @@ -139,8 +139,10 @@ def report_method(name, record=None, *, language="zh", scope): methods = (report_method_catalog() if language == "zh" else report_method_catalog(language))["methods"] record = record or scope.records.get(name, {}) metadata = record.get("provider_metadata") or {} - if metadata.get("engine"): - return methods.get(metadata["engine"], {}) + engine = metadata.get('engine') + adapter = report_method_catalog(language)['adapters'].get(record.get('provider_type'), {}) + if engine and adapter.get('engine_is_method', True): + return methods.get(engine, {}) if isinstance(engine, str) else {} execution = browser_method_registry(scope=scope).get(name, {}) for key in (execution.get("engine"), name): if key in methods: diff --git a/src/harness/web_fetch/report.py b/src/harness/web_fetch/report.py index 59d402f79..1936f50d9 100644 --- a/src/harness/web_fetch/report.py +++ b/src/harness/web_fetch/report.py @@ -457,9 +457,9 @@ def comparative_rows(rows, directions, *, ctx): metric,direction=directions[index];column,extreme,unique=numbers[index] fragment=cells[index].group();opening,body=fragment.split('>',1) if column[row_number] is None:opening=re.sub(r' data-sort="[^"]+"','',opening) - opening+=' data-metric="'+metric+'" data-metric-direction="'+direction+'"' + opening+=' data-metric="'+metric+'" data-metric-direction="'+(direction if ctx.comparison_highlights else 'neutral')+'"' content=body[:-5] - if (unique or ctx.descriptive_ranks) and column[row_number] is not None and column[row_number]==extreme: + if ctx.comparison_highlights and (unique or ctx.descriptive_ranks) and column[row_number] is not None and column[row_number]==extreme: content=''+content+'' values=values[:cells[index].start()]+opening+'>'+content+''+values[cells[index].end():] result.append((attrs,values)) @@ -2076,6 +2076,7 @@ def _render_model(out,dataset,records,manifests,*,model,scope): score_binding=dataset.get('comparison',{}).get('score_audit') score_audit=json.loads(contained_path(out,score_binding['path']).read_text(encoding='utf-8')) if score_binding else None diagnostic=bool(score_audit) or (local_snapshot and not local_pass_rate_ranking(dataset)) + ctx=replace(ctx,comparison_highlights=not diagnostic) if local_snapshot and not show_local_status_banners: raise ValueError('Uncertified local diagnostic status cannot be hidden') reliability=assess_reliability(dataset,records) diff --git a/src/harness/web_fetch/report_explainer.py b/src/harness/web_fetch/report_explainer.py index 062c41f34..3c1e26dff 100644 --- a/src/harness/web_fetch/report_explainer.py +++ b/src/harness/web_fetch/report_explainer.py @@ -1098,7 +1098,7 @@ def handle_endtag(self,tag): def _saved_failure_chapters(cases, records, *, ctx): """Explain the full failure population using recorded program evidence only.""" - from harness.web_fetch.report import provider_label, measured, succeeded, result_case, result_href + from harness.web_fetch.report import provider_label, measured, succeeded, result_case, result_href, failure_category heading = t('saved_failure_chapters', 'Why each method did not pass') note = t('saved_failure_categories_note', 'These categories cover every failed result and come from program checks and returned evidence. One category can have different causes; unreviewed results do not establish a site or provider root cause.') chapters = [] @@ -1108,8 +1108,7 @@ def _saved_failure_chapters(cases, records, *, ctx): failed = [row for row in eligible if not succeeded(row, cases[row['case_id']], ctx=ctx)] grouped = {} for row in failed: - category = (row.get('diagnosis') or {}).get('category') or t( - 'failed_without_detailed_diagnosis', 'Failed without a detailed diagnosis') + category = failure_category(row, cases[row['case_id']], ctx=ctx) grouped.setdefault(category, []).append(row) rows, examples = [], [] for category, members in sorted(grouped.items(), key=lambda item: (-len(item[1]), item[0])): @@ -1173,7 +1172,8 @@ def render_explainer(out, cases, records, *, table=None, cell=None, link=None, a context = '
'+report_table( [t('method', 'Method'), t('saved_results', 'Saved results'), t('saved_passed', 'Passed'), t('saved_pass_rate', 'Pass rate')], - comparative_rows(rows,{3:('saved-guide-pass-rate','max')}, ctx=ctx),metrics=[])+'
' + comparative_rows(rows,{} if scope.get('presentation') == 'audit' else { + 3:('saved-guide-pass-rate','max')}, ctx=ctx),metrics=[])+'' context += '

'+t('saved_task_acceptance_note', 'Passing requires every applicable task check to succeed. Returned content can still omit required passages, records, resources or files; result details retain the full returned output and frozen reference.')+'

' context += _saved_failure_chapters(cases, records, ctx=ctx) context += '

' + bilingual_text('结果说明与限制', 'Findings and limitations') + '

' diff --git a/src/harness/web_fetch/report_model.py b/src/harness/web_fetch/report_model.py index 733017273..c5d303775 100644 --- a/src/harness/web_fetch/report_model.py +++ b/src/harness/web_fetch/report_model.py @@ -158,8 +158,9 @@ class RenderContext: scope_presentation: dict | None = None descriptive_ranks: bool = False result_views: dict | None = None - source_root: Path | None = None methods: MethodScope = field(default_factory=MethodScope) + source_root: Path | None = None + comparison_highlights: bool = True def model_render_context(model=None, *, methods, descriptive_ranks=False, result_views=None, source_root=None): diff --git a/src/harness/web_fetch/report_package.py b/src/harness/web_fetch/report_package.py index 2693fda6e..187972012 100644 --- a/src/harness/web_fetch/report_package.py +++ b/src/harness/web_fetch/report_package.py @@ -71,7 +71,14 @@ def identity(root: Path) -> None: def evidence(root: Path) -> bool: return _certified_evidence(root) if kind['certified'] else False - return gate(source, ReleaseRules(identity=identity, evidence=evidence, links=None))['evidence'] + # Frozen predecessor pages keep their original renderer. Their hash-bound + # bytes are checked by identity; current projections use the shared UI rules. + presentation = None + if (source/'saved-extension.json').is_file() or (source/'saved-composition.json').is_file(): + from harness.web_fetch.report_saved_composition import check_saved_presentation + presentation = check_saved_presentation + return gate(source, ReleaseRules(identity=identity, evidence=evidence, links=None, + presentation=presentation))['evidence'] def _release_identity(source: Path, presentation_binding, snapshot_audit) -> bool: diff --git a/src/harness/web_fetch/report_saved_composition.py b/src/harness/web_fetch/report_saved_composition.py index 0da83662b..160533d9d 100644 --- a/src/harness/web_fetch/report_saved_composition.py +++ b/src/harness/web_fetch/report_saved_composition.py @@ -1032,6 +1032,61 @@ def _check_frozen_configuration_extension(output, proof): 'providers': len(proof['providers']), 'provider_calls_added': 0, 'frozen_base': True} +def check_saved_presentation(output): + """Check current views while retaining hash-bound predecessor HTML unchanged. + + The release identity stage verifies these source inventories first. A new + comparison and every current detail still use the shared semantic checker. + """ + from bs4 import BeautifulSoup + from harness.reporting.presentation import check_presentation + frozen, homes, roots = {}, {}, [output] + proof_path = output/'saved-extension.json' + if proof_path.is_file(): + proof = _read(proof_path) + if proof.get('configuration_base'): + base = proof['configuration_base'] + authority = _read(output/base['path']) + frozen.update({name:digest for name,digest in authority['files'].items() + if name not in base['homes']}) + homes = {route:output/path for route,path in base['homes'].items()} + else: + authority = _read(output/'saved-matrix-audit.json') + frozen.update({name:digest for name,digest in authority['files'].items() + if name != 'index.html' and name not in proof.get('presentation_pages', [])}) + added = _read(output/'additional/saved-matrix-audit.json') + frozen.update({'additional/'+name:digest for name,digest in added['files'].items()}) + homes['index.html'] = output/'extension-base-home.txt' + roots.extend(output/entry['path'] for entry in proof.get('configuration_comparisons', [])) + for root in roots: + composition = root/'saved-composition.json' + if not composition.is_file() or composition.relative_to(output).as_posix() in frozen: + continue + model = _read(root/'matrix.json') + for prefix in model.get('frozen_source_prefixes', []): + source = root/prefix + authority = _read(source/'saved-matrix-audit.json') + frozen.update({(source/name).relative_to(output).as_posix():digest + for name,digest in authority['files'].items()}) + checked = 0 + for page in sorted(output.rglob('*.html')): + relative = page.relative_to(output).as_posix() + if relative in frozen: + if _hash(page) != frozen[relative]: + raise ValueError('Frozen presentation changed: '+relative) + continue + document = BeautifulSoup(page.read_text(encoding='utf-8'), 'html.parser') + if relative in homes: + original = BeautifulSoup(homes[relative].read_text(encoding='utf-8'), 'html.parser') + for table in original.select('table[id]'): + current = document.find('table', id=table['id']) + if current is not None and str(current) == str(table): + current.decompose() + check_presentation(document) + checked += 1 + return checked + + def check_published_extension(output): from bs4 import BeautifulSoup proof = _read(output / 'saved-extension.json') @@ -1271,6 +1326,7 @@ def _public_spec(spec): def composition_model(output, spec, snapshots): from harness.web_fetch.report_saved_matrix import _case_identity, _totals, check_saved_matrix providers, rows, cases, suites, families = [], [], {}, None, None + execution_settings = [] expected_population = None for snapshot in snapshots: if snapshot['path'] != 'evidence/saved-reports/' + safe_identifier(snapshot['id']): @@ -1332,12 +1388,16 @@ def composition_model(output, spec, snapshots): if 'score_revision' in row: row['source_score_revision'] = row.pop('score_revision') rows.extend(projected) + selected_providers = {provider['id'] for provider in model['providers']} + execution_settings.extend(deepcopy(group) for group in model.get('execution_settings', []) + if group['provider'] in selected_providers) if not rows: raise ValueError('Saved composition requires reports') result = dict(title=spec['title'], providers=providers, suites=suites, rows=rows, totals=_totals(rows), limitations=spec.get('limitations', []), presentation=spec.get('presentation', 'audit'), combined_ranking=spec.get('combined_ranking', True), + execution_settings=execution_settings, source_bindings=[{'name': s['id'], 'sha256': s['sha256']} for s in snapshots], scores_changed=any(row.get('score_revision') or row.get('source_score_revision') for row in rows)) if families is not None: @@ -1389,14 +1449,18 @@ def render_source_reviews(output, model): elif not urlsplit(href).scheme and not urlsplit(href).netloc: target = urlsplit(urljoin('https://report.invalid/' + source['path'], href)) node['href'] = '../' + target.path.lstrip('/') + ('#' + target.fragment if target.fragment else '') - section = page.new_tag('section', attrs={'data-source-review': source['path']}) - heading = page.new_tag('h2') + section = page.new_tag('section', attrs={'class':'section', 'data-source-review': source['path']}) + body = page.new_tag('div', attrs={'class':'wrap'}) + section.append(body) + heading = page.new_tag('h2', attrs={'style':'font-size:1.25rem;line-height:1.5'}) heading.string = ', '.join(p.get('label', p['id']) for p in source['providers']) - section.append(heading) + body.append(heading) + for inherited in content.select('h2'): + inherited['style'] = 'font-size:1.25rem;line-height:1.5' for title in content.find_all('h1'): title.decompose() for child in list(content.children): - section.append(child) + body.append(child) main.append(section) path.write_text(str(page), encoding='utf-8') diff --git a/src/harness/web_fetch/report_saved_matrix.py b/src/harness/web_fetch/report_saved_matrix.py index 61f7ff885..eae446b41 100644 --- a/src/harness/web_fetch/report_saved_matrix.py +++ b/src/harness/web_fetch/report_saved_matrix.py @@ -3030,7 +3030,7 @@ def project(value, key='', prefix=prefix): records.append(record) identities.append({'case_route': route, 'attempt_route': record['attempt_id'], 'source_record': row['record_path'], 'source_case': row['case_path']}) - scope = {'providers': [], 'limitations': model.get('limitations', []), 'missing': [r for r in model['rows'] + scope = {'presentation':model.get('presentation','audit'), 'providers': [], 'limitations': model.get('limitations', []), 'missing': [r for r in model['rows'] if r['passed'] is None or not r['called']]} scope['execution_settings'] = model.get('execution_settings', []) reruns = [r['parameter_rerun'] for r in model['rows'] if r.get('parameter_rerun')] diff --git a/tests/test_configuration_comparisons.py b/tests/test_configuration_comparisons.py index e53a4895f..ed0503045 100644 --- a/tests/test_configuration_comparisons.py +++ b/tests/test_configuration_comparisons.py @@ -76,6 +76,16 @@ def test_configuration_comparison_keeps_leaderboard_population_and_checks_eviden frozen_spec = tmp_path / 'frozen-extension.json' previous = tmp_path / 'baseline/extended' source_proof = previous / 'saved-extension.json' + # An older renderer highlighted all tied extrema without the later HTML + # marker. Retain that frozen table while checking every new comparison. + legacy = '' + ''.join( + '' + for _ in range(2)) + '
1
' + home = previous/'index.html' + home.write_text(home.read_text(encoding='utf-8').replace('', legacy+''), encoding='utf-8') + prior = json.loads(source_proof.read_bytes()) + prior['files']['index.html'] = hashlib.sha256(home.read_bytes()).hexdigest() + write(source_proof, prior) write(frozen_spec, {'published_base': {'root': str(previous), 'audit': { 'path': str(source_proof), 'sha256': hashlib.sha256(source_proof.read_bytes()).hexdigest()}}, 'configuration_comparisons': spec['configuration_comparisons']}) @@ -91,6 +101,27 @@ def test_configuration_comparison_keeps_leaderboard_population_and_checks_eviden if name != 'index.html': assert (frozen / name).read_bytes() == (previous / name).read_bytes() assert refresh_published_extension(frozen, spec_path=frozen_spec)['valid'] + from harness.web_fetch.report_package import validate_release + assert validate_release(frozen) is False + # A newly embedded comparison is still checked even when its source audit + # retains the altered bytes exactly. + bad_page = BeautifulSoup((comparison/'index.html').read_text(encoding='utf-8'), 'html.parser') + for index, cell in enumerate(bad_page.select('#ranking-overall tbody tr > td:first-child')): + cell['data-metric'], cell['data-metric-direction'], cell['data-sort'] = 'control', 'max', str(2-index) + if index: + marker = bad_page.new_tag('strong', attrs={'class':'comparison-winner'}) + marker.string = 'wrong' + cell.append(marker) + (comparison/'index.html').write_text(str(bad_page), encoding='utf-8') + changed = json.loads(audit.read_bytes()) + changed['files']['index.html'] = hashlib.sha256((comparison/'index.html').read_bytes()).hexdigest() + new_audit = write(audit, changed) + bad_spec = json.loads(frozen_spec.read_bytes()) + bad_spec['configuration_comparisons'][0]['audit'] = new_audit + write(tmp_path/'bad-highlight.json', bad_spec) + bad_report = build_saved_matrix(tmp_path/'bad-highlight.json', tmp_path/'bad-highlight').parent + with pytest.raises(ValueError, match='highlight'): + validate_release(bad_report) frozen_content = tmp_path / 'packed-frozen' extend_published_content(frozen, packed, frozen_content) frozen_archive = tmp_path / 'frozen.zip' @@ -216,3 +247,24 @@ def test_frozen_comparison_keeps_each_saved_task_contract(tmp_path): assert all('report_source_case' not in record for record in records) assert all(row['passed'] for row in json.loads((output/'matrix.json').read_bytes())['rows']) + +def test_composition_retains_selected_execution_settings_and_review_layout(tmp_path): + spec, entries = reports(tmp_path) + expected = [group for entry in entries + for group in json.loads((Path(entry['root'])/'matrix.json').read_bytes())['execution_settings']] + assert expected + config = json.loads(spec.read_bytes()) + config['retain_source_reviews'] = True + write(spec, config) + output = build_saved_matrix(spec, tmp_path/'combined').parent + model = json.loads((output/'matrix.json').read_bytes()) + assert model['execution_settings'] == expected + from bs4 import BeautifulSoup + method = BeautifulSoup((output/'methodology/index.html').read_text(encoding='utf-8'), 'html.parser') + assert method.select_one('#execution-settings') + assert not BeautifulSoup((output/'index.html').read_text(encoding='utf-8'), 'html.parser').select('.comparison-winner') + review = BeautifulSoup((output/'review/index.html').read_text(encoding='utf-8'), 'html.parser') + assert len(review.select('section.section[data-source-review] > .wrap')) == 2 + guide = BeautifulSoup((output/'guide/index.html').read_text(encoding='utf-8'), 'html.parser') + assert not guide.select('[aria-label] .comparison-winner') + diff --git a/tests/test_report_method_registry.py b/tests/test_report_method_registry.py index f380e9ee8..21d95e344 100644 --- a/tests/test_report_method_registry.py +++ b/tests/test_report_method_registry.py @@ -417,6 +417,14 @@ def render(out, dataset, records, *, scope): assert render(tmp_path, {}, [row]) == "new-engine" + (" 2.3.4" if version else "") +@pytest.mark.parametrize('engine', ['lightmount_domstable', 'lightmount_lite', 'lightmount_dcl', None]) +def test_service_route_engine_keeps_api_account_requirements(engine): + row = {'provider':'renamed-api', 'provider_type':'lexmount', 'provider_metadata':{'engine':engine}} + access = method_access('renamed-api', [row], scope=MethodScope()) + assert access['type'] == 'hosted' + assert access['env_vars'] == ['LEXMOUNT_API_KEY', 'LEXMOUNT_PROJECT_ID'] + + @pytest.mark.parametrize("provider, version, expected", [ ("obscura", "obscura 0.2.2", "Obscura 0.2.2"), ("lightpanda", "Lightpanda 0.4.1+build.7", "Lightpanda 0.4.1+build.7"), diff --git a/tests/test_saved_report_explainer.py b/tests/test_saved_report_explainer.py index 84e7d2c26..3b6981eca 100644 --- a/tests/test_saved_report_explainer.py +++ b/tests/test_saved_report_explainer.py @@ -36,6 +36,23 @@ def test_unbound_report_does_not_invent_saved_findings(tmp_path): assert '0/0' in page +def test_saved_failures_use_the_same_program_category_as_result_details(tmp_path): + from bs4 import BeautifulSoup + from harness.web_fetch.report import failure_category + case = {'id':'one', 'task_kind':'body', 'url':'https://example.test/'} + record = {'provider':'api', 'provider_type':'lexmount', 'case_id':'one', + 'attempt_id':'api-one', 'ok':False, 'status_code':502, + 'error_type':'api_error', 'error_message':'proxy CONNECT returned HTTP 502', + 'metrics':{'content_pass':False}} + (tmp_path/'dataset.json').write_text(json.dumps({'saved_matrix_scope':{ + 'presentation':'audit', 'limitations':[]}}), encoding='utf-8') + page = BeautifulSoup(render_explainer(tmp_path, {'one':case}, [record], authored=False, + ctx=RenderContext()), 'html.parser') + category = failure_category(record, case, ctx=RenderContext()) + assert category in page.select_one('[data-method-failures]').get_text() + assert not page.select('.comparison-winner') + + def test_saved_failure_chapters_cover_every_method_and_failure_with_exact_evidence(tmp_path): from copy import deepcopy from bs4 import BeautifulSoup