Skip to content

refactor(harness): share hash and JSON helpers through record_io - #137

Merged
lanyue-llk merged 10 commits into
mainfrom
refactor/shared-hash-and-json-helpers
Nov 3, 2026
Merged

lanyue-llk merged 10 commits into
mainfrom
refactor/shared-hash-and-json-helpers

Conversation

@lanyue-llk

@lanyue-llk lanyue-llk commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

What, why and how of this PR

Issues

Closes #91. This PR covers hashing and JSON file I/O only. Data-home, .env and local-path redaction helpers landed separately in #136.

Remaining work, moved to #150:

Summary

Private SHA-256, canonical JSON digest and JSON read/write helpers under src/harness now use harness/record_io.py.

  • record_io.py gains bytes_sha256, optional_file_sha256, read_json, write_json(parents=) and json_bytes (moved from reporting/publication.py, callers migrated, no re-export).
  • canonical_json_sha256 gains explicit ensure_ascii and allow_nan options. Defaults are unchanged. Callers whose digests were ASCII-escaped or strict name that choice at the call site.
  • Guard: tests/test_shared_hash_json_helpers.py bans the fully retired names and rejects new bare copies by structure, with paired negative controls. It is an AST test rather than ruff TID251, because TID251 bans imports, not local definitions.

Semantics compared before each swap

Old form Replacement Why the bytes stay the same
json.dumps(sort_keys, compact, ensure_ascii=False) canonical_json_sha256(v) Same options; allow_nan was already the json.dumps default
Same, without ensure_ascii=False (_proposal_digest, canonical_digest, profile_digest, rainbond) canonical_json_sha256(v, ensure_ascii=True) Keeps the ASCII escaping
Same, with allow_nan=False (webarena_state.digest, retrieval_acceptance.digest) canonical_json_sha256(v, allow_nan=False) Keeps strict rejection
_case_ids_sha256 (no sort_keys) canonical_json_sha256(sorted(ids)) sort_keys has no effect on a list of strings
Chunked and whole-file reads file_sha256 Digest of the same bytes; missing-file and directory errors are the same OSError types
sha256(path) if path.is_file() else None, as a helper or inline optional_file_sha256 None is kept, including in browser_use/report_check.py, which used both a strict and an optional helper. webarena_replay.py keeps its conditional because it returns a dict, and runner.py's dataset_sha256 keeps its own because it reads through read_dataset_bytes
json.loads(read_text(encoding="utf-8")) read_json Newline translation does not change a strict JSON parse. BOM and invalid UTF-8 raise the same errors, covered by a test
(dumps(ensure_ascii=False, indent=2) + "\n").encode() as a helper (report_diagnostic.encode, browser_observation_bytes) json_bytes Same expression
atomic_write(path, <same document bytes>) (web_search/publication.save) web_search/core.write_json Same atomic_write, same bytes
hashlib.file_digest behind exists() (report_package._archive_identity) exists() check kept, then file_sha256 Same digest. optional_file_sha256 was not used because it returns None for a directory, where this raises
write_text(dumps(indent=2) + "\n") write_json Same bytes on POSIX. Two old sites used the locale encoding and now always write UTF-8 (review_execution.write_content_document, webmainbench_correction.write)

Deliberately not migrated

  • Different parser: comparison_audit._read_json and webmainbench_certification._read_json use json.loads(bytes), which also accepts UTF-16/32. web_fetch/config.load_json and refresh_assembly._read_json read through read_dataset_bytes.
  • Different atomicity: web_search/core.write_json stays atomic, shares json_bytes, and is the one atomic JSON document writer the guard allows. rainbond._atomic_json is unchanged.
  • Source hashed by a binding: lexbench/resource_matrix.py, lexbench/resource_profiles.py and reporting/visual.py keep their copies, because editing them changes orchestrator_sha256 or visual-proof checker_sources. They are named exemptions in the guard. lexbench/reproduction.py also stays: it is published as reproduction/run.py.
  • Thin wrappers with a real difference remain: containment or symlink preconditions (checked_file_sha256, _checked_sha256, _revision_file_sha256), str | bytes input (reference_lifecycle.sha256), named frozen options (webarena_state.digest), and a cache (reporting/locales._catalog).
  • Named digest contracts remain: task_definition_sha256 and scoring_revision_history_sha256 only call canonical_json_sha256, but each name states a contract. task_definition_sha256 names a public protocol: the task_definition_sha256 field that a retrieval contract declares. scoring_revision_history_sha256 is shared by the code that writes the digest (assembly.py) and the code that verifies it (reference_lifecycle.py). reference_freeze.browser_observation_bytes now returns json_bytes(observation) and stays for the same reason: its writer and its verifier share those bytes.
  • Forwarding wrappers are gone: _attempts_sha256, _parameters_sha256, _planned_actions_digest, write_agent_response and the three text_digest copies are replaced at their call sites, using the bytes_sha256(x.encode()) form the harness already uses elsewhere.
  • Short loaders that do more than read: a read followed by schema validation or field selection stays, such as evaluator_transition.load_transition, remote_runtime.validate_remote_reset_receipt and rainbond.validate_receipt.
  • Reads that read_json cannot replace: json.loads(x.read_text()) without an encoding follows the locale (lexbench/verification.resource_document, local_execution_contract.read, local_execution_legacy.read, report_version._profile_binding, report_interfaces.method_provenance). public_webarena/diagnostics._official_dataset and webarena_dataset._official_evaluator_names read an importlib.resources object, which is not always a filesystem path.
  • Inline expressions: these are not private helpers, so this PR leaves them; see "Remaining work, moved to Follow-up to #91: remaining hash, JSON and redaction helper work #150". AST counts under src/harness at the current head, excluding the record_io.py owner, with the count in the 91 files this PR edits in parentheses:
    • json.dumps(v, ensure_ascii=False, indent=2) + "\n": 219 (150), of which 46 (25) add .encode() and so equal json_bytes exactly. The others are mostly write_text(..., encoding="utf-8").
    • hashlib.sha256(x.read_bytes()).hexdigest(): 113 (53).
    • json.loads(x.read_text(...)), with or without an encoding: 833 (515).
    • hashlib.file_digest: 3 outside record_io.py, in safety.py and two providers.
  • Other protocols: tree digests, JSONL helpers (read_jsonl, write_jsonl) and publication_verify's network digest are out of scope.

The names digest, sha256, sha and _read_json are not banned because distinct definitions remain; the structural rule still rejects bare copies under those names. It also rejects wrappers that only forward their parameters to bytes_sha256, file_sha256, read_json or write_json, the inline <digest of path> if path.is_file() else None form, the json_bytes helper form, the hashlib.file_digest helper form (with or without a leading return None check), and a body that only calls atomic_write with one JSON document. Run against the previous head, the new rules flag exactly the four copies migrated in round 3. It does not flag json.loads(path.read_bytes()), because that parser accepts inputs read_json rejects.

Round 4 added two structural rules. The first rejects a function of up to five statements that returns json.loads(<path>.read_text(encoding="utf-8")) after preconditions, directly, as a tuple element, as the true branch of a conditional, through a one-argument wrapper, or after a not isinstance check. The second rejects a function of up to two statements that passes the json_bytes expression to an output call. Both have negative controls for a locale read, a constant input, schema validation, field selection and a writer that also uses the bytes. Those rules flagged the sites below, and each now calls read_json or json_bytes with its preconditions unchanged:

  • From the review: failure_cause_review.load_failure_cause_review, browser_use/publication.read_public_json, catalog_comparison._read, remote_runtime._read_frozen_input, webarena_results._read and _read_cohort_input, diagnostics.write_diagnostic and its nested read.
  • Found by the same rules: evaluator_transition._regular_json, webarena_report._load_artifact, web_fetch/evidence._read and web_fetch/local_audit._read_bound_receipt.

Hash-bound evidence

  • No frozen binding broke. I hashed the 84 src/harness files edited by the first commit at the base commit and searched for those hashes in the repository and in evidence, reviews, report-builds, datasets and implementations under ~/.browser-eval. The repository had none, and the only data-home hits were harness_files inventories in 10 pre-call files under evidence/research/webfetch-430-refresh-20261014/. In the one inventory I compared in full, 211 of 246 entries already differ from the base commit, so it is a historical snapshot and not a live gate. public_webarena/runner.py, first edited in the round 1 fix, was checked the same way and its base hash has no hits.
  • Round 3 files: the base and previous-head hashes of web_search/publication.py, web_fetch/report_package.py, web_fetch/report_diagnostic.py and web_fetch/reference_freeze.py have no hits in evaluation, research, configs or those data-home directories (JSON files only).
  • Round 4 files: the base and previous-head hashes of the 10 files edited in round 4, including the newly edited web_fetch/evidence.py and web_fetch/local_audit.py, have no hits in evaluation, research, configs or those data-home directories (JSON files only).
  • After rebasing onto main with refactor(wcxb): bind the metric module by normalized AST #133 to refactor(research): move adoption survey into harness and fix stale doc paths #138: the same 144 files are edited, so no file newly joined the migration. I hashed the 91 edited src/harness files as they stand on main and searched evaluation, research, configs, tests, src, scripts, docs and those data-home directories (JSON files only). The repository has no hits, and the data-home hits are the same 10 pre-call inventories described above. wcxb_metrics.py, the module refactor(wcxb): bind the metric module by normalized AST #133 binds, is not edited. wcxb_scoring.py is edited, as it was before the rebase: its hash is recorded as scorer_sha256 and watched for changes during a WCXB latency collection, so like the other modules under "In-flight work" it should not change during an unfinished collection. Nothing compares that hash to a frozen value.
  • Not scanned: build-cache, builds, runtime and toolchains under the data home, and any evidence on other machines.
  • In-flight work: web_search.validate_resume_implementation and the Web Fetch runtime_source_sha256 continuation checks compare live source. As with any edit to these modules, an unfinished cohort started before this PR cannot resume and needs a new cohort.

Golden snapshot

One route changed: web-search manifest.json. I built the Web Search example from the base commit and from this branch and compared the trees. Only manifest.json and browser-eval-version.json differ, and the manifest differs only in renderer_sha256, browser_eval and the matching bundle entry. renderer_sha256 is the hash of web_search/report.py, which this PR edits. The other two come from browser-eval-version.json, which my comparison left unpinned; the golden test pins the builder identity, and that route's snapshot is unchanged. So renderer_sha256 is what moves the snapshot. No HTML route changed, and no other track's snapshot changed.

Rechecked after rebasing onto #133 to #136: with the builder identity pinned, the 19 normalized routes built from main at that point and from this branch differ only in manifest.json's renderer_sha256, which equals the SHA-256 of each side's web_search/report.py. #138 does not touch that module or the snapshot, and the golden test passes on the final rebase.

Deleted files

None, so no reference scan was needed for deletions. For removed helper names, I resolved every from harness... import and module attribute access across src, scripts, tests, evaluation and research by importing the modules. No import was missing. The nine attribute reports were local variables that share a module's name. Dynamic lookups by string and non-Python files were not covered by that check.

Deferred

Test plan

Local, Python from the shared locked environment:

  • ruff check --config 'include=["*.py"]' --select F,TID252 . and ruff check: pass.
  • Rebase onto main with refactor(wcxb): bind the metric module by normalized AST #133 to refactor(research): move adoption survey into harness and fix stale doc paths #138, at the current head:
    • ruff check --config 'include=["*.py"]' --select F,TID252 . and ruff check: pass.
    • tests/test_golden_reports.py and tests/test_shared_hash_json_helpers.py: 97 passed, in a run of 200 with test_documented_paths.py, test_report_methods.py, test_packaging_hygiene.py and trajectory_replay/test_hf_inputs.py.
    • The 145 test files that name a module whose rebase conflicted, from a scratch export: 3,408 passed, 3 skipped, 5 failed. Three are on the known local macOS list. The other two, test_packaging_hygiene.py::test_documented_make_commands_name_the_required_profile and test_hf_inputs.py::test_default_catalog_output_is_private_and_only_created_after_validation[None], also fail in a scratch export of main before refactor(research): move adoption survey into harness and fix stale doc paths #138 and pass in the git worktree, because the export has no .git.
    • Every from harness... import under src, scripts, tests, evaluation, research and examples resolves.
  • Before the rebase, at round 4: lint passes. The guard, the golden test and the 62 test files that reference a module edited in round 4: 1,175 passed, 4 skipped, no failures. Golden snapshots are unchanged by this round.
  • After round 3: lint passes. tests/web_search, the Web Fetch package, freeze, reference, privacy and publication test files, the guard and the golden test: 912 passed, 23 skipped, no failures. Golden snapshots are unchanged by this round.
  • After the round 2 fix, the guard, the golden test and every test file that references a module edited by the round 2 fix (webarena_report, report_build, reference_lifecycle, web_fetch.runner): 2,381 passed, 7 skipped, 4 failed. All 4 are on the known local macOS list.
  • The same scope after the round 1 fix, for that fix's modules: 1,369 passed, 3 skipped, no failures.
  • Full suite, in four chunks, from scratch copies of the base commit and the first commit of this branch (not rerun locally after the round 1 fix; CI covers the current head): the same 20 tests fail on both, so there are no new failures. Passes: 18,902 on this branch and 18,870 on the base; the 32 extra are the new guard file.
    • 15 of the 20 are on the known local macOS list.
    • The other 5 fail identically on the base copy: test_optional_reports.py (3), test_report_software_versions.py (1) and test_hf_inputs.py (1).
  • Running inside the nested worktree gave extra failures with Historical benchmark source is not recorded in the dataset lock. reference_inputs.py walks up to the parent checkout's older evaluation/lexbench-webfetch.json. This is a local path artifact: the failures unique to that location passed from the scratch copy, and CI is the gate.

CI results are in the checks on this PR.

@lexmount-ocr lexmount-ocr Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Review complete · 6602c7e

No findings in this review.

@lanyue-llk lanyue-llk left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review, round 1

Head reviewed: 6602c7ef. I found no correctness, evidence or CI defects. There are two P3 findings. Both concern how the guard and the PR body describe what remains.

Findings

P3: the guard tells authors to replace a parser that this PR says differs from read_json

tests/test_shared_hash_json_helpers.py:70

_copied_primitive includes read_bytes in the forms it reports as copies read_json. I ran _violations on def f(path): return json.loads(path.read_bytes()), and it returned copies read_json. The PR body says json.loads(bytes) is a different parser, and that is why comparison_audit._read_json and webmainbench_certification._read_json stay. I confirmed the difference: a UTF-16 file parses with json.loads(path.read_bytes()) and raises UnicodeDecodeError in read_json. An author who follows the guard message on a bytes parser would change which inputs are accepted. No control exercises this branch either way.

Fix: limit the set to read_text, and add def f(path): return json.loads(path.read_bytes()) to test_guard_keeps_behaviorally_distinct_helpers.

P3: wrappers with no real difference remain, and the rewrite takes them out of the guard's reach

  • src/harness/browser_use/review.py:19: _attempts_sha256 is only return file_sha256(path) and has one caller, at line 136.
  • src/harness/trajectory_replay/retrieval_acceptance.py:39, src/harness/web_fetch/webmainbench_correction.py:455 and src/harness/web_fetch/webmainbench_diagnostics.py:1023: three separate text_digest definitions, each bytes_sha256(<str>.encode()).

The PR body says the thin wrappers that remain have "a real difference". These do not. The guard flags hashlib.sha256(text.encode()), but it passes the same logic once it is written with bytes_sha256, so these copies now pass unnoticed.

Fix: inline _attempts_sha256. Then either give text_digest one shared owner or call bytes_sha256(x.encode()) at each call site. If you keep them for now, list them in the PR body and correct the sentence.

What I verified

Serialization. I read all 55 removed lines that contain json.dumps, json.loads or their options against their replacements.

  • ensure_ascii=True is kept at all four sites that used the default: rainbond, _proposal_digest, canonical_digest and profile_digest.
  • allow_nan=False is kept in webarena_state.digest and retrieval_acceptance.digest.
  • _case_ids_sha256 is unchanged in bytes, because sort_keys has no effect on a list of strings.
  • The Web Search forms with default separators stay as bytes_sha256(json.dumps(...)), including collection_protocol_sha256, normalized_results_sha256 and request_sha256.

File hashing. I listed all 76 helper definitions the PR removes.

  • The optional None behaviour is kept where the old helper had it, including the two report_check.py sites that used the aliased optional helper.
  • manifest_repair._sha256 keeps its unlinked and missing-file checks as _checked_sha256.
  • I listed every file_sha256 and bytes_sha256 argument in src/harness to catch bytes passed as a path or a path passed as bytes. The two file_sha256(raw) calls in report_build.py do receive paths.

JSON reads and writes.

  • No json.loads(bytes) site moved to read_json.
  • Every old site that created parent directories now passes parents=True.
  • No atomic write became non-atomic: web_search/core.write_json still uses atomic_write.
  • _clean is kept in webarena_report.
  • No helper name is rebound as a local variable or parameter under src/harness.
  • publication.json_bytes has no remaining importers or qualified users, so nothing depends on a re-export.

Source-hash bindings.

  • The base-commit hashes of the 84 edited src/harness files appear nowhere in the repository at the base commit, and not in src/lexbench_webfetch. I did not repeat the data-home search of evidence, reviews, report-builds, datasets and implementations, so that claim rests on the PR's own scan.
  • I traced the live source checks. metric_implementation_binding hashes only word_f1 and snippet_check, which this PR does not change. capture_source_identity, remote_execution and wcxb_latency compare within a run. The latency certifier uses frozen source copies.
  • The exemptions in FROZEN_SOURCE_COPIES match the checks in lexbench/resource_matrix.py, lexbench/resource_profiles.py and reporting/visual.py.
  • webarena_state.py also hashes its own source, in rule_identity. The file's docstring says existing profiles do not opt in, and the repository search found no binding of its old hash.

Golden snapshots. The only change is the web-search manifest.json route. That is consistent with the PR's explanation, because web_search/report.py feeds renderer_sha256 and is edited here. I did not rebuild the base and branch trees to compare them.

Tests. Each of the 30 removed assert lines in the test diff calls a removed helper name, which is what a rename produces. I did not pair each one with its replacement line.

Scope. "Part of #91" is accurate. Data-home, .env and redaction work is listed as remaining, and the unmigrated copies are disclosed.

Commands run

  • ruff check --config 'include=["*.py"]' --select F,TID252 . and ruff check: pass.
  • tests/test_golden_reports.py and tests/test_shared_hash_json_helpers.py: 42 passed.
  • tests/test_webarena_state.py, tests/browser_use/test_report.py, tests/test_webmainbench_assembly.py and tests/test_wcxb_contract.py: 136 passed.
  • I did not run the full suite locally. CI is the full-suite gate.

CI

All checks pass on 6602c7ef: "Tests and static checks", "Installation and packaging", "Rendered reference and report checks" and "Python 3.11". The PR is mergeable and its merge state is clean.

@lanyue-llk

lanyue-llk commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Review round 1: both findings are fixed, and none are disputed.

  • Guard reported the bytes parser as a read_json copy (ab1d77b). The rule now matches only read_text, and json.loads(path.read_bytes()) is a negative control.
  • Wrappers with no real difference (2f39a06).
    • Inlined _attempts_sha256.
    • Replaced the three text_digest definitions with bytes_sha256(x.encode()) at each call site, including tests, and added text_digest to the retired names.
    • A scan for the same pattern found two more forwarding wrappers, _parameters_sha256 and write_agent_response, so I inlined those too.
    • The guard now rejects wrappers that only forward to bytes_sha256, file_sha256, read_json or write_json, with paired controls.

Wrappers I kept: three wrappers still only call canonical_json_sha256: task_definition_sha256, scoring_revision_history_sha256 and _planned_actions_digest. Each name is shared by a digest's writer and verifier, so the guard allows that form. reporting/locales._catalog stays because it adds a cache. The PR body now lists these and corrects the wrapper sentence.

Local checks at 2f39a06: lint passes. The guard, the golden test and every test file referencing a module edited in this round gave 1,369 passed, 3 skipped, with golden snapshots unchanged. I did not rerun the full suite locally; CI is the gate for that.

Newly edited file: public_webarena/runner.py was not edited by the first commit. Its base-commit hash has no hits in the repository or in the data-home directories scanned earlier.

@lexmount-ocr lexmount-ocr Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Review complete · 2f39a06

No findings in this review.

@lanyue-llk lanyue-llk left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review, round 2

Head reviewed: 2f39a06ed7d8ce77b12370750057b5cf45ba0c69. Two P3 findings and no correctness defects.

Findings

1. P3: src/harness/trajectory_replay/webarena_report.py:192 and the "Named digest contracts" paragraph in the PR body

  • Problem: The PR body says task_definition_sha256, scoring_revision_history_sha256 and _planned_actions_digest are each shared by the code that writes a digest and the code that verifies it. The guard comment in tests/test_shared_hash_json_helpers.py:53 gives the same reason. This holds only for scoring_revision_history_sha256 (assembly.py:495 writes, reference_lifecycle.py:1183 verifies).
    • _planned_actions_digest has one src caller, the verifier at webarena_report.py:206. Only tests use it to build fixtures. The writer path sets planned_actions_sha256 from plan["bound_calls_sha256"] (webarena_results.py:461) and does not call this helper.
    • task_definition_sha256 has one caller in the repository, at web_fetch/config.py:50, which computes the current value to compare with the declared one. Nothing in src, scripts, research, evaluation or docs writes through it.
  • Fix: Inline _planned_actions_digest as canonical_json_sha256(actions) and update its three test uses. It has the same shape as _attempts_sha256, which round 1 removed. Then correct the sentence: keep task_definition_sha256 because it names a public protocol, not because a writer shares it.

2. P3: src/harness/web_fetch/report_build.py:165 and src/harness/web_fetch/reference_lifecycle.py:1045

  • Problem: The semantics table says sha256(path) if path.is_file() else None is replaced by optional_file_sha256, but both files, which this PR edits, keep that exact form inline:

    • input_sha256 = file_sha256(source) if source.is_file() else None
    • review_hash = sha256(review_path.read_bytes()) if review_path.is_file() else None

    The digests are correct, so this is an incomplete migration and not a behaviour bug. The guard does not cover this conditional form.

  • Fix: Call optional_file_sha256(...) at both sites. webarena_replay.py:91 returns a dict rather than a digest, so it can stay.

What I verified

  • Digest options: I checked every removed json.dumps hash input against its replacement.
    • All have sort_keys and compact separators, except _case_ids_sha256, which hashes a sorted list of strings, so the bytes are the same.
    • The five sites without ensure_ascii=False now pass ensure_ascii=True.
    • The two allow_nan=False sites keep it.
    • collection_protocol_sha256, normalized_results_sha256 and request_sha256 keep their non-compact json.dumps and change only the hash wrapper.
  • Removed helpers: I read all of them and their call sites, including the round 1 fix commit.
    • Optional helpers map to optional_file_sha256 and strict ones to file_sha256, including both helpers in browser_use/report_check.py.
    • parents=True is kept wherever the old helper created directories.
    • webarena_report._write_clean_json keeps _clean.
    • The _json_file_sha256 bytes are unchanged, and it hashes the indented document form through json_bytes.
  • JSON read and write: read_json decodes strict UTF-8 and leaves a BOM in place, as the UTF-8 read_text form did. write_json writes the same bytes on POSIX.
  • Source bindings:
    • The base-commit hash of all 85 changed src files has no hit anywhere in the repository at this head.
    • metric_implementation_binding hashes word_f1 and snippet_check, which this PR does not touch.
    • reporting/visual.py, resource_matrix.py and resource_profiles.py are unchanged.
    • webarena_state.load_contracts compares a binding with the live rule_identity(), and webarena_state.py is edited here, but no profile under evaluation or research declares observed_state.
    • My own data-home scan was inconclusive, because a time-limited grep over evidence, reviews, report-builds, datasets, implementations and reference-inputs returned nothing and may have been cut off. I did not confirm or contradict the PR's data-home scan result.
  • Imports: A static scan of src, tests and scripts found no import of a removed helper from its old module. The attribute reports I reviewed were __file__ lookups or local variables that share a module's name; the last 8 of the 48 reports were not displayed, and CI imports and runs the full suite. No new compatibility alias was added. A repository search finds no remaining use of the removed wrapper names checked outside the guard file.
  • Other wrappers: The remaining thin wrappers I found have a precondition, a keyword option or an input transformation, apart from the two named in finding 1.

Tests and CI

  • Local:
    • Both ruff gates pass.
    • tests/test_golden_reports.py and tests/test_shared_hash_json_helpers.py: 56 passed.
    • Six test files covering the round 1 fix and related modules: 256 passed.
  • Golden snapshot: Only tests/golden/web-search.json changed, by one line. I did not rebuild the Web Search example to repeat the PR's route comparison.
  • CI at this head: Tests and static checks, Installation and packaging, Rendered reference and report checks, and OCR dispatch all pass. The PR is mergeable.
  • Scope: "Part of #91" is the correct label, because the data-home, .env and redaction work remains.

@lanyue-llk

Copy link
Copy Markdown
Contributor Author

Round 2 findings are fixed. None are disputed.

  • _planned_actions_digest (fe76446): inlined as canonical_json_sha256(actions), its three test uses updated, and the name added to the guard's retired list. The guard docstring and its negative-control comment no longer claim every canonical digest wrapper is shared by a writer and a verifier. task_definition_sha256 stays because it names a public protocol.
  • Conditional digests (eb30a3d): report_build.py:165 and reference_lifecycle.py:1045 now call optional_file_sha256.
    • Beyond the finding: web_fetch/runner.py's provider_config_sha256 had the same form, so I migrated it too.
    • Guard: it now rejects this inline form, with negative controls for a dict return (webarena_replay.py:91), a different path, a non-None default and another reader (dataset_sha256 in runner.py, through read_dataset_bytes).

Digests are unchanged and the golden snapshots did not change. The PR body's semantics table, contracts paragraph and test plan are updated. Local results are in the test plan; CI on the new head is the full-suite gate.

@lexmount-ocr lexmount-ocr Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Re-review complete · eb30a3d

No findings in this incremental review.

@lanyue-llk lanyue-llk left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review, round 3

Head reviewed: eb30a3ddaea195f34bd282bd27ae274829e2dd58. Two P3 findings and no correctness defects. Both are private helpers that this PR's scope covers and that its guard and PR body do not mention. Round 1 and 2 fixes are correct.

Findings

1. P3: src/harness/web_search/publication.py:35

  • Problem: save is atomic_write(path, (json.dumps(value, ensure_ascii=False, indent=2) + "\n").encode()). That is the same operation as web_search/core.write_json (atomic_write(Path(path), json_bytes(value))), and I confirmed the encoded bytes match json_bytes. The PR edits this file and says core.write_json is the atomic writer, and delivery.py and example.py already import it, but publication.py keeps its own copy. The guard does not flag it.
  • Fix: Import write_json from harness.web_search.core and replace the four save(...) calls. Writes go to the same paths, so the bytes do not change.

2. P3: src/harness/web_fetch/report_package.py:558, src/harness/web_fetch/report_diagnostic.py:85, src/harness/web_fetch/reference_freeze.py:61

  • Problem: Three more private copies remain. The PR body lists neither migrated nor deliberately kept for any of them, and I ran each form through _violations: it returns [].
    • _archive_identity is file_sha256 written with hashlib.file_digest, behind an exists() check. It is the same digest, and it is a private hash helper of the kind this PR retires.
    • The nested encode(value) is exactly json_bytes.
    • browser_observation_bytes is exactly json_bytes. Its docstring and four call sites may justify keeping the name as a retained-bytes contract, but then it should call json_bytes or be listed.
  • Fix:
    • _archive_identity: keep the exists() check, because a missing file must still return None, and call file_sha256(path). optional_file_sha256 is not the same: it returns None for a directory, where this one raises.
    • encode: use json_bytes directly.
    • browser_observation_bytes: make it return json_bytes(observation), or add it to the PR body's kept list with a reason.
    • Guard: add a rule and paired controls for the (json.dumps(v, ensure_ascii=False, indent=2) + "\n").encode() helper form and the file_digest helper form.
    • None of these three source files is named by a source-hash check I could find. All three are under web_fetch, so they already fall within the runtime_source_sha256 note in the PR body.

Inline, non-helper uses of these forms remain elsewhere, including providers/headless.py:497, providers/moli.py:279 and many (json.dumps(...) + "\n").encode() expressions. The PR's scope is named helpers, so I am not raising those. safety.py:60 is a tree digest.

What I verified

  • Round 2 fixes: I read the diff from 2f39a06ed to head.
    • _planned_actions_digest is inlined, its three test uses are updated, and it is on the retired list.
    • report_build.py:165, reference_lifecycle.py:1051 and runner.py:594 now call optional_file_sha256. All three arguments are Path values, and the old and new forms give the same digest or None. reference_lifecycle.py line 1054 still has its own is_file check for review_candidates, which returns a list rather than a digest.
    • The dataset_sha256 conditional at runner.py:595 stays, as the PR body says.
  • Guard: The new optional-form rule and its negative controls behave as the PR body describes. Its check for inline conditionals returns no violation on the current tree.
  • Remaining wrappers: I ran my own AST scan of short functions under src/harness that hash or read and write JSON, and read each one.
    • Apart from the findings above, the ones left have a precondition, a shape check, a different parser, an option, a cache or another distinct behaviour.
    • review_execution.write_content_document is a one-line write_json(path, value, parents=True) with five callers and a test import. The guard allows a fixed keyword option, so I am not raising it.
  • Source hash checks: I traced the __file__ and source-file hashing sites.
    • Edited and hashed by live code: webarena_state.py, webmainbench_runner.py, webmainbench_latency_diagnostic.py, webmainbench_diagnostics.py, review_execution.py, result_review.py and web_search/report.py.
    • review_execution.py compares its identity only inside a review workspace, and a changed one requires a new directory. That in-flight effect is like the ones the PR body discloses, though the body does not name it.
    • Not edited: reporting/visual.py, web_search/visual.py, web_search/pages.py, browser_use/report_visual.py, trajectory_replay/webarena_report_visual.py, title_quality.py, rescoring.py and providers/cloudflare.py.
    • I did not repeat the data-home scan, so that claim still rests on the PR's own scan.
  • Golden snapshots: The only change across all tracks is the manifest.json route in tests/golden/web-search.json, as the PR explains. I did not rebuild the base and branch trees to compare them.
  • Removed names: Outside the guard file, a repository search finds no use of text_digest, _attempts_sha256, _parameters_sha256, write_agent_response, _planned_actions_digest, sha256_file, _sha256_file, json_digest or input_digest. No importer of json_bytes from reporting/publication remains, and publication.py only uses it internally.
  • Scope: "Part of #91" is accurate. Data-home, .env and redaction work is listed as remaining.

Commands run

  • ruff check --config 'include=["*.py"]' --select F,TID252 . and ruff check: pass.
  • tests/test_golden_reports.py and tests/test_shared_hash_json_helpers.py: 63 passed, matching the PR body.
  • tests/web_search and tests/test_webmainbench_content_review.py: 502 passed.
  • tests/test_reference_lifecycle.py and tests/trajectory_replay/test_webarena_report.py: 134 passed.
  • I did not run the full suite locally. CI is the full-suite gate.

CI

All checks pass at this head: "Tests and static checks", "Installation and packaging", "Rendered reference and report checks", "Python 3.11", "Select check scope", "OCR dispatch". The PR is mergeable, its merge state is clean, and main is still 27401304.

@lanyue-llk

Copy link
Copy Markdown
Contributor Author

Round 3 findings, all fixed. Nothing disputed.

  • web_search/publication.py, save: removed; the four calls now use web_search.core.write_json. Same atomic_write, same bytes. (98531f1)
  • report_package._archive_identity: keeps its exists() check and calls file_sha256, so a directory still raises. (810aad7)
  • report_diagnostic nested encode: replaced by json_bytes at its call sites. (810aad7)
  • reference_freeze.browser_observation_bytes: now returns json_bytes(observation). It stays as a named wrapper because its writer and verifier share those bytes; the PR body lists it as kept. (810aad7)
  • Guard: new rules cover the json_bytes helper form, the file_digest helper form and atomic JSON writers, with paired controls. web_search/core.write_json is the one allowed owner. Run against the previous head, the new rules flag exactly these four copies. (9ee970e)

Tests: lint passes, and the affected test files plus the guard and golden test give 912 passed, 23 skipped, no failures. Golden snapshots did not change. CI on 9ee970e is the full-suite gate.

The PR body also now states that inline json.dumps(...) document expressions and inline file_digest calls inside larger functions are not migrated.

@lexmount-ocr lexmount-ocr Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Re-review complete · 9ee970e

No findings in this incremental review.

@lanyue-llk lanyue-llk left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review, round 4

Head: 9ee970ec. CI passes for this head (run 41404445616, conclusion success), including "Tests and static checks" and "Installation and packaging". No findings below are correctness or byte-stability defects.

Findings

P2, PR body, "Deliberately not migrated", Inline expressions bullet (and "Remaining for #91"). The body says the json.dumps(...) document expression remains inline "in about 30 places". An AST count of json.dumps(x, ensure_ascii=False, indent=2) + '\n' under src/harness finds 218, 144 of them in files this PR edits. The bullet also omits 113 inline hashlib.sha256(x.read_bytes()).hexdigest() (53 in edited files) and 841 inline json.loads(x.read_text(...)) (506 in edited files). The issue's acceptance is "no private re-implementations remain", so a reader relying on this list would underestimate what is left. The guard checks function definitions and does not cover these.
Fix: correct the count, add the two missing forms, and state under "Remaining for #91" or "Deferred" whether inline forms are in scope for #91. No code migration is requested by this finding.

P3, private JSON helpers left in edited files, neither migrated nor listed as kept. These have the same semantics as forms this PR did migrate (public_webarena/publication._read_json, webmainbench_case_correction._read_json, browser_use/report._read_json), and the guard does not flag them because of the added precondition or return value:

  • src/harness/trajectory_replay/diagnostics.py:56: write_diagnostic builds (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode(), which is exactly json_bytes(payload).
  • src/harness/browser_use/failure_cause_review.py:31: load_failure_cause_review
  • src/harness/browser_use/publication.py:60: read_public_json
  • src/harness/trajectory_replay/catalog_comparison.py:44: _read
  • src/harness/trajectory_replay/remote_runtime.py:380: _read_frozen_input
  • src/harness/trajectory_replay/webarena_results.py:26 and :234: _read, _read_cohort_input
  • src/harness/trajectory_replay/diagnostics.py:646: nested read

Fix: use json_bytes and read_json at these sites and keep their preconditions, or list them as kept with a reason. Editing these files needs the same hash-binding scan as the other edited files; all of them are already edited by this PR, so the scan should already cover them.

Verified

  • Every removed or changed hash and JSON helper in the 89 edited src/harness files, compared with its replacement: ensure_ascii, allow_nan, sort_keys, separators, trailing newline, optional versus strict digest (including the sha256 as file_sha256 optional alias in browser_use/report.py and report_check.py), and parents=True on all 16 browser_use/report.py writes and on _write_clean_json. No byte or error-type difference found beyond those disclosed.
  • webarena_corrections._digest used no allow_nan=False, so canonical_json_sha256 is equivalent.
  • Hunks that remain after normalizing helper names are mechanical, apart from the wrappers the body describes.
  • word_f1 and snippet_check, bound by wcxb-metric-bindings.json, are not in the wcxb_scoring.py diff.
  • All from harness... import names across src, scripts, tests, evaluation and research resolve. Retired names have no remaining references outside the guard. No caller imports json_bytes through reporting/publication.
  • Guard: run against eb30a3dd it flags exactly the four copies the body names, and it passes at the head. The BOM parity test exists.
  • Lint gate passes. tests/test_golden_reports.py and tests/test_shared_hash_json_helpers.py: 83 passed.
  • No base-commit hash of an edited source file appears anywhere in the repository (git grep).

Not verified

  • My independent scan of the data home for those base hashes did not complete, so I did not confirm the body's data-home scan results. This matters most for webarena_state.py: rule_identity() includes its own source hash and load_contracts rejects a profile that binds a different one. I confirmed no repository file binds it, but not that no data-home profile does.
  • I ran no other local tests; the full suite rests on CI.
  • Aggregated source digests (such as runtime_source_sha256) cannot be found by a per-file hash search. The body discloses this for in-flight cohorts.

@lexmount-ocr lexmount-ocr Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Re-review complete · 6abb2f9

No findings in this incremental review.

@lanyue-llk

Copy link
Copy Markdown
Contributor Author

Round 4 review fixes, head 6abb2f9c.

Fixed

  • P2, PR body counts: corrected and extended the "Inline expressions" bullet, with counts at the current head. json.dumps document expression: 217 (150 in edited files). Inline hashlib.sha256(x.read_bytes()).hexdigest(): 113 (53). Inline json.loads(x.read_text(...)): 830 (515). The review's 218/144 and 841/506 match the previous head under the same AST scan; the numbers moved because this round migrates sites and adds two edited files. "Remaining for Consolidate copy-pasted hashing, JSON I/O, data-home, dotenv and redaction helpers #91" now says these inline forms are not migrated, that the guard does not cover them, and that whether Consolidate copy-pasted hashing, JSON I/O, data-home, dotenv and redaction helpers #91 extends to them is an owner decision.
  • P3, private JSON helpers (8637da28): every named site now calls read_json or json_bytes with its preconditions unchanged. The extended guard also found evaluator_transition._regular_json, webarena_report._load_artifact, web_fetch/evidence._read and web_fetch/local_audit._read_bound_receipt, which are migrated too. The two web_fetch files are new to this PR; their base hashes have no hits in the scanned bindings.
  • P3, guard (6abb2f9c): it now rejects short loaders that end in a read_json-equivalent read after preconditions, and short writers that pass the json_bytes expression to an output call, with paired negative controls. Added behavior tests for load_failure_cause_review, read_public_json and write_diagnostic.

Short loaders that validate a schema or select a field, locale-encoded reads and importlib.resources reads stay, and the PR body lists them with reasons.

Disputed: none.

Local tests: lint passes. Guard, golden test and the 62 test files that reference a module edited this round: 1,175 passed, 4 skipped. Golden snapshots unchanged.

@lanyue-llk lanyue-llk left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review, round 5

Reviewed head: 6abb2f9c, base 27401304.

No defects found. There are no findings at any severity.

What I verified

  • CI at this head: "Tests and static checks", "Installation and packaging", "Rendered reference and report checks", Python 3.11 and the OCR review all pass.
  • Local gates: both ruff commands pass. tests/test_golden_reports.py and tests/test_shared_hash_json_helpers.py: 97 passed. tests/trajectory_replay, tests/test_webarena_state.py and tests/browser_use/test_failure_cause_review.py together with those two files: 2,200 passed, 5 skipped. I did not run the full suite locally; CI covers it.
  • Byte-level semantics: I extracted every function removed or changed in src/harness and compared old and new bodies. I also normalized helper names across the whole source diff and read every line that was not a plain rename.
    • json.dumps options match at each site, including the ensure_ascii=True and allow_nan=False callers. _case_ids_sha256 is unchanged because it hashes a sorted list of strings.
    • parents=True is passed where the old writer created parents, and not where it did not. _clean is still applied through _write_clean_json.
    • browser_use/report_check.py keeps the optional-hash None behaviour.
  • read_json against json.loads(read_text(encoding="utf-8")): a differential run gave the same value or the same error type for CRLF, bare CR between tokens, CR inside a string, non-ASCII text, NaN, an empty file and a BOM.
  • Call sites: an AST scan over src, scripts and tests found no helper shadowed by a local name, no undefined helper, no unresolved from harness... import, and no import of a shared helper through a non-owner module. web_search.core.write_json is the named atomic owner, and reporting/visual.py is a named exemption. No aliases were added. Removed test assertions were call-site renames.
  • Guard: I read each rule and its controls. My own scan of short functions found no remaining bare copy. The remaining functions have a real difference, such as chmod, schema checks, field selection, atomic replacement, a locale read or an importlib.resources read.
  • Scope claim: "Part of #91" is accurate, and the remaining work and the owner decision on inline forms are stated. I reproduced the body's counts: 217 (150), 46 (25), 830 (515) and 3 for file_digest. My count of hashlib.sha256(x.read_bytes()) is 115 (54) against the body's 113 (53), because my pattern does not require .hexdigest(). At least one extra is the .digest() form in webarena_report_package.tree_sha256; I did not identify the other.
  • Hash-bound inputs:
    • No base-commit hash of the 91 edited source files appears in evaluation, research, configs, tests, scripts or src.
    • word_f1 and snippet_check, which wcxb_scoring binds through inspect.getsource, are unchanged.
    • The source_code_sha256 checks in webmainbench_diagnostics compare retained correction-source copies, not live files.
  • Golden snapshots: only web-search manifest.json changed, as the body explains. I did not rebuild the base tree to reproduce that comparison.

Limits and one note

  • Data-home scan incomplete: my own scan for the base hashes under ~/.browser-eval did not finish within the time I allowed, so I did not independently reproduce the body's data-home result. It therefore rests on the author's scan.
  • Live gate not listed in the body: webarena_state.load_contracts compares a profile's rules.source_sha256 with the live source, and this PR edits that file. A form-state profile frozen before this PR would be rejected before a run. A search of the 29,906 JSON files under 2 MB in the scanned data-home directories found no webarena_observed_form_state/1, and the repository has none either, so nothing here is affected. This is not a finding.

lanyue-llk added a commit that referenced this pull request Nov 2, 2026
Replace private SHA-256, canonical JSON digest and JSON file helpers under src/harness with harness/record_io.py. Options that differ from the shared defaults stay explicit at the call site so every bound digest keeps its bytes. Guard the fully migrated names with a test.
Inline _attempts_sha256, _parameters_sha256 and write_agent_response, and replace the three text_digest copies with bytes_sha256(x.encode()) at each call site. The guard now rejects wrappers that only forward to a shared helper, so these forms cannot return unnoticed. Digests are unchanged.
_planned_actions_digest had one verifier caller and only tests used it to build fixtures, so it named no shared contract. Call canonical_json_sha256 directly and retire the name in the guard. Correct the guard's reason for keeping canonical digest names: task_definition_sha256 names a public protocol, and only scoring_revision_history_sha256 is shared by a writer and a verifier. Digests are unchanged.
Replace the three remaining digest-if-file-else-None expressions in report_build, reference_lifecycle and runner, and extend the guard to reject that form with negative controls for other returns, paths and readers. Digests are unchanged.
@lanyue-llk
lanyue-llk force-pushed the refactor/shared-hash-and-json-helpers branch from 6abb2f9 to bd6cb63 Compare November 3, 2026 06:19
@lanyue-llk

Copy link
Copy Markdown
Contributor Author

Rebased onto main at b951a7c (#133 to #138). The only golden snapshot this PR changes is still tests/golden/web-search.json, and only its manifest.json route hash. That hash moves because the manifest records renderer_sha256, the SHA-256 of web_search/report.py, and this PR edits that module to call bytes_sha256. With the builder identity pinned, the 19 normalized routes built from main and from this branch differ only in that field. This comparison ran on the rebase over #136; #138 does not touch the module or the snapshot, and the golden test passes on the final head. No HTML route and no other track's snapshot changed.

@lexmount-ocr lexmount-ocr Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Review complete · bd6cb63

No findings in this review.

@lanyue-llk
lanyue-llk merged commit e92e70c into main Nov 3, 2026
7 checks passed
@lanyue-llk
lanyue-llk deleted the refactor/shared-hash-and-json-helpers branch November 3, 2026 06:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Consolidate copy-pasted hashing, JSON I/O, data-home, dotenv and redaction helpers

1 participant