Skip to content

refactor(io): read and write all text files as explicit UTF-8 - #163

Merged
lanyue-llk merged 2 commits into
mainfrom
refactor/explicit-utf8-text-io
Nov 3, 2026
Merged

lanyue-llk merged 2 commits into
mainfrom
refactor/explicit-utf8-text-io

Conversation

@lanyue-llk

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

Copy link
Copy Markdown
Contributor

What, why and how of this PR

Issues

Closes #90
Closes #84

Remaining hash-bound files and subprocess pipes are tracked in #162.

Summary

Text files now use explicit UTF-8 instead of the host locale. A mechanical AST codemod added encoding="utf-8" to 5,106 read_text, write_text and text-mode open calls across src, scripts, tests, examples and .agents. Bytes on a UTF-8 host do not change. The diff is large but almost entirely mechanical; statements that passed the 100-column limit were reformatted individually.

Please review the receipt edit. Fixing #84 means editing src/lexbench_webfetch/risk_control_dataset.py, which code-migration.json binds. I updated its after_sha256 and added a correction entry with the root cause and test. It is the only receipt edit. The compiler is not in SCORING_SOURCE_FILES, so SCORING_SOURCE_SHA256 does not move.

Enforcement. tests/test_explicit_utf8_io.py is an AST guard with negative controls. I did not enable ruff PLW1514, for two reasons:

  • It found only 76 calls across the repository, because it sees only calls on inferred Path values.
  • Selecting it means editing pyproject.toml, which collection_implementation binds.

Regression test. The same file runs every track in tests/test_golden_reports.py in a subprocess with PYTHONUTF8=0 PYTHONCOERCECLOCALE=0 LC_ALL=C, and a probe confirms that environment really selects ASCII. PYTHONCOERCECLOCALE=0 is needed because Python otherwise upgrades the C locale to UTF-8.

Other non-mechanical changes

  • Three short JSON loaders now call read_json (lexbench/verification.py, local_execution_contract.py, local_execution_legacy.py). The explicit form is what tests/test_shared_hash_json_helpers.py rejects as a copy.
  • native_projection.py was tried and reverted: tests/fixtures/native-route-baseline.json freezes its hash.

Hash-bound files left unedited

Each is exempt in the guard with its reason and the number of implicit calls (38 in total).

Binding Files (calls)
Web Fetch scoring_source_sha256 lexbench_webfetch/scoring.py (1)
after_sha256 in code-migration.json lexbench_webfetch/cli.py (3), lexbench_webfetch/scoring_regressions.py (3)
Search scoring_source_sha256 and collection_implementation lexbench_websearch/qualification.py (1), relevance.py (1), rubric.py (2)
collection_implementation harness/web_search/runner.py (7)
Resource protocol orchestrator_sha256 harness/lexbench/resource_matrix.py (5), resource_profiles.py (7)
Copied to the public reproduction directory harness/lexbench/charts.py (2)
Visual receipts harness/reporting/visual.py (1), trajectory_replay/webarena_report_visual.py (1), web_search/visual.py (2)
Frozen native route baseline harness/web_fetch/native_projection.py (2)

Other named bindings needed no exemption because those files have no implicit calls: lexbench/reproduction.py, the frozen certifier text and scripts, webarena_state.py, wcxb_metrics.py, and the other collection_implementation sources.

Hashes that do move

  • runtime_source_sha256: it hashes every .py file under harness/web_fetch, as with any change there. Stored manifests still verify against stored plans, and no value is frozen in Git. A continuation plan written before this PR must finish on its old revision.
  • Self-hashes recorded at run time: runner_sha256, adapter_sha256, scorer_sha256 and review implementation_sha256, among others. New runs record new values and stored evidence keeps its own. I traced how these are used rather than testing each one against real evidence, because this environment has no private evidence to run against.
  • Resource image worker hash: providers/headless_worker.py is edited, and ContainerResources.validate() compares its hash with the copy inside the resource image. Resource images built before this PR are rejected until rebuilt with make resource-image. Stored evidence is not affected.

Golden snapshots

One route changed: web-search.json manifest.json. It records renderer_sha256 for harness/web_search/report.py, which this PR edits. Swapping the old hash back into the new manifest reproduces the old snapshot digest (ec03e220...), so nothing else in that file changed.

Test plan

  • Regression control: at base 6c97f2cc, the Web Fetch and WCXB golden builds under the ASCII locale fail with UnicodeEncodeError. On this branch all 10 golden builds pass under it, byte-identical to the snapshots.
  • Risk-control compiler relies on locale encoding for UTF-8 definitions and output #84 reproduction: at base it raises UnicodeDecodeError under US-ASCII; on this branch it succeeds. test_local_compilation_works_offline_in_a_fresh_process now also runs in the ASCII locale and reads the output back as UTF-8.
  • Focused run: the guard, golden, native route, shared helper, migration receipt, compiler, catalog and packaging tests gave 454 passed.
  • Review round 1 (guard change only, no source edits): tests/test_explicit_utf8_io.py and tests/test_golden_reports.py gave 69 passed, and both ruff commands pass. The stricter guard found no new implicit call and left the exemption counts unchanged.
  • Lint gate: both ruff commands pass.
  • Full local suite: this was not clean, and it ran before the native_projection.py revert, the last formatting fix and the final regression test change.
    • In the worktree: 72 failed, 19,344 passed. Most hit Historical benchmark source is not recorded in the dataset lock, because this worktree is nested inside a checkout with an older evaluation/lexbench-webfetch.json.
    • In a copy outside that checkout: 28 failed, 19,414 passed. The failures are the known macOS and missing-node_modules list, tests that need .git (absent from the copy), the native baseline since fixed, and test_optional_reports, whose subprocess imports the shared environment's checkout.
    • test_run_inputs_bind_resolved_routing_and_stop_when_it_changes failed once in the worktree run and passed when rerun without the full suite. I did not find the cause.
  • CI (Linux, full-suite gate): all checks pass on the final commit, including "Tests and static checks" and "Installation and packaging".

@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 · 22c7623

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: 22c7623f. I found no correctness defects, no broken hash binding and no CI failures. Two P3 items are worth a small follow-up commit.

Findings

P3: the guard fails open on text opens it cannot classify (tests/test_explicit_utf8_io.py:47, :73, :76, with OTHER_OPENERS at :43)

Problem: implicit_encoding_lines returns [] for all of these, and each one uses the locale encoding:

  • open(path, mode) and path.open(mode), because a non-constant mode counts as binary
  • io.open(path, "w") and builtins.open(path), because the mode is read from position 0, which holds the path
  • gzip.open(path, "rt"), because gzip is on the skip list
  • lzma.open(path, "rt"), because the mode is read from position 0
  • io.TextIOWrapper(stream), because it is not checked at all

No such call exists in the repository today (I checked every .py file with a separate AST scan), so nothing is broken now. But #90 asks for enforcement, and a later open(path, mode) would pass silently.

Fix:

  • Treat a non-constant mode as needing an encoding; explicit binary callers can still pass a constant mode.
  • Read the mode from position 1 when the receiver is a module-style opener (io, builtins, gzip, bz2, lzma).
  • Flag text modes on gzip, and flag TextIOWrapper without an encoding.
  • Add these cases to test_guard_rejects_locale_dependent_text_io.

P3: the PR body omits one live check that moves (src/harness/web_fetch/providers/headless_worker.py, checked at src/harness/web_fetch/container_resources.py:71 and :78)

Problem: this PR edits headless_worker.py. validate() compares that file's hash with the copy inside the resource image, and raises Resource image worker differs from the selected runtime; rebuild the declared image on a mismatch. So every resource image built before this PR is rejected until it is rebuilt. "Hashes that do move" describes only values recorded at run time, plus continuation plans.

Stored evidence is not affected, and the error message says what to do, so this is an operator note and not a defect.

Fix: add one line to "Hashes that do move" saying that existing resource images need make resource-image.

What I verified

Mechanical diff. I parsed both sides of the changed Python files (the other three changed files, CONTRIBUTING.md, code-migration.json and tests/golden/web-search.json, I read as diffs) and stripped encoding="utf-8". Only these differ beyond that:

  • the new guard
  • the three read_json swaps; read_json decodes strict UTF-8 and behaves the same as json.loads(read_text(encoding="utf-8")), including rejecting a BOM
  • the parametrized #84 test
  • Python source embedded in test strings

Remaining implicit calls. A separate AST scan of every tracked .py file found exactly the 38 exempt calls in the 14 listed files, plus only binary, non-file or positional-encoding calls. The table in the PR body matches the guard's counts. No .read_text(encoding=...) landed on a Distribution-style receiver that lacks that parameter.

Hash bindings.

  • I hashed the base blob of every changed file and searched all 1,526 tracked files for those digests. The only hit is risk_control_dataset.py in code-migration.json, which is the disclosed edit.
  • tests/benchmarks/test_current_scoring_controls.py requires after_sha256 to equal the current file, so updating it with a correction entry is the intended route.
  • None of the fixed collection_implementation sources, lexbench_websearch/*.py or SCORING_SOURCE_FILES changed.
  • metric_implementation_binding hashes wcxb_metrics.py, which is unchanged, and the webmainbench-latency-source.json registry and its frozen certifier artifact are unchanged.
  • No .json file in the local evidence, implementations or reviews directories contains a base digest of a changed src or scripts file. Evidence published elsewhere could not be checked from here.
  • The other self-hashes that move (scorer_sha256, runner_sha256, review implementation_sha256, renderer_sha256) are recorded at run time, compared with stored values, or only trigger a rebuild.

Golden snapshots. The only change is web-search.json manifest.json, which records renderer_sha256 for the edited web_search/report.py.

Regression tests.

  • At base, 8 of the 10 golden builds fail under PYTHONUTF8=0 PYTHONCOERCECLOCALE=0 LC_ALL=C. All 10 pass at this head, byte-identical to the snapshots. This is stronger than the PR body's claim, which names only Web Fetch and WCXB.
  • The issue's #84 snippet prints US-ASCII and now completes.
  • Making the compiler's final write implicit again fails test_local_compilation_works_offline_in_a_fresh_process[ascii-locale]. So does making its rule read implicit again. The test covers compilation and the UTF-8 read-back that #84 asks for.

Issue scope. Closes #90 and Closes #84 hold, with the exempt files and subprocess pipes tracked in open issue #162. I confirmed the PR's figure for ruff PLW1514: 76 findings at base with ruff 0.16.7 and --preview, which supports using the AST guard instead.

Test runs at this head.

  • Both ruff lint commands pass.
  • Guard, golden, compiler and shared-helper tests: 137 passed.
  • Scoring controls, Search scoring provenance and native route contract tests: 151 passed.
  • test_run_inputs_bind_resolved_routing_and_stop_when_it_changes passed when run alone. I did not run the full suite locally, so the failure the PR reports in its full worktree run remains unexplained.

CI. All checks pass on this head, and the PR is mergeable. "Tests and static checks" reports 19,345 passed and 157 skipped, and its timing output confirms the guard test ran.

@lanyue-llk

Copy link
Copy Markdown
Contributor Author

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

  • Guard fails open on text opens it cannot classify (P3): fixed in 3e30491.
    • A mode known only at run time now counts as text. A conditional mode counts as text if either branch can be.
    • io and builtins openers read the mode from the second argument.
    • gzip, bz2 and lzma are flagged when the mode has t and no encoding is given. A bare r stays binary, as it does in those modules.
    • TextIOWrapper without an encoding is flagged, and so is path.open(newline="").
    • The new cases are in test_guard_rejects_locale_dependent_text_io, with matching binary and explicit controls in test_guard_keeps_binary_and_explicit_io.
    • The stricter guard found no new implicit call in the repository. Its one new hit, target.open("r+b" if existing else "wb") in map_setup.py, is binary, so the guard now reads conditional modes. Exemption counts are unchanged.
  • Resource image hash missing from the PR body (P3): fixed by editing the PR body, so there is no commit. "Hashes that do move" now says that existing resource images need make resource-image.

@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 skipped · 3e30491

No reviewable content was selected for this run.

@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: 3e304913. No defects found. Round 1's two P3 findings are resolved: the guard change is in the commit and the resource image note is in the PR body.

What I verified

The change is mechanical.

  • I compared the AST of every changed Python file with base 6c97f2cc, after removing encoding="utf-8" keywords.
  • Only seven files differ beyond that keyword. Three are the read_json swaps. Four are tests with test edits or embedded child scripts, and I read their diffs.
  • The added keywords are 2,831 write_text, 2,260 read_text, 11 open and 1 fdopen. None of the open or fdopen calls is binary or on a zipfile-style object, so none can raise at run time.
  • No repository class with its own read_text or write_text signature received the keyword.

The read_json swaps keep their semantics. The helper is json.loads(raw.decode("utf-8")). That matches a strict UTF-8 text read for JSON, because newline translation cannot change a valid document.

Hash bindings still hold.

  • I took the base SHA-256 and git blob hash of every edited file and searched all of Git at this head for them: no matches.
  • I ran the same SHA-256 search, read-only, over the JSON, JSONL and TOML files in the local data home's evidence, datasets and reviews directories. That home holds only research cohorts, with no current evidence tree.
  • The only match is harness/lexbench/pack.py, in the harness_files map of three pre-call contract files. No code in src or scripts reads that field.
  • Bound sources are unedited, as claimed: collection_implementation, SCORING_SOURCE_FILES (only risk_control_dataset.py changed under lexbench_webfetch), webarena_state.py, wcxb_metrics.py, web_search/pages.py and the visual checkers.
  • The self-hashes in edited files are written at run time or compared with values captured in the same run: wcxb_scoring.py, rescoring.py and remote_runtime.py.
  • The code-migration.json edit is the only receipt change. tests/benchmarks/test_current_scoring_controls.py and tests/benchmarks/websearch/test_scoring_provenance.py pass.

The golden change is what the PR says. I built all 10 tracks at base and at this head with GOLDEN_KEEP and ran diff -r. The only difference is the renderer_sha256 line in web-search/manifest.json.

The new controls fail without the fix. I copied this head's tests/test_explicit_utf8_io.py and tests/benchmarks/webfetch/test_risk_control_compiler.py onto base, and three tests failed:

  • the guard
  • the ASCII-locale report build, with 8 of 10 golden builds failing
  • test_local_compilation_works_offline_in_a_fresh_process[ascii-locale]

The PR's test plan names only the Web Fetch and WCXB builds, so it understates the first of these. The last one covers #84's compilation case and the UTF-8 consumer roundtrip.

Local runs at this head. Both ruff commands pass. The guard, golden, compiler, shared-helper, scoring-provenance and reproduction targets all pass (167 and 21 tests). I did not run the full suite locally and relied on CI for it.

Scope.

  • Closes #90 and Closes #84 match the standing rule. The 38 exempt calls and the subprocess pipes are tracked in #162.
  • The exemption table's counts add up to 38 and match the guard.
  • Python embedded in strings and non-Python files has no locale-sensitive read of non-ASCII data. What remains is ASCII-only test child scripts, the .python-version read in the Makefile, and one line in ci.yml, which this token cannot edit.

CI at this head. All checks pass: "Tests and static checks", "Installation and packaging", "Rendered reference and report checks", "Python 3.11", "Select check scope" and "OCR dispatch". The PR is mergeable against main at 6c97f2cc.

Considered and not raised

The guard still accepts Path.read_text(path), Path.write_text(path, value), read_text(encoding=None) and aliased imports such as from io import open as o. None of these forms exists in the repository, and catching them would add complexity for little benefit, so I am not asking for a change.

lanyue-llk added a commit that referenced this pull request Nov 3, 2026
Add encoding="utf-8" to every text read, write and text-mode open with a mechanical codemod, so Chinese HTML and JSON no longer follow the host locale. Guard every call with an AST test, because ruff PLW1514 only sees calls on inferred Path values and the ruff config lives in pyproject.toml, which collection_implementation binds.

Files whose bytes frozen evidence compares with current source stay unedited and are listed in the guard with the number of calls left implicit.

The risk-control compiler is the one exception: it records a new correction and after_sha256 in code-migration.json. Three short JSON loaders now call read_json, since the explicit form is what the shared helper guard rejects.
Treat a mode known only at run time as text, read the mode from the second
argument of module-style openers, and flag text modes on gzip, bz2, lzma and
TextIOWrapper without an encoding.
@lanyue-llk
lanyue-llk force-pushed the refactor/explicit-utf8-text-io branch from 3e30491 to a925a54 Compare November 3, 2026 14:36

@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 · a925a54

No findings in this review.

@lanyue-llk
lanyue-llk merged commit a239d1c into main Nov 3, 2026
7 checks passed
@lanyue-llk
lanyue-llk deleted the refactor/explicit-utf8-text-io branch November 3, 2026 14:44
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.

Read and write all text files as explicit UTF-8 Risk-control compiler relies on locale encoding for UTF-8 definitions and output

1 participant