Repository navigation
refactor(wcxb): bind the metric module by normalized AST - #133
Conversation
Move word_f1 and snippet_check into wcxb_metrics.py and bind a digest of that module's AST without docstrings instead of inspect.getsource() text. Formatting and comments no longer break the binding, and any code change in the module does, including added helpers. The module may import only the standard library. The authority maps the retired source-text digest to the module digest it represents, so frozen profiles, certificates, summaries and timing receipts keep verifying without being rewritten.
lanyue-llk
left a comment
There was a problem hiding this comment.
Independent review, round 1
Reviewed head 8c630d70. Two findings, one P1 and one P2.
Findings
P1: the binding no longer proves that scoring runs the bound code
src/harness/web_fetch/wcxb_scoring.py:61 (import at :26, calls at :499-501)
Problem: metric_implementation_binding now hashes wcxb_metrics.py from disk, but _score calls the names word_f1 and snippet_check in wcxb_scoring's own namespace. Nothing connects the two. On the base commit, inspect.getsource followed those same names, so a replaced function was rejected.
I replaced both names on the imported module with functions that return zero, then ran score() on the fixture cohort. It was accepted, reported digest 34fd9387 and produced alpha f1 = 0.0, where the unmodified cohort gives f1 == 1.
The source-level equivalent is a local def word_f1 or a wrapper added to wcxb_scoring.py, or an import changed to point elsewhere. Any of these changes scores without changing the digest. That is the failure #116 sets out to remove, and it contradicts the PR's "nothing that can affect a score sits outside the binding".
The PR also deleted the two negative controls that covered this: test_changed_word_metric_rejects_legacy_profile and test_changed_snippet_metric_rejects_legacy_profile.
Fix: have the binding also require that the functions in use come from the bound module, for example:
if word_f1 is not wcxb_metrics.word_f1 or snippet_check is not wcxb_metrics.snippet_check:
raise ValueError('WCXB metric implementation binding mismatch')Restore both deleted controls. The fault-injection tests at tests/test_wcxb_scoring.py:248 and :311 already stub the binding, so they keep working.
P2: the new evidence guards have no failing test
src/harness/web_fetch/wcxb_scoring.py:359, src/harness/web_fetch/wcxb_latency.py:146, :270, :286
Problem: the PR describes these as behaviour changes, but none of them is exercised. I applied each mutation below on its own and ran test_wcxb_metric_binding, test_wcxb_latency_collection, test_wcxb_scoring and test_wcxb_profile_admission. All 125 tests passed each time:
| Mutation | Lost behaviour |
|---|---|
Drop read=inputs.read in _score |
Changes to the module or authority during scoring go undetected |
Remove wcxb_metrics.py from the collect watch list |
Module changes during a timing run go undetected |
Remove wcxb_metrics.py from the certify watch list |
Module changes during timing certification go undetected |
Delete metric_implementation_binding(authority, receipt=receipt) in certify |
certify accepts a receipt with an unknown digest |
The receipt= branch is tested only by calling the binding function directly, so the PR's "verifies in a ... receipt" holds at function level but not through certify.
Fix: add behaviour tests through the public entry points:
- Change the metric module or the authority during
score()and expect "changed during scoring". Inject the change from a hook other thanword_f1so it still works after the P1 fix. - Change the module during
collectand duringcertify, and expect rejection. - Run
certifyon one receipt naming the superseded digest, which must pass, and one naming an unknown digest, which must fail.
Using METRIC_MODULE in wcxb_latency.py instead of a second Path(__file__).with_name(...) would make the first two watch-list tests easier to write.
Verified, no defect
- Golden values: I downloaded
evaluate.pyat the pinned revision and its SHA-256 matchesUPSTREAM_EVALUATOR_SHA256. Upstreamtokenize,word_f1andsnippet_checkmatch all 24 golden cases exactly and matchwcxb_metrics.pyon 200,000 random inputs for each metric. They also agree onNoneinputs toword_f1. - Moved code: re-deriving the old
inspect.getsourcetext from the base commit gives35dc50a1.... The test's retired text with the imports added normalizes to34fd9387.... - Digest stability:
34fd9387...is the same on Python 3.11.16 and 3.13.16. I read_normal_formand found no field collisions, and droppedtype_params,kindandtype_commentdo not affect the digest. Python 3.12 and 3.14 were not available to run. - Metric hash consumers: every use goes through
metric_implementation_binding(certification.py,report_build.py,wcxb_latency.py,wcxb_scoring.py), so none compares the old digest directly. Mixed documents, with an old-digest profile or certificate and a new-digest summary, pass the same check. scorer_sha256: it changes becausewcxb_scoring.pychanged, but it is only recorded in new summaries and nothing verifies it, so frozen summaries are unaffected.- Other evidence: no hash-bound evidence, profile or receipt is modified in this diff. A search of
.jsonfiles under the local~/.browser-eval/evidencefound no file naming the digest, which matches the PR's disclosure. Real certified evidence remains unchecked. - Scope: the code changes cover the module move, the AST binding and the golden cases. The decorator deviation from the issue text is disclosed and defensible.
Closes #116is appropriate once the P1 is fixed.
Tests and CI
- Local: both lint gate commands pass.
tests/test_golden_reports.py,test_wcxb_metric_binding,test_wcxb_scoring,test_wcxb_profile_admission,test_wcxb_latency_collectionandtest_wcxb_huggingface_inputsgave 142 passed. No route hashes changed.test_ruff_format_keeps_the_bindingran rather than being skipped. - CI at this head: "Tests and static checks", "Installation and packaging", "Rendered reference and report checks", "Python 3.11" and
ocr-reviewall pass. No failure is caused by this PR. CI does not cover either finding.
The digest covers the module bytes, but scoring calls names in its own namespace, so a local definition, wrapper or redirected import changed scores without changing the digest. Reject any name that is not the bound module's function, and restore the two negative controls that covered this.
Changing the metric module or authority during score, collect or certify must be rejected, and certify must accept a receipt naming the superseded digest but not an unknown one. Certify now also watches the authority, and the latency watch lists use the scoring module's paths so they follow the same binding.
|
Review round 1 fixes, new head P1, scoring names not tied to the bound module: fixed in
P2, evidence guards had no failing test: fixed in
One addition beyond the finding: Mutation check Each mutation below was applied alone, then the four target files were run (
Local test results
|
There was a problem hiding this comment.
✅ Re-review complete · 1799b84
No findings in this incremental review.
There was a problem hiding this comment.
Independent review, round 2
Reviewed head 1799b846. Two P3 findings and no defect in scoring or evidence verification. Both round 1 fixes hold.
Findings
P3: the module docstring and PR body overstate what the binding covers
src/harness/web_fetch/wcxb_metrics.py:9, and the Summary bullet "nothing that can affect a score sits outside the binding"
Problem: the docstring says "Everything that can change a WCXB score belongs here" and that the binding "covers the whole metric". The call arguments, classify, the exclusions and the aggregation are all in wcxb_scoring._score, outside the digest. I changed snippet_check(predicted, gt["with"]) to pass gt["without"] at wcxb_scoring.py:505. score() accepted it with digest 34fd9387, and with_rate for alpha, beta and gamma went from 1.0, 0.5, 1.0 to 0.0, 0.0, 0.0. scorer_sha256 records that file, but nothing verifies it. This scope matches the base commit and #116, so it is not a regression. Only the claim is wrong, and a later reader may rely on it.
Fix: say what is actually bound, for example "The per-page metric functions and everything they call belong here... The call site and aggregation in wcxb_scoring.py are not part of this binding." Correct the PR body line the same way.
P3: the import x branch of the import guard has no failing test
src/harness/web_fetch/wcxb_scoring.py:53, tests/test_wcxb_metric_binding.py:90
Problem: the guard behaves correctly. import harness.web_fetch.safety, import numpy as np and a nested import harness inside a function are all rejected. The test covers only from harness.web_fetch import safety and from . import safety. With the ast.Import branch reduced to imported = [], all 135 tests in test_wcxb_metric_binding, test_wcxb_latency_collection, test_wcxb_scoring and test_wcxb_profile_admission still pass. The digest would still catch the edit, so only the guard's protection during a deliberate authority revision is unproven.
Fix: add import harness.web_fetch.safety\n and a nested import to the rejected inputs in that test.
What I verified
Metric code
word_f1andsnippet_checkinwcxb_metrics.pyare byte-identical to the base commit's function source. Joining the base source the wayinspect.getsourcedid reproduces35dc50a1....- I downloaded
evaluate.pyat the pinned revision and its SHA-256 matchesUPSTREAM_EVALUATOR_SHA256. Itstokenize,word_f1andsnippet_check, extracted by AST, return the exact expected value for all 24 golden cases. - They also matched this module on 200,000 random inputs covering Unicode, underscores, case folding and empty strings.
Digest
metric_module_digestgives34fd9387...on Python 3.11.16 and 3.13.16.requires-pythonis>=3.11.- It keeps the digest for the
ustring prefix. It separatesreturnfromreturn None,a[1:]froma[:1],1from1.0fromTrue, moved defaults, and a docstring-only body frompass. - A second string statement is not treated as a docstring.
Frozen evidence
- Every consumer of the digest goes through
binds_current:score(),certify,collect,certification.pyandreport_build.py. None of them compares a frozen value directly. - No hash in Git covers
wcxb_scoring.pyor the card, and nothing verifiesscorer_sha256. Editing the scoring file therefore invalidates nothing. ~/.browser-evalholds no WCXB evidence and Git holds no WCXB publication target, so I could not check real evidence either. The PR's disclosure is accurate, and its suggested report build against the real evidence is still worth doing once.
Round 1 fixes
- The identity check and both restored controls are in place.
- The behaviour tests for
score(),collectandcertifyexist. I did not repeat the author's mutation table. - The disclosed limit is real: replacing
wcxb_metrics.word_f1itself together with the scoring name is not caught. I am not raising it, because that takes deliberate in-process replacement.
Scope and rules
- "Closes #116" holds. Treating a decorator as a breaking change departs from the issue, but the PR explains it and the reason is sound, since a decorator can change scores.
- I found no compatibility alias or parallel implementation, and no evidence or frozen profile is touched. The retired source text in the test is justified by the authority naming its digest.
Tests and CI
- Both lint gates pass.
test_wcxb_metric_binding,test_wcxb_latency_collection,test_wcxb_scoring,test_wcxb_profile_admission,test_wcxb_huggingface_inputsandtest_golden_reportsgive 152 passed with no skips, so theruff formattest ran. Route hashes are unchanged. I did not run the full suite locally.- CI on
1799b846: all checks pass, including "Tests and static checks" and "Installation and packaging". The PR is mergeable and its base is the current main (27401304).
There was a problem hiding this comment.
This review found 1 issue(s), including 1 blocking issue(s).
| if word_f1 is not wcxb_metrics.word_f1 or snippet_check is not wcxb_metrics.snippet_check: | ||
| raise ValueError('WCXB metric implementation binding mismatch') |
There was a problem hiding this comment.
P2 — This checks that two mutable references agree, not that either executes the module source being hashed. For example, adding wcxb_metrics.word_f1 = word_f1 = lambda predicted, reference: (0., 0., 0.) in the unbound scoring module after its imports passes this check and the unchanged module digest, while score() publishes zero word scores under the approved implementation hash. Mutating the shared function's __code__ also preserves this identity check. The current replacement tests only patch the scoring alias, so they miss this bypass of the stated call-site binding requirement. Tie the functions actually used for scoring to the validated module bytes (rather than trusting mutable module attributes), and add a negative control that replaces both references before scoring.
|
Review round 2, head Fixed
Disputed: The finding is factually correct. I replaced both references with a zero function, and I am not changing the code, because the same result needs no reference replacement at all. Adding Binding the call site and aggregation would be a real scope extension and an owner decision. It would change what certified evidence is bound to, so it should have its own issue rather than go in this PR. The PR body claimed more than the identity check does, so it now says the check catches drift and is not tamper protection. The Checks
|
lanyue-llk
left a comment
There was a problem hiding this comment.
Independent review, round 3
Reviewed head b57580cb. One P3 finding, in documentation. I found no defect in scoring, the digest or evidence verification.
Finding
P3: the README and binding docstring still say a local definition or wrapper in wcxb_scoring.py is rejected
src/harness/web_fetch/README.md:145-146, src/harness/web_fetch/wcxb_scoring.py:65-66, and the same Summary bullet in the PR body
Problem: the check only compares the names word_f1 and snippet_check with the module's attributes. It does not look at what _score calls. I added def _local(predicted, reference): return 0., 0., 0. to wcxb_scoring.py and changed line 504 to call it. score() accepted this with digest 34fd9387 and published alpha f1 = 0.0. So a local definition or wrapper under another name is not rejected, and the sentence "The binding also requires wcxb_scoring.py to call this module's functions" is not true as written.
Round 2 corrected the PR body with a "not tamper protection" caveat and corrected the wcxb_metrics.py docstring. The README has no caveat, and it is the text that will outlast this PR. The binding docstring also says "The digest covers the module bytes", but the digest covers the AST without docstrings, and comments and layout are excluded.
Fix: describe the check as it is, in both places. For example: "The binding also requires the word_f1 and snippet_check names in wcxb_scoring.py to be this module's functions, so rebinding either name there is rejected. This catches drift. It does not prove what _score calls, and wcxb_scoring.py itself is not bound." Change "module bytes" to "module's code". Reword the PR body's "so a local definition, wrapper or redirected import there is rejected" the same way. No code change is needed, and the digest does not change if only the wcxb_scoring.py docstring and the README are edited.
Disputes from round 2
I accept the author's dispute of the ocr-review P2. I reproduced the same result without replacing any reference, as shown above. wcxb_scoring.py is outside the binding in both the base commit and #116, so hardening the function objects would close one route and leave the others open. Binding the call site is a separate owner decision. I am not raising it as a finding.
CI on b57580cb
- Pass: "Tests and static checks", "Installation and packaging", "Rendered reference and report checks", "Python 3.11", "OCR dispatch", "Select check scope".
- Fail: the
ocr-reviewcommit status, because of the disputed finding above. It is not caused by a test or build failure. I found no required status checks onmain(the branch rules query returned none, and classic protection returned 404), but someone with admin access should confirm that. An owner still has to decide what to do about this status.
What I verified
- Moved code: the source of
word_f1andsnippet_checkis byte-identical between base27401304andwcxb_metrics.py, and the oldinspect.getsource()method still gives35dc50a1...on the moved functions. - Upstream parity: I downloaded
evaluate.pyat the pinned revision and its SHA-256 equalsUPSTREAM_EVALUATOR_SHA256. I extracted itstokenize,word_f1andsnippet_checkby AST. All 24 golden cases match exactly, and 200,000 randomized word and snippet comparisons (mixed Unicode, including casefold edge characters) showed no difference. - Digest:
metric_module_digestgives34fd9387...on both Python 3.11 and 3.13. I read_normal_formfor collisions and found none:Noneconstants,returnversusreturn None,1versus1.0andTrueall stay distinct. Removing docstrings duringast.walkis safe because children are queued before each node is yielded. - Evidence consumers: every reader of
metric_implementation_sha256goes throughmetric_implementation_binding(certification.py,wcxb_latency.py,report_build.py,wcxb_scoring.py). None compares the digest directly, and no file inevaluation/names it. As the PR body says, real certified evidence was not available, so this is covered only by synthetic documents and fixture cohorts. - Issue scope:
Closes #116is supported. The module move, AST binding and golden cases are all present, and the one deliberate difference (a decorator breaks the binding) is stated in the PR body. - Local checks: the lint gate passes, and
tests/test_golden_reports.py,tests/test_wcxb_*.pyandtests/benchmarksgive 11580 passed with route hashes unchanged.test_ruff_format_keeps_the_bindingruns rather than skips. I did not run the full suite locally.
|
Review round 3 follow-up, head Fixed
The change is documentation only. Disputed None in this round. Checks
|
lanyue-llk
left a comment
There was a problem hiding this comment.
Independent review, round 4
Head reviewed: 47ef8c60. No defects found.
What I verified
- Round 3 fix: the README and the
metric_implementation_bindingdocstring now describe the name check as it is. The commit changes only documentation, and the digest is still34fd9387.... - Upstream match: I downloaded
evaluate.pyat the pinned revision, and its SHA-256 matchesUPSTREAM_EVALUATOR_SHA256. I extractedtokenize,word_f1andsnippet_checkby AST and ran them on all 24 golden cases, and they gave exactly the expected floats. They also matchedwcxb_metrics.pyon 200,000 random Unicode-heavy inputs (case folding, combining marks, underscores) and onNoneinputs, under Python 3.11 and 3.13. - Digest stability:
metric_module_digestreturns34fd9387...under Python 3.11.16 and 3.13.16, so the 3.12+type_paramsAST field does not change it. I read_normal_formfor collisions from the droppedNoneand empty-list fields and found none that could change behaviour. - Frozen evidence: the only comparisons against stored digests go through
binds_current, inscore(),certifyand the WCXB report build. Other callers only record the current digest or compare it with itself. No profile or evidence file in Git names35dc50a1...; it appears only in the authority and in tests.scorer_sha256is recorded but not compared with the current source, so changingwcxb_scoring.pydoes not invalidate it. - Scope: the
Closes #116claim holds. The metric moved to its own module, the binding uses a normalized AST and the golden cases are in place. The one departure, adding a decorator still breaks the binding, is disclosed in the PR body and is reasonable because a decorator can change scores. - AGENTS.md: I found no aliases or parallel implementation.
wcxb_scoringimports the two names because_scorecalls them. Stale references were updated inTHIRD_PARTY.md,docs/architecture.mdand the dataset card. No measured evidence was changed. - Local checks:
tests/test_golden_reports.pyand alltests/test_wcxb_*targets gave 260 passed, and the lint gate passes. Golden snapshots are not modified by this PR. - CI on this head: "Tests and static checks", "Installation and packaging", "Rendered reference and report checks" and "Python 3.11" all pass.
ocr-reviewpasses with 0 findings.
Not verified
This machine has no certified WCXB evidence (no wcxb-score-summary.json under ~/.browser-eval), so frozen verification was only exercised with synthetic documents and fixture cohorts. The PR body already says this. A WCXB report build against the real evidence is still worth running once.
I did not repeat the guard-removal mutations from rounds 1 and 2, because no code has changed since them.
Main moved the other regex uses out of wcxb_scoring in #133, and the shared WCXB_ERROR policy replaced the last one.
…#136) * refactor(helpers): share data-home, dotenv parsing and path redaction Replace the private copies with harness.data_home, harness.env_file and the policy table in harness.reporting.privacy. Resolve the data home at call time, parse every .env with python-dotenv without interpolation, and keep each surface's redaction output unchanged. * fix(web-fetch): read the WCXB visual check binary through the shared parser * fix(env-file): drop values that span lines instead of delivering them * fix(web-fetch): judge imported credentials by the shared parser * test(env-file): reject line-split, startswith and regex .env parsers * test(data-home): pin the retained entry point defaults to the selected home * fix(env-file): stop a rejected statement from reviving an earlier value * test(data-home): catch getenv and tilde-path copies in the grep guard * test(privacy): recognise home, tmp and root copies in the grep guard * fix(wcxb): drop the re import left unused after the rebase Main moved the other regex uses out of wcxb_scoring in #133, and the shared WCXB_ERROR policy replaced the last one.
Issues
Closes #116
Summary
The WCXB metric binding hashed the
inspect.getsource()text ofword_f1andsnippet_check. Reformatting broke it, and it did not cover the helpers those functions call. This PR changes what is bound:word_f1andsnippet_checkmove unchanged tosrc/harness/web_fetch/wcxb_metrics.py. The module may import only the standard library, and an import from anywhere else is rejected, so the binding covers the per-page metric functions and everything they call. The call site and aggregation inwcxb_scoring.py(which arguments are passed, classification, exclusions, averaging) are not bound, the same scope as before this PR and as WCXB metric binding hashes source text instead of behaviour #116 asks.wcxb-metric-bindings.json(schema 2) now binds a digest of the module's AST with docstrings removed. Comments, docstrings, quotes and layout keep the binding. Any code change breaks it, including an added helper, a changed constant or a decorator.ast.dump, whose output differs between Python versions.wcxb_latency.pynow watches the new module and the authority for changes during timing runs, andwcxb_scoring.pyreads them through the same guarded evidence reader.word_f1andsnippet_checknames inwcxb_scoring.pymust also be the bound module's functions, so rebinding either name is rejected. This catches the scoring module drifting away from the bound functions. It does not prove what_scorecalls, andwcxb_scoring.pyitself is not bound, so it is not tamper protection.The issue lists adding a decorator as a change that should not break the binding. I kept it as a breaking change on purpose, because a decorator can change scores.
Existing evidence
Certified WCXB profiles, certificates, score summaries and timing receipts may name the old digest
35dc50a1.... They cannot be rewritten, so the authority keeps it insuperseded_source_text_digests, mapped to the new module digest34fd9387....35dc50a1..., and with the module's imports added it normalizes to the digest now bound.35dc50a1...under the oldinspect.getsource()method.Not checked against real evidence: this machine has no certified WCXB evidence (no
wcxb-score-summary.jsonunder~/.browser-eval), and no profile in Git names the digest. Frozen verification is covered only by synthetic documents and fixture cohorts carrying the old digest. It is worth running the WCXB report build against the real evidence once.Golden cases
The golden cases are fixed inputs with exact expected floats, and they replace the two smaller metric tests in
test_wcxb_huggingface_inputs.py. I downloadedevaluate.pyat the pinned revision, confirmed its SHA-256 matchesUPSTREAM_EVALUATOR_SHA256, and ran only its three metric functions (extracted by AST) on all 24 inputs. The results were identical to this module's. Upstream code is not part of the repository or of test runs, so CI checks the fixed values only.Test plan
tests/test_wcxb_metric_binding.pycovers:import xand imports nested in a functionword_f1orsnippet_checkname inwcxb_scoringis rejectedscore()is rejectedruff format --isolatedoutput keep the bindingtests/test_wcxb_latency_collection.pycovers changing the module or authority duringcollectandcertify, andcertifyon a receipt naming the superseded digest (passes) and an unknown digest (fails).tests/test_golden_reports.py,tests/benchmarksand alltests/test_wcxb_*targets: 11576 passed. Route hashes are unchanged.ruff check --config 'include=["*.py"]' --select F,TID252 .andruff checkboth pass.tests/test_golden_reports.pyand alltests/test_wcxb_*targets: 260 passed, lint gate passes. Reducing theimport xguard branch toimported = []fails the two newimport xcases.b57580cb: "Tests and static checks", "Installation and packaging", "Rendered reference and report checks" and "Python 3.11" pass.ocr-reviewreports one blocking finding, disputed in the round 2 comment. I did not run the full suite ortests/package_smoke.pylocally.tests/test_golden_reports.py,tests/test_wcxb_metric_binding.pyandtests/test_wcxb_latency_collection.py: 95 passed, lint gate passes.