From 3fb443a0e0536e65115cfe9ff13bde9ca21fc2c1 Mon Sep 17 00:00:00 2001
From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com>
Date: Tue, 3 Nov 2026 15:16:27 +0800
Subject: [PATCH 001/103] feat(web-scraper): add frozen product extraction
evaluation pipeline
---
.env.example | 7 +
README.md | 3 +-
THIRD_PARTY.md | 1 +
configs/report-templates.json | 16 +
docs/README.zh-CN.md | 3 +-
examples/web_scraper/README.md | 111 ++
pyproject.toml | 9 +
scripts/run_certified_benchmark.py | 3 +-
.../cards/zyte-product-extraction.json | 42 +
src/harness/reporting/certified_cli.py | 14 +
src/harness/web_scraper/__init__.py | 1 +
src/harness/web_scraper/certification.py | 153 +++
src/harness/web_scraper/cli.py | 99 ++
src/harness/web_scraper/example.py | 126 ++
src/harness/web_scraper/pipeline.py | 1015 +++++++++++++++++
src/harness/web_scraper/report.py | 549 +++++++++
src/harness/web_scraper/stagehand.py | 128 +++
tests/web_scraper/test_certification.py | 42 +
tests/web_scraper/test_pipeline.py | 448 ++++++++
uv.lock | 140 ++-
20 files changed, 2906 insertions(+), 4 deletions(-)
create mode 100644 examples/web_scraper/README.md
create mode 100644 src/harness/benchmarks/cards/zyte-product-extraction.json
create mode 100644 src/harness/reporting/certified_cli.py
create mode 100644 src/harness/web_scraper/__init__.py
create mode 100644 src/harness/web_scraper/certification.py
create mode 100644 src/harness/web_scraper/cli.py
create mode 100644 src/harness/web_scraper/example.py
create mode 100644 src/harness/web_scraper/pipeline.py
create mode 100644 src/harness/web_scraper/report.py
create mode 100644 src/harness/web_scraper/stagehand.py
create mode 100644 tests/web_scraper/test_certification.py
create mode 100644 tests/web_scraper/test_pipeline.py
diff --git a/.env.example b/.env.example
index 43f287952..8b4b9027e 100644
--- a/.env.example
+++ b/.env.example
@@ -106,3 +106,10 @@ BOCHA_API_KEY=
# Optional, only for explicitly selected model relevance evaluation.
SEARCH_JUDGE_API_KEY=
SEARCH_JUDGE_BASE_URL=
+
+# Native product extraction: https://app.diffbot.com/get-started/
+DIFFBOT_API_TOKEN=
+# https://scrapegraphai.com/signup (v2 Extract)
+SGAI_API_KEY=
+# https://dashboard.oxylabs.io/ (current Web API Bearer authentication)
+OXYLABS_API_KEY=
diff --git a/README.md b/README.md
index 5ac461cbe..866d65ce6 100644
--- a/README.md
+++ b/README.md
@@ -12,7 +12,7 @@
-Benchmark browsers and Web tools for AI agents through Web Fetch, Web Search and Browser Trajectory Replay. Compare correctness, latency, resource use and recorded cost. Optionally turn saved results into local reports you can inspect, rebuild and share, with drilldown to every individual result.
+Benchmark browsers and Web tools for AI agents through Web Fetch, Web Search, Web Scraper and Browser Trajectory Replay. Compare correctness, latency, resource use and recorded cost. Optionally turn saved results into local reports you can inspect, rebuild and share, with drilldown to every individual result.
## Quickstart
@@ -38,6 +38,7 @@ Choose a workflow for its task contract, setup and runnable example.
| --- | --- | --- |
| Web Fetch | [LexBench-Web-Fetch](https://huggingface.co/datasets/Lexmount/LexBench-Web-Fetch), [LexBench-WebMainBench](https://huggingface.co/datasets/Lexmount/LexBench-WebMainBench), [LexBench-WCXB](https://huggingface.co/datasets/Lexmount/LexBench-WCXB) | [Local example](examples/web_fetch/README.md) · [Full guide](src/harness/web_fetch/README.md) |
| Web Search | [LexBench-Web-Search](https://huggingface.co/datasets/Lexmount/LexBench-Web-Search): scenario queries and [LexBench-SimpleQA-Verified](https://huggingface.co/datasets/Lexmount/LexBench-SimpleQA-Verified) retrieval tasks | [Local example](examples/web_search/README.md) · [Full guide](src/harness/web_search/README.md) |
+| Web Scraper | 140 archived product pages with upstream price, SKU and stock labels | [Archived product extraction](examples/web_scraper/README.md) |
| Browser Trajectory Replay | [LexBench-Headless-Browser](https://huggingface.co/datasets/Lexmount/LexBench-Headless-Browser) scenarios; [curated fixed-action tasks](https://huggingface.co/datasets/Lexmount/LexBench-Trajectory-Replay) with explicit checks; [WebArena replay](https://huggingface.co/datasets/Lexmount/LexBench-WebArena-Replay) with the official evaluator | [Headless inputs and upstream runner](https://huggingface.co/datasets/Lexmount/LexBench-Headless-Browser#execute-with-the-original-runner) · [Curated suite](examples/trajectory_replay/README.md) · [WebArena replay](examples/trajectory_replay/public_webarena/README.md) |
Use these suites or [bring your own tasks](docs/benchmarks.md). Add browsers and tools through the existing [adapter contracts](docs/provider-contract.md).
diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md
index 9642b8731..5641f87a9 100644
--- a/THIRD_PARTY.md
+++ b/THIRD_PARTY.md
@@ -8,6 +8,7 @@ The root Apache-2.0 license covers project-owned code and documentation. It does
| LexBench datasets | Hugging Face commits and hashes in `src/harness/benchmarks/data-lock.json` | Downloaded separately; preserve each snapshot's upstream notices. SimpleQA Verified data retains MIT attribution |
| WebArena-Verified | Source repository and commit pinned in `pyproject.toml` and `uv.lock` | Installed as a dependency; retain upstream license and attribution |
| Humanizer / Humanizer Chinese | [blader/humanizer](https://github.com/blader/humanizer), [jiji262/humanizer-chinese](https://github.com/jiji262/humanizer-chinese); commits and file hashes in each skill's `SOURCE.json` | MIT; upstream skill and license files are copied unchanged. See [skill sources and updates](.agents/skills/README.md) |
+| Zyte product extraction benchmark | [Upstream repository](https://github.com/scrapinghub/product-extraction-benchmark); commit and hashes in `src/harness/benchmarks/cards/zyte-product-extraction.json` | Downloaded separately; retain upstream MIT notices and source-page rights. No archived pages or measured provider outputs ship in Git or the wheel |
| WebMainBench | Pinned scorer and versioned dataset inputs selected by `src/harness/benchmarks/data-lock.json`; historical evidence retains its own bindings | Preserve upstream Apache-2.0 notices and source-page terms |
| WCXB dataset and metric adaptations | [Murrough Foley's Web Content Extraction Benchmark](https://github.com/Murrough-Foley/web-content-extraction-benchmark); the metric owner records the original evaluator hash | CC-BY-4.0. Token multiset F1 and snippet checks are adapted in `src/harness/web_fetch/wcxb_metrics.py`; retain the [original license](src/harness/licenses/WCXB-CC-BY-4.0.txt). Dataset snapshots retain upstream attribution, selection provenance and original input hashes |
| Independently captured pages, PDFs, media and reference snapshots | Task provenance, `evaluation/source-inputs.json` and each track's external evidence bindings | Private data storage; import approved copies through manifests. Public accessibility does not imply redistribution permission |
diff --git a/configs/report-templates.json b/configs/report-templates.json
index f5512e2c0..87255858a 100644
--- a/configs/report-templates.json
+++ b/configs/report-templates.json
@@ -64,6 +64,22 @@
"combined-cohorts"
],
"release_check": "uv run --frozen python scripts/build_search_report.py --output /absolute/report --release-check /absolute/visual-receipt.json --publication-plan /absolute/release/publication-plan.json"
+ },
+ "web-scraper": {
+ "renderer": "src/harness/web_scraper/report.py",
+ "entrypoint": "src/harness/web_scraper/cli.py",
+ "example": "examples/web_scraper/README.md",
+ "example_version": 1,
+ "example_build": "uv run --frozen python -m harness.web_scraper.example --output /tmp/scraper-example",
+ "build": "uv run --frozen python -m harness.web_scraper.cli report --profile /absolute/report-profile.json --content /absolute/content.json --output /absolute/report --language zh",
+ "check": "uv run --frozen python -m harness.web_scraper.cli check /absolute/report",
+ "tests": "tests/web_scraper/test_pipeline.py",
+ "variants": [
+ "research-and-compatibility",
+ "synthetic"
+ ],
+ "release_check": "uv run --frozen python -m harness.web_scraper.cli check /absolute/report --release --visual-receipt /absolute/visual-receipt.json",
+ "benchmark": "src/harness/benchmarks/cards/zyte-product-extraction.json"
}
}
}
diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.md
index 4d76c8eda..86a10d75f 100644
--- a/docs/README.zh-CN.md
+++ b/docs/README.zh-CN.md
@@ -12,7 +12,7 @@
-面向 AI Agent,评测浏览器与 Web 工具,覆盖内容抓取、搜索和 Browser Trajectory Replay。比较正确性、延迟、资源使用和已记录的成本,并可按需将保存的结果生成本地报告,下钻检查每一个结果,重建或分享报告。
+面向 AI Agent,评测浏览器与 Web 工具,覆盖内容抓取、搜索、商品字段提取和 Browser Trajectory Replay。比较正确性、延迟、资源使用和已记录的成本,并可按需将保存的结果生成本地报告,下钻检查每一个结果,重建或分享报告。
## 快速开始
@@ -38,6 +38,7 @@ uv run --frozen browser-harness-eval run --delay 0
| --- | --- | --- |
| Web Fetch | [LexBench-Web-Fetch](https://huggingface.co/datasets/Lexmount/LexBench-Web-Fetch)、[LexBench-WebMainBench](https://huggingface.co/datasets/Lexmount/LexBench-WebMainBench)、[LexBench-WCXB](https://huggingface.co/datasets/Lexmount/LexBench-WCXB) | [本地示例](../examples/web_fetch/README.md) · [完整指南](../src/harness/web_fetch/README.md) |
| Web Search | [LexBench-Web-Search](https://huggingface.co/datasets/Lexmount/LexBench-Web-Search):场景问题,以及 [LexBench-SimpleQA-Verified](https://huggingface.co/datasets/Lexmount/LexBench-SimpleQA-Verified) 检索任务 | [本地示例](../examples/web_search/README.md) · [完整指南](../src/harness/web_search/README.md) |
+| Web Scraper | 140 个归档商品页,使用上游价格、SKU 和库存标注 | [商品字段提取](../examples/web_scraper/README.md) |
| Browser Trajectory Replay | [LexBench-Headless-Browser](https://huggingface.co/datasets/Lexmount/LexBench-Headless-Browser) 固定场景、[自建固定动作任务](https://huggingface.co/datasets/Lexmount/LexBench-Trajectory-Replay)使用显式断言;[WebArena Replay](https://huggingface.co/datasets/Lexmount/LexBench-WebArena-Replay)使用官方评测器 | [Headless 输入与上游运行器](https://huggingface.co/datasets/Lexmount/LexBench-Headless-Browser#execute-with-the-original-runner) · [自建任务集](../examples/trajectory_replay/README.md) · [WebArena Replay](../examples/trajectory_replay/public_webarena/README.md) |
可使用这些评测集,也可[接入自己的任务](benchmarks.md)。新的浏览器和工具通过已有[适配接口](provider-contract.md)接入。
diff --git a/examples/web_scraper/README.md b/examples/web_scraper/README.md
new file mode 100644
index 000000000..295d36a77
--- /dev/null
+++ b/examples/web_scraper/README.md
@@ -0,0 +1,111 @@
+# Archived product extraction
+
+Evaluate complete extraction APIs on the 140 archived product pages in
+[Zyte's product extraction benchmark](https://github.com/scrapinghub/product-extraction-benchmark).
+The dataset commit, label hashes, original scorer and extruct baseline are pinned in
+[`zyte-product-extraction.json`](../../src/harness/benchmarks/cards/zyte-product-extraction.json).
+Page bytes, labels and upstream code are downloaded separately with their notices.
+
+## Prepare and reproduce
+
+```sh
+uv sync --frozen --extra web-scraper-eval --extra test
+uv run --frozen python -m harness.web_scraper.cli prepare
+uv run --frozen python -m harness.web_scraper.cli reproduce
+```
+
+The default data directory is `~/.browser-eval/web-scraper/`, configurable through
+`BROWSER_EVAL_DATA_HOME`. Evidence, report content and report-instance profiles stay
+outside Git. Runtime API credentials come from the repository `.env`; variable names
+are documented in `.env.example`. Never include credentials in a profile or report.
+
+Reproduction scores the upstream saved predictions. New provider runs use the same
+price, SKU and stock labels and original evaluator. Price and SKU require the
+original scorer's exact normalized values. Missing output contributes to recall;
+HTTP success alone does not establish extraction success. Bootstrap dispersion is
+reported as the upstream standard deviation, not a 95% confidence interval.
+Historical predictions are separate from new measurements.
+
+## Participants and inputs
+
+| Method ID | Complete interface | Input |
+| --- | --- | --- |
+| `cloudflare-json` | Browser Rendering JSON | Uploaded HTML and JSON Schema |
+| `firecrawl-json` | Scrape JSON | Frozen HTTPS URL and JSON Schema |
+| `scrapegraph-extract` | Hosted Extract | Uploaded HTML, instruction and JSON Schema |
+| `scrapfly-product` | Product Extraction | Raw uploaded HTML |
+| `oxylabs-json` | Web API JSON | Frozen HTTPS URL and JSON Schema |
+| `zyte-product` | Product extraction, `userHtml` | Uploaded HTML with original URL as context |
+| `diffbot-product` | Product API POST | Raw uploaded HTML with original URL as context |
+| `browserbase-stagehand` | Hosted Stagehand Extract | Frozen HTTPS URL; provider-hosted browser and inference |
+| `extruct` | Upstream local baseline | Archived HTML |
+
+Browser infrastructure requiring a separately connected model is outside this
+comparison. Stagehand uses its native Model Gateway; it does not read an OpenAI
+key. Bright Data's site-specific scraper remains discoverable as a candidate, but
+is rejected by the full archived-page plan because it cannot parse arbitrary HTML.
+
+URL-only interfaces need a reachable HTTPS address serving the frozen snapshots.
+Start the fixture origin with `serve --port 8767`, then expose that origin through
+an HTTPS reverse proxy. Only the registered HTML paths are served. Gzip transport
+preserves the original decompressed bytes. The collector checks every selected
+remote file against its frozen hash before and after collection. Original live
+websites are never substituted for archived inputs. External images and scripts
+are not archived, so browser rendering can still fetch those resources.
+
+## Freeze and run the full population
+
+```sh
+uv run --frozen python -m harness.web_scraper.cli plan \
+ --methods cloudflare-json firecrawl-json scrapegraph-extract scrapfly-product \
+ oxylabs-json zyte-product diffbot-product browserbase-stagehand extruct \
+ --output /absolute/data/full-cohort.json
+uv run --frozen python scripts/run_certified_benchmark.py --track web-scraper \
+ --profile /absolute/data/full-cohort.json --method firecrawl-json \
+ --run-dir /absolute/data/runs/firecrawl \
+ --fixture-base https://your-frozen-origin.example
+uv run --frozen python -m harness.web_scraper.cli score /absolute/data/runs/firecrawl
+```
+
+Run each participant once across the complete 140-case population. The plan binds
+cases, input hashes, pacing and retry policy before calls. Calls within a provider
+are serial; Diffbot additionally waits after each response. A quota or permission
+denial pauses collection. After access is repaired, repeat the same certified
+command and directory: completed cases are retained, the blocked case may be retried
+once, and both physical responses remain inspectable. The final response is scored;
+there is no best-response selection or quality retry. The certificate is emitted
+only after the complete scope and reference checks pass.
+
+`probe` checks three stock/field strata; `probe --largest-page` checks the largest
+input. These are compatibility diagnostics, not a substitute for a 140-page run.
+The lower-level `run` command also collects the full population, but formal cohorts
+must go through `scripts/run_certified_benchmark.py`.
+
+## Research and compatibility reports
+
+```sh
+uv run --frozen python -m harness.web_scraper.example --output /tmp/scraper-example
+uv run --frozen python -m harness.web_scraper.cli check /tmp/scraper-example
+uv run --frozen python -m pytest tests/web_scraper -q
+```
+
+The runnable example uses three synthetic cases, including successful extraction
+and blocked access. It downloads nothing and needs no credentials. Chinese is the
+default; English navigation shows a not-generated notice with a return link.
+`--language en` explicitly generates both editions with matching inventories.
+
+For a research report, pass `report --profile /absolute/report-profile.json
+--content /absolute/content.json --output /absolute/new-report`. The external profile
+binds dataset provenance and optional authored content hashes. The current research
+renderer accepts compatibility diagnostics and rejects full-quality cohorts;
+certified full runs can already be scored and inspected in their saved evidence.
+
+The separate release check requires a receipt from browser checks covering the
+core route classes, generated languages, themes and viewport sizes:
+
+```sh
+uv run --frozen python -m harness.web_scraper.cli check /absolute/report \
+ --release --visual-receipt /absolute/private/visual-receipt.json
+```
+
+Building a local report does not upload it or change access permissions.
diff --git a/pyproject.toml b/pyproject.toml
index ac6b9979a..520b9a776 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -68,6 +68,12 @@ oss-eval = [
"python-pptx==1.0.2",
]
+web-scraper-eval = [
+ "extruct==0.18.0",
+ "price-parser==0.5.0",
+ "requests>=2.32,<3",
+]
+
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = ["--import-mode=importlib"]
@@ -78,6 +84,8 @@ markers = [
[tool.ruff]
line-length = 100
include = [
+ "src/harness/web_scraper/**/*.py",
+ "tests/web_scraper/**/*.py",
"src/harness/environments/**/*.py",
"tests/environments/**/*.py",
"src/harness/browser_use/**/*.py",
@@ -94,6 +102,7 @@ select = ["B", "E", "F", "I", "TID252", "UP"]
ban-relative-imports = "all"
[tool.ruff.lint.per-file-ignores]
+"src/harness/web_scraper/report.py" = ["E501"]
# Retain scorer import spelling so published source hashes remain verifiable.
"src/lexbench_webfetch/*.py" = ["TID252"]
"src/lexbench_websearch/*.py" = ["TID252"]
diff --git a/scripts/run_certified_benchmark.py b/scripts/run_certified_benchmark.py
index 9248b5490..fe3fff0e2 100644
--- a/scripts/run_certified_benchmark.py
+++ b/scripts/run_certified_benchmark.py
@@ -1,10 +1,11 @@
#!/usr/bin/env python3
"""Command entry for certified benchmark cohorts."""
+
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
-from harness.web_fetch.certification import main
+from harness.reporting.certified_cli import main
if __name__ == "__main__":
main()
diff --git a/src/harness/benchmarks/cards/zyte-product-extraction.json b/src/harness/benchmarks/cards/zyte-product-extraction.json
new file mode 100644
index 000000000..f5565bc27
--- /dev/null
+++ b/src/harness/benchmarks/cards/zyte-product-extraction.json
@@ -0,0 +1,42 @@
+{
+ "schema_version": 1,
+ "dataset": {
+ "id": "zyte-product-extraction-140",
+ "repository": "scrapinghub/product-extraction-benchmark",
+ "commit": "cba97d7a8d42aeefd4021bc15d482f297faceaa3",
+ "cases": 140,
+ "files": {
+ "dataset/ground-truth.json": "5be72a7a44898427343d136d84b21ef377f2f68503c6212c2ab9970e1399899a",
+ "evaluate.py": "864ff31d8f06cc70546bb9b477c15912369e85dda1a5015c766ef42130de9fd7"
+ },
+ "inventory_sha256": "3d2456e66c053e3e6b2c3b4c4dab880ec1afd5e3bd6d64674eb5163a5aead514"
+ },
+ "historical_f1": {
+ "Zyte": {
+ "price": 0.918,
+ "sku": 0.841,
+ "availability": 0.957
+ },
+ "Diffbot": {
+ "price": 0.824,
+ "sku": 0.765,
+ "availability": 0.943
+ },
+ "extruct": {
+ "price": 0.685,
+ "sku": 0.537,
+ "availability": 0.626
+ }
+ },
+ "baseline_extractor": {
+ "url": "https://raw.githubusercontent.com/scrapinghub/product-extraction-benchmark/cba97d7a8d42aeefd4021bc15d482f297faceaa3/extractors/run_extruct.py",
+ "path": "extractors/run_extruct.py",
+ "sha256": "409abc3a2e5c26c09324ed988aeb363544f68032ce6548ec880b21cf919d0aeb",
+ "dependencies": {
+ "extruct": "0.18.0",
+ "price-parser": "0.5.0"
+ }
+ },
+ "name": "Zyte product extraction benchmark",
+ "source_license": "MIT, Copyright (c) 2021 Zyte"
+}
diff --git a/src/harness/reporting/certified_cli.py b/src/harness/reporting/certified_cli.py
new file mode 100644
index 000000000..00ce42d37
--- /dev/null
+++ b/src/harness/reporting/certified_cli.py
@@ -0,0 +1,14 @@
+"""Dispatch certified collection through each track's maintained owner."""
+
+import argparse
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(add_help=False)
+ parser.add_argument("--track", choices=["webfetch", "web-scraper"], default="webfetch")
+ args, remaining = parser.parse_known_args(argv)
+ if args.track == "web-scraper":
+ from harness.web_scraper.certification import main as run
+ else:
+ from harness.web_fetch.certification import main as run
+ return run(remaining)
diff --git a/src/harness/web_scraper/__init__.py b/src/harness/web_scraper/__init__.py
new file mode 100644
index 000000000..759aa70f8
--- /dev/null
+++ b/src/harness/web_scraper/__init__.py
@@ -0,0 +1 @@
+"""Structured extraction benchmarks, isolated from Fetch and Search scoring."""
diff --git a/src/harness/web_scraper/certification.py b/src/harness/web_scraper/certification.py
new file mode 100644
index 000000000..db813406d
--- /dev/null
+++ b/src/harness/web_scraper/certification.py
@@ -0,0 +1,153 @@
+"""Freeze complete archived-page cohorts before calls and certify after collection."""
+
+import argparse
+import importlib.util
+from pathlib import Path
+
+from harness.web_scraper.pipeline import (
+ PROFILE,
+ ROOT,
+ available_methods,
+ data_home,
+ digest,
+ load_run,
+ probe,
+ read_json,
+ save_json,
+ score_run,
+ validate_dataset,
+)
+
+
+def create_plan(home, methods, output):
+ registry = available_methods()
+ if (
+ not methods
+ or len(set(methods)) != len(methods)
+ or any(m not in registry or registry[m]["input"] == "site_specific" for m in methods)
+ ):
+ raise ValueError("Select distinct complete extraction interfaces or the extruct baseline")
+ validate_dataset(home)
+ truth = read_json(home / "dataset/dataset/ground-truth.json")
+ plan = {
+ "schema": "archived-product-full-cohort/1",
+ "case_count": len(truth),
+ "case_ids_sha256": digest(("\n".join(sorted(truth)) + "\n").encode()),
+ "dataset_manifest_sha256": digest((home / "dataset/manifest.json").read_bytes()),
+ "scorer_sha256": read_json(PROFILE)["dataset"]["files"]["evaluate.py"],
+ "matrix_size": len(truth) * len(methods),
+ "participants": {
+ m: {
+ "minimum_call_interval_seconds": 13 if m == "diffbot-product" else 0,
+ "post_call_cooldown_seconds": 10 if m == "diffbot-product" else 0,
+ "input": registry[m]["input"],
+ }
+ for m in methods
+ },
+ "timeout_seconds": 120,
+ "quality_retries": 0,
+ "access_retries_after_repair": 1,
+ "account_policy": (
+ "Use existing allocations; pause on explicit denial; never purchase plans"
+ ),
+ "review": "Machine scoring only; independent review requires an explicit request",
+ "primary_language": "zh",
+ "english": "Generated only on explicit request",
+ }
+ save_json(output, plan, exclusive=True)
+ return plan
+
+
+def frozen_probe(run_dir, expected_sha):
+ source = run_dir / "execution/pipeline.py"
+ if source.is_symlink() or digest(source.read_bytes()) != expected_sha:
+ raise ValueError("Certified resume execution snapshot changed")
+ spec = importlib.util.spec_from_file_location("harness.web_scraper._frozen_runner", source)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ module.ROOT, module.PROFILE = ROOT, PROFILE
+ return module.probe
+
+
+def run(home: Path, profile: Path, method: str, run_dir: Path, fixture_base=None):
+ plan = read_json(profile)
+ participant = plan["participants"][method]
+ if available_methods()[method]["input"] == "site_specific":
+ raise ValueError("A site-specific scraper is not a generic archived-HTML participant")
+ validate_dataset(home)
+ truth = read_json(home / "dataset/dataset/ground-truth.json")
+ case_hash = digest(("\n".join(sorted(truth)) + "\n").encode())
+ if plan.get("dataset_manifest_sha256") != digest((home / "dataset/manifest.json").read_bytes()):
+ raise ValueError("Frozen plan reference manifest differs")
+ if plan.get("scorer_sha256") != read_json(PROFILE)["dataset"]["files"]["evaluate.py"]:
+ raise ValueError("Frozen plan scorer differs")
+ if len(truth) != plan["case_count"] or case_hash != plan["case_ids_sha256"]:
+ raise ValueError("Full cohort population differs from the frozen plan")
+ precall = {
+ "schema": "archived-extraction-precall/1",
+ "profile_sha256": digest(profile.read_bytes()),
+ "method": method,
+ "case_ids_sha256": case_hash,
+ "dataset_manifest_sha256": digest((home / "dataset/manifest.json").read_bytes()),
+ "pipeline_sha256": digest(Path(__file__).with_name("pipeline.py").read_bytes()),
+ "fixture_base": fixture_base,
+ }
+ binding = run_dir / "certification-precall.json"
+ collector = probe
+ if binding.exists():
+ original = read_json(binding)
+ if original["pipeline_sha256"] != precall["pipeline_sha256"]:
+ collector = frozen_probe(run_dir, original["pipeline_sha256"])
+ precall["pipeline_sha256"] = original["pipeline_sha256"]
+ if original != precall:
+ raise ValueError("Certified resume inputs changed")
+ else:
+ save_json(binding, precall, exclusive=True)
+ pacing = (
+ {"post_call_cooldown": participant["post_call_cooldown_seconds"]}
+ if participant.get("post_call_cooldown_seconds")
+ else {}
+ )
+ source = collector(
+ home,
+ [method],
+ full=True,
+ fixture_base=fixture_base,
+ min_call_interval=participant.get("minimum_call_interval_seconds", 0),
+ run_dir=run_dir,
+ **pacing,
+ )
+ contract, rows = load_run(source)
+ validate_dataset(home)
+ if (
+ digest(profile.read_bytes()) != precall["profile_sha256"]
+ or contract["pipeline_sha256"] != precall["pipeline_sha256"]
+ ):
+ raise ValueError("Certified implementation or plan changed")
+ if set(contract["case_ids"]) != set(truth) or len(rows) != len(truth):
+ raise ValueError("Certified cohort is incomplete")
+ result = score_run(home, source)
+ certificate = {
+ "schema": "archived-extraction-certificate/1",
+ "method": method,
+ "case_count": len(rows),
+ "precall_sha256": digest(binding.read_bytes()),
+ "profile_sha256": precall["profile_sha256"],
+ "manifest_sha256": digest((source / "manifest.json").read_bytes()),
+ "scores_sha256": digest((source / "scores.json").read_bytes()),
+ "dataset_manifest_sha256": precall["dataset_manifest_sha256"],
+ "review_scope": "machine scoring only; no independent result review",
+ }
+ save_json(source / "certificate.json", certificate)
+ return {"run": str(source), "cases": len(rows), "scores": result["scores"]}
+
+
+def main(argv=None):
+ p = argparse.ArgumentParser(description=__doc__)
+ p.add_argument("--home", type=Path, default=data_home())
+ p.add_argument("--profile", type=Path, required=True)
+ p.add_argument("--method", required=True)
+ p.add_argument("--run-dir", type=Path, required=True)
+ p.add_argument("--fixture-base")
+ a = p.parse_args(argv)
+ print(run(a.home, a.profile, a.method, a.run_dir, a.fixture_base))
diff --git a/src/harness/web_scraper/cli.py b/src/harness/web_scraper/cli.py
new file mode 100644
index 000000000..cda2dd0a8
--- /dev/null
+++ b/src/harness/web_scraper/cli.py
@@ -0,0 +1,99 @@
+"""Public entry point for the structured extraction track."""
+
+import argparse
+from pathlib import Path
+
+from harness.web_scraper.pipeline import (
+ data_home,
+ prepare,
+ probe,
+ reproduce,
+ score_run,
+ serve_fixtures,
+)
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--home", type=Path, default=data_home())
+ sub = parser.add_subparsers(dest="command", required=True)
+ sub.add_parser("prepare")
+ sub.add_parser("reproduce")
+ p = sub.add_parser("plan")
+ p.add_argument("--methods", nargs="+", required=True)
+ p.add_argument("--output", type=Path, required=True)
+ p = sub.add_parser("serve")
+ p.add_argument("--port", type=int, default=8767)
+ for command in ("probe", "run"):
+ p = sub.add_parser(command)
+ p.add_argument("--methods", nargs="+", required=True)
+ p.add_argument("--fixture-base")
+ p.add_argument(
+ "--run-dir",
+ type=Path,
+ help="Resume the exact frozen scope without repeating completed cases",
+ )
+ p.add_argument(
+ "--min-call-interval",
+ type=float,
+ default=0,
+ help="Minimum seconds between request starts; recorded before calls",
+ )
+ if command == "probe":
+ p.add_argument("--largest-page", action="store_true")
+ p = sub.add_parser("score")
+ p.add_argument("run", type=Path)
+ p = sub.add_parser("report")
+ p.add_argument("--content", type=Path, required=True)
+ p.add_argument("--profile", type=Path, required=True, help="External report-instance profile")
+ p.add_argument("--output", type=Path, required=True)
+ p.add_argument("--language", choices=["en", "zh"], default="zh")
+ p.add_argument("--run", type=Path)
+ p = sub.add_parser("check")
+ p.add_argument("output", type=Path)
+ p.add_argument("--release", action="store_true")
+ p.add_argument("--visual-receipt", type=Path)
+ args = parser.parse_args(argv)
+ if args.command == "prepare":
+ print("Verified", prepare(args.home)["cases"], "frozen pages")
+ elif args.command == "reproduce":
+ print(reproduce(args.home))
+ elif args.command == "plan":
+ from harness.web_scraper.certification import create_plan
+
+ print(create_plan(args.home, args.methods, args.output))
+ elif args.command == "serve":
+ serve_fixtures(args.home, port=args.port)
+ elif args.command in ("probe", "run"):
+ print(
+ probe(
+ args.home,
+ args.methods,
+ fixture_base=args.fixture_base,
+ full=args.command == "run",
+ largest=getattr(args, "largest_page", False),
+ min_call_interval=args.min_call_interval,
+ run_dir=args.run_dir,
+ )
+ )
+ elif args.command == "score":
+ print(score_run(args.home, args.run))
+ elif args.command == "report":
+ from harness.web_scraper.report import build
+
+ build(
+ args.output,
+ args.content,
+ home=args.home,
+ run=args.run,
+ language=args.language,
+ profile=args.profile,
+ )
+ elif args.command == "check":
+ from harness.web_scraper.report import check
+
+ print(check(args.output, release=args.release, visual_receipt=args.visual_receipt))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/harness/web_scraper/example.py b/src/harness/web_scraper/example.py
new file mode 100644
index 000000000..40485cd11
--- /dev/null
+++ b/src/harness/web_scraper/example.py
@@ -0,0 +1,126 @@
+"""Version-one synthetic report exercising success, blocked inputs and evidence."""
+
+import argparse
+from pathlib import Path
+
+from harness.web_scraper.pipeline import digest, save_json
+from harness.web_scraper.report import PAGES, build
+
+
+def create(output: Path, *, language="zh"):
+ home = output.parent / (output.name + "-synthetic-inputs")
+ home.mkdir(parents=True, exist_ok=False)
+ truth = {
+ str(i) * 64: {
+ "url": "https://example.org/product/" + str(i),
+ "sku": [str(i)],
+ "availability": ["InStock"],
+ }
+ for i in range(1, 4)
+ }
+ root = home / "dataset"
+ save_json(root / "dataset/ground-truth.json", truth)
+ for cid in truth:
+ p = root / "html" / (cid + ".html")
+ p.parent.mkdir(exist_ok=True)
+ p.write_text("
synthetic product
")
+ files = {
+ p.relative_to(root).as_posix(): {
+ "sha256": digest(p.read_bytes()),
+ "bytes": p.stat().st_size,
+ }
+ for p in root.rglob("*")
+ if p.is_file()
+ }
+ save_json(root / "manifest.json", {"commit": "synthetic-v1", "cases": 3, "files": files})
+ profile = home / "profile.json"
+ save_json(
+ profile,
+ {
+ "dataset": {
+ "id": "synthetic",
+ "repository": "example/synthetic",
+ "commit": "synthetic-v1",
+ "cases": 3,
+ "files": {},
+ }
+ },
+ )
+ sha = digest((root / "manifest.json").read_bytes())
+ save_json(
+ home / "historical-reproduction.json",
+ {
+ "kind": "synthetic",
+ "dataset_manifest_sha256": sha,
+ "scores": {
+ "Synthetic A": {
+ f: {"f1": 0.8} for f in ("price", "sku", "availability", "OutOfStock")
+ },
+ "Synthetic B": {
+ f: {"f1": 0.5} for f in ("price", "sku", "availability", "OutOfStock")
+ },
+ },
+ },
+ )
+ run = home / "runs/example-v1"
+ run.mkdir(parents=True)
+ save_json(
+ run / "contract.json",
+ {
+ "case_ids": list(truth),
+ "methods": ["synthetic-success", "synthetic-blocked"],
+ "kind": "input_compatibility_only",
+ "dataset_manifest_sha256": sha,
+ },
+ )
+ entries = []
+ for method in ("synthetic-success", "synthetic-blocked"):
+ for cid in truth:
+ good = method == "synthetic-success"
+ row = {
+ "method": method,
+ "case_id": cid,
+ "state": "response_received" if good else "input_blocked",
+ "compatibility": "structured_output" if good else "no_structured_output",
+ "normalized_fields": {"sku": cid[0]} if good else None,
+ "response": {"json": {"sku": cid[0]}} if good else {},
+ "http_status": 200 if good else None,
+ "error": "" if good else "Synthetic route rejects archived HTML",
+ "elapsed_seconds": 1.0,
+ }
+ p = run / "calls" / f"{method}-{cid}.json"
+ save_json(p, row)
+ entries.append(
+ {"path": p.relative_to(run).as_posix(), "sha256": digest(p.read_bytes())}
+ )
+ save_json(
+ run / "manifest.json",
+ {"contract_sha256": digest((run / "contract.json").read_bytes()), "calls": entries},
+ )
+ content = home / "content.json"
+ save_json(
+ content,
+ {
+ "evidence_runs": [{"run": "example-v1"}],
+ "pages": {
+ p: {
+ "title": {"en": "Synthetic example · " + p, "zh": "合成示例 · " + p},
+ "body": {
+ "en": "
Synthetic evidence for renderer testing only.
",
+ "zh": "
用于测试报告展示的合成数据。
",
+ },
+ }
+ for p in PAGES
+ },
+ },
+ )
+ build(output, content, home=home, profile=profile, language=language)
+ return home
+
+
+if __name__ == "__main__":
+ p = argparse.ArgumentParser(description=__doc__)
+ p.add_argument("--output", type=Path, required=True)
+ p.add_argument("--language", choices=["en", "zh"], default="zh")
+ a = p.parse_args()
+ create(a.output, language=a.language)
diff --git a/src/harness/web_scraper/pipeline.py b/src/harness/web_scraper/pipeline.py
new file mode 100644
index 000000000..9765eaa87
--- /dev/null
+++ b/src/harness/web_scraper/pipeline.py
@@ -0,0 +1,1015 @@
+"""Pinned public inputs, immutable compatibility calls and upstream scoring."""
+
+from __future__ import annotations
+
+import ast
+import base64
+import fcntl
+import gzip
+import io
+import json
+import os
+import re
+import runpy
+import tarfile
+import time
+import uuid
+from concurrent.futures import ThreadPoolExecutor
+from datetime import UTC, datetime
+from pathlib import Path
+from urllib.parse import urlsplit
+
+from harness.data_home import data_home as shared_data_home
+from harness.distribution import repository_root
+from harness.record_io import bytes_sha256 as digest
+from harness.record_io import read_json as shared_read_json
+from harness.web_fetch.config import load_runtime_env
+from harness.web_fetch.providers.http_client import request
+
+ROOT = repository_root()
+PROFILE = Path(__file__).resolve().parents[1] / "benchmarks/cards/zyte-product-extraction.json"
+FIELDS = ("price", "sku", "availability", "InStock", "OutOfStock")
+_RAW_SESSIONS = {}
+
+
+def read_json(path: Path):
+ if path.is_symlink() or unsafe_parents(path):
+ raise ValueError("Symlink inputs are prohibited")
+ return shared_read_json(path)
+
+
+def unsafe_parents(path: Path):
+ # macOS exposes the system temporary roots through these fixed OS aliases.
+ aliases = {Path("/tmp"), Path("/var")} if os.uname().sysname == "Darwin" else set()
+ return any(p.is_symlink() and p not in aliases for p in path.parents)
+
+
+def save_json(path: Path, data, *, exclusive=False):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("x" if exclusive else "w", encoding="utf-8") as f:
+ json.dump(data, f, ensure_ascii=False, indent=2, allow_nan=False)
+ f.write("\n")
+
+
+def data_home() -> Path:
+ return shared_data_home() / "web-scraper"
+
+
+def prepare(destination: Path, profile=PROFILE):
+ contract = read_json(profile)
+ pin = contract["dataset"]
+ target = destination / "dataset"
+ if (target / "manifest.json").exists():
+ return validate_dataset(destination, profile)
+ if target.exists():
+ raise ValueError("Incomplete dataset exists; retain it and use a new destination")
+ url = f"https://codeload.github.com/{pin['repository']}/tar.gz/{pin['commit']}"
+ response = request(url, timeout=120, max_bytes=40_000_000)
+ if response.status != 200:
+ raise ValueError(f"Dataset download failed: HTTP {response.status}")
+ blobs = {}
+ with tarfile.open(fileobj=io.BytesIO(response.body), mode="r:gz") as archive:
+ for member in archive:
+ parts = Path(member.name).parts[1:]
+ if not parts:
+ continue
+ relative = Path(*parts)
+ if relative.is_absolute() or ".." in relative.parts or member.issym() or member.islnk():
+ raise ValueError("Unsafe upstream archive")
+ if member.isfile() and (
+ str(relative).startswith("dataset/")
+ or str(relative) in {"evaluate.py", "README.rst", "LICENSE"}
+ ):
+ blobs[relative.as_posix()] = archive.extractfile(member).read()
+ for name, expected in pin.get("files", {}).items():
+ if name not in blobs or digest(blobs[name]) != expected:
+ raise ValueError("Pinned upstream bytes changed: " + name)
+ truth = json.loads(blobs["dataset/ground-truth.json"])
+ if len(truth) != pin["cases"]:
+ raise ValueError("Dataset population changed")
+ for case_id in truth:
+ source = "dataset/html/" + case_id + ".html.gz"
+ alternatives = [n for n in blobs if n.startswith("dataset/html/" + case_id + ".")]
+ if source not in blobs:
+ if len(alternatives) != 1:
+ raise ValueError("Missing or ambiguous HTML: " + case_id)
+ source = alternatives[0]
+ blobs["html/" + case_id + ".html"] = gzip.decompress(blobs[source])
+ manifest = {
+ "schema_version": 1,
+ "dataset_id": pin["id"],
+ "commit": pin["commit"],
+ "archive_sha256": digest(response.body),
+ "cases": len(truth),
+ "files": {
+ name: {"sha256": digest(body), "bytes": len(body)}
+ for name, body in sorted(blobs.items())
+ },
+ }
+ for name, body in blobs.items():
+ path = target / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(body)
+ save_json(target / "manifest.json", manifest, exclusive=True)
+ return validate_dataset(destination, profile)
+
+
+def validate_dataset(home: Path, profile=PROFILE):
+ contract = read_json(profile)
+ root = home / "dataset"
+ manifest = read_json(root / "manifest.json")
+ pin = contract["dataset"]
+ inventory = digest(
+ json.dumps(manifest["files"], sort_keys=True, separators=(",", ":")).encode()
+ )
+ if pin.get("inventory_sha256") and inventory != pin["inventory_sha256"]:
+ raise ValueError("Pinned dataset inventory changed")
+ if manifest["commit"] != pin["commit"] or manifest["cases"] != pin["cases"]:
+ raise ValueError("Dataset is not the selected pinned cohort")
+ for name, item in manifest["files"].items():
+ path = root / name
+ if (
+ Path(name).is_absolute()
+ or ".." in Path(name).parts
+ or path.is_symlink()
+ or unsafe_parents(path)
+ ):
+ raise ValueError("Unsafe evidence path")
+ if not path.is_file() or digest(path.read_bytes()) != item["sha256"]:
+ raise ValueError("Dataset bytes changed: " + name)
+ for name, expected in pin.get("files", {}).items():
+ if manifest["files"].get(name, {}).get("sha256") != expected:
+ raise ValueError("Pinned source binding changed")
+ truth = read_json(root / "dataset/ground-truth.json")
+ expected = {"html/" + key + ".html" for key in truth}
+ if len(truth) != pin["cases"] or not expected.issubset(manifest["files"]):
+ raise ValueError("Incomplete HTML population")
+ return manifest
+
+
+def official_scorer(home: Path):
+ validate_dataset(home)
+ # tabulate is used only by upstream's command-line presentation. Keep its
+ # scoring functions unmodified and avoid adding an unrelated runtime dependency.
+ source = (home / "dataset/evaluate.py").read_bytes()
+ tree = ast.parse(source)
+ tree.body = [
+ n
+ for n in tree.body
+ if not (isinstance(n, ast.Import) and any(a.name == "tabulate" for a in n.names))
+ ]
+ scope = {"__name__": "pinned_upstream_scorer"}
+ exec(compile(tree, "pinned_upstream_evaluate.py", "exec"), scope)
+ return scope
+
+
+def score_predictions(truth: dict, predictions: dict, scorer, *, bootstrap=1000):
+ if set(truth) != set(predictions):
+ raise ValueError("Predictions must cover the exact declared population")
+ return {
+ field: scorer["evaluate"](
+ truth,
+ predictions,
+ field,
+ scorer["decimal_matching"] if field == "price" else scorer["hard_matching"],
+ n_bootstrap=bootstrap,
+ show_errors=False,
+ )
+ for field in FIELDS
+ }
+
+
+def reproduce(home: Path):
+ scorer = official_scorer(home)
+ truth = read_json(home / "dataset/dataset/ground-truth.json")
+ scores = {}
+ for path in sorted((home / "dataset/dataset/output").glob("*.json")):
+ scores[path.stem] = score_predictions(truth, read_json(path), scorer)
+ expected = read_json(PROFILE)["historical_f1"]
+ for method, fields in expected.items():
+ for field, value in fields.items():
+ if round(scores[method][field]["f1"], 3) != value:
+ raise ValueError("Historical result did not reproduce")
+ result = {
+ "kind": "upstream_historical_reproduction",
+ "cases": len(truth),
+ "scores": scores,
+ "dataset_manifest_sha256": digest((home / "dataset/manifest.json").read_bytes()),
+ }
+ save_json(home / "historical-reproduction.json", result)
+ return result
+
+
+def probe_cases(truth: dict):
+ """Select inputs before calls, without looking at provider predictions."""
+ criteria = [
+ lambda x: bool(x.get("InStock")) and bool(x.get("price")),
+ lambda x: bool(x.get("OutOfStock")),
+ lambda x: not x.get("price"),
+ ]
+ selected = []
+ for predicate in criteria:
+ matches = [key for key in sorted(truth) if key not in selected and predicate(truth[key])]
+ if not matches:
+ raise ValueError("Compatibility sampling stratum is absent")
+ selected.append(matches[0])
+ return selected
+
+
+SCHEMA = {
+ "type": "object",
+ "properties": {
+ "price": {
+ "type": ["number", "null"],
+ "description": (
+ "Current price of the page's main product, not original price "
+ "or a recommendation. Null if absent."
+ ),
+ },
+ "sku": {
+ "type": ["string", "null"],
+ "description": "Main product SKU or unique product identifier. Null if absent.",
+ },
+ "availability": {
+ "type": ["string", "null"],
+ "enum": ["InStock", "OutOfStock", None],
+ "description": "Main product stock status. Null if unknown.",
+ },
+ },
+ "required": ["price", "sku", "availability"],
+ "additionalProperties": False,
+}
+
+
+def available_methods():
+ return {
+ "firecrawl-json": {"keys": ["FIRECRAWL_API_KEY"], "input": "url"},
+ "cloudflare-json": {
+ "keys": ["CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_API_TOKEN"],
+ "input": "html",
+ },
+ "zyte-product": {"keys": ["ZYTE_API_KEY"], "input": "html"},
+ "diffbot-product": {"keys": ["DIFFBOT_API_TOKEN"], "input": "html"},
+ "scrapegraph-extract": {"keys": ["SGAI_API_KEY"], "input": "html"},
+ "scrapfly-product": {"keys": ["SCRAPFLY_API_KEY"], "input": "html"},
+ "oxylabs-json": {"keys": ["OXYLABS_API_KEY"], "input": "url"},
+ "brightdata-scrapers": {"keys": ["BRIGHTDATA_API_TOKEN"], "input": "site_specific"},
+ "extruct": {"keys": [], "input": "html"},
+ "browserbase-stagehand": {
+ "keys": ["BROWSERBASE_API_KEY", "BROWSERBASE_PROJECT_ID"],
+ "input": "url",
+ },
+ }
+
+
+def baseline_extractor(home: Path):
+ """Execute the hash-pinned upstream baseline, without its CLI entry point."""
+ pin = read_json(PROFILE)["baseline_extractor"]
+ source = home / pin["path"]
+ if not source.exists():
+ response = request(pin["url"], timeout=60)
+ if response.status != 200 or digest(response.body) != pin["sha256"]:
+ raise ValueError("Baseline source does not match the pinned upstream extractor")
+ source.parent.mkdir(parents=True, exist_ok=True)
+ source.write_bytes(response.body)
+ if source.is_symlink() or digest(source.read_bytes()) != pin["sha256"]:
+ raise ValueError("Pinned baseline source changed")
+ return runpy.run_path(str(source), run_name="pinned_extruct_baseline")["extract"]
+
+
+def redact(value):
+ if isinstance(value, dict):
+ return {
+ k: "[REDACTED]"
+ if re.search(
+ r"(?:^|[_-])(?:token|secret|authorization|password|cookies?|api[_-]?key)(?:$|[_-])",
+ re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", k),
+ re.I,
+ )
+ else redact(v)
+ for k, v in value.items()
+ }
+ if isinstance(value, list):
+ return [redact(x) for x in value]
+ if isinstance(value, str):
+ for key, secret in os.environ.items():
+ if (
+ any(
+ x in key
+ for x in ("KEY", "TOKEN", "PASSWORD", "SECRET", "ACCOUNT_ID", "CDP_URL")
+ )
+ and len(secret) >= 8
+ ):
+ value = value.replace(secret, "[REDACTED]")
+ return value
+
+
+def provider_call(method, html, source_url, fixture_url=None, *, timeout=120, home=None):
+ """One native route per provider; no hidden fallback or quality retry."""
+ if method == "extruct":
+ extract = baseline_extractor(home or data_home())
+ started = time.monotonic()
+ result = extract(html)
+ return {
+ "state": "response_received",
+ "http_status": 200,
+ "elapsed_seconds": time.monotonic() - started,
+ "response": {"result": result},
+ "request": {
+ "input": "html",
+ "endpoint": "local:extruct",
+ "html_sha256": digest(html.encode()),
+ "source_url": source_url,
+ },
+ }
+ if method == "browserbase-stagehand":
+ if not fixture_url:
+ return {"state": "input_blocked", "error": "A frozen HTTPS snapshot URL is required"}
+ started = time.monotonic()
+ from harness.web_scraper.stagehand import extract
+
+ result = extract(fixture_url, SCHEMA, timeout=timeout)
+ return {
+ **redact(result),
+ "elapsed_seconds": time.monotonic() - started,
+ "request": {
+ "input": "url",
+ "endpoint": "stagehand:extract",
+ "html_sha256": digest(html.encode()),
+ "source_url": source_url,
+ "fixture_url": fixture_url,
+ },
+ }
+ if method == "cloudflare-json":
+ url = f"https://api.cloudflare.com/client/v4/accounts/{os.environ['CLOUDFLARE_ACCOUNT_ID']}/browser-rendering/json"
+ headers = {"Authorization": "Bearer " + os.environ["CLOUDFLARE_API_TOKEN"]}
+ body = {"html": html, "response_format": {"type": "json_schema", "json_schema": SCHEMA}}
+ elif method in ("firecrawl-json", "oxylabs-json"):
+ if not fixture_url:
+ return {
+ "state": "input_blocked",
+ "error": (
+ "Native endpoint requires a remotely reachable frozen HTML URL; "
+ "original live URLs are prohibited."
+ ),
+ }
+ url = (
+ "https://api.firecrawl.dev/v2/scrape"
+ if method == "firecrawl-json"
+ else "https://webapi.oxylabs.io/v1/scrape"
+ )
+ headers = {
+ "Authorization": "Bearer "
+ + os.environ["FIRECRAWL_API_KEY" if method == "firecrawl-json" else "OXYLABS_API_KEY"]
+ }
+ body = (
+ {
+ "url": fixture_url,
+ "formats": [{"type": "json", "schema": SCHEMA}],
+ "onlyMainContent": False,
+ "maxAge": 0,
+ }
+ if method == "firecrawl-json"
+ else {
+ "url": fixture_url,
+ "output": ["json"],
+ "json": {"schema": SCHEMA},
+ "run_js": False,
+ }
+ )
+ elif method == "zyte-product":
+ url = "https://api.zyte.com/v1/extract"
+ headers = {
+ "Authorization": "Basic "
+ + base64.b64encode((os.environ["ZYTE_API_KEY"] + ":").encode()).decode()
+ }
+ body = {
+ "url": source_url,
+ "product": True,
+ "productOptions": {"extractFrom": "userHtml", "userHtml": html},
+ }
+ elif method == "scrapegraph-extract":
+ url = "https://v2-api.scrapegraphai.com/api/extract"
+ headers = {"SGAI-APIKEY": os.environ["SGAI_API_KEY"]}
+ body = {
+ "html": html,
+ "prompt": (
+ "Extract the main product current price, SKU and stock availability. "
+ "Use null for absent fields."
+ ),
+ "schema": SCHEMA,
+ }
+ elif method in ("diffbot-product", "scrapfly-product"):
+ # These native uploaded-HTML routes use a raw body rather than JSON.
+ from urllib.parse import urlencode
+
+ import requests
+
+ endpoint = (
+ "https://api.diffbot.com/v3/product"
+ if method == "diffbot-product"
+ else "https://api.scrapfly.io/extraction"
+ )
+ params = (
+ {"token": os.environ["DIFFBOT_API_TOKEN"], "url": source_url}
+ if method == "diffbot-product"
+ else {
+ "key": os.environ["SCRAPFLY_API_KEY"],
+ "url": source_url,
+ "extraction_model": "product",
+ "timeout": timeout,
+ }
+ )
+ url = endpoint + "?" + urlencode(params)
+ started = time.monotonic()
+ session = _RAW_SESSIONS.setdefault(method, requests.Session())
+ with session.post(
+ url,
+ data=html.encode(),
+ headers={"Content-Type": "text/html"},
+ timeout=timeout,
+ stream=True,
+ allow_redirects=False,
+ ) as response:
+ raw = response.raw.read(10_000_001, decode_content=True)
+ if len(raw) > 10_000_000:
+ raise ValueError("Provider response exceeded limit")
+ return {
+ "state": "response_received",
+ "http_status": response.status_code,
+ "elapsed_seconds": time.monotonic() - started,
+ "response": redact(json.loads(raw)),
+ "provider_usage": {
+ k: response.headers.get(k)
+ for k in ("X-Scrapfly-Api-Cost", "X-Scrapfly-Remaining-Api-Credit")
+ if response.headers.get(k) is not None
+ },
+ "request": {
+ "endpoint": endpoint,
+ "input": "html",
+ "html_sha256": digest(html.encode()),
+ "source_url": source_url,
+ "mode": "product",
+ },
+ }
+ else:
+ raise ValueError("This method has no generic frozen-HTML route")
+ started = time.monotonic()
+ response = request(url, method="POST", headers=headers, json_body=body, timeout=timeout)
+ try:
+ payload = response.json()
+ except ValueError:
+ payload = {"non_json_response": response.text()}
+ return {
+ "state": "response_received",
+ "http_status": response.status,
+ "elapsed_seconds": time.monotonic() - started,
+ "response": redact(payload),
+ "request": {
+ "endpoint": url,
+ "input": available_methods()[method]["input"],
+ "html_sha256": digest(html.encode()),
+ "schema": SCHEMA,
+ "fixture_url": fixture_url,
+ "source_url": source_url,
+ },
+ }
+
+
+def normalize(method: str, payload: dict):
+ """Map exposed fields only. Never infer answers from labels or source URLs."""
+ if payload.get("success") is False:
+ return None
+ if method == "extruct":
+ item = payload.get("result")
+ return (
+ {f: str(item[f]) for f in FIELDS if item.get(f) is not None}
+ if isinstance(item, dict)
+ else None
+ )
+ if method == "firecrawl-json":
+ item = payload.get("data", {}).get("json")
+ elif method in ("cloudflare-json", "browserbase-stagehand"):
+ item = payload.get("result")
+ elif method == "oxylabs-json":
+ results = payload.get("results") or []
+ item = results[0].get("json") if len(results) == 1 else None
+ elif method == "scrapegraph-extract":
+ item = payload.get("json")
+ elif method == "scrapfly-product":
+ p = payload.get("data") or payload.get("result", {}).get("extracted_data", {}).get("data")
+ if isinstance(p, dict):
+ offers = p.get("offers") or []
+ offer = offers[0] if offers else {}
+ price = offer.get("price")
+ if isinstance(price, dict):
+ price = price.get("amount")
+ stock = offer.get("availability")
+ item = {
+ "price": price,
+ "sku": (p.get("identifiers") or {}).get("sku"),
+ "availability": {"available": "InStock", "unavailable": "OutOfStock"}.get(
+ stock, stock
+ ),
+ }
+ else:
+ item = None
+ elif method == "zyte-product":
+ p = payload.get("product")
+ item = (
+ {"price": p.get("price"), "sku": p.get("sku"), "availability": p.get("availability")}
+ if isinstance(p, dict)
+ else None
+ )
+ elif method == "diffbot-product":
+ objects = payload.get("objects", [])
+ p = objects[0] if len(objects) == 1 else None
+ offer = p.get("offerPriceDetails", {}).get("amount", p.get("offerPrice")) if p else None
+ item = (
+ {"price": offer, "sku": p.get("sku"), "availability": p.get("availability")}
+ if p
+ else None
+ )
+ if item and isinstance(item["availability"], bool):
+ item["availability"] = "InStock" if item["availability"] else "OutOfStock"
+ else:
+ item = None
+ if not isinstance(item, dict) or not any(f in item for f in ("price", "sku", "availability")):
+ return None
+ result = {}
+ for field in ("price", "sku", "availability"):
+ value = item.get(field)
+ if value is not None and not isinstance(value, (dict, list, bool)):
+ result[field] = str(value)
+ if result.get("availability") in {"InStock", "OutOfStock"}:
+ result[result["availability"]] = result["availability"]
+ return result
+
+
+def serve_fixtures(home: Path, *, port=8767):
+ """Expose only the selected public snapshot files, without changing their bytes."""
+ from functools import lru_cache
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+ validate_dataset(home)
+ truth = read_json(home / "dataset/dataset/ground-truth.json")
+ allowed = {key + ".html" for key in truth}
+
+ @lru_cache(maxsize=140)
+ def encoded(name, compressed):
+ raw = (home / "dataset/html" / name).read_bytes()
+ return gzip.compress(raw, mtime=0) if compressed else raw
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ self.respond(send_body=True)
+
+ def do_HEAD(self):
+ self.respond(send_body=False)
+
+ def respond(self, *, send_body):
+ name = urlsplit(self.path).path.lstrip("/")
+ if name not in allowed:
+ self.send_error(404)
+ return
+ compressed = "gzip" in self.headers.get("Accept-Encoding", "")
+ raw = encoded(name, compressed)
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html; charset=utf-8")
+ self.send_header("Cache-Control", "no-transform")
+ self.send_header("Vary", "Accept-Encoding")
+ if compressed:
+ self.send_header("Content-Encoding", "gzip")
+ self.send_header("Content-Length", str(len(raw)))
+ self.end_headers()
+ if send_body:
+ self.wfile.write(raw)
+
+ ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()
+
+
+def access_blocker(row):
+ """Stop calls after evidenced authentication, permission or quota denial."""
+ if row.get("state") == "credentials_missing":
+ return "credentials_missing"
+ status = row.get("http_status")
+ message = str(row.get("response", {})) + str(row.get("error", ""))
+ if status == 401:
+ return "authentication"
+ if status == 402:
+ return "quota_or_payment"
+ if status in (403, 429) or row.get("state") == "provider_error":
+ if re.search(
+ r"quota|credits?|balance|free plan|usage period|upgrade|subscription|payment|"
+ r"insufficient|expired",
+ message,
+ re.I,
+ ):
+ return "quota_or_permission"
+ return None
+
+
+def probe(home: Path, methods: list[str], **options):
+ """Run or resume one declared scope; never attach two workers to one run."""
+ run = options.pop("run_dir", None)
+ if run is None:
+ run = (
+ home
+ / "runs"
+ / (datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") + "-" + uuid.uuid4().hex[:8])
+ )
+ run = Path(run)
+ if run.is_symlink() or unsafe_parents(run):
+ raise ValueError("Unsafe run directory")
+ if run.resolve().is_relative_to(ROOT):
+ raise ValueError("Provider evidence must stay outside the source repository")
+ run.mkdir(parents=True, exist_ok=True)
+ with (run / "execution.lock").open("a") as lock:
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ return _probe_unlocked(home, methods, run_dir=run, **options)
+
+
+def _probe_unlocked(
+ home: Path,
+ methods: list[str],
+ *,
+ fixture_base=None,
+ full=False,
+ largest=False,
+ min_call_interval=0,
+ post_call_cooldown=0,
+ run_dir=None,
+):
+ if not isinstance(min_call_interval, (int, float)) or not 0 <= min_call_interval <= 3600:
+ raise ValueError("Minimum call interval must be between 0 and 3600 seconds")
+ if not isinstance(post_call_cooldown, (int, float)) or not 0 <= post_call_cooldown <= 3600:
+ raise ValueError("Post-call cooldown must be between 0 and 3600 seconds")
+ validate_dataset(home)
+ load_runtime_env()
+ registry = available_methods()
+ if not methods or len(set(methods)) != len(methods) or any(m not in registry for m in methods):
+ raise ValueError("Select supported methods explicitly")
+ if fixture_base and urlsplit(fixture_base).scheme != "https":
+ raise ValueError("Remote frozen fixtures require HTTPS")
+ truth = read_json(home / "dataset/dataset/ground-truth.json")
+ if full and largest:
+ raise ValueError("Full scope and a size probe are mutually exclusive")
+ case_ids = (
+ sorted(truth)
+ if full
+ else (
+ [
+ max(
+ sorted(truth),
+ key=lambda key: (home / "dataset/html" / (key + ".html")).stat().st_size,
+ )
+ ]
+ if largest
+ else probe_cases(truth)
+ )
+ )
+
+ def verify_remote():
+ def one(case_id):
+ for attempt in range(3):
+ try:
+ response = request(
+ f"{fixture_base.rstrip('/')}/{case_id}.html",
+ headers={"Accept-Encoding": "gzip"},
+ timeout=60,
+ )
+ break
+ except (TimeoutError, OSError):
+ if attempt == 2:
+ raise
+ time.sleep(2)
+ expected = digest((home / "dataset/html" / (case_id + ".html")).read_bytes())
+ body = (
+ gzip.decompress(response.body)
+ if response.headers.get("content-encoding") == "gzip"
+ else response.body
+ )
+ if response.status != 200 or digest(body) != expected:
+ raise ValueError("Remote fixture differs from frozen HTML: " + case_id)
+ return {
+ "case_id": case_id,
+ "sha256": expected,
+ "http_status": response.status,
+ "qualification_fetch_attempts": attempt + 1,
+ }
+
+ if not fixture_base:
+ return []
+ with ThreadPoolExecutor(max_workers=4) as executor:
+ return list(executor.map(one, case_ids))
+
+ run = (
+ Path(run_dir)
+ if run_dir
+ else (
+ home
+ / "runs"
+ / (datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") + "-" + uuid.uuid4().hex[:8])
+ )
+ )
+ continuing = (run / "contract.json").exists()
+ run.mkdir(parents=True, exist_ok=True)
+ remote_before = verify_remote()
+ requested = {
+ "schema_version": 1,
+ "kind": "full_archived_extraction"
+ if full
+ else ("input_size_boundary_only" if largest else "input_compatibility_only"),
+ "case_ids": case_ids,
+ "methods": methods,
+ "timeout_seconds": 120,
+ "retries": 0,
+ "access_resume_policy": (
+ "Retain every call; after repairing access, retry blocked cases once "
+ "and select the final response"
+ ),
+ "access_retry_limit": 1,
+ "concurrency": 1,
+ "minimum_call_interval_seconds": min_call_interval,
+ "post_call_cooldown_seconds": post_call_cooldown,
+ "method_order": "rotate_by_case_ordinal",
+ "fixture_base": fixture_base,
+ "dataset_manifest_sha256": digest((home / "dataset/manifest.json").read_bytes()),
+ "pipeline_sha256": digest(Path(__file__).read_bytes()),
+ "pipeline_snapshot": "execution/pipeline.py",
+ "stagehand_sha256": digest(Path(__file__).with_name("stagehand.py").read_bytes())
+ if "browserbase-stagehand" in methods
+ else None,
+ "baseline_extractor": read_json(PROFILE).get("baseline_extractor")
+ if "extruct" in methods
+ else None,
+ "schema": SCHEMA,
+ "remote_fixture_before": remote_before,
+ }
+ if continuing:
+ contract = read_json(run / "contract.json")
+ for field in (
+ "kind",
+ "case_ids",
+ "methods",
+ "minimum_call_interval_seconds",
+ "post_call_cooldown_seconds",
+ "fixture_base",
+ "dataset_manifest_sha256",
+ "pipeline_sha256",
+ "stagehand_sha256",
+ "baseline_extractor",
+ ):
+ if contract[field] != requested[field]:
+ raise ValueError("Resume contract changed: " + field)
+ if (run / "manifest.json").exists():
+ load_run(run)
+ return run
+ else:
+ contract = requested
+ (run / "execution").mkdir()
+ (run / "execution/pipeline.py").write_bytes(Path(__file__).read_bytes())
+ if "browserbase-stagehand" in methods:
+ stagehand_source = Path(__file__).with_name("stagehand.py")
+ (run / "execution/stagehand.py").write_bytes(stagehand_source.read_bytes())
+ contract["stagehand_sha256"] = digest(stagehand_source.read_bytes())
+ save_json(run / "contract.json", contract, exclusive=True)
+ journal = run / "calls.journal.jsonl"
+ prior = {}
+ physical = []
+ attempts = {}
+ if journal.exists():
+ for line in journal.read_text().splitlines():
+ entry = json.loads(line)
+ path = run / entry["path"]
+ if digest(path.read_bytes()) != entry["sha256"]:
+ raise ValueError("Checkpoint call changed")
+ record = read_json(path)
+ key = (record["method"], record["case_id"])
+ prior[key] = entry
+ physical.append(entry)
+ attempts[key] = attempts.get(key, 0) + 1
+ if {p.relative_to(run).as_posix() for p in (run / "calls").glob("*.json")} - {
+ e["path"] for e in physical
+ }:
+ raise ValueError("Uncheckpointed call exists; preserve and reconcile it before resuming")
+ records = []
+ last_call_started = None
+ last_call_finished = None
+ for ordinal, case_id in enumerate(case_ids):
+ offset = ordinal % len(methods)
+ for method in methods[offset:] + methods[:offset]:
+ if (method, case_id) in prior:
+ entry = prior[(method, case_id)]
+ prior_row = read_json(run / entry["path"])
+ if not (full and access_blocker(prior_row)):
+ records.append(entry)
+ continue
+ if attempts[(method, case_id)] > contract["access_retry_limit"]:
+ raise PermissionError("Access remains blocked; declared retry budget exhausted")
+ missing = [key for key in registry[method]["keys"] if not os.getenv(key)]
+ raw = (home / "dataset/html" / (case_id + ".html")).read_bytes()
+ row = {
+ "method": method,
+ "case_id": case_id,
+ "input_sha256": digest(raw),
+ "kind": "structured_extraction_attempt" if full else "compatibility_probe",
+ }
+ if missing:
+ row.update(state="credentials_missing", missing_variables=missing)
+ elif registry[method]["input"] == "site_specific":
+ row.update(
+ state="input_blocked",
+ error="Site-specific scraper cannot be substituted for a generic HTML parser",
+ )
+ else:
+ try:
+ if last_call_started is not None:
+ remaining = max(
+ min_call_interval - (time.monotonic() - last_call_started),
+ post_call_cooldown - (time.monotonic() - last_call_finished),
+ )
+ while remaining > 0:
+ time.sleep(min(remaining, 30))
+ remaining = max(
+ min_call_interval - (time.monotonic() - last_call_started),
+ post_call_cooldown - (time.monotonic() - last_call_finished),
+ )
+ last_call_started = time.monotonic()
+ row.update(
+ provider_call(
+ method,
+ raw.decode("utf-8"),
+ truth[case_id]["url"],
+ f"{fixture_base.rstrip('/')}/{case_id}.html" if fixture_base else None,
+ **({"home": home} if method == "extruct" else {}),
+ )
+ )
+ normalized = normalize(method, row.get("response", {}))
+ row["normalized_fields"] = normalized
+ row["compatibility"] = (
+ "structured_output"
+ if normalized is not None and row.get("http_status") == 200
+ else "no_structured_output"
+ )
+ except Exception as error:
+ row.update(state="call_error", error=redact(str(error)))
+ last_call_finished = time.monotonic()
+ number = attempts.get((method, case_id), 0) + 1
+ row["physical_attempt"] = number
+ if number > 1:
+ prior_row = read_json(run / prior[(method, case_id)]["path"])
+ row["retry_execution_seconds"] = prior_row.get(
+ "elapsed_seconds", 0
+ ) + prior_row.get("retry_execution_seconds", 0)
+ suffix = "" if number == 1 else f"-attempt{number}"
+ path = run / "calls" / f"{method}-{case_id}{suffix}.json"
+ save_json(path, redact(row), exclusive=True)
+ entry = {"path": path.relative_to(run).as_posix(), "sha256": digest(path.read_bytes())}
+ with journal.open("a") as checkpoint:
+ checkpoint.write(json.dumps(entry) + "\n")
+ checkpoint.flush()
+ os.fsync(checkpoint.fileno())
+ records.append(entry)
+ physical.append(entry)
+ print(
+ method,
+ case_id[:10],
+ row["state"],
+ row.get("http_status", ""),
+ row.get("compatibility", ""),
+ flush=True,
+ )
+ blocker = access_blocker(row) if full else None
+ if blocker:
+ save_json(
+ run / "access-blocked.json",
+ {
+ "method": method,
+ "case_id": case_id,
+ "reason": blocker,
+ "call": entry,
+ "remaining_logical_cases": len(case_ids) * len(methods) - len(records),
+ },
+ )
+ raise PermissionError(
+ f"{method}: {blocker}; calls retained; repair access then resume the same run"
+ )
+ validate_dataset(home)
+ if (
+ "extruct" in methods
+ and read_json(PROFILE).get("baseline_extractor") != contract["baseline_extractor"]
+ ):
+ raise ValueError("Baseline extractor binding changed during execution")
+ save_json(run / "remote-fixture-after.json", verify_remote(), exclusive=True)
+ save_json(
+ run / "manifest.json",
+ {
+ "kind": "compatibility_evidence",
+ "contract_sha256": digest((run / "contract.json").read_bytes()),
+ "calls": records,
+ "physical_calls": physical,
+ "remote_fixture_after_sha256": digest((run / "remote-fixture-after.json").read_bytes()),
+ },
+ exclusive=True,
+ )
+ return run
+
+
+def load_run(run: Path):
+ manifest = read_json(run / "manifest.json")
+ contract = read_json(run / "contract.json")
+ if contract.get("pipeline_snapshot"):
+ snapshot = run / contract["pipeline_snapshot"]
+ if (
+ Path(contract["pipeline_snapshot"]).is_absolute()
+ or ".." in Path(contract["pipeline_snapshot"]).parts
+ or snapshot.is_symlink()
+ or digest(snapshot.read_bytes()) != contract["pipeline_sha256"]
+ ):
+ raise ValueError("Frozen execution source changed")
+ if digest((run / "contract.json").read_bytes()) != manifest["contract_sha256"]:
+ raise ValueError("Call contract changed")
+ if (
+ contract.get("stagehand_sha256")
+ and digest((run / "execution/stagehand.py").read_bytes()) != contract["stagehand_sha256"]
+ ):
+ raise ValueError("Frozen Stagehand client changed")
+ for entry in manifest.get("physical_calls", []):
+ relative = Path(entry["path"])
+ if relative.is_absolute() or ".." in relative.parts:
+ raise ValueError("Unsafe physical evidence path")
+ path = run / relative
+ if path.is_symlink() or digest(path.read_bytes()) != entry["sha256"]:
+ raise ValueError("Physical call evidence changed")
+ if (
+ manifest.get("remote_fixture_after_sha256")
+ and digest((run / "remote-fixture-after.json").read_bytes())
+ != manifest["remote_fixture_after_sha256"]
+ ):
+ raise ValueError("Remote fixture receipt changed")
+ rows = []
+ for entry in manifest["calls"]:
+ relative = Path(entry["path"])
+ if relative.is_absolute() or ".." in relative.parts:
+ raise ValueError("Unsafe call evidence path")
+ path = run / relative
+ if path.is_symlink() or digest(path.read_bytes()) != entry["sha256"]:
+ raise ValueError("Call evidence changed")
+ rows.append(read_json(path))
+ expected = {(m, c) for m in contract["methods"] for c in contract["case_ids"]}
+ if len(rows) != len(expected) or {(r["method"], r["case_id"]) for r in rows} != expected:
+ raise ValueError("Incomplete or duplicate compatibility matrix")
+ return contract, rows
+
+
+def score_run(home: Path, run: Path):
+ """Score the declared population; retain empty predictions for failed calls."""
+ from decimal import InvalidOperation
+
+ contract, rows = load_run(run)
+ validate_dataset(home)
+ if contract["dataset_manifest_sha256"] != digest((home / "dataset/manifest.json").read_bytes()):
+ raise ValueError("Scoring input does not match call contract")
+ all_truth = read_json(home / "dataset/dataset/ground-truth.json")
+ truth = {key: all_truth[key] for key in contract["case_ids"]}
+ if contract["kind"] == "full_archived_extraction" and set(truth) != set(all_truth):
+ raise ValueError("Full-cohort scoring requires all frozen cases")
+ scorer = official_scorer(home)
+ original_decimal = scorer["decimal_matching"]
+
+ def price_match(gold, prediction):
+ try:
+ return original_decimal(gold, prediction)
+ except InvalidOperation:
+ # A non-numeric emitted value is a false positive, not an omitted value.
+ return scorer["hard_matching"](gold, prediction)
+
+ scores = {}
+ for method in contract["methods"]:
+ predictions = {
+ r["case_id"]: (r.get("normalized_fields") or {}) if r.get("http_status") == 200 else {}
+ for r in rows
+ if r["method"] == method
+ }
+ per_field = {}
+ for field in FIELDS:
+ matcher = price_match if field == "price" else scorer["hard_matching"]
+ per_field[field] = scorer["evaluate"](
+ truth, predictions, field, matcher, n_bootstrap=1000, show_errors=False
+ )
+ scores[method] = per_field
+ result = {
+ "kind": contract["kind"],
+ "cases": len(truth),
+ "scores": scores,
+ "call_manifest_sha256": digest((run / "manifest.json").read_bytes()),
+ "scorer_sha256": digest((home / "dataset/evaluate.py").read_bytes()),
+ }
+ target = run / "scores.json"
+ if target.exists():
+ if read_json(target) != result:
+ raise ValueError("Existing score differs; use an explicit correction")
+ else:
+ save_json(target, result, exclusive=True)
+ return result
diff --git a/src/harness/web_scraper/report.py b/src/harness/web_scraper/report.py
new file mode 100644
index 000000000..33d565663
--- /dev/null
+++ b/src/harness/web_scraper/report.py
@@ -0,0 +1,549 @@
+"""Bilingual research and input-compatibility reports for structured extraction."""
+
+from __future__ import annotations
+
+import json
+import re
+import struct
+from html import escape as esc
+from pathlib import Path
+from urllib.parse import unquote, urljoin, urlsplit
+
+from bs4 import BeautifulSoup
+
+from harness.reporting.presentation import check_presentation
+from harness.web_scraper.pipeline import (
+ PROFILE,
+ digest,
+ load_run,
+ read_json,
+ redact,
+ save_json,
+ validate_dataset,
+)
+
+VERSION = "web-scraper-research/1"
+
+
+def image_width(raw: bytes):
+ if raw[:8] == b"\x89PNG\r\n\x1a\n" and len(raw) >= 24:
+ return struct.unpack(">I", raw[16:20])[0]
+ if raw[:2] == b"\xff\xd8":
+ offset = 2
+ while offset + 4 <= len(raw):
+ if raw[offset] != 255:
+ break
+ marker = raw[offset + 1]
+ if marker == 255:
+ offset += 1
+ continue
+ offset += 2
+ size = int.from_bytes(raw[offset : offset + 2], "big")
+ if size < 2:
+ break
+ if marker in {
+ 0xC0,
+ 0xC1,
+ 0xC2,
+ 0xC3,
+ 0xC5,
+ 0xC6,
+ 0xC7,
+ 0xC9,
+ 0xCA,
+ 0xCB,
+ 0xCD,
+ 0xCE,
+ 0xCF,
+ } and offset + 7 <= len(raw):
+ return int.from_bytes(raw[offset + 5 : offset + 7], "big")
+ offset += size
+ raise ValueError("Unsupported screenshot image header")
+
+
+LABELS = {
+ "en": [
+ "Overview",
+ "Dataset",
+ "Compatibility",
+ "Protocol",
+ "Candidates",
+ "Research",
+ "Accounts",
+ "Research and compatibility only · no current quality ranking",
+ "Theme",
+ "Evidence",
+ "Close",
+ "Blocked",
+ "Structured output",
+ "All",
+ "Case",
+ "Method",
+ "Status",
+ "HTTP",
+ "Seconds",
+ "Reference",
+ "Output",
+ "Raw evidence",
+ "Historical reproduction · 140 pages",
+ "Price F1",
+ "SKU F1",
+ "Availability F1",
+ "Pending",
+ ],
+ "zh": [
+ "概览",
+ "数据集",
+ "兼容性实测",
+ "评测协议",
+ "候选选手",
+ "相关研究",
+ "账号与额度",
+ "调研与输入兼容验证 · 尚无当前质量排名",
+ "切换主题",
+ "查看证据",
+ "关闭",
+ "受阻",
+ "返回结构化字段",
+ "全部",
+ "题目",
+ "方法",
+ "状态",
+ "HTTP",
+ "秒",
+ "标注",
+ "输出",
+ "原始证据",
+ "历史结果复现 · 140 页",
+ "价格 F1",
+ "SKU F1",
+ "库存 F1",
+ "待验证",
+ ],
+}
+PAGES = ("index", "dataset", "results", "protocol", "candidates", "research", "accounts")
+CSS = """*{box-sizing:border-box}html{color-scheme:light;--bg:#f8f9fb;--panel:white;--ink:#17283b;--muted:#516277;--line:#d7dfe8;--accent:#075f79;--soft:#e1f3ed}html.dark{color-scheme:dark;--bg:#101923;--panel:#172431;--ink:#e8f0f7;--muted:#afbfce;--line:#354b60;--accent:#7cdbed;--soft:#174638}body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.75 system-ui,-apple-system,"PingFang SC",sans-serif}header,main,footer{max-width:1190px;margin:auto;padding:24px 32px}header{padding-bottom:0}.eyebrow{font-size:13px;letter-spacing:.06em;color:var(--muted)}h1{font-size:clamp(28px,4vw,44px);line-height:1.25;letter-spacing:-.025em;margin:18px 0}h2{font-size:25px;margin:34px 0 12px}h3{font-size:19px;margin:26px 0 10px}p{max-width:900px}a{color:var(--accent);text-underline-offset:3px}nav{display:flex;flex-wrap:wrap;gap:7px;margin:20px 0}nav a,button,select{font:inherit;border:1px solid var(--line);border-radius:7px;background:var(--panel);color:var(--ink);padding:7px 12px;cursor:pointer;text-decoration:none}nav a[aria-current]{background:var(--ink);color:var(--bg)}.notice{border-left:4px solid var(--accent);padding:10px 16px;background:var(--panel);font-size:14px}.table-wrap{overflow:auto;max-width:100%;border:1px solid var(--line);border-radius:10px;background:var(--panel)}.inventory{max-height:540px}table{border-collapse:collapse;min-width:650px;width:100%;font-size:14px}th,td{padding:12px 14px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}th{background:var(--panel);position:sticky;top:0;z-index:1;color:var(--muted);white-space:nowrap}td{max-width:440px}td code{overflow-wrap:anywhere}.comparison-winner{background:var(--soft);font-weight:700;padding:3px 7px;border-radius:5px}section{margin:24px 0 40px}.flow{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;list-style:none;padding:0;counter-reset:stage}.flow li{counter-increment:stage;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:16px}.flow li:before{content:counter(stage,decimal-leading-zero);display:block;color:var(--accent);font-size:24px;font-weight:700}code,pre{font:12px/1.6 ui-monospace,monospace}pre{overflow:auto;padding:18px;background:var(--panel);border:1px solid var(--line);border-radius:8px;max-height:540px;white-space:pre-wrap;overflow-wrap:anywhere}code{overflow-wrap:anywhere}dialog{background:var(--panel);color:var(--ink);border:1px solid var(--line);border-radius:12px;width:min(950px,94vw);max-height:90vh;overflow:auto}dialog::backdrop{background:#0008}dialog pre{max-height:62vh}details{margin:12px 0}summary{cursor:pointer;color:var(--accent)}footer{font-size:13px;color:var(--muted);border-top:1px solid var(--line)}.controls{display:flex;flex-wrap:wrap;gap:12px;margin:14px 0}.status{font-weight:600}small{color:var(--muted)}@media(max-width:650px){header,main,footer{padding:20px 16px}.flow{grid-template-columns:1fr 1fr}nav{gap:5px}nav a{font-size:13px;padding:6px 9px}td,th{padding:10px}}"""
+CSS += ".diagram{overflow:auto;background:#fff;border:1px solid var(--line);border-radius:10px;padding:16px}.diagram img{display:block;width:100%;min-width:850px;height:auto}"
+JS = """document.querySelector('#theme').onclick=()=>{document.documentElement.classList.toggle('dark')};for(const b of document.querySelectorAll('[data-call-log-open]'))b.onclick=async()=>{const d=document.getElementById(b.dataset.callLogOpen);d.showModal();const p=d.querySelector('pre');try{const r=await fetch(b.dataset.src);if(!r.ok)throw Error('HTTP '+r.status);p.textContent=JSON.stringify(await r.json(),null,2)}catch(e){p.textContent=String(e)}};for(const b of document.querySelectorAll('[data-call-log-close]'))b.onclick=()=>b.closest('dialog').close();const f=document.querySelector('#filter');if(f){const update=()=>{for(const r of document.querySelectorAll('tr[data-status]'))r.hidden=f.value!=='all'&&r.dataset.status!==f.value};f.onchange=update;update()}"""
+
+
+def table(headers, rows, *, inventory=False, attrs=""):
+ return (
+ '
"
+ + "".join("
" + h + "
" for h in headers)
+ + "
"
+ + "".join(
+ "
" + "".join("
" + str(c) + "
" for c in row) + "
" for row in rows
+ )
+ + "
"
+ )
+
+
+def page(language, route, title, body, *, detail=False, languages=("en", "zh")):
+ labels = LABELS[language]
+ other = "zh" if language == "en" else "en"
+ nav = "".join(
+ f'"
+ + labels[i]
+ + ""
+ for i, p in enumerate(PAGES)
+ )
+ other_route = route if not detail else "results"
+ if other not in languages:
+ other_route = "index"
+ html = f'{esc(title)} · Web Scraper
WEB SCRAPER / STRUCTURED EXTRACTION
{esc(title)}
{labels[7]}
{body}'
+ # Artifact Site injects a site-root base even on nested pages. Use the same
+ # root-relative references locally, where our own base supplies that root.
+ soup = BeautifulSoup(html, "html.parser")
+ for element in soup.select("a[href],link[href],script[src],img[src],[data-src]"):
+ for attr in ("href", "src", "data-src"):
+ value = element.get(attr)
+ if value is not None and not urlsplit(value).scheme and not urlsplit(value).netloc:
+ element[attr] = urljoin(f"/{language}/{route}.html", value).lstrip("/")
+ return str(soup)
+
+
+def build(output: Path, content: Path, *, home: Path, run=None, language="zh", profile=PROFILE):
+ if language not in LABELS:
+ raise ValueError("Unsupported language")
+ languages = ("zh",) if language == "zh" else ("en", "zh")
+ model = read_json(content)
+ validate_dataset(home, profile)
+ binding = read_json(profile).get("research_report", {}).get("content", {}).get("sha256")
+ if binding and digest(content.read_bytes()) != binding:
+ raise ValueError("Report prose differs from the profile-bound source")
+ truth = read_json(home / "dataset/dataset/ground-truth.json")
+ history = read_json(home / "historical-reproduction.json")
+ if history["dataset_manifest_sha256"] != digest((home / "dataset/manifest.json").read_bytes()):
+ raise ValueError("Reproduction belongs to different inputs")
+ selections = (
+ model.get("evidence_runs", []) if run is None else [{"run": str(run), "methods": None}]
+ )
+ rows = []
+ bindings = []
+ for selection in selections:
+ source = Path(selection["run"])
+ source = source if source.is_absolute() else home / "runs" / source
+ contract, records = load_run(source)
+ if contract.get("kind") not in ("input_compatibility_only", "input_size_boundary_only"):
+ raise ValueError(
+ "Research report accepts compatibility evidence only; full quality cohorts need their own certified report mode"
+ )
+ if contract["dataset_manifest_sha256"] != history["dataset_manifest_sha256"]:
+ raise ValueError("Run belongs to different inputs")
+ records = [
+ r
+ for r in records
+ if selection.get("methods") is None or r["method"] in selection["methods"]
+ ]
+ for record in records:
+ r = json.loads(json.dumps(record))
+ r["run_id"] = source.name
+ if "request" in r:
+ r["request"]["endpoint"] = re.sub(
+ r"/accounts/[^/]+/", "/accounts/[REDACTED]/", r["request"]["endpoint"]
+ )
+ rows.append(redact(r))
+ bindings.append(
+ {
+ "run_id": source.name,
+ "manifest_sha256": digest((source / "manifest.json").read_bytes()),
+ "methods": selection.get("methods"),
+ "contract": contract,
+ }
+ )
+ keys = [(r["method"], r["case_id"]) for r in rows]
+ if len(keys) != len(set(keys)):
+ raise ValueError("Select exactly one compatibility observation per method and case")
+ if output.exists() and any(output.iterdir()):
+ raise ValueError("Use an empty output directory")
+ output.mkdir(parents=True, exist_ok=True)
+ (output / "style.css").write_text(CSS)
+ (output / "app.js").write_text(JS)
+ for asset in model.get("assets", []):
+ source = content.parent / asset["source"]
+ target = output / asset["path"]
+ if (
+ Path(asset["path"]).is_absolute()
+ or ".." in Path(asset["path"]).parts
+ or source.is_symlink()
+ or digest(source.read_bytes()) != asset["sha256"]
+ ):
+ raise ValueError("Unsafe or changed report asset")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(source.read_bytes())
+ for r in rows:
+ save_json(output / "evidence" / f"{r['method']}-{r['case_id']}.json", r, exclusive=True)
+ for lang in languages:
+ lab = LABELS[lang]
+ directory = output / lang
+ directory.mkdir()
+ bodies = {p: model["pages"].get(p, {}).get("body", {}).get(lang, "") for p in PAGES}
+ titles = {
+ p: model["pages"].get(p, {}).get("title", {}).get(lang, lab[i])
+ for i, p in enumerate(PAGES)
+ }
+ # Scope and observed current interfaces lead; historical scores remain separate.
+ methods = sorted({r["method"] for r in rows})
+ summary = []
+ for method in methods:
+ subset = [r for r in rows if r["method"] == method]
+ called = sum(r["state"] in ("response_received", "call_error") for r in subset)
+ structured = sum(r.get("compatibility") == "structured_output" for r in subset)
+ summary.append(
+ [
+ esc(method),
+ str(len(subset)),
+ str(called),
+ str(structured),
+ '' + lab[2] + "",
+ ]
+ )
+ bodies["index"] = (
+ table(
+ [
+ lab[15],
+ "计划样本" if lang == "zh" else "Planned cases",
+ "实际调用" if lang == "zh" else "API calls",
+ lab[12],
+ lab[9],
+ ],
+ summary,
+ attrs='data-core-metrics="compatibility"',
+ )
+ + bodies["index"]
+ )
+ hr = []
+ fields = ("price", "sku", "availability")
+ historical_fields = (*fields, "OutOfStock")
+ for method, scores in history["scores"].items():
+ cells = [esc(method)]
+ for field in historical_fields:
+ v = scores[field]["f1"]
+ best = max(s[field]["f1"] for s in history["scores"].values())
+ unique = sum(s[field]["f1"] == best for s in history["scores"].values()) == 1
+ text = f"{v:.3f}"
+ if unique and v == best:
+ text = '' + text + ""
+ cells.append(f'{text}')
+ hr.append(cells)
+ names = [*lab[23:26], "缺货 F1" if lang == "zh" else "Out-of-stock F1"]
+ headers = [
+ lab[15],
+ *[
+ f"{name} {sum(bool(gt.get(field)) for gt in truth.values())}/{len(truth)} annotated"
+ for name, field in zip(names, historical_fields, strict=True)
+ ],
+ ]
+ if lang == "zh":
+ headers = [x.replace("annotated", "有标注") for x in headers]
+ hist = table(headers, hr, attrs='data-history-table="true"')
+ soup = BeautifulSoup(hist, "html.parser")
+ for row in soup.select("tbody tr"):
+ method = row.select_one("td").get_text()
+ for field, cell in zip(historical_fields, row.select("td")[1:], strict=True):
+ cell.attrs.update(
+ {
+ "data-metric": field,
+ "data-metric-direction": "max",
+ "data-sort": str(history["scores"][method][field]["f1"]),
+ }
+ )
+ historical_title = lab[22].replace("140", str(len(truth)))
+ bodies["index"] += "
" + historical_title + "
" + str(soup) + ""
+ dr = []
+ pin = read_json(profile)["dataset"]
+ for cid, gt in sorted(truth.items()):
+ url = f"https://github.com/{pin['repository']}/blob/{pin['commit']}/dataset/html/{cid}.html.gz"
+ ref = {f: gt.get(f, []) for f in fields}
+ dr.append(
+ [
+ f"{cid}",
+ f'{esc(urlsplit(gt["url"]).netloc)}',
+ f'HTML.gz',
+ f"{lab[19]}
'
)
+ if cohort:
+ observed = {(r["method"], r["case_id"]) for r in rows}
+ for method in methods:
+ for cid in sorted(truth):
+ if (method, cid) not in observed:
+ pending = "待执行" if lang == "zh" else "Not executed"
+ inventory.append(
+ f'
{esc(method)}
{cid[:12]}
{pending}
—
—
—
'
+ )
initial = (
"fail" if any(r.get("compatibility") != "structured_output" for r in rows) else "all"
)
filt = f''
+ if cohort:
+ filt = filt.replace(
+ "",
+ '",
+ )
bodies["results"] += (
'
Usage comes from native response metadata or billing headers, including retained retries. Credit prices differ between services. An unavailable receipt does not mean zero cost; see Accounts for balances and access requirements.
"
+ )
hr = []
fields = ("price", "sku", "availability")
historical_fields = (*fields, "OutOfStock")
@@ -593,12 +701,12 @@ def build(output: Path, content: Path, *, home: Path, run=None, language="zh", p
text = '' + text + ""
cells.append(f'{text}')
hr.append(cells)
- names = [*lab[23:26], "缺货 F1" if lang == "zh" else "Out-of-stock F1"]
+ historical_names = [*lab[23:26], "缺货 F1" if lang == "zh" else "Out-of-stock F1"]
headers = [
lab[15],
*[
f"{name} {sum(bool(gt.get(field)) for gt in truth.values())}/{len(truth)} annotated"
- for name, field in zip(names, historical_fields, strict=True)
+ for name, field in zip(historical_names, historical_fields, strict=True)
],
]
if lang == "zh":
@@ -644,8 +752,15 @@ def build(output: Path, content: Path, *, home: Path, run=None, language="zh", p
url = "result-" + key + ".html"
error = r.get("error") or ""
payload = r.get("response") or {}
+ if not isinstance(payload, dict):
+ payload = {"message": json.dumps(payload, ensure_ascii=False)}
if not error and not ok:
- value = payload.get("error") or payload.get("message") or payload.get("errors")
+ value = (
+ payload.get("error")
+ or payload.get("message")
+ or payload.get("errors")
+ or payload.get("non_json_response")
+ )
if isinstance(value, dict):
error = str(value.get("message") or value.get("type") or value)
elif value:
@@ -668,9 +783,9 @@ def build(output: Path, content: Path, *, home: Path, run=None, language="zh", p
error = ""
evidence = "../evidence/" + (r["method"] if cohort else key) + ".json"
evidence_key = f' data-key="{cid}"' if cohort else ""
- detail = f'
'
)
if cohort:
observed = {(r["method"], r["case_id"]) for r in rows}
@@ -708,7 +823,7 @@ def build(output: Path, content: Path, *, home: Path, run=None, language="zh", p
if (method, cid) not in observed:
pending = "待执行" if lang == "zh" else "Not executed"
inventory.append(
- f'
{esc(method)}
{cid[:12]}
{pending}
—
—
—
'
+ f'
{esc(names.get(method, method))}
{cid[:12]}
{pending}
—
—
—
'
)
initial = (
"fail" if any(r.get("compatibility") != "structured_output" for r in rows) else "all"
@@ -761,6 +876,7 @@ def build(output: Path, content: Path, *, home: Path, run=None, language="zh", p
"template": VERSION,
"mode": state,
"planned_methods": list(cohort_plan["participants"]) if cohort else None,
+ "method_labels": names,
"renderer_sha256": digest(Path(__file__).read_bytes()),
"content_sha256": digest(content.read_bytes()),
"profile_sha256": digest(profile.read_bytes()),
@@ -834,6 +950,7 @@ def check(output: Path, *, release=False, visual_receipt=None):
raise ValueError("Broken evidence anchor")
if manifest.get("mode") == "full-cohort-progress":
methods = manifest["planned_methods"]
+ names = manifest.get("method_labels", {})
data = {m: read_json(output / "evidence" / (m + ".json")) for m in methods}
scores = {
m: b["scores"][m]
@@ -865,6 +982,21 @@ def check(output: Path, *, release=False, visual_receipt=None):
value = scores.get(method, {}).get(field, {}).get("f1")
if cell.get_text(strip=True) != ("—" if value is None else f"{value:.3f}"):
raise ValueError("Displayed quality differs from certified scores")
+ protocol = BeautifulSoup((output / lang / "protocol.html").read_text(), "html.parser")
+ rows = [r for method in methods for r in data[method].values()]
+ _, expected_time = cohort_metrics(
+ methods, rows, manifest["source_runs"], manifest["case_count"], lang, names
+ )
+ for selector, expected_html in [
+ ("[data-latency-table]", expected_time),
+ ("[data-usage-table]", usage_table(methods, rows, lang, names)),
+ ]:
+ observed_tables = protocol.select(selector)
+ expected_table = BeautifulSoup(expected_html, "html.parser").select_one(selector)
+ if len(observed_tables) != 1 or [
+ c.get_text(strip=True) for c in observed_tables[0].select("td")
+ ] != [c.get_text(strip=True) for c in expected_table.select("td")]:
+ raise ValueError("Timing or usage values differ from retained calls")
inventory = BeautifulSoup((output / lang / "results.html").read_text(), "html.parser")
if len(inventory.select("tr[data-status]")) != len(methods) * manifest["case_count"]:
raise ValueError("Full planned result inventory is incomplete")
diff --git a/tests/web_scraper/test_certification.py b/tests/web_scraper/test_certification.py
index 2e1565e35..a121f3e9d 100644
--- a/tests/web_scraper/test_certification.py
+++ b/tests/web_scraper/test_certification.py
@@ -87,3 +87,10 @@ def timeout(*args, **kwargs):
_, rows = load_run(run)
assert len(rows) == 3
assert all(r["state"] == "call_error" and r["elapsed_seconds"] == 5 for r in rows)
+
+
+@pytest.mark.parametrize("payload", [None, [], "invalid", 42])
+def test_unexpected_native_envelope_retains_no_fabricated_fields(payload):
+ from harness.web_scraper.pipeline import normalize
+
+ assert normalize("scrapfly-product", payload) is None
diff --git a/tests/web_scraper/test_cohort_report.py b/tests/web_scraper/test_cohort_report.py
index a027bc0d8..ad30a97da 100644
--- a/tests/web_scraper/test_cohort_report.py
+++ b/tests/web_scraper/test_cohort_report.py
@@ -88,3 +88,80 @@ def test_requested_english_requires_matching_authored_translation(tmp_path):
profile=home / "profile.json",
language="en",
)
+
+
+def test_latency_uses_one_population_and_separates_missing_time_and_retries():
+ rows = [
+ {"method": "a", "elapsed_seconds": 1, "compatibility": "structured_output"},
+ {"method": "a", "elapsed_seconds": 2, "compatibility": "structured_output"},
+ {"method": "a", "elapsed_seconds": 10, "retry_execution_seconds": 0.5},
+ {"method": "a", "state": "call_error"},
+ {"method": "b", "elapsed_seconds": 100, "compatibility": "structured_output"},
+ ]
+ _, html = cohort_metrics(["a", "b"], rows, [], 140, "en")
+ soup = check_presentation(html)
+ cells = [[c.get_text(strip=True) for c in r.select("td")] for r in soup.select("tbody tr")]
+ assert cells[0][2:] == ["3", "1", "0.50", "4.33", "2.00", "10.00"]
+ assert cells[1][2:] == ["2", "0", "0.00", "1.50", "1.50", "2.00"]
+
+
+def test_usage_retains_denied_physical_attempt_without_inventing_a_charge():
+ from harness.web_scraper.report import usage_table
+
+ failed = {"response": {"success": False}, "http_status": 402}
+ paid = {"response": {"data": {"metadata": {"creditsUsed": 5}}}}
+ rows = [{"method": "native", "physical_attempts": [failed, paid]}]
+ soup = BeautifulSoup(usage_table(["native"], rows, "en"), "html.parser")
+ assert [c.get_text(strip=True) for c in soup.select("tbody td")] == [
+ "native",
+ "2",
+ "1",
+ "5 credits",
+ ]
+
+
+@pytest.mark.parametrize(
+ "selector", ["[data-latency-table] td:nth-child(6)", "[data-usage-table] td:nth-child(2)"]
+)
+def test_progress_check_rejects_timing_or_usage_value_changes(tmp_path, selector):
+ output = tmp_path / "report"
+ create(output, mode="full-cohort-progress")
+ page = output / "zh/protocol.html"
+ soup = BeautifulSoup(page.read_text(), "html.parser")
+ cell = soup.select_one(selector)
+ marker = cell.select_one(".comparison-winner")
+ (marker if marker is not None else cell).string = "9999"
+ page.write_text(str(soup))
+ manifest = read_json(output / "report-manifest.json")
+ manifest["files"]["zh/protocol.html"] = digest(page.read_bytes())
+ save_json(output / "report-manifest.json", manifest)
+ with pytest.raises(ValueError, match="Timing or usage"):
+ check(output)
+
+
+def test_external_participant_labels_are_used_without_changing_evidence_identity(tmp_path):
+ home = create(tmp_path / "first", mode="full-cohort-progress")
+ content = read_json(home / "content.json")
+ content["method_labels"] = {"synthetic-success": "Source A", "synthetic-blocked": "Source B"}
+ save_json(home / "content.json", content)
+ output = tmp_path / "labeled"
+ build(output, home / "content.json", home=home, profile=home / "profile.json")
+ check(output)
+ soup = BeautifulSoup((output / "zh/index.html").read_text(), "html.parser")
+ assert [
+ r.select_one("td").get_text(strip=True) for r in soup.select("[data-core-metrics] tbody tr")
+ ] == ["Source A", "Source B"]
+
+
+def test_mathematically_equal_f1_is_neutral_despite_float_arithmetic_noise():
+ def metrics(value):
+ return {f: {"f1": value} for f in ("price", "sku", "availability", "OutOfStock")}
+
+ bindings = [
+ {"certified": True, "scores": {"a": metrics(2 / 3), "b": metrics(0.6666666666666667)}}
+ ]
+ html, _ = cohort_metrics(["a", "b"], [], bindings, 140, "en")
+ assert not check_presentation(html).select(".comparison-winner")
+ bindings[0]["scores"] = {"a": metrics(0.8104), "b": metrics(0.8101)}
+ html, _ = cohort_metrics(["a", "b"], [], bindings, 140, "en")
+ assert len(check_presentation(html).select(".comparison-winner")) == 4
From a4e38937050548657d90e2b975cf446711f24c17 Mon Sep 17 00:00:00 2001
From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com>
Date: Tue, 3 Nov 2026 16:48:07 +0800
Subject: [PATCH 004/103] fix(web-scraper): complete native extraction and
required comparison metrics
---
.agents/skills/benchmark-report/SKILL.md | 1 +
.../references/report-and-release.md | 2 +
examples/web_scraper/README.md | 13 +-
research/provider-pricing.json | 57 ++++++
src/harness/reporting/templates.py | 36 +++-
src/harness/web_fetch/config.py | 2 +-
src/harness/web_fetch/publication_privacy.py | 4 +-
src/harness/web_scraper/certification.py | 21 ++-
src/harness/web_scraper/example.py | 12 ++
src/harness/web_scraper/pipeline.py | 75 ++++----
src/harness/web_scraper/report.py | 134 ++++++++++++--
src/harness/web_scraper/stagehand.py | 10 +-
tests/test_publication_privacy.py | 16 ++
tests/test_report_templates.py | 24 ++-
tests/web_scraper/test_cohort_report.py | 51 +++++-
.../web_scraper/test_execution_boundaries.py | 166 +++++++++++++++++-
tests/web_scraper/test_pipeline.py | 47 ++++-
17 files changed, 606 insertions(+), 65 deletions(-)
diff --git a/.agents/skills/benchmark-report/SKILL.md b/.agents/skills/benchmark-report/SKILL.md
index 59940ef09..6d8010047 100644
--- a/.agents/skills/benchmark-report/SKILL.md
+++ b/.agents/skills/benchmark-report/SKILL.md
@@ -43,6 +43,7 @@ Public report CLIs fall back to English. `BROWSER_EVAL_REPORT_LANGUAGE` changes
3. Let each method use its strongest documented route to produce the required output. Equalize the task, inputs, output contract, call budget, and scoring. Do not require identical internals. For fixed-native cohorts, declare the input media type independently of URL patterns and expected answers, freeze the class-level route and transport parameters before calls, and verify the retained request receipts at aggregation and release. Record material asymmetries such as local versus remote execution, cold versus warm start, bundled conversion, network transit, account tier, and billable time.
4. Preserve evidence as an append-only chain by default: task definition, reference, provider call, raw artifact, normalized artifact, score, review, revision, and release. If the user explicitly requests deletion of superseded history, validate the chain first and use the existing owner's current-only authority described in [audit and revision](references/audit-and-revision.md); remove obsolete full snapshots rather than storing reverse patches. Keep current provider outputs, call identities, real scoring sources and necessary review evidence immutable. Routine refresh and publication reuse current inputs without redundant historical snapshots. A presentation or scoring change must not masquerade as a new provider result. Declare the native answer fields and validate their structural projection before accepting a scored artifact. Adapters must not remove returned candidates by URL meaning or consult expected answers when selecting candidate fields. Apply privacy redaction only to separately identified public views after scoring, preserving the private originals and distinguishing original, scored and public-view hashes.
5. Separate retrieval success, task acceptance, content quality, latency, cost, and freshness. Treat missing telemetry as unavailable. A request that received no first byte contributes to total latency, but not to first-byte or body-transfer stage means; show each stage’s observed population. A missing or partial reference makes the affected metric unavailable or scoped; it does not prove success or failure. Do not derive binary acceptance from an unrelated aggregate similarity score.
+ Every report type must cover latency and cost/pricing for every participant. The shared template resolver supplies this metric contract automatically to existing and newly registered tracks. Freeze timer boundaries before calls, retain success and failure timers, report mean/P50/P95 with one population, and retain retry execution cost separately. Price comparisons need official sources, verification dates, commitments and billing units; use USD per 1,000 requests where a defensible conversion exists. Keep estimates, native usage and actual charges distinct. Decide whether CPU and memory measurements are applicable during design, with a reason when omitted. Release checks must verify participant coverage; unavailable values require an evidenced reason and affected count, never a substituted zero.
6. For heterogeneous same-window latency evidence, preserve the full predeclared task-by-method matrix. Show all-call latency on that common denominator separately from successful-call latency on each method's conditional subset. Treat the all-method shared-pass intersection as a diagnostic, never as a post-outcome selector or ranking sample.
7. At aggregate and publication boundaries, copy only explicit hash-bound evidence and public audit files. Reject symlinks and exclude worker trees, host paths, credentials, and internal run logs. Verify primary, auxiliary, delivered-file, and retained retry artifacts before release.
When a saved-input handoff needs host-metadata redaction, use the shared publication privacy owner. Preserve private originals and distinguish original from public file hashes; rebind dependent metadata references and disclose auxiliary debug-log projections. Never rewrite original scored answers, references or response payloads as a privacy repair. When a scored answer or native envelope itself contains private values, create a separately identified post-score public view through the shared privacy owner, verify its native-field projection and unchanged task verdict, and disclose that omitted original bytes cannot be reconstructed from the public copy. A public frozen presentation must explicitly bind its complete view inventory, verify displayed bytes against those views, keep acquisition gates strict, and distinguish preserved original diagnostics from what redacted text can reproduce. Verify unchanged verdicts, timings and review decisions, and rebuild from the public inputs. Keep regenerated package/report wrappers outside the original-input projection receipt so normal rebuilding does not invalidate it or create circular hashes.
diff --git a/.agents/skills/benchmark-report/references/report-and-release.md b/.agents/skills/benchmark-report/references/report-and-release.md
index 9f28832d7..5fb9ff7d7 100644
--- a/.agents/skills/benchmark-report/references/report-and-release.md
+++ b/.agents/skills/benchmark-report/references/report-and-release.md
@@ -72,6 +72,8 @@ A composed cohort can use a compact current-report profile with `frozen_inputs`
## Claims and rankings
+Every comparison includes latency and cost/pricing for all participants. These are shared template requirements, not optional track features. The discovery command returns the inherited contract for new tracks. Before calls, select the timer boundaries, native usage receipts, pricing sources and normalization unit. CPU and memory are contextual: measure them for local execution or a controlled resource comparison; state the reason when they do not apply. A remote API client's CPU or memory does not measure the provider's infrastructure. Release checks must reject omitted participants or missing dimensions. An unavailable measurement retains its scope, count and reason; it is never rendered as zero.
+
Pair every ranking with its task family, denominator, acceptance meaning, a typical input-to-output route, and limits. Keep task acceptance separate from continuous quality, latency, cost, and title/body diagnostics. Do not call conditional averages global quality or explain a correlation as a verified mechanism.
Prefer concise tables for exact comparisons and prose for interpretation. Remove repeated caveats after placing each limitation where it changes interpretation. Run a factual pass before a prose/humanization pass; never let editing change numbers or scope.
diff --git a/examples/web_scraper/README.md b/examples/web_scraper/README.md
index b43c6e98d..1f632d37b 100644
--- a/examples/web_scraper/README.md
+++ b/examples/web_scraper/README.md
@@ -37,12 +37,14 @@ Historical predictions are separate from new measurements.
| `oxylabs-json` | Web API JSON | Frozen HTTPS URL and JSON Schema |
| `zyte-product` | Product extraction, `userHtml` | Uploaded HTML with original URL as context |
| `diffbot-product` | Product API POST | Raw uploaded HTML with original URL as context |
+| `browserbase-json` | Native JSON extraction | Frozen HTTPS URL and JSON Schema; built-in extraction |
| `browserbase-stagehand` | Hosted Stagehand Extract | Frozen HTTPS URL; provider-hosted browser and inference |
| `extruct` | Upstream local baseline | Archived HTML |
Browser infrastructure requiring a separately connected model is outside this
-comparison. Stagehand uses its native Model Gateway; it does not read an OpenAI
-key. Bright Data's site-specific scraper remains discoverable as a candidate, but
+comparison. Browserbase JSON uses only the Browserbase API key. The separately
+registered Stagehand route uses its native Model Gateway and needs a project ID;
+it does not read an OpenAI key. Bright Data's site-specific scraper remains discoverable as a candidate, but
is rejected by the full archived-page plan because it cannot parse arbitrary HTML.
URL-only interfaces need a reachable HTTPS address serving the frozen snapshots.
@@ -107,8 +109,11 @@ binds dataset provenance and optional authored content hashes. The `full-cohort-
per participant. It validates certificates for complete cohorts and immutable
journal entries for paused cohorts. Quality is shown only for complete certified
methods; the result inventory includes every planned method and case, with
-unexecuted cases labeled separately. Raw evidence is grouped by method and loaded
-on demand. This progress report does not certify an incomplete comparison.
+unexecuted cases labeled separately. Credential-redacted evidence views are grouped
+by method and loaded on demand, with original/public hashes and unchanged extracted
+fields. Combining independently frozen source plans requires an explicit
+`source_cohorts` method-to-plan-hash binding; each run retains its own timing policy.
+This progress report does not certify an incomplete comparison.
Exercise this mode with the same renderer:
diff --git a/research/provider-pricing.json b/research/provider-pricing.json
index 6aa371893..c475d2313 100644
--- a/research/provider-pricing.json
+++ b/research/provider-pricing.json
@@ -2,6 +2,63 @@
"checked_at": "2026-09-03",
"currency": "USD",
"scope": "公开 Web Fetch / Contents / Extract / Scrape / Markdown 与 Search 报价;不作为历史调用账单",
+ "structured_extraction_products": [
+ {
+ "id": "browserbase-json", "verified_at": "2026-11-03", "currency": "USD",
+ "billing_unit": "JSON extraction request without proxies", "rates_per_1000": {"paid_overage": 4, "with_proxies": 7},
+ "commitment": "Developer USD 20/month or Startup USD 99/month; included allocations precede overage. Free plan includes 1,000 Fetch calls; extraction access was independently tested.",
+ "sources": ["https://www.browserbase.com/pricing", "https://dev.browserbase.com/changelog/fetch-api-extract"]
+ },
+ {
+ "id": "firecrawl-json", "verified_at": "2026-11-03", "currency": "USD",
+ "billing_unit": "JSON scrape page, 5 credits", "rates_per_1000": {"hobby_monthly_full_utilization": 19, "standard_monthly_full_utilization": 4.95, "growth_monthly_full_utilization": 3.99, "scale_monthly_full_utilization": 3.745},
+ "commitment": "Monthly tiers USD 19/5,000 credits, USD 99/100,000, USD 399/500,000, USD 749/1,000,000. Base scrape 1 credit plus JSON 4 credits. Full utilization assumptions; annual and overage rates differ.",
+ "sources": ["https://www.firecrawl.dev/pricing"]
+ },
+ {
+ "id": "scrapegraph-extract", "verified_at": "2026-11-03", "currency": "USD",
+ "billing_unit": "extract request, 5 credits without stealth", "rates_per_1000": {"starter_monthly_full_utilization": 10, "growth_monthly_full_utilization": 5, "pro_monthly_full_utilization": 3.3333333333333335, "small_topup": 25, "medium_topup": 20, "large_topup": 15},
+ "commitment": "Monthly USD 20/10,000 credits, USD 100/100,000, USD 500/750,000. One-time packs USD 5/1,000, USD 40/10,000, USD 150/50,000. Stealth adds 5 credits; free grant is one-time 500 credits.",
+ "sources": ["https://scrapegraphai.com/pricing"]
+ },
+ {
+ "id": "scrapfly-product", "verified_at": "2026-11-03", "currency": "USD",
+ "billing_unit": "product extraction model, 5 credits per 500 KB document chunk", "rates_per_1000": {"discovery_full_utilization_base_chunk": 0.75, "pro_full_utilization_base_chunk": 0.5, "enterprise_full_utilization_base_chunk": 0.45454545454545453},
+ "commitment": "USD 30/month for 200,000 shared credits; USD 100/1,000,000; USD 500/5,500,000. Each additional 500 KB chunk costs another 5 credits. Use X-Scrapfly-Api-Cost to account for actual document sizes; the base-chunk price is not a flat price for every document.",
+ "sources": ["https://scrapfly.io/docs/extraction-api/billing", "https://scrapfly.io/pricing"]
+ },
+ {
+ "id": "diffbot-product", "verified_at": "2026-11-03", "currency": "USD",
+ "billing_unit": "Extract page, 1 credit without datacenter proxy", "rates_per_1000": {"startup_full_utilization": 1.196, "startup_overage": 1, "plus_full_utilization": 0.899, "plus_overage": 0.9},
+ "commitment": "Startup USD 299/month for 250,000 shared credits; Plus USD 899/month for 1,000,000. Free 10,000 credits/month with 5 requests/min. Datacenter proxy doubles extraction credits.",
+ "sources": ["https://www.diffbot.com/pricing"]
+ },
+ {
+ "id": "zyte-product", "verified_at": "2026-11-03", "currency": "USD",
+ "billing_unit": "automatic extraction per data type", "rates_per_1000": {"published_extraction_min": 0.27, "published_extraction_max": 1.07},
+ "commitment": "PAYG without monthly commitment; published range covers automatic extraction data types, not an exact quote for this userHtml product cohort. userHtml performs no download or browser rendering. Native response receipts do not expose an exact per-call USD amount; target fetch/browser costs apply to live-URL workflows.",
+ "sources": ["https://docs.zyte.com/zyte-api/pricing.html", "https://docs.zyte.com/zyte-api/usage/reference"]
+ },
+ {
+ "id": "cloudflare-json", "verified_at": "2026-11-03", "currency": "USD",
+ "billing_unit": "browser hour", "rates_per_1000": {},
+ "conversion": "USD 0.025 * mean billable browser seconds per request, per 1,000 requests, after included hours. Client end-to-end seconds are not billable browser seconds.",
+ "commitment": "Workers Paid includes 10 browser hours/month, then USD 0.09/hour. Quick Actions charge browser time only. This cohort did not retain X-Browser-Ms-Used, so an exact USD/1,000 conversion is unavailable.",
+ "sources": ["https://developers.cloudflare.com/browser-run/pricing/"]
+ },
+ {
+ "id": "oxylabs-json", "verified_at": "2026-11-03", "currency": "USD",
+ "billing_unit": "custom-domain non-JS scrape plus AI parsing", "rates_per_1000": {"welcome_and_starter": 4, "basic": 3.9, "flexible": 3.8, "enterprise_from": 3.75},
+ "commitment": "USD 5 welcome credit; Starter USD 30/month, Basic USD 100/month, Flexible USD 500/month, Enterprise from USD 2,500/month. AI parsing costs USD 3/1,000 parsed pages, added to custom-domain non-JS scraping at USD 1/0.90/0.80/0.75 per 1,000 results. The advertised USD 0.50 scrape starting price is not this generic JSON configuration.",
+ "sources": ["https://oxylabs.io/pricing", "https://developers.oxylabs.io/products/web-api/scrape/ai-parsing"]
+ },
+ {
+ "id": "extruct", "verified_at": "2026-11-03", "currency": "USD",
+ "billing_unit": "local extraction", "rates_per_1000": {"external_api_fee": 0},
+ "commitment": "No vendor API fee. Local CPU, hosting, maintenance and HTML acquisition are excluded; this does not mean zero total cost.",
+ "sources": ["https://github.com/scrapinghub/extruct"]
+ }
+ ],
"search_products": [
{
"id": "browserbase-search",
diff --git a/src/harness/reporting/templates.py b/src/harness/reporting/templates.py
index 3f0a24a8d..6f578bcd1 100644
--- a/src/harness/reporting/templates.py
+++ b/src/harness/reporting/templates.py
@@ -1,25 +1,55 @@
"""Discover maintained report owners and pinned examples before building."""
+
import json
+from copy import deepcopy
from harness.distribution import repository_root
ROOT = repository_root()
+# Every registered track inherits these dimensions, including future tracks.
+METRIC_CONTRACT = {
+ "required": {
+ "latency": {
+ "unit": "seconds",
+ "summaries": ["mean", "p50", "p95"],
+ "population": "every participant; declare sample and missing counts",
+ "collection": "measure failures as well as successes; retain retry cost separately",
+ },
+ "cost": {
+ "scope": "every participant",
+ "pricing": "Source/date/unit/commitment; use USD/1,000 requests where supported.",
+ "usage": "Native receipts; distinguish estimates, actual charges and free allocations.",
+ },
+ },
+ "contextual": {
+ "cpu": "Decide before calls; measure local or controlled compute, else explain omission.",
+ "memory": "Decide before calls; measure local or controlled memory, else explain omission.",
+ },
+ "unavailable": "Never substitute zero; retain the affected count and an evidenced reason.",
+}
+
def resolve_template(track, *, root=ROOT):
registry = json.loads((root / "configs/report-templates.json").read_text())
if registry.get("schema_version") != 1:
raise ValueError("Unsupported report template registry")
if track not in registry["tracks"]:
- raise ValueError("Unregistered report track; add its maintained renderer, runnable example and release checks first")
+ raise ValueError(
+ "Unregistered report track; add its maintained renderer, "
+ "runnable example and release checks first"
+ )
result = dict(registry["tracks"][track])
for key in ("renderer", "entrypoint", "tests"):
path = root / result[key]
- if not path.is_file() or not path.resolve().is_relative_to(root.resolve()):
+ exists = path.is_file() or (key == "tests" and path.is_dir())
+ if not exists or not path.resolve().is_relative_to(root.resolve()):
raise ValueError("Report template has a missing or unsafe " + key)
if not result.get("example"):
raise ValueError("Report template needs a version-pinned example")
- return {"track": track, **result}
+ if "metric_contract" in result:
+ raise ValueError("A report track cannot replace the shared required metric contract")
+ return {"track": track, **result, "metric_contract": deepcopy(METRIC_CONTRACT)}
def template_identity(track):
diff --git a/src/harness/web_fetch/config.py b/src/harness/web_fetch/config.py
index 5b7b65415..8e6001cba 100644
--- a/src/harness/web_fetch/config.py
+++ b/src/harness/web_fetch/config.py
@@ -66,7 +66,7 @@ def _validate_ground_truth_evidence(item: dict[str, Any]) -> None:
def _evaluation_credential(name: str) -> bool:
- return bool(re.fullmatch(r"[A-Z0-9_]+_(?:API_KEY|API_TOKEN|ACCOUNT_ID)", name))
+ return name == "BROWSERBASE_PROJECT_ID" or bool(re.fullmatch(r"[A-Z0-9_]+_(?:API_KEY|API_TOKEN|ACCOUNT_ID)", name))
def load_runtime_env(path: Path | None = None) -> None:
diff --git a/src/harness/web_fetch/publication_privacy.py b/src/harness/web_fetch/publication_privacy.py
index 025a8943a..6bcd9bd68 100644
--- a/src/harness/web_fetch/publication_privacy.py
+++ b/src/harness/web_fetch/publication_privacy.py
@@ -204,9 +204,9 @@ def _public_cors_policy(data):
rb'(?:(?:[a-z0-9]+[-_])*(?:proxy[-_]?authorization|authorization|(?:set[-_])?cookie|'
rb'(?:access|refresh|id)[-_]?token|x[-_]?auth[-_]?token|private[-_]?token|token|'
rb'(?:aws[-_])?secret[-_]?access[-_]?key|client[-_]?secret|secret|credentials?|'
- rb'x[-_]?api[-_]?key|api[-_]?key|password|passwd))'
+ rb'x[-_]?api[-_]?key|api[-_]?key|signing[-_]?key|password|passwd))'
)
-EMBEDDED_URL = re.compile(r"(?i)\bhttps?://[^\s<>\"'\\\x00]+")
+EMBEDDED_URL = re.compile(r"(?i)\b(?:https?|wss?)://[^\s<>\"'\\\x00]+")
QUERY_SENSITIVE_KEY = re.compile(
r'(?i)(?:' + SENSITIVE_KEY.decode('ascii') +
r'|(?:[a-z0-9]+[-_])*(?:signature|sig|signed|auth|key)|'
diff --git a/src/harness/web_scraper/certification.py b/src/harness/web_scraper/certification.py
index d91300a4b..7c9d19dd6 100644
--- a/src/harness/web_scraper/certification.py
+++ b/src/harness/web_scraper/certification.py
@@ -5,6 +5,7 @@
import sys
from pathlib import Path
+from harness.reporting.templates import resolve_template
from harness.web_scraper.pipeline import (
PROFILE,
ROOT,
@@ -54,6 +55,11 @@ def create_plan(home, methods, output):
"review": "Machine scoring only; independent review requires an explicit request",
"primary_language": "zh",
"english": "Generated only on explicit request",
+ "metric_contract": resolve_template("web-scraper")["metric_contract"],
+ "resource_decision": {
+ "cpu": "Remote CPU unavailable; client CPU does not measure the provider.",
+ "memory": "Remote memory unavailable; the local baseline is timed separately.",
+ },
}
save_json(output, plan, exclusive=True)
return plan
@@ -66,7 +72,13 @@ def frozen_probe(run_dir, expected_sha):
spec = importlib.util.spec_from_file_location("harness.web_scraper._frozen_runner", source)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
+ frozen_profile = module.PROFILE
module.ROOT, module.PROFILE = ROOT, PROFILE
+ # Function defaults are bound at import, before the snapshot is relocated.
+ for name in ("prepare", "validate_dataset"):
+ function = getattr(module, name, None)
+ if function is not None and function.__defaults__ == (frozen_profile,):
+ function.__defaults__ = (PROFILE,)
contract = read_json(run_dir / "contract.json")
adapter_sha = contract.get("stagehand_sha256")
adapter = None
@@ -134,8 +146,13 @@ def run(home: Path, profile: Path, method: str, run_dir: Path, fixture_base=None
collector = probe
if binding.exists():
original = read_json(binding)
- collector = frozen_probe(run_dir, original["pipeline_sha256"])
- precall["pipeline_sha256"] = original["pipeline_sha256"]
+ if (run_dir / "contract.json").exists():
+ collector = frozen_probe(run_dir, original["pipeline_sha256"])
+ precall["pipeline_sha256"] = original["pipeline_sha256"]
+ elif any(
+ (run_dir / name).exists() for name in ("calls.journal.jsonl", "inflight.json")
+ ) or any((run_dir / "calls").glob("*")):
+ raise ValueError("Cannot recover initialization with unbound dispatch evidence")
if original != precall:
raise ValueError("Certified resume inputs changed")
else:
diff --git a/src/harness/web_scraper/example.py b/src/harness/web_scraper/example.py
index 27adf1392..ac9289392 100644
--- a/src/harness/web_scraper/example.py
+++ b/src/harness/web_scraper/example.py
@@ -129,6 +129,18 @@ def create(output: Path, *, language="zh", mode="compatibility"):
model["mode"] = mode
model["cohort_plan"] = {"path": str(plan_path), "sha256": digest(plan_path.read_bytes())}
model["evidence_runs"] = []
+ model["prices"] = {
+ m: {
+ "usd_per_1000": "$0 external API fee (synthetic)",
+ "terms": {
+ "zh": "合成数据,不产生实际费用。",
+ "en": "Synthetic data; no actual charge.",
+ },
+ "verified_at": "2026-01-01",
+ "sources": ["https://example.org/synthetic-pricing"],
+ }
+ for m in methods
+ }
for method in methods:
target = home / "runs" / method
source = b"# explicitly synthetic execution snapshot\n"
diff --git a/src/harness/web_scraper/pipeline.py b/src/harness/web_scraper/pipeline.py
index d96266881..0a646ff4a 100644
--- a/src/harness/web_scraper/pipeline.py
+++ b/src/harness/web_scraper/pipeline.py
@@ -257,6 +257,7 @@ def available_methods():
"oxylabs-json": {"keys": ["OXYLABS_API_KEY"], "input": "url"},
"brightdata-scrapers": {"keys": ["BRIGHTDATA_API_TOKEN"], "input": "site_specific"},
"extruct": {"keys": [], "input": "html"},
+ "browserbase-json": {"keys": ["BROWSERBASE_API_KEY"], "input": "url"},
"browserbase-stagehand": {
"keys": ["BROWSERBASE_API_KEY", "BROWSERBASE_PROJECT_ID"],
"input": "url",
@@ -346,6 +347,12 @@ def provider_call(method, html, source_url, fixture_url=None, *, timeout=120, ho
url = f"https://api.cloudflare.com/client/v4/accounts/{os.environ['CLOUDFLARE_ACCOUNT_ID']}/browser-rendering/json"
headers = {"Authorization": "Bearer " + os.environ["CLOUDFLARE_API_TOKEN"]}
body = {"html": html, "response_format": {"type": "json_schema", "json_schema": SCHEMA}}
+ elif method == "browserbase-json":
+ if not fixture_url:
+ return {"state": "input_blocked", "error": "A frozen HTTPS snapshot URL is required"}
+ url = "https://api.browserbase.com/v1/fetch"
+ headers = {"X-BB-API-Key": os.environ["BROWSERBASE_API_KEY"]}
+ body = {"url": fixture_url, "format": "json", "schema": SCHEMA, "proxies": False}
elif method in ("firecrawl-json", "oxylabs-json"):
if not fixture_url:
return {
@@ -497,6 +504,11 @@ def normalize(method: str, payload: dict):
)
if method == "firecrawl-json":
item = payload.get("data", {}).get("json")
+ elif method == "browserbase-json":
+ status = payload.get("statusCode")
+ if not isinstance(status, int) or not 200 <= status < 300:
+ return None
+ item = payload.get("content")
elif method in ("cloudflare-json", "browserbase-stagehand"):
item = payload.get("result")
elif method == "oxylabs-json":
@@ -608,11 +620,13 @@ def access_blocker(row):
return "authentication"
if status == 402:
return "quota_or_payment"
- if status == 403 and re.search(
- r"forbidden|access denied|not authorized|permission", message, re.I
- ):
+ if status == 403:
return "permission"
- if status in (403, 429) or row.get("state") == "provider_error":
+ native = row.get("response", {})
+ native_error = isinstance(native, dict) and (
+ native.get("success") is False or bool(native.get("error"))
+ )
+ if status == 429 or row.get("state") == "provider_error" or native_error:
if re.search(
r"quota|credits?|balance|free plan|usage period|upgrade|subscription|payment|"
r"insufficient|expired",
@@ -821,8 +835,9 @@ def one(case_id):
)
inflight.unlink()
records = []
- last_call_started = None
- last_call_finished = None
+ # Conservatively observe the full frozen pause after a cross-process resume.
+ last_call_started = time.monotonic() if prior else None
+ last_call_finished = last_call_started
for ordinal, case_id in enumerate(case_ids):
offset = ordinal % len(methods)
for method in methods[offset:] + methods[:offset]:
@@ -850,34 +865,34 @@ def one(case_id):
error="Site-specific scraper cannot be substituted for a generic HTML parser",
)
else:
- try:
- if last_call_started is not None:
+ if last_call_started is not None:
+ remaining = max(
+ min_call_interval - (time.monotonic() - last_call_started),
+ post_call_cooldown - (time.monotonic() - last_call_finished),
+ )
+ while remaining > 0:
+ time.sleep(min(remaining, 30))
remaining = max(
min_call_interval - (time.monotonic() - last_call_started),
post_call_cooldown - (time.monotonic() - last_call_finished),
)
- while remaining > 0:
- time.sleep(min(remaining, 30))
- remaining = max(
- min_call_interval - (time.monotonic() - last_call_started),
- post_call_cooldown - (time.monotonic() - last_call_finished),
- )
- save_json(
- inflight,
- {
- "method": method,
- "case_id": case_id,
- "physical_attempt": attempts.get((method, case_id), 0) + 1,
- "input_sha256": digest(raw),
- "state": "dispatch_pending",
- },
- exclusive=True,
- )
- descriptor = os.open(run, os.O_RDONLY)
- try:
- os.fsync(descriptor)
- finally:
- os.close(descriptor)
+ save_json(
+ inflight,
+ {
+ "method": method,
+ "case_id": case_id,
+ "physical_attempt": attempts.get((method, case_id), 0) + 1,
+ "input_sha256": digest(raw),
+ "state": "dispatch_pending",
+ },
+ exclusive=True,
+ )
+ descriptor = os.open(run, os.O_RDONLY)
+ try:
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
+ try:
last_call_started = time.monotonic()
row.update(
provider_call(
diff --git a/src/harness/web_scraper/report.py b/src/harness/web_scraper/report.py
index 08ecfa0f1..3c10b1e5c 100644
--- a/src/harness/web_scraper/report.py
+++ b/src/harness/web_scraper/report.py
@@ -14,13 +14,14 @@
from bs4 import BeautifulSoup
from harness.reporting.presentation import check_presentation
+from harness.reporting.templates import resolve_template
+from harness.web_fetch.publication_privacy import project_evidence_view, publication_risk
from harness.web_scraper.pipeline import (
PROFILE,
digest,
load_run,
normalize,
read_json,
- redact,
save_json,
score_run,
validate_dataset,
@@ -258,7 +259,9 @@ def cohort_source(source, selection, home, truth):
"certified": True,
"scores": saved["scores"],
"certificate_sha256": digest(certificate.read_bytes()),
- "assessment": assessment,
+ "assessment": {"artifact_id": assessment_path.name, "sha256": assessment["sha256"]}
+ if assessment
+ else None,
},
)
journal = source / "calls.journal.jsonl"
@@ -480,6 +483,46 @@ def cohort_metrics(methods, rows, bindings, count, lang, labels=None):
return str(result) + "
" + note + "
", str(timing)
+def price_table(methods, prices, lang, labels=None):
+ labels = labels or {}
+ records = []
+ for method in methods:
+ value = prices.get(method, {})
+ sources = value.get("sources", [])
+ if (
+ not value.get("usd_per_1000")
+ or not value.get("terms", {}).get(lang)
+ or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", value.get("verified_at", ""))
+ or not sources
+ or any(urlsplit(u).scheme != "https" for u in sources)
+ ):
+ raise ValueError("Every participant requires sourced cost/pricing terms: " + method)
+ records.append(
+ [
+ esc(labels.get(method, method)),
+ esc(value["usd_per_1000"]),
+ esc(value["terms"][lang]),
+ esc(value["verified_at"]),
+ " · ".join(
+ f'{i}' for i, u in enumerate(sources, 1)
+ ),
+ ]
+ )
+ return table(
+ ["方法", "美元/1,000 次", "计费条件与套餐门槛", "核对日期", "官方来源"]
+ if lang == "zh"
+ else [
+ "Method",
+ "USD / 1,000 requests",
+ "Billing terms and commitment",
+ "Verified",
+ "Official sources",
+ ],
+ records,
+ attrs='data-price-table="true"',
+ )
+
+
def usage_table(methods, rows, lang, labels=None):
labels = labels or {}
records = []
@@ -552,6 +595,15 @@ def build(output: Path, content: Path, *, home: Path, run=None, language="zh", p
source = source if source.is_absolute() else home / "runs" / source
extra = {}
if cohort:
+ selected_plan = selection["plan_sha256"]
+ for method in read_json(source / "contract.json")["methods"]:
+ authorized_plan = model.get("source_cohorts", {}).get(
+ method, model["cohort_plan"]["sha256"]
+ )
+ if selected_plan != authorized_plan:
+ raise ValueError(
+ "Selected source cohort is not bound by the report composition"
+ )
contract, records, extra = cohort_source(source, selection, home, truth)
else:
contract, records = load_run(source)
@@ -576,7 +628,7 @@ def build(output: Path, content: Path, *, home: Path, run=None, language="zh", p
r["request"]["endpoint"] = re.sub(
r"/accounts/[^/]+/", "/accounts/[REDACTED]/", r["request"]["endpoint"]
)
- rows.append(redact(r))
+ rows.append(r)
bindings.append(
{
"run_id": source.name,
@@ -584,6 +636,7 @@ def build(output: Path, content: Path, *, home: Path, run=None, language="zh", p
if (source / "manifest.json").exists()
else None,
**extra,
+ "source_plan_sha256": selection.get("plan_sha256"),
"methods": selection.get("methods"),
"contract": contract,
}
@@ -618,16 +671,40 @@ def build(output: Path, content: Path, *, home: Path, run=None, language="zh", p
raise ValueError("Unsafe or changed report asset")
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(source.read_bytes())
- if cohort:
- for method in cohort_plan["participants"]:
- save_json(
- output / "evidence" / (method + ".json"),
- {r["case_id"]: r for r in rows if r["method"] == method},
- exclusive=True,
- )
- else:
- for r in rows:
- save_json(output / "evidence" / f"{r['method']}-{r['case_id']}.json", r, exclusive=True)
+ buckets = (
+ {
+ m: {r["case_id"]: r for r in rows if r["method"] == m}
+ for m in cohort_plan["participants"]
+ }
+ if cohort
+ else {f"{r['method']}-{r['case_id']}": r for r in rows}
+ )
+ public_receipts, public_rows = [], []
+ for key, bucket in buckets.items():
+ name = f"public-evidence/{key}.json"
+ raw = json.dumps(bucket, ensure_ascii=False, indent=2, allow_nan=False).encode()
+ public, receipt = project_evidence_view(
+ name,
+ raw,
+ role="native_response",
+ content_format="json",
+ host_names=("go-connect.connect.svc.cluster.local", "10.255.255.1"),
+ )
+ projected = json.loads(public)
+ before = list(bucket.values()) if cohort else [bucket]
+ after = list(projected.values()) if cohort else [projected]
+ for original, view in zip(before, after, strict=True):
+ method = original["method"]
+ if normalize(method, original.get("response", {})) != normalize(
+ method, view.get("response", {})
+ ):
+ raise ValueError("Public evidence projection changed extracted fields")
+ target = output / name
+ target.parent.mkdir(exist_ok=True)
+ target.write_bytes(public)
+ public_receipts.append(receipt)
+ public_rows.extend(after)
+ rows = public_rows
for lang in languages:
lab = LABELS[lang]
directory = output / lang
@@ -675,6 +752,12 @@ def build(output: Path, content: Path, *, home: Path, run=None, language="zh", p
bodies["protocol"] += (
"
" + ("调用耗时" if lang == "zh" else "Call latency") + "
" + timings
)
+ bodies["accounts"] += (
+ "
"
+ + ("各方法价格" if lang == "zh" else "Prices by method")
+ + "
All {audit['case_count']} pages and {count} current results are covered. The original {audit['original_results_reviewed']} results were reviewed field by field, with {audit['supplemental_results_reviewed']} changed responses audited separately. No unreviewed passes were accepted.
"
+ )
+ + "
"
+ + (
+ "审查模型为 "
+ + esc(audit["reviewer"]["model"])
+ + ",依据冻结原文、标注和完整原生响应核查,并按原评测规则裁决争议;这不等于双人人工金标。逐题页面保留原文片段与裁决理由。"
+ if zh
+ else "The model audited frozen sources, annotations and complete native responses, followed by original-rule adjudication. This is not dual human annotation. Quotations are checked against frozen bytes; literal excerpts are retained separately from original opinions."
+ )
+ + "
"
+ )
+ fields = ("price", "sku", "availability", "OutOfStock")
+ comparison = BeautifulSoup(
+ table(
+ [
+ "方法" if zh else "Method",
+ *[FIELD_LABELS[f][0 if zh else 1] + " F1" for f in fields],
+ ],
+ [
+ [
+ esc(labels.get(method, method)),
+ *[f"{audit['audited_scores'][method][field]['f1']:.3f}" for field in fields],
+ ]
+ for method in methods
+ ],
+ attrs='data-audited-quality="true" data-sortable',
+ ),
+ "html.parser",
+ )
+ for method, row in zip(methods, comparison.select("tbody tr"), strict=True):
+ for field, cell in zip(fields, row.select("td")[1:], strict=True):
+ value = round(audit["audited_scores"][method][field]["f1"], 12)
+ values = [round(audit["audited_scores"][m][field]["f1"], 12) for m in methods]
+ cell.attrs.update(
+ {
+ "data-sort": str(value),
+ "data-metric": "audited-" + field,
+ "data-metric-direction": "max",
+ }
+ )
+ if value == max(values) and values.count(value) == 1:
+ span = comparison.new_tag("span", attrs={"class": "comparison-winner"})
+ span.string = cell.get_text()
+ cell.clear()
+ cell.append(span)
+ review += (
+ "
"
+ + ("核查参考值后的诊断 F1" if zh else "Diagnostic F1 after reference audit")
+ + "
"
+ )
+ review += (
+ (
+ f"各方法仍为 {audit['case_count']} 页,使用相同原生输出和同一个官方评分器,仅替换有源证据的参考值。该表属于事后源证据诊断,不替代首页保留原标注的成绩。"
+ if zh
+ else f"Each method still covers {audit['case_count']} pages. The same native outputs and official scorer use only source-qualified reference amendments. This post-hoc diagnostic does not replace the original-reference scores on the home page."
+ )
+ + "
"
+ )
+ review += (
+ "保留原始标注与原始评分;下表列出有源证据的修正,逐题详情同时显示两种口径。空标注和库存默认值均按原规则核对,不能把未知库存直接当成标注错误。"
+ if zh
+ else "Original annotations and scores are retained. These source-qualified amendments are shown alongside the original result in each detail. Empty labels and stock defaults follow the original benchmark rules."
+ ) + "
" + ("评分看的是字段是否匹配" if zh else "Scoring checks field matches") + "
"
+ )
+ interpretation += (
+ "每个字段允许多个参考值,但每次只接受一个预测值。价格按 Decimal 比较;错误值会同时造成误报与漏报,空值遇到非空参考值则计漏报。库存没有明确缺货证据时,原规则默认有货。原标注的金额分隔符、商品 ID 和库存问题会影响分数,因此源核查与原始成绩同时保留。"
+ if zh
+ else "Each field allows multiple accepted reference values but one prediction. Prices use Decimal equality; wrong values add false positives and false negatives, while missing required values add false negatives. The original contract defaults to InStock without clear out-of-stock evidence. Source-qualified reference corrections are retained alongside official scores."
+ ) + "
"
+ if audit["reference_changes"]:
+ example = audit["reference_changes"][0]
+ interpretation += (
+ '
"
+ )
+ for method in methods:
+ selected = [r for r in rows if r["method"] == method]
+ counts = []
+ for field in ("price", "sku", "availability"):
+ missing = sum(r["field_results"][field]["status"] == "missing" for r in selected)
+ wrong = sum(
+ r["field_results"][field]["status"] in ("wrong", "unexpected") for r in selected
+ )
+ counts.append(
+ [
+ FIELD_LABELS[field][0 if zh else 1],
+ str(missing),
+ str(wrong),
+ f''
+ + ("查看全部差异" if zh else "Inspect all differences")
+ + "",
+ ]
+ )
+ failures = [r for r in selected if r.get("compatibility") != "structured_output"]
+ interpretation += (
+ '
'
+ + esc(labels.get(method, method))
+ + "
"
+ )
+ interpretation += (
+ f"{len(selected)} 页中 {len(selected) - len(failures)} 页返回字段;下面按原标注列出全部字段差异,调用失败也计入漏提。"
+ if zh
+ else f"{len(selected) - len(failures)}/{len(selected)} pages returned structured fields. All original-reference differences are counted below; failed calls also contribute missing fields."
+ ) + "
"
+ + (
+ "上游基线在缺少库存时写入 InStock 辅助键,却没有写回主 availability 字段;原始库存分数因此与 README 的默认规则不一致。本次从同一原生输出中投影唯一明确的库存辅助键,没有新增本地提取调用;原分数仍保留在历史复现中。它只读取嵌入式结构化数据,和托管 API 的运行位置及能力范围不同。"
+ if zh
+ else "The upstream baseline emits an InStock indicator without filling availability when stock is absent. Its original availability score therefore differs from the README default. The current projection uses only an unambiguous native indicator, without new extraction calls; historical scores remain intact. This embedded-data baseline differs from hosted APIs in execution location and scope."
+ )
+ + "
"
+ )
+ repaired = [r for r in selected if r.get("diagnosis")]
+ representative = (
+ failures[:1]
+ or repaired[:1]
+ or [
+ r
+ for r in selected
+ if any(f["status"] != "correct" for f in r["field_results"].values())
+ ][:1]
+ )
+ if representative:
+ row = representative[0]
+ diagnosis = row.get("diagnosis", {})
+ interpretation += (
+ "
"
+ + esc(
+ diagnosis.get("cause")
+ or (
+ "接口已经返回字段,差异发生在提取内容与参考值的匹配;原文与参考值核查见同题详情。"
+ if zh
+ else "Fields were returned; these differences concern extracted content versus references. Inspect source and reference audit in the same-case detail."
+ )
+ )
+ + "
Original annotations follow. An empty array contains no accepted value; it does not mean the whole case is unannotated. The original benchmark assumes InStock unless clearly out of stock.
"
+ + (
+ "核查参考值后的字段诊断"
+ if lang == "zh"
+ else "Field diagnosis after reference audit"
+ )
+ + "
"
+ )
+ detail += (
+ "
"
+ + (
+ "原始评分保留不变;这里使用已裁决的参考值作诊断。来源证据和标注改动见页面与标注。"
+ if lang == "zh"
+ else "Original scores remain unchanged. This diagnostic uses adjudicated references; see source and annotations for evidence and changes."
+ )
+ + "
"
)
if cohort:
observed = {(r["method"], r["case_id"]) for r in rows}
@@ -914,29 +1733,35 @@ def build(output: Path, content: Path, *, home: Path, run=None, language="zh", p
if (method, cid) not in observed:
pending = "待执行" if lang == "zh" else "Not executed"
inventory.append(
- f'
{esc(names.get(method, method))}
{cid[:12]}
{pending}
—
—
—
'
+ f'
{esc(names.get(method, method))}
{cid[:12]}
{pending}
'
+ + "
—
" * 6
+ + "
"
)
- initial = (
- "fail" if any(r.get("compatibility") != "structured_output" for r in rows) else "all"
- )
- filt = f''
- if cohort:
- filt = filt.replace(
- "",
- '",
- )
bodies["results"] += (
- '
",
+ "https://original.example",
+ "https://frozen.example/hash",
+ native_options=options,
+ )
+ body = request.call_args.kwargs["json_body"]
+ assert "html" not in body and "input_route" not in body
+ assert body["url"] == "https://frozen.example/hash"
+ assert body["response_format"]["json_schema"] == SCHEMA
+ assert result["request"]["html_sha256"] == digest(b"