Skip to content

Pin utf-8 on shipping-code text I/O instead of the operator locale - #7486

Merged
danielhanchen merged 7 commits into
mainfrom
fix-runtime-text-encoding-v2
Jul 27, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
fix-runtime-text-encoding-v2

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

Problem

Path.read_text(), Path.write_text() and open() with no encoding use locale.getencoding(). That is utf-8 on the Linux and macOS runners, and cp1252 on a stock Windows install (cp932 in Japan, cp949 in Korea, cp1251 in Russia). So the same file decodes differently depending on who is running it.

The failure has two shapes, and the quiet one is worse:

  • cp1252 leaves five bytes undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D), so a file containing one raises UnicodeDecodeError.
  • Every other non-ASCII byte decodes to the wrong character instead, so the read succeeds and returns mojibake.

This is the shipping-code counterpart to #7438, which fixed the same defect in the test trees.

What this changes

Across unsloth/, studio/ and unsloth_cli/, 39 files:

  • 111 call sites gain encoding = "utf-8". That includes the one live ConfigParser.read("/etc/wsl.conf"), which had no encoding either.
  • 3 reads of Python source in remote_code_scan.py instead go through a new _read_python_source, which honours the PEP 263 cookie via tokenize.detect_encoding. Forcing utf-8 there would make the scanner read something other than what Python executes, and since remote_code_fingerprint hashes decoded text, two different cp1252 sources could collapse onto the same replacement characters and keep an existing approval.
  • 1 read (the JSONL dedup preload in the data-designer plugin) gains errors = "replace" so a file an older build wrote in the operator's locale is read past rather than aborting the preload. That file is deliberately left byte for byte intact: no encoding guess is safe, because a single-byte codepage round-trips almost any bytes.

Adds tests/test_runtime_text_encoding.py so it stays fixed. The guard resolves openers through the imports visible in each call's own lexical scope, rather than a fixed list of module names, because the name alone settles nothing in either direction:

  • import tarfile as tf hides an opener that takes no encoding behind an unfamiliar name.
  • from PIL.Image import open puts one behind the most familiar name there is.

Also exempt: zipfile.ZipFile(p).open(name) and the same object held in a variable, importlib.metadata Distribution.read_text(filename), binary modes, and calls whose mode is not a literal, where demanding an encoding would leave no correct edit. gzip, bz2 and lzma are in scope only in an explicit text mode, since they default to "rb". encoding = locale.getencoding() is reported, since that is the platform default written out.

Verification

  • AST equivalence on the mechanical part: stripping the added encoding = "utf-8" reproduces the original tree exactly, with zero other differences.
  • The applier routed through the guard's own _offender, so nothing was handed an encoding it rejects.
  • Adversarial corpus over the guard: 13 shapes, 0 false positives and 0 false negatives, covering every exemption above.
  • Backend suite, this branch against main at the same commit: 52 failed / 9902 passed on both, identical.
  • Repo suite: same failure count as main.
  • Guard reports 0 offenders over the 403 shipping files it scans, and only files git is tracking, so a stale build/lib artifact cannot fail it.

Follow-up

A read that used to return mojibake on Windows now raises instead. #7487 adds UnicodeDecodeError to the handlers where that would otherwise escape a helper written to fail closed. It is a behaviour change rather than a mechanical one, so it is a separate PR based on this branch.

113 read_text/write_text/open call sites across unsloth, studio and
unsloth_cli let locale.getencoding() decide the encoding. That is utf-8 on
the Linux and macOS runners and cp1252 on a stock Windows install, so the
same file decodes differently for a Windows user and silently produces
mojibake or raises UnicodeDecodeError.

Adds tests/test_runtime_text_encoding.py to keep it that way. It resolves
openers through each file's own imports rather than a fixed list of module
names, so an aliased tarfile.open or a local from PIL.Image import open is
not asked for an encoding it does not take.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d9d2af8c7b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/test_runtime_text_encoding.py Outdated
for root in ROOTS:
if not root.is_dir():
continue
for path in sorted(root.rglob("*.py")):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Exclude generated build trees from the scan

When either Studio plugin has previously been built, this recursively scans its ignored build/lib copy as shipping source, so stale artifacts can fail the test even though every tracked source file is compliant. In the provided clean worktree, running python -m pytest -q tests/test_runtime_text_encoding.py reports five offenders solely under the two plugin build/lib directories; restrict the scan to tracked files or explicitly skip build directories.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. Switched the scan from rglob to git ls-files, with the walk kept as a fallback when the tree is not a checkout. A walk picks up whatever happens to be lying around, a built build/lib copy of a plugin being the case you hit, and none of that is ours to police. Also added build and dist to SKIP_DIRS so the fallback path behaves the same. Scope is now 403 shipping files out of 1008 tracked.

Verified in faf7b51: guard self-tests pass, adversarial corpus 13 shapes 0 false positives / 0 false negatives, shipping tree still 0 offenders.

Comment thread tests/test_runtime_text_encoding.py Outdated
Comment on lines +185 to +186
if func.attr == "read_text" and call.args:
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Detect positional locale encodings on Path.read_text

When a real Path.read_text call supplies its encoding positionally, this blanket exemption treats it as importlib.metadata.Distribution.read_text and skips validation. For example, Path("x").read_text(None) legally selects the locale default but _offenders_in returns no offender, allowing the exact Windows decoding regression this guard is intended to prevent; distinguish known Path receivers before applying the foreign-reader exemption.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. The blanket read_text exemption on any positional is now narrowed: a positional that is literally None or "locale" re-selects the platform default and is reported, anything else is importlib.metadata.Distribution.read_text, whose argument is a filename and which takes no encoding at all.

Path("x").read_text(None)                    flagged
Path("x").read_text("locale")                flagged
distribution("x").read_text("METADATA")      not flagged

Verified in faf7b51: guard self-tests pass, adversarial corpus 13 shapes 0 false positives / 0 false negatives, shipping tree still 0 offenders.

Comment thread tests/test_runtime_text_encoding.py Outdated
return None
if _foreign_receiver(func.value, modules):
return None
if not _is_text(call, 0):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Handle the unbound Path.open calling form

When text I/O is written as the valid unbound call Path.open(path), _is_text(call, 0) interprets the path argument as the mode, classifies it as unknown, and emits no offender. Consequently a new locale-dependent open can bypass this guard merely by using the class-form method; resolve Path-class receivers and inspect mode at positional index 1 for unbound calls.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. Added _is_path_class and a shift, so an unbound Path.open(p) or Path.read_text(p) has the instance in slot 0 and the mode is read from index 1. Resolves aliases too, so from pathlib import Path as P then P.read_text(p) is caught. Path.open(p, "rb") correctly stays quiet.

Verified in faf7b51: guard self-tests pass, adversarial corpus 13 shapes 0 false positives / 0 false negatives, shipping tree still 0 offenders.


try:
manifest = json.loads(tag_file.read_text())
manifest = json.loads(tag_file.read_text(encoding = "utf-8"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Catch decoding failures while scanning Ollama manifests

On Windows installations where an existing Ollama manifest contains a non-UTF-8 byte that the previous single-byte locale could decode, read_text(encoding = "utf-8") now raises UnicodeDecodeError, which is not covered by this JSONDecodeError/OSError handler. Instead of logging and skipping the unreadable manifest as intended, one such file aborts model inventory; include decoding errors in the invalid-manifest fallback (and the equivalent config-blob path).

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, and this is exactly what #7487 does: it adds UnicodeDecodeError to that handler and to the config-blob path two functions down, along with 31 others in the same shape. I split it out because pinning the encoding is mechanical and AST-provable while widening a handler is a real behaviour change, and #7487 is based on this branch so they land in order.

Selection there was mechanical rather than by eye: a handler qualifies only if it already misses UnicodeDecodeError, ValueError, Exception and BaseException, and every arm is fail-closed.

Verified in faf7b51: guard self-tests pass, adversarial corpus 13 shapes 0 false positives / 0 false negatives, shipping tree still 0 offenders.

Comment thread tests/test_runtime_text_encoding.py Outdated
Comment on lines +35 to +37
-- the exact failure mode this guard is built to avoid. The one live
`ConfigParser.read` in the tree (/etc/wsl.conf, hub/utils/paths.py) names its
encoding; a future one has to be caught in review.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Pin the live ConfigParser read before exempting it

This assertion about the only live ConfigParser.read call is false: studio/backend/hub/utils/paths.py still calls parser.read("/etc/wsl.conf") without an encoding. Under a non-UTF-8 WSL locale, a UTF-8 config containing non-ASCII text raises during parsing, the surrounding broad handler silently falls back to /mnt/, and custom automount roots are translated incorrectly; pass encoding = "utf-8" at that call rather than leaving the known live exception outside the guard.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, the assertion was simply false: hub/utils/paths.py:127 did call parser.read("/etc/wsl.conf") bare. Pinned it, and reworded the docstring to say the call is pinned by hand rather than claiming it already named an encoding. The guard still does not try to police ConfigParser.read in general, since resp.read(limit) and handle.read(chunk) are spelled identically and flagging those would leave no compliant edit.

Verified in faf7b51: guard self-tests pass, adversarial corpus 13 shapes 0 false positives / 0 false negatives, shipping tree still 0 offenders.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: faf7b517e2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +433 to +435
files[str(p.relative_to(root))] = p.read_text(
errors = "replace", encoding = "utf-8"
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Decode Python sources using their declared encoding

When an auto_map source has a valid PEP 263 encoding cookie such as # coding: cp1252, Python executes it using that declared encoding, but this read now forces UTF-8 and replaces every invalid byte. On a Windows cp1252 installation this changes previously exact input into lossy text, so the scanner examines content different from what Python executes and remote_code_fingerprint can hash distinct source bytes identically (for example, different cp1252 characters both become U+FFFD), allowing a local model's stored approval to survive a semantic source change. Decode through Python's source-encoding detection and/or fingerprint the original bytes.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, and this was a regression my own diff introduced. errors = "replace" was already there; adding encoding = "utf-8" is what made a cp1252-cookied source lossy on a Windows box, where the previous locale read decoded it exactly.

Fixed by decoding the way Python itself does, through tokenize.detect_encoding (PEP 263), in a new _read_python_source:

cp1252 cookie -> "S = 'caf\u00e9 na\u00efve'"   lossless, no U+FFFD
old behaviour  -> "S = 'caf\ufffd na\ufffdve'"   lossy
two distinct cp1252 sources now hash differently
plain utf-8 unchanged, undecodable file still returns text rather than raising

On the fingerprint half: I left remote_code_fingerprint hashing decoded text rather than raw bytes. Switching it would be more robust against genuinely undecodable input, but it changes every stored fingerprint and so silently invalidates existing approvals, which needs a migration rather than a one-line change. The decode fix removes the lossy path for every well-formed source, which is the reachable case here.

Verified in 9cfb86e: guard self-tests pass, shipping tree still 0 offenders, 112 remote_code/consent backend tests pass.

Comment thread tests/test_runtime_text_encoding.py Outdated
Comment on lines +190 to +193
receiver = func.value.id if isinstance(func.value, ast.Name) else None
# `Path.read_text(p)` is the unbound spelling of `p.read_text()`: the
# instance takes slot 0, so every argument shifts one place right.
shift = 1 if _is_path_class(receiver, modules) else 0

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Recognize fully qualified pathlib classes

For valid unbound spellings such as pathlib.Path.read_text(path) and pathlib.Path.open(path), func.value is an ast.Attribute, so receiver becomes None and shift remains zero. The read is then mistaken for a foreign Distribution.read_text(filename) call, while the open treats the path argument as an unknown mode; both return no offender even though they use the platform-default encoding. Resolve qualified pathlib receivers so these calls cannot bypass the new repository-wide guard.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. I had added _is_path_class for Name receivers but not the qualified form, so pathlib.Path.read_text(path) still fell through to the Distribution exemption and pathlib.Path.open(path) read the path as a mode. Added _is_path_attr and folded it into the same shift.

pathlib.Path.read_text(p)   flagged
pathlib.Path.open(p)        flagged
pathlib.Path.open(p, "rb")  not flagged
distribution(x).read_text("MD")  not flagged

Verified in 9cfb86e: guard self-tests pass, shipping tree still 0 offenders, 112 remote_code/consent backend tests pass.

self.path.parent.mkdir(parents = True, exist_ok = True)
self._lock = threading.Lock()
self._fh = self.path.open("a", buffering = 1)
self._fh = self.path.open("a", buffering = 1, encoding = "utf-8")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Migrate legacy JSONL before appending UTF-8

On a non-UTF-8 Windows installation, resuming a scrape whose JSONL was created by the previous version can corrupt the output: write() uses ensure_ascii=False, so existing non-ASCII records were encoded with the old locale (for example cp1252), while this append handle now writes UTF-8 into the same file. The UTF-8 preload below also stops at the first legacy byte that cannot be decoded, leaving later keys absent from _count_seen_keys; the resumed scrape can therefore append duplicate records and produce a mixed-encoding dataset. Detect or migrate an existing file's legacy encoding before opening it for UTF-8 append.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct: the append handle and the dedup preload both moved to utf-8, so a JSONL an older build wrote in cp1252 would break the preload at the first bad byte, and the outer except swallowed it, losing every key after that point and re-appending those records into a file that then held two encodings.

Added _migrate_legacy_encoding, called before the append handle opens: if the existing file is not valid utf-8 it is decoded with the operator's locale and rewritten as utf-8 through a temp file and os.replace. Verified against a cp1252 file holding two records:

keys preloaded: ['id:1', 'id:2']   (both, so no duplicate append)
file afterwards: valid utf-8
re-writing record 1: suppressed as already present

Verified in 9cfb86e: guard self-tests pass, shipping tree still 0 offenders, 112 remote_code/consent backend tests pass.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9cfb86ea93

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

f"{model_name}: present file {fn} could not be fetched ({exc})"
) from exc
files[fn] = Path(fp).read_text(errors = "replace")
files[fn] = Path(fp).read_text(errors = "replace", encoding = "utf-8")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Decode downloaded Python with the PEP 263-aware helper

When a Hub model ships a .py file with a non-UTF-8 PEP 263 cookie, this branch—and the corresponding external-repo branch—still decodes it as UTF-8 instead of using the newly added _read_python_source. Invalid bytes are replaced, so the scanner and fingerprint operate on different source from what Python executes; distinct executable byte sequences can even collapse to the same replacement characters and retain an existing approval fingerprint. Use the PEP 263-aware helper for every downloaded Python file.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed, my previous fix was incomplete: I converted the local rglob branch and left the two downloaded-file branches on read_text(errors = "replace", encoding = "utf-8"). Both now call _read_python_source, so all three sites decode a Hub .py the way Python executes it. Grep confirms no remaining raw decode of a Python source in that module.

Verified in 6ca5972: guard self-tests pass, adversarial corpus 13 shapes 0 false positives / 0 false negatives, shipping tree still 0 offenders.

return
except UnicodeDecodeError:
pass
text = data.decode(locale.getpreferredencoding(False), errors = "replace")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid destructively guessing the legacy file encoding

When an existing resume file was written under a different locale, or a user enables Python UTF-8 mode after it was written, getpreferredencoding(False) describes the current process rather than the file's original encoding. Decoding with errors = "replace" and then replacing the original file silently corrupts record contents and deduplication keys. Migration should preserve the original unless decoding is lossless or the legacy encoding is known explicitly.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, and the sharper point is that mine was destructive on a wrong guess: getpreferredencoding(False) describes the current process, and I then overwrote the original with an errors = "replace" decode of it.

The migration now only proceeds when the guess is provably right: decode strictly with the locale encoding, re-encode, and rewrite only if the bytes round-trip. Anything else leaves the file exactly as it was. To keep the dedup correct in that case, the preload reads with errors = "replace", so a mangled key is at worst one possible duplicate rather than a lost key and a re-append.

cp1252 file, cp1252 host   migrated=True   valid utf-8 after   keys=['id:1','id:2']
cp1252 file, utf-8  host   migrated=False  bytes untouched     keys=['id:1','id:2']
undecodable bytes          migrated=False  bytes untouched     keys=['id:3']

Verified in 6ca5972: guard self-tests pass, adversarial corpus 13 shapes 0 false positives / 0 false negatives, shipping tree still 0 offenders.

Comment thread tests/test_runtime_text_encoding.py Outdated
up to date.
"""
bound = {}
for node in ast.walk(tree):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Track imports in their lexical scope

When one function contains a local import such as from PIL.Image import open and another function uses the builtin open, walking the entire module records the local import as a global binding. _open_alias consequently exempts the unrelated builtin call, allowing locale-dependent text I/O to pass the new guard. Resolve bindings within the call's lexical scope rather than aggregating every import in the module.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. _imported_names walked the whole module, so a function-local from PIL.Image import open was recorded as a module binding and exempted every other function's builtin open. It now stops at nested function bodies, and a new _imports_at_each_call gives each call the imports visible in its own scope.

local PIL import, sibling function's open("t.txt")   flagged
the PIL call inside that same function               not flagged

Verified in 6ca5972: guard self-tests pass, adversarial corpus 13 shapes 0 false positives / 0 false negatives, shipping tree still 0 offenders.

return None
if not _is_text(call, shift):
return None
return None if _names_encoding(call) else "Path.open()"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Exempt open methods on assigned foreign objects

When a foreign object is assigned before use—for example, z = zipfile.ZipFile(path); z.open("item")—the detector cannot associate z with its imported constructor and classifies the call as Path.open(). The guard then demands an encoding argument that ZipFile.open does not accept, so otherwise valid shipping code cannot pass CI. Extend receiver resolution beyond inline constructor calls or restrict the fallback to receivers known to be paths.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. Added _foreign_names, which collects names assigned from a foreign constructor, so z = zipfile.ZipFile(p) then z.open("item") is exempt rather than being asked for an encoding ZipFile.open does not take. This was the false-positive direction, so it would have blocked otherwise valid shipping code in CI.

Verified in 6ca5972: guard self-tests pass, adversarial corpus 13 shapes 0 false positives / 0 false negatives, shipping tree still 0 offenders.

continue
if isinstance(kw.value, ast.Constant) and kw.value.value in (None, "locale"):
return False
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject explicit calls that still select the locale encoding

When code passes encoding = locale.getencoding() or locale.getpreferredencoding(False), _names_encoding accepts it because it rejects only the literal values None and "locale". Those expressions are precisely the operator-dependent encodings this guard is intended to eliminate, so such a call silently passes the regression test. Recognize the locale encoding call shapes as platform defaults rather than treating every non-constant expression as pinned.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. _names_encoding only rejected the literals None and "locale", so encoding = locale.getencoding() counted as pinned when it is the platform default written out. Added PLATFORM_DEFAULT_CALLS covering getencoding, getpreferredencoding and getdefaultencoding; both spellings are now reported and encoding = "utf-8" is unaffected.

Verified in 6ca5972: guard self-tests pass, adversarial corpus 13 shapes 0 false positives / 0 false negatives, shipping tree still 0 offenders.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6ca59721f7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +104 to +106
legacy = locale.getpreferredencoding(False)
try:
text = data.decode(legacy)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve ambiguous JSONL instead of locale-rewriting it

When a UTF-8 JSONL file has a torn final multibyte sequence after an interrupted append, this treats the entire file as legacy locale text. On Windows single-byte locales such as cp1252, decoding and re-encoding usually round-trips arbitrary bytes, so the check below does not establish that the guessed encoding is correct; the subsequent replacement permanently turns valid non-ASCII content in all earlier records into mojibake. Since the preload already skips malformed individual lines, avoid destructively migrating an invalid UTF-8 file unless its legacy encoding can be identified unambiguously.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You are right, and the round-trip check I added last round was not the proof I claimed. cp1252 leaves only five bytes undefined, so it round-trips 251 of 256:

cp1252 single bytes: round-trip 251/256, undefined 5 -> ['0x81','0x8d','0x8f','0x90','0x9d']

So any file failing utf-8 for any reason, including your torn-append case, passes the check and gets rewritten:

torn file fails utf-8: unexpected end of data
cp1252 round-trips it: True   -> migration fires
record 1 becomes {"id": 1, "t": "caf\u00c3\u00a9"}   (was {"id": 1, "t": "caf\u00e9"})

Since the legacy encoding cannot be identified unambiguously, I removed the migration entirely rather than trying to make the guess smarter. A pre-existing file is now left byte for byte as it was, and the preload keeps errors = "replace" purely so dedup reads past a line it cannot decode:

cp1252 legacy   bytes preserved   keys ['id:1','id:2']
torn utf-8      bytes preserved   keys ['id:1']
clean utf-8     bytes preserved   keys ['id:1']

Verified in b08872b: guard self-tests pass, adversarial corpus 9 shapes 0 false positives / 0 false negatives, shipping tree still 0 offenders.

if text.encode(legacy) != data:
return # the guess does not round-trip, so rewriting would lose bytes
tmp = self.path.with_suffix(self.path.suffix + ".mig")
tmp.write_text(text, encoding = "utf-8")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Disable newline translation while migrating JSONL

For the Windows legacy files this migration targets, text already contains \r\n because it was decoded directly from raw bytes. Path.write_text() uses platform newline translation by default, so every existing \n becomes another \r\n, producing \r\r\n and therefore a blank logical line after every record. The plugin's _read_jsonl() skips those blanks only after enumerate, so they consume max_rows and can cause a resumed scrape to materialize roughly half the requested records; write without translation or normalize line endings first.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct about write_text and platform newline translation. It is moot now: the migration that would have done the writing is gone, for the reason in the sibling comment, so nothing rewrites the file and no \r\r\n can be introduced. Worth flagging regardless, since the same trap would apply to any future migration written that way.

Verified in b08872b: guard self-tests pass, adversarial corpus 9 shapes 0 false positives / 0 false negatives, shipping tree still 0 offenders.

Comment thread tests/test_runtime_text_encoding.py Outdated
root = name = func.id
else:
return False
return root in modules and name not in PATH_CLASSES

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resolve pathlib aliases before exempting foreign openers

When Path is imported under an alias, such as from pathlib import Path as P, this compares the local spelling P against PATH_CLASSES and classifies P(...) as a foreign constructor. _foreign_names() then exempts the resulting variable, so p = P('x'); p.open() passes this new guard without an encoding. Path aliases are already used in shipping modules such as studio/backend/main.py, so resolve the imported origin here rather than comparing only the alias text.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. _foreign_receiver compared the local spelling against PATH_CLASSES, so from pathlib import Path as P made P(...) look like a foreign constructor and _foreign_names then exempted the variable. It now goes through _is_path_class, which resolves the imported origin.

p = P("x"); p.open()        flagged
p = Path("x"); p.open()     flagged
z = zipfile.ZipFile(q); z.open("i")   still exempt

Verified in b08872b: guard self-tests pass, adversarial corpus 9 shapes 0 false positives / 0 false negatives, shipping tree still 0 offenders.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: b08872bb17

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 70f9441fc7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +135 to +138
if not isinstance(node, ast.Assign) or not isinstance(node.value, ast.Call):
continue
if _foreign_receiver(node.value, modules):
names.update(t.id for t in node.targets if isinstance(t, ast.Name))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Recognize context-managed foreign openers

When shipping code uses the common with zipfile.ZipFile(path) as archive: archive.open("foo") pattern, no ast.Assign records archive, so _offender treats the call as Path.open() and reports a missing encoding. ZipFile.open() has no encoding parameter, leaving no compliant edit and causing this repository-wide test to reject valid code; track foreign receivers bound by with statements (and annotated assignments) as well.

Useful? React with 👍 / 👎.

Comment on lines +246 to +248
if isinstance(first, ast.Constant) and first.value in PLATFORM_DEFAULT_ENCODINGS:
return "read_text()"
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject positional calls to locale encodings

When a bound path call spells the platform default positionally, such as path.read_text(locale.getencoding()), this branch returns None because the first argument is not a constant, even though the equivalent keyword call is correctly rejected by _names_encoding. This lets the exact locale-dependent read the guard is intended to prevent pass CI; check positional call expressions against PLATFORM_DEFAULT_CALLS before treating them as pinned encodings.

Useful? React with 👍 / 👎.

Comment on lines +151 to +154
while stack:
node = stack.pop()
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
continue # that function's business, not this scope's

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep class imports out of the enclosing scope

When a class body imports a foreign open, such as class Decoder: from PIL.Image import open, _imported_names() descends into that class and records the name as though it were module-level. Consequently, an unrelated module function calling the real builtin open("config.json") is classified as the PIL opener and escapes this guard; class definitions need their own lexical import scope just like functions.

Useful? React with 👍 / 👎.

self.path.parent.mkdir(parents = True, exist_ok = True)
self._lock = threading.Lock()
self._fh = self.path.open("a", buffering = 1)
self._fh = self.path.open("a", buffering = 1, encoding = "utf-8")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Migrate legacy JSONL before appending UTF-8

When the standalone scraper resumes a JSONL created by an older Windows build, any cp1252 non-ASCII bytes remain in place while this handle appends new UTF-8 bytes, producing a mixed-encoding file. The replacement-error preload does not rewrite those bytes, and scraper.py later opens the same file as strict UTF-8 in _read_jsonl, so materialization fails with UnicodeDecodeError; transcode or archive the legacy file before opening it for UTF-8 append.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen merged commit 3fd948e into main Jul 27, 2026
73 of 74 checks passed
@danielhanchen
danielhanchen deleted the fix-runtime-text-encoding-v2 branch July 27, 2026 09:14
danielhanchen added a commit that referenced this pull request Jul 28, 2026
#7507)

test_shipping_code_names_an_encoding is red on main. #7373 added
sync_marker_llama_backend, whose read_text/write_text pair does not name
an encoding, so both fall back to locale.getencoding():

  AssertionError: 2 text read/write call sites in shipping code let the
  operator's locale decide the encoding, so they crash or silently
  produce mojibake on Windows. Pass encoding = "utf-8":
  ['studio/install_llama_prebuilt.py:5656: write_text()',
   'studio/install_llama_prebuilt.py:5647: read_text()']

Reproduced on a clean checkout of main at 7917c78: 1 failed, 7 passed.

That guard landed in #7486 a few commits earlier, so the rule predates
these call sites; nothing about the Vulkan work is wrong beyond the
missing kwarg. The create path that writes the same file, 26 lines above
at 5621, already passes encoding = "utf-8", so main is also internally
inconsistent about one file: written as utf-8, read back under the
operator locale.

Scope, stated honestly: json.dumps defaults to ensure_ascii = True, so
the marker this module writes is pure ASCII and round-trips under cp1252
as well as utf-8. The exposure is a marker produced or edited by
something else. A decode failure on the read would not even surface,
because UnicodeDecodeError subclasses ValueError and the surrounding
except (OSError, ValueError) swallows it into the early return, leaving
the backend silently unsynced. So this restores a green suite and makes
the file self-consistent rather than fixing a live crash.

Verified: tests/test_runtime_text_encoding.py 1 failed / 7 passed before,
8 passed after; tests/test_source_read_encoding.py still passes.
danielhanchen pushed a commit that referenced this pull request Jul 28, 2026
main landed the same UTF-8 text I/O pinning independently (#7486, #7487), so
every conflict was the same shape: both sides had pinned the same read, just
with a different encoding name or a different guard.

Resolution rule: main wins, except where this branch carries something main
does not have.

Where the two overlapped, main won:
  - remote_code_scan.py keeps main's PEP 263 aware _read_python_source, which
    honours a coding cookie via tokenize.detect_encoding, at all three call
    sites. The io and tokenize imports come across unchanged.
  - The wider decode guards from main are kept as is. Where main widened
    except OSError to include UnicodeDecodeError, only the encoding on the read
    line itself was reapplied. utf-8-sig strips a BOM but still raises on
    genuinely undecodable bytes, so the wider clause is still the one that
    matters.
  - llama_cpp.py drops the now redundant text = True next to encoding, matching
    main.
  - transformers_version.py takes main's keyword order on the METADATA read.
    The two spellings are identical in behaviour.

Where this branch had something main lacks, it was reapplied on top:
  - JSON reads use utf-8-sig, not plain utf-8. json.loads raises on a leading
    BOM, so a config.json written by a Windows editor would fail to parse.
    Nothing else changes: utf-8-sig decodes ordinary UTF-8 identically.
  - Python children get utf8_child_env, so a child's stdout is not written in
    the ANSI code page while the parent reads the pipe as UTF-8.
  - The logging stream reconfigure keys off the stream's own encoding rather
    than sys.platform, so LANG=C in a container is covered too, not just
    Windows.

No write path uses utf-8-sig, which would emit a BOM.
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.

1 participant