Repository navigation
refactor(io): read and write all text files as explicit UTF-8 - #163
Conversation
There was a problem hiding this comment.
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)andpath.open(mode), because a non-constant mode counts as binaryio.open(path, "w")andbuiltins.open(path), because the mode is read from position 0, which holds the pathgzip.open(path, "rt"), becausegzipis on the skip listlzma.open(path, "rt"), because the mode is read from position 0io.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 flagTextIOWrapperwithout 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_jsonswaps;read_jsondecodes strict UTF-8 and behaves the same asjson.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.pyincode-migration.json, which is the disclosed edit. tests/benchmarks/test_current_scoring_controls.pyrequiresafter_sha256to equal the current file, so updating it with a correction entry is the intended route.- None of the fixed
collection_implementationsources,lexbench_websearch/*.pyorSCORING_SOURCE_FILESchanged. metric_implementation_bindinghasheswcxb_metrics.py, which is unchanged, and thewebmainbench-latency-source.jsonregistry and its frozen certifier artifact are unchanged.- No
.jsonfile in the local evidence, implementations or reviews directories contains a base digest of a changedsrcorscriptsfile. Evidence published elsewhere could not be checked from here. - The other self-hashes that move (
scorer_sha256,runner_sha256, reviewimplementation_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-ASCIIand 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_changespassed 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.
|
Review round 1: both findings are fixed and none are disputed.
|
There was a problem hiding this comment.
ℹ️ Review skipped · 3e30491
No reviewable content was selected for this run.
lanyue-llk
left a comment
There was a problem hiding this comment.
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 removingencoding="utf-8"keywords. - Only seven files differ beyond that keyword. Three are the
read_jsonswaps. Four are tests with test edits or embedded child scripts, and I read their diffs. - The added keywords are 2,831
write_text, 2,260read_text, 11openand 1fdopen. None of theopenorfdopencalls is binary or on azipfile-style object, so none can raise at run time. - No repository class with its own
read_textorwrite_textsignature 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 theharness_filesmap of three pre-call contract files. No code insrcorscriptsreads that field. - Bound sources are unedited, as claimed:
collection_implementation,SCORING_SOURCE_FILES(onlyrisk_control_dataset.pychanged underlexbench_webfetch),webarena_state.py,wcxb_metrics.py,web_search/pages.pyand 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.pyandremote_runtime.py. - The
code-migration.jsonedit is the only receipt change.tests/benchmarks/test_current_scoring_controls.pyandtests/benchmarks/websearch/test_scoring_provenance.pypass.
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 #90andCloses #84match 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-versionread in the Makefile, and one line inci.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.
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.
3e30491 to
a925a54
Compare
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,106read_text,write_textand text-modeopencalls acrosssrc,scripts,tests,examplesand.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, whichcode-migration.jsonbinds. I updated itsafter_sha256and added a correction entry with the root cause and test. It is the only receipt edit. The compiler is not inSCORING_SOURCE_FILES, soSCORING_SOURCE_SHA256does not move.Enforcement.
tests/test_explicit_utf8_io.pyis an AST guard with negative controls. I did not enable ruffPLW1514, for two reasons:Pathvalues.pyproject.toml, whichcollection_implementationbinds.Regression test. The same file runs every track in
tests/test_golden_reports.pyin a subprocess withPYTHONUTF8=0 PYTHONCOERCECLOCALE=0 LC_ALL=C, and a probe confirms that environment really selects ASCII.PYTHONCOERCECLOCALE=0is needed because Python otherwise upgrades the C locale to UTF-8.Other non-mechanical changes
read_json(lexbench/verification.py,local_execution_contract.py,local_execution_legacy.py). The explicit form is whattests/test_shared_hash_json_helpers.pyrejects as a copy.native_projection.pywas tried and reverted:tests/fixtures/native-route-baseline.jsonfreezes 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).
scoring_source_sha256lexbench_webfetch/scoring.py(1)after_sha256incode-migration.jsonlexbench_webfetch/cli.py(3),lexbench_webfetch/scoring_regressions.py(3)scoring_source_sha256andcollection_implementationlexbench_websearch/qualification.py(1),relevance.py(1),rubric.py(2)collection_implementationharness/web_search/runner.py(7)orchestrator_sha256harness/lexbench/resource_matrix.py(5),resource_profiles.py(7)harness/lexbench/charts.py(2)harness/reporting/visual.py(1),trajectory_replay/webarena_report_visual.py(1),web_search/visual.py(2)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 othercollection_implementationsources.Hashes that do move
runtime_source_sha256: it hashes every.pyfile underharness/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.runner_sha256,adapter_sha256,scorer_sha256and reviewimplementation_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.providers/headless_worker.pyis edited, andContainerResources.validate()compares its hash with the copy inside the resource image. Resource images built before this PR are rejected until rebuilt withmake resource-image. Stored evidence is not affected.Golden snapshots
One route changed:
web-search.jsonmanifest.json. It recordsrenderer_sha256forharness/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
6c97f2cc, the Web Fetch and WCXB golden builds under the ASCII locale fail withUnicodeEncodeError. On this branch all 10 golden builds pass under it, byte-identical to the snapshots.UnicodeDecodeErrorunderUS-ASCII; on this branch it succeeds.test_local_compilation_works_offline_in_a_fresh_processnow also runs in the ASCII locale and reads the output back as UTF-8.tests/test_explicit_utf8_io.pyandtests/test_golden_reports.pygave 69 passed, and both ruff commands pass. The stricter guard found no new implicit call and left the exemption counts unchanged.native_projection.pyrevert, the last formatting fix and the final regression test change.Historical benchmark source is not recorded in the dataset lock, because this worktree is nested inside a checkout with an olderevaluation/lexbench-webfetch.json.node_moduleslist, tests that need.git(absent from the copy), the native baseline since fixed, andtest_optional_reports, whose subprocess imports the shared environment's checkout.test_run_inputs_bind_resolved_routing_and_stop_when_it_changesfailed once in the worktree run and passed when rerun without the full suite. I did not find the cause.