Repository navigation
Studio: name utf-8 explicitly on the remaining text I/O, with an AST guard - #7465
Conversation
a14ce6f to
b9fa749
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8c41152339
ℹ️ 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".
| BACKEND_ROOT = Path(__file__).resolve().parent.parent | ||
|
|
||
| # Directories that are not Studio's own runtime source. | ||
| _SKIPPED_DIRS = ("node_modules", "plugins", "tests", "__pycache__", "sandbox_site") |
There was a problem hiding this comment.
Include runtime plugins in the encoding guard
On Windows with a non-ANSI repository value (for example 世界 under cp1252), the GitHub seed plugin still opens its JSONL file using locale defaults at plugins/data-designer-github-repo-seed/.../state_store.py:66 and writes it with ensure_ascii=False at line 100, which can raise UnicodeEncodeError and abort scraping. Excluding plugins lets this reported Unicode failure remain while the new guard passes; the scan should cover these runtime plugins and recognize their Path.open() text calls.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Verified and fixed. Both halves of this were right.
The plugin gap. state_store.py opens its JSONL with Path.open("a", buffering = 1) and writes ensure_ascii = False, so a repo name like 世界 raises UnicodeEncodeError under a non-UTF-8 default. Fixed there, plus the two sibling reads and the temp-file write in the same module.
The guard gap. It only matched the open() builtin, so Path.open() slipped through everywhere, not just in plugins. Extended to both, and the plugin exclusion is now narrowed to build artifacts so plugins/*/src is covered.
Discriminating Path.open() from other libraries' open() needed care. A first pass flagged fitz.open(stream = ..., filetype = "pdf") and av.open(..., metadata_errors = "ignore") as false positives, so the check now matches Path.open's actual signature: at most one positional argument, and only mode/buffering/encoding/errors/newline keywords.
The widened guard then found a real one outside plugins: data-designer-unstructured-seed/impl.py read <file_id>.meta.json without an encoding, and that file holds original_filename for an upload. So a German user uploading Bücher.pdf lost the original name, and since the handler catches only JSONDecodeError/OSError the UnicodeDecodeError would have propagated. Fixed.
Guard is now 300 tests, all passing, and the full backend suite has the same failure set as main on my machine.
There was a problem hiding this comment.
Premise does not hold. _SKIPPED_DIRS at the reviewed commit 52fc4b4 was (node_modules, build, tests, pycache, sandbox_site); plugins was never excluded, so the runtime plugins were already in the guard's scan set. The sandbox shim half is tracked separately and was a real gap.
Follow-up to the model-text reads in #7467, covering the rest of the backend: system probes (nvidia-smi, amd-smi, powershell, git, node), package installers, /proc and /sys readers, and internal marker files (pid, install id, bootstrap password, Colab credentials). Same reason as #7467. open(), Path.read_text()/write_text() and subprocess(text = True) fall back to locale.getencoding(), which on Windows is the ANSI codepage rather than UTF-8. These paths are mostly ASCII today, so this is hardening, not a live bug. Encoding arguments only, no logic changes. Adds tests/test_text_io_encoding.py: an AST guard walking every backend source and asserting text I/O names its encoding, so the class of bug cannot creep back in one call at a time. 275 files.
7d93838 to
1f6ca02
Compare
07380fe to
52fc4b4
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ee0d420226
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| 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") |
There was a problem hiding this comment.
Migrate legacy JSONL before appending UTF-8
When resuming a scrape created by an earlier release on a non-UTF-8 Windows locale, existing non-ASCII lines are encoded in that locale because the previous writer used the platform default. Opening the same file for UTF-8 append creates a mixed-encoding JSONL file; additionally, the UTF-8 preload fails and is swallowed, so previously seen keys are forgotten and duplicate records may be appended. Decode legacy files with a compatible fallback and rewrite/migrate them to UTF-8 before opening for append.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 22298ae. ensure_ascii = False is on main too, so a pre-fix release on a non-UTF-8 machine really did write locale-encoded bytes here, and the UTF-8 preload then raised into the bare except and forgot every seen key.
Reproduced before/after on cp1252, cp1251 and cp932 legacy files with the writing codepage pinned. Before: zero keys recovered in all three cases, so every record is re-appended. After: both keys recovered, the repeat is refused, and the legacy text survives byte-exact (Jürgen, Юрий, 田中).
The preload now reads bytes, tries UTF-8, falls back to locale.getencoding(), and lands on latin-1 with replacement so a resume can never lose the file outright. When the file was not already UTF-8 it is rewritten via temp plus os.replace before the append handle opens, which is also why the handle moved below the preload: Windows cannot replace a file it still holds open. A failed rewrite unlinks the temp and leaves the original alone.
StateStore got the same lenient decode. It rewrites the whole file on the next set() so it was never at risk of mixing, but a legacy checkpoint used to decode to {} and silently restart the scrape.
Covered by test_resuming_a_legacy_jsonl_migrates_it, parametrized over the three codepages.
| def _is_subprocess_call(node: ast.Call) -> bool: | ||
| func = node.func | ||
| if not isinstance(func, ast.Attribute) or func.attr not in _SUBPROCESS_CALLS: | ||
| return False | ||
| value = func.value | ||
| return isinstance(value, ast.Name) and value.id == "subprocess" |
There was a problem hiding this comment.
Track subprocess import aliases in the guard
The new guard recognizes only calls whose receiver is literally named subprocess, so aliased imports bypass it. The current runtime already has import subprocess as _sp in core/training/worker.py and _sp.run(..., text = True) calls at lines 604 and 847 without an encoding; both pass this test, leaving locale-dependent installer output decoding on Windows despite the asserted backend-wide invariant. Resolve import aliases, or otherwise match these calls too.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct on both counts, fixed in 22298ae. Verified before changing anything: feeding import subprocess as _sp plus _sp.run(["ls"], text = True) through the old _offenders() returned nothing.
The guard now collects the names subprocess is bound to per file from the ast.Import nodes and matches any of them, rather than the literal subprocess. Re-running it over the backend flagged exactly the two lines you named and nothing else.
Both are fixed, plus a third the guard still cannot see: _run_kwargs at worker.py:384 is a dict literal holding "text": True that is splatted into _sp.run at line 411, so it never appears as a keyword on the call node. All three now pass encoding = "utf-8", errors = "replace", matching the rest of the PR. These capture pip output, which carries the install path, so a user under C:\Users\Jürgen was getting mojibake or a decode error in the training log.
| if len(node.args) > 1: | ||
| return False |
There was a problem hiding this comment.
Scan positional Path.open calls
Path.open permits buffering, encoding, errors, and newline as positional arguments, so rejecting every call with more than one positional argument lets a valid text call such as path.open("w", 1) omit its encoding while the new guard passes. This leaves a straightforward path for the Windows locale regression to return; inspect the positional encoding slot rather than excluding these calls wholesale.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, fixed in 22298ae. Confirmed the hole first: path.open("w", 1) through the old _offenders() returned nothing, because len(node.args) > 1 bailed out before the encoding check.
The guard now allows up to the five positional arguments Path.open actually takes and reads the encoding slot at index 2, so path.open("w", 1) is flagged and path.open("w", 1, "utf-8") is not.
The shape check that keeps other libraries out is unaffected, since it keys off the first argument being a mode string rather than off the argument count. zf.open("member.txt") and tarfile.open(name, "r:gz") are still rejected: the first has a filename where the mode would be, the second a non-constant. No new offenders turned up across the backend after widening it, so the change added no false positives.
The guard only matched a receiver literally named subprocess, so worker.py's `import subprocess as _sp` hid three text = True installs that decode pip output with the ANSI codepage. It also skipped any .open() with more than one positional argument, though Path.open takes buffering/encoding/errors/newline positionally. Resuming a scrape written by an older release is the other half: those JSONL lines are in the locale codepage, so the UTF-8 preload raised, the dedup keys were silently forgotten and duplicates were appended to a now mixed-encoding file. Decode with the locale codepage as fallback and rewrite as UTF-8 before the append handle opens, since Windows cannot replace a file it holds open.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 22298aedd7
ℹ️ 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".
| except OSError: | ||
| tmp.unlink(missing_ok = True) |
There was a problem hiding this comment.
Stop appending when legacy migration fails
When a legacy locale-encoded JSONL file is appendable but its directory does not permit creating/replacing the temporary file, this handler silently ignores the failed migration and the constructor subsequently opens the original file for UTF-8 append. The next non-ASCII record creates a mixed-encoding file, corrupting persisted scrape results and future preload decoding; the new best-effort except OSError path is fresh evidence beyond the earlier migration comment. Propagate the migration failure or continue writing with the detected legacy encoding instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, swallowing that left the file mixed. Fixed in 11b7e9d, taking your second option.
_rewrite_as_utf8 now returns whether it succeeded, and when it fails the append handle opens with the legacy encoding instead of UTF-8, so the file stays internally consistent rather than gaining a second encoding halfway through. Propagating instead would kill the scrape over a directory permission, which seemed worse than continuing in the encoding already on disk.
That handle also carries errors = "replace" now. A legacy codepage cannot represent everything GitHub returns, and this path is already degraded, so a character outside cp1252 should cost one substitution rather than raise mid-scrape.
Verified with the file appendable but its directory not writable, so the temp cannot be created: the legacy key is still recovered, the new record is appended, and the result still decodes cleanly as cp1252 end to end with both umlauts intact. No stray temp is left behind, since the failure path unlinks it.
| if not isinstance(func, ast.Attribute) or func.attr not in _SUBPROCESS_CALLS: | ||
| return False | ||
| value = func.value | ||
| return isinstance(value, ast.Name) and value.id in names |
There was a problem hiding this comment.
Track subprocess callables passed through helpers
Unlike the previously fixed module-alias case, this rejects every call whose function is not an attribute. wheel_utils.install_wheel accepts run=subprocess.run—and training passes _sp.run—then invokes run(..., text = True) at lines 204 and 216 without an encoding, so both production wheel-install paths still use locale-dependent decoding while this backend-wide guard passes. Track callable bindings/defaults or add the encoding in that helper.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Verified and fixed in 11b7e9d. install_wheel does take run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run, and both calls at lines 204 and 216 were missing an encoding, so the default path and the one worker.py drives with run = _sp.run were both decoding installer output with the ANSI codepage.
Fixed in the helper rather than in the guard, which is the half of your suggestion I can actually verify. Both calls now pass encoding = "utf-8", errors = "replace".
I did not try to track callable bindings in the guard. Following a parameter default and a keyword argument across module boundaries is data flow analysis, and an AST check that guesses at it would produce false positives on every unrelated run(...) in the tree. The guard stays deliberate about what it can prove: direct calls on a module that is bound to subprocess in that file. The gap is real, so it is worth being explicit that this class of indirection is out of its reach and is caught by review, not by the test.
|
|
||
| def _preload_seen_keys(self) -> None: | ||
| try: | ||
| raw = self.path.read_bytes() |
There was a problem hiding this comment.
Stream JSONL preload instead of reading whole shards
When resuming a large repository scrape, this now loads the entire JSONL shard as bytes and then decodes it into a second full-size string before scanning lines. These append-only outputs can grow to gigabytes for commits, issues, or comments, so a resume that previously streamed line by line can now exhaust memory and abort before scraping starts. Stream the UTF-8 preload and only perform a streaming rewrite when legacy decoding is actually required.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in 11b7e9d. read_bytes() plus a full decode was a real regression against the streaming loop it replaced, and these shards do get large.
The preload now iterates the file handle in binary and decodes one line at a time, and the migration streams source to temp the same way. Neither the bytes nor the decoded text are held whole any more.
Measured on a 62 MB shard of 140,000 records: peak traced allocation during construction is 11 MB, and all 140,000 keys are recovered. What remains is the seen-keys set itself, which is inherent to the dedup and was there before this PR.
Migration also only runs when a line actually decoded as legacy, so the common case of an already-UTF-8 shard reads once and rewrites nothing.
| try: | ||
| return raw.decode(encoding), index == 0 | ||
| except (UnicodeDecodeError, LookupError): | ||
| continue |
There was a problem hiding this comment.
Isolate malformed UTF-8 lines before legacy fallback
When a current UTF-8 shard contains one damaged or partially written multibyte character—for example after a disk-full or interrupted append—the whole-file UTF-8 decode fails and this retries every byte using the locale code page. On cp1252, valid UTF-8 text such as Jürgen then becomes Jürgen, and _rewrite_as_utf8 permanently rewrites all otherwise valid records with that corruption even though the malformed JSONL line would have been skipped. The new whole-file fallback is fresh evidence beyond the earlier migration comment; decode and recover per line rather than changing the inferred encoding of the entire shard because of one bad byte.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, and this was the worst of the four. Fixed in 11b7e9d.
The whole-file retry was mine and it was a genuine corruption risk: one torn multibyte character at the tail of an interrupted append made the UTF-8 decode fail, every byte got retried as cp1252, and _rewrite_as_utf8 then persisted the mojibake over records that were perfectly fine.
The fix is to classify per line, and to require more than a successful decode. A line counts as legacy only if the locale codepage both decodes it and yields valid JSON. A torn UTF-8 line decodes under cp1252 but does not parse, so it is treated as damaged: skipped for keys, copied through byte for byte, and it no longer votes on the encoding of the shard.
Verified with a UTF-8 shard holding two good records around one line cut mid-character, locale pinned to cp1252. The good keys are recovered, the torn line yields none, no rewrite is triggered at all, and the file still starts with its original bytes. Regression test is test_a_torn_line_does_not_relabel_a_utf8_shard, which asserts Jürgen stays UTF-8 and never appears as the cp1252 reinterpretation.
Reading the whole shard to migrate it was wrong twice over. These files reach gigabytes on a large scrape, so the preload now streams line by line and the rewrite streams through a temp file. Worse, one interrupted append used to condemn the file: the whole-file UTF-8 decode failed, every byte was retried as cp1252, and the rewrite persisted mojibake over records that were fine. A line now counts as legacy only if the locale codepage both decodes it and yields valid JSON, which a torn UTF-8 line does not. Damaged lines are skipped and copied through byte for byte. When the rewrite cannot be written at all, the append handle opens with the legacy encoding rather than mixing UTF-8 into the file. install_wheel takes run = subprocess.run as a parameter, so the guard cannot see it. Both wheel installs there now name their encoding.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 11b7e9d0d3
ℹ️ 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".
| try: | ||
| return json.loads(raw.decode("utf-8")), False |
There was a problem hiding this comment.
Detect legacy lines before accepting coincidental UTF-8
When a legacy code-page sequence also happens to be valid UTF-8, this UTF-8-first parse silently changes persisted data instead of migrating it. For example, cp1251 text Р° is stored as bytes D0 B0, which decode successfully as UTF-8 а; json.loads therefore succeeds here, the line is marked non-legacy, and resuming the shard permanently exposes the wrong author/text alongside newly appended records. Encoding detection needs to account for this ambiguity rather than treating every UTF-8-decodable legacy line as current UTF-8.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The byte-level claim is exactly right and it is fixed in abb9b98. Checked it first: Р° encodes to D0 B0 under cp1251, and that decodes as UTF-8 а, so the UTF-8-first parse did take the wrong reading.
What the ambiguity does not survive is context. Real Cyrillic is invalid UTF-8 several times per line, because cp1251 puts the letters in C0 to FF and consecutive letters give a lead byte followed by another lead byte. Measured: Привет, Юрий, Здравствуйте, Москва and a bare а all fail a UTF-8 decode. Only Р°, which is itself the mojibake form, survives it.
So the decision moved from the line to the file. Each line now yields both readings, any line that parses under the codepage but not as UTF-8 is unambiguous evidence, and ambiguous lines follow that verdict. Keys for those lines are re-derived from the legacy reading during the rewrite, so dedup matches what actually gets written.
Verified on a cp1251 shard holding Привет next to Р°: both convert, Р° stays Р° rather than collapsing to а, and the appended record is intact. A genuine UTF-8 shard holding а and Привет read under a cp1251 locale is left byte for byte untouched, so the detection did not simply invert. The torn-line and cp1252 cases still pass.
One case stays undecidable and I would rather name it than paper over it: a shard where every single line is ambiguous carries no evidence either way. It also cannot arise from a scrape with any ordinary non-ASCII prose in it.
Separately, latin-1 is now tried after the locale codepage. A shard written on Windows and opened on a UTF-8 machine previously had no legacy reading at all, which put it straight back into the mixed-encoding case from your first comment. Requiring valid JSON rather than a bare decode is what stops latin-1, which accepts any byte, from claiming torn lines.
Some byte strings parse both ways. cp1251 `Р°` is D0 B0, which is also valid UTF-8 for `а`, so a UTF-8-first parse quietly showed the wrong text instead of migrating it. A line now yields both readings, and the file decides. Any line that parses under the codepage but not as UTF-8 is unambiguous evidence, and ambiguous lines then follow that verdict, which is enough for any real shard: ordinary Cyrillic or Japanese prose is invalid UTF-8 several times per line. Keys for ambiguous lines are re-derived from the legacy reading during the rewrite. A shard is undecidable only if every line is ambiguous, and nothing can tell those apart. latin-1 is also tried after the locale codepage, so a scrape carried from Windows to a UTF-8 machine still has a reading rather than none. Requiring valid JSON, not just a decode, keeps that from claiming torn lines.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: abb9b98fd5
ℹ️ 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".
| if as_utf8 is None and as_legacy is not None: | ||
| legacy = True | ||
| self._append_encoding = encoding |
There was a problem hiding this comment.
Do not relabel a shard from one damaged JSON line
When an otherwise UTF-8 shard contains a structurally complete JSON line with an invalid UTF-8 byte, such as {"id":2,"author":"bad \x96 byte"}, that line parses as cp1252 and this condition marks the entire shard as legacy. _rewrite_as_utf8() then decodes every valid UTF-8 record as cp1252, permanently changing values such as Jürgen to Jürgen. This line-level legacy verdict is fresh evidence beyond the earlier malformed-line finding because the new test covers only an unterminated line that fails legacy JSON parsing; an isolated damaged but parseable line still corrupts the whole shard.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 3a156c8. This one was a real hole in my previous fix: I required valid JSON to guard against torn lines, but {"id":2,"author":"bad \x96 byte"} is structurally complete, so cp1252 parses it and the single-line verdict relabelled the shard.
The verdict now weighs the whole file. Every line with non-ASCII bytes votes: parsing only under the codepage is evidence for legacy, parsing as UTF-8 is evidence against, since arbitrary codepage text almost never forms valid multibyte UTF-8. Pure ASCII lines are identical either way and cast no vote.
Ties leave the file alone deliberately. Rewriting a healthy shard mojibakes every good record in it, while declining to convert a legacy one still recovers the keys through the legacy reading, so the two errors are not equally bad.
Verified on your exact case: three UTF-8 umlaut records around one stray-0x96 line, locale pinned to cp1252. The file comes back byte-identical, so no rewrite ran, and Jürgen, Grüße, Björn are untouched. Detection did not simply invert either: a cp1252 shard with a single umlaut record still migrates, and one with twenty still migrates. Regression test is test_one_damaged_byte_does_not_relabel_a_utf8_shard.
| # Could not convert it, so keep matching what is already there | ||
| # rather than appending UTF-8 into a legacy file. | ||
| encoding = self._append_encoding | ||
| self._fh = self.path.open("a", buffering = 1, encoding = encoding, errors = "replace") |
There was a problem hiding this comment.
Avoid lossy appends after migration failure
When the existing legacy file is appendable but its directory prevents the temporary rewrite or replacement, this opens it with the legacy code page and errors = "replace". Any subsequent record containing characters outside that code page—for example 世界 in a cp1252 shard—is silently persisted as ??, while write() returns success and marks its key as seen, permanently losing scrape output. The lossy error handler is fresh evidence beyond the earlier migration-failure thread; aborting the append is safer than reporting success after replacement.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
You are right that the lossy handler was wrong, fixed in 3a156c8. I did not take the abort, because there is a third option that loses nothing.
On that fallback path the record is now serialised with ensure_ascii = True. JSON escapes non-ASCII as \uXXXX, which is plain ASCII, so cp1252 or any other codepage can hold it and json.loads gives back the exact original characters. Since nothing can be unrepresentable any more, the handle opens with errors = "strict" rather than "replace", so a silent substitution cannot happen at all.
That keeps the file single-encoding, keeps every record, and keeps the scrape running, which aborting would not.
Verified with the file appendable but its directory not writable, so the migration cannot run: writing {"author": "世界", "note": "Grüße"} into a cp1252 shard returns success, and reading the file back as cp1252 gives 世界 and Grüße exactly. No question marks anywhere in the file, and the pre-existing Jürgen record is still intact.
| encoding = "utf-8", | ||
| errors = "replace", | ||
| env = env, |
There was a problem hiding this comment.
Force the Python installer to emit UTF-8
On Windows with an ANSI locale, both inspected callers (llama_cpp_update.py:472 and whisper_cpp_update.py:377) pass a sys.executable installer command and an ordinary inherited environment here. The child therefore emits redirected stdout in the locale code page, but this newly decodes it as UTF-8; output containing a representable non-ASCII install path such as C:\Users\Jürgen\... becomes replacement characters in the InstallerExit tail shown after an update failure, whereas it decoded correctly before this change. Wrap env with utf8_child_env() so the Python child and parent agree on the encoding.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Verified and fixed in 3a156c8. Both callers do build a sys.executable command (llama_cpp_update.py:446, whisper_cpp_update.py:354) and both pass env = dict(os.environ, ...) with no encoding forced, so the Popen I added was decoding an ANSI-codepage child as UTF-8.
Fixed in stream_installer rather than at each caller, since that is the single point both go through and it cannot be forgotten by a third one later. The env is now wrapped with utf8_child_env(), which is the same helper used for the other Python children.
Same regression as the llama_cpp diffusion shim you caught earlier in this series, and the AST guard cannot see it: the mismatch is between a parent that names an encoding and a child that was never told which one to emit, which is not visible at either call site alone.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1de2bf5f48
ℹ️ 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".
| for candidate in (preferred, "latin-1"): | ||
| if candidate.lower().replace("-", "").replace("_", "") == "utf8": | ||
| continue |
There was a problem hiding this comment.
Preserve the source code page when migrating moved shards
When a legacy shard is resumed on a machine with a different or UTF-8 locale, this fallback treats every non-UTF-8 byte sequence as Latin-1, even though Latin-1 is not the encoding that produced it. For example, a cp1251 shard containing Привет copied to a UTF-8 host parses as Latin-1 Ïðèâåò, after which _rewrite_as_utf8() permanently writes that mojibake into the shard; cp932 data is corrupted similarly. Fresh evidence in the final migration fix is that _legacy_encodings() now drops the UTF-8 host encoding and retains only Latin-1, so the claimed cross-machine fallback cannot recover the source code page. Preserve encoding metadata or avoid rewriting when the original code page cannot be established.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
You are right, and this was my own regression, fixed in a294183. I added latin-1 to give a moved shard some reading, and did not think through that a reading is not the same as the right reading.
Measured it: cp1251 Привет reads back through latin-1 as Ïðèâåò and cp932 こんにちは as raw bytes. Only cp1252 survives, because latin-1 is very nearly cp1252. So the fallback was fine for exactly the one codepage that did not need it.
A codepage is now trusted only when it is the locale codepage, that is, when this machine plausibly wrote the file. latin-1 is still used, but only to recover the dedup keys, which are ASCII ids and come back correct either way. An untrusted reading never reaches _rewrite_as_utf8().
That leaves the question of what to append to a shard we cannot attribute. Appending UTF-8 would mix encodings, which is the problem your first comment raised. Those appends are now serialised with ensure_ascii = True, so they are pure ASCII, which every ASCII-compatible codepage stores identically. The file keeps decoding exactly as it did, and json.loads returns the exact characters.
Verified across cp1251, cp932 and cp1252 shards opened on a UTF-8 host: the original bytes are untouched, the appended record is pure ASCII, the whole file still decodes in its own codepage with both records readable, and the dedup key is recovered. Regression test is test_a_moved_shard_is_not_rewritten_by_guesswork.
One structurally valid JSON line carrying a stray 0x96 parses as cp1252, so a single-line verdict let it relabel a healthy shard and mojibake every good record in it. Each line with non-ASCII bytes now votes: parsing only under the codepage is evidence for legacy, parsing as UTF-8 is evidence against, since codepage text rarely forms valid multibyte UTF-8. Ties leave the file alone. When the migration cannot be written the append handle uses the legacy codepage, and errors = "replace" quietly turned characters it cannot hold into question marks while write() still reported success. That path now escapes to \uXXXX instead, which is ASCII, so every codepage holds it and json.loads returns the exact characters. Nothing needs replacing, so errors = "strict" is safe. stream_installer runs sys.executable, so its output is now decoded as UTF-8 by utf8_child_env rather than read as the ANSI codepage.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3a156c81ba
ℹ️ 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".
| elif as_utf8 is not None: | ||
| utf8_votes += 1 |
There was a problem hiding this comment.
Do not count ambiguous lines as UTF-8 evidence
When a legacy shard contains more code-page lines that also happen to parse as UTF-8 than unambiguous legacy lines, these ambiguous lines vote for UTF-8 and prevent migration. For example, a cp1251 shard with two Р° records and one Привет record produces two UTF-8 votes versus one legacy vote; the constructor then opens the still-cp1251 file for UTF-8 append, creating a mixed-encoding shard that cannot be decoded as either encoding. Fresh evidence beyond the earlier coincidental-line finding is that the new majority heuristic explicitly counts every dual-parse line on the UTF-8 side rather than leaving it undecided.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a294183, though not by changing the vote, because I do not think the vote can be made correct.
Your case and the damaged-byte case from the previous round are the same shape: one legacy-only line plus N lines that parse both ways. Counting ambiguous lines as UTF-8 evidence gets yours wrong, and treating them as neutral gets the damaged-byte one wrong, where it mojibakes an entire healthy shard. There is no counting rule that separates them, because the two files genuinely differ only in which reading is plausible prose.
So the correctness no longer rests on winning that vote. Whenever the file holds bytes UTF-8 cannot read and we are not converting it, the appends are serialised with ensure_ascii = True. Pure ASCII is stored identically by every ASCII-compatible codepage, so the mixed-encoding shard your example produces cannot occur regardless of how the vote lands. The vote now only decides whether to attempt a rewrite, where a wrong answer is conservative rather than corrupting.
Verified with your exact file, two Р° records and one Привет under a cp1251 locale: the vote does go to UTF-8 and no migration runs, but the original bytes are untouched, the appended record is ASCII, and all four records still read back through cp1251 with Москва intact.
The kept-as-is outcome is the honest one here. The shard is genuinely ambiguous, and this leaves it readable exactly as it was found rather than guessing.
| except OSError: | ||
| return False |
There was a problem hiding this comment.
Abort appends when the shard preload fails
When an existing locale-encoded shard permits append access but not read access, or a transient OSError interrupts the preload, this returns the same False used for a healthy UTF-8 file. The constructor consequently opens the unread legacy file with UTF-8 and can append a second encoding, corrupting the persisted output; unlike the previously reviewed rewrite-failure path, this failure occurs before legacy encoding is detected and therefore bypasses its fallback entirely. Propagate the preload failure rather than treating it as a UTF-8 verdict.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct that returning the same False conflated an unread file with a healthy UTF-8 one, fixed in a294183. The scan now reports readability separately from the verdict.
I did not propagate the failure, and want to be explicit rather than quietly do something else. This class is best-effort throughout, every method swallows, and a resume that raises here loses a scrape that may have been running for hours. What it cannot be allowed to do is what you identified: append a second encoding into a file it never read. So an unreadable shard now takes the same path as an unattributable one, appending pure ASCII, which every ASCII-compatible codepage stores identically. The corruption is prevented without ending the run.
The cost is that dedup keys are lost when the file cannot be read, so a resume may re-append records. That is recoverable downstream, unlike a corrupted shard, and it was already the behaviour before this PR.
Verified with the shard chmod-ed write-only, so append works and read does not: original bytes untouched, appended record pure ASCII, whole file still decodes as cp1252, and both Jürgen and Grüße read back intact.
| self._append_encoding = encoding | ||
| elif as_utf8 is not None: | ||
| utf8_votes += 1 | ||
| obj = as_utf8 if as_utf8 is not None else as_legacy |
There was a problem hiding this comment.
Do not deduplicate records from damaged UTF-8 lines
When an otherwise UTF-8 shard contains a structurally valid JSON line with an invalid UTF-8 byte, this selects the legacy parse and adds its key even when the shard-level vote correctly concludes that the file is UTF-8 and leaves the damaged line untouched. A line such as {"id":99,"author":"bad \x96 byte"} therefore makes write({"id":99,...}) return False on a retry, preventing the scraper from replacing the unreadable record and permanently omitting that item from consumers that skip invalid UTF-8. Only collect the legacy interpretation's key after the shard has actually been classified as legacy.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in a294183. The preload was falling back to the legacy reading for key extraction on any line UTF-8 could not read, including damaged lines in a shard the vote then classified as UTF-8, so id:99 was marked seen and the retry that would have replaced the unreadable record was refused.
The scan now keeps the two sets apart: keys from lines UTF-8 could read, and keys only the codepage reading yields. The second set is merged in only when the shard is actually classified as legacy. In a UTF-8 shard the damaged line contributes nothing, so its record is free to be written again.
Verified on a shard of three healthy UTF-8 records around one stray-0x96 line: the healthy keys are all present, id:99 is not, write({"id": 99, ...}) returns True, the replacement reads back as valid UTF-8, and a genuine duplicate is still refused. Regression test is test_a_damaged_line_does_not_block_its_own_retry.
latin-1 was doing too much work. It reads any byte, so it gave a moved shard a reading, but it is the right text only for cp1252: cp1251 Привет came back as Ïðèâåò and the rewrite made that permanent. The codepage is now trusted only when it is the locale's, and an untrusted reading is never written back. That leaves three cases where the file holds bytes UTF-8 cannot read and we are not converting it: no codepage to attribute it to, ambiguous lines outvoting the unambiguous ones, and a preload that could not read the file at all. All three used to append UTF-8 into it. They now append pure ASCII, which every ASCII-compatible codepage stores identically, so the file keeps decoding exactly as it did and no record is lost. Keys from the two readings are also kept apart. A damaged line in a healthy shard was marked seen through its codepage reading, so the retry that would have replaced the unreadable record was refused as a duplicate.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a294183aae
ℹ️ 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".
| os.replace(tmp, self.path) | ||
| return True | ||
| except (OSError, UnicodeError): | ||
| tmp.unlink(missing_ok = True) |
There was a problem hiding this comment.
Suppress temp cleanup errors during migration fallback
When migration fails because the temporary path cannot be created, replaced, or removed—such as a stale .utf8.tmp directory or a Windows process locking the temp file—this unguarded unlink() raises another OSError, so _rewrite_as_utf8() never returns False and the constructor never reaches its safe ASCII-append fallback. Fresh evidence beyond the earlier rewrite-failure thread is that the cleanup operation itself remains outside any best-effort handler; suppress cleanup errors before returning the failed-migration verdict.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in b8ac9fe. Reproduced it first with a stale .utf8.tmp directory holding a file, so open("wb") fails and the unlink() then fails too: the constructor raised PermissionError instead of returning False, so the ASCII append fallback was never reached.
The cleanup is now wrapped, and the failure verdict is returned regardless. Same scenario after the fix: the constructor completes, the legacy key is recovered, the append succeeds as ASCII, the original bytes are untouched, the file still decodes as cp1252 end to end with Jürgen and Grüße both intact, and the stale directory is left alone rather than half-removed.
| encoding = "utf-8", | ||
| errors = "replace", | ||
| env = child_env_without_native_path_secret(), |
There was a problem hiding this comment.
Force the pip child to emit UTF-8
On Windows with an ANSI locale when this falls back to python_executable -m pip, the Python child emits redirected output in its locale code page while the newly added parent decoder assumes UTF-8. Non-ASCII install paths such as C:\Users\Jürgen\... are therefore replaced in the failure output surfaced by both inspected callers. Fresh evidence beyond the earlier missing-encoding comment is that this module already applies utf8_child_env() to its Python probe but omits it here; wrap this environment with the same helper so the pip child and decoder agree.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and the inconsistency you point at is the giveaway: line 111 in this same file already wraps its probe with utf8_child_env(), and the pip fallback did not. Fixed in b8ac9fe.
Left the other two children in this module alone deliberately. The uv call above it runs the uv binary and the check at the top runs nvidia-smi, neither of which is a Python process, so PYTHONIOENCODING would have no effect on either. Only the python_executable -m pip child reads it.
_run_kwargs gained encoding and errors, so the one stub in this file that spelled its signature out rejected the call. The other four here already take **kwargs; this one now matches.
unlink() on the failure path could raise in its own right, on a stale .utf8.tmp directory or a temp another process holds. That escaped the constructor instead of returning False, so the caller never reached the ASCII append fallback that keeps the shard single-encoding. The pip fallback in install_wheel also spawns a Python child, so it gets utf8_child_env like the probe above it already had. The uv and nvidia-smi children are native binaries, where PYTHONIOENCODING would do nothing.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b8ac9fe7ef
ℹ️ 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".
|
|
||
| # Not Studio's own runtime source. Shipped plugins under plugins/*/src are, so | ||
| # only their build artifacts are skipped. | ||
| _SKIPPED_DIRS = ("node_modules", "build", "tests", "__pycache__", "sandbox_site") |
There was a problem hiding this comment.
Include the shipped sandbox shim in the encoding scan
sandbox_site is runtime source rather than a build artifact: core/inference/tools.py:332,2658-2659 places this directory on PYTHONPATH for every sandboxed Python run, while core/inference/sandbox_site/sitecustomize.py:114,134 still contains text open() calls without an encoding. Excluding the directory therefore lets the new guard pass despite unannotated text I/O in shipped code—for example, a UTF-8 remap sidecar supplied in a sandbox can still be decoded through the Windows ANSI codepage—so remove this exclusion and annotate the shim's text I/O.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 0e2420d. sandbox_site is on the sandboxed child PYTHONPATH for every Python run (tools.py:332 builds the path, tools.py:2660 sets it), so it is shipped code and the exclusion was simply wrong. My own comment above that list says it is meant for build artifacts only.
The directory is off the list and the two calls at sitecustomize.py:114 and :134 name their encoding. They read and write the remap sidecar, which holds file paths, so a sandbox CWD under C:\Users\Jürgen\ is exactly the case that would have gone through the ANSI codepage.
Worth noting PYTHONIOENCODING is already set for that child at tools.py:2657, but that governs stdio only and does nothing for open(), which is why these two survived.
Checked the fix both ways: with the directory scanned and the calls left bare, the guard flags both lines; with them annotated it passes, and no other offender turned up anywhere under sandbox_site. The 204 sandbox and sitecustomize tests still pass.
| with self.path.open() as f: | ||
| for line in f: | ||
| scan = self._scan_existing() | ||
| migrated = scan.legacy and scan.trusted and self._rewrite_as_utf8() |
There was a problem hiding this comment.
Avoid trusting the reader's locale when migrating shards
When a legacy shard is resumed under a different non-UTF-8 locale, scan.trusted only means that the bytes form valid JSON under the current machine's codepage, not that this codepage originally wrote them. For example, a cp1251 shard containing Привет opened on a cp1252 Windows machine is classified as trusted legacy data and rewritten here as UTF-8 containing Ïðèâåò, permanently corrupting the scraped results. Migration needs recorded encoding provenance or must leave ambiguous legacy files untouched rather than trusting the reader's locale.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
You are right, and this one goes deeper than the fix I put up for it. Verified the mechanism: a cp1251 shard holding Привет is CF F0 E8 E2 E5 F2, every one of those bytes is defined in cp1252, so it decodes to Ïðèâåò and parses as JSON. trusted only ever meant that the local codepage can read the bytes, which for a single-byte codepage is nearly always true. It never meant that codepage wrote them.
Recorded provenance is the only thing that would make the rewrite safe, and there is none to read for shards that already exist. So in 32a0c89 the rewrite is gone entirely rather than patched again.
This is the fourth distinct way that rewrite could corrupt a shard across this review: the whole-file legacy retry, the latin-1 fallback, the single-line verdict, and now the reader locale. They all have the same root, that a file does not carry its encoding, and I should have concluded that two rounds earlier instead of narrowing the guess each time.
Nothing is lost by dropping it. The no-mixed-encoding guarantee that motivated the migration in your first comment is actually delivered by the ASCII appends, not by the rewrite: whenever the shard holds bytes UTF-8 cannot read, records are written with ensure_ascii = True, which every codepage stores identically. The file is now left exactly as found, byte for byte, and still decodes in whatever encoding it always had. Dedup is unaffected, since the keys are ASCII ids that come back the same under either reading.
Re-verified across cp1252, cp1251 and cp932 shards under matching and mismatched locales: the original bytes are untouched in every case, appended records are ASCII, and every record round-trips in the shard own encoding.
| """ | ||
| tmp = self.path.with_suffix(self.path.suffix + ".utf8.tmp") | ||
| try: | ||
| with self.path.open("rb") as src, tmp.open("wb") as dst: |
There was a problem hiding this comment.
Preserve shard permissions during the UTF-8 rewrite
When a legacy shard has restrictive permissions, the migration creates a fresh temp file using the process umask and then replaces the original without copying its mode or ACLs. For example, a 0600 shard becomes 0644 under the common 022 umask after this path runs, potentially exposing scraped private-repository data to other local users. Preserve the original file metadata on the temp file before replacing it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct as written, and it is moot as of 32a0c89: the UTF-8 rewrite is gone, so there is no temp file and no mode or ACL to carry over. The shard is now left exactly as found.
The reasoning is in the reply to the provenance comment above. A file does not carry its encoding, so the conversion could not be made safe, and this permissions gap was one more cost of attempting it.
…able trusted only ever meant that the bytes parse under this machine's codepage, which for a single-byte codepage is nearly always true. A cp1251 shard opened on a cp1252 Windows box decodes cleanly and would have been rewritten with Привет as Ïðèâåò. That is the fourth way this rewrite could corrupt a shard, and the common cause is that a file's encoding cannot be recovered from its bytes. So the rewrite is gone. The shard is left exactly as found, and appends are pure ASCII whenever it holds bytes UTF-8 cannot read, which is what actually delivered the no-mixed-encoding guarantee the rewrite was added for. Dedup keys still come from whichever reading parses, since ids are ASCII either way. This also removes the temp file, so there is no longer any file mode or ACL to carry across.
sandbox_site is on the sandboxed child's PYTHONPATH for every Python run (tools.py:332, 2660), so excluding it let two unannotated text calls through in code we ship. Both read and write the remap sidecar, which holds file paths. The exclusion list is meant for build output only, so the directory comes off it and the two calls name their encoding.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0e2420de64
ℹ️ 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".
| as_legacy = _parse(raw, codepage) | ||
| if as_legacy is not None: | ||
| return _Reading(as_utf8, as_legacy) | ||
| return _Reading(as_utf8, _parse(raw, "latin-1")) |
There was a problem hiding this comment.
Recover keys from multibyte legacy JSONL lines
When a cp932 shard is resumed on a UTF-8 or different-locale host, Latin-1 is not always safe even for extracting ASCII keys: 表 encodes as bytes 95 5c, so the 5c becomes a JSON backslash under this fallback and _parse() rejects the otherwise valid record. JsonlWriter then forgets its id, accepts the same record again, and appends a duplicate to the scrape output. Fresh evidence beyond the earlier moved-shard thread is this Shift-JIS trail-byte case; key recovery needs to avoid parsing the non-ASCII value bytes through a single-byte codec.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed, and the Shift-JIS trail byte is a good catch. Verified it exactly: 表 in cp932 is 95 5C, so latin-1 reads the trail byte as a backslash, the JSON string is left unterminated, and the record is dropped along with its id.
Reproduced before the fix on a UTF-8 host: cp932 and cp936 shards recovered zero keys and grew from three records to four on resume. cp950 too, since 功 is A5 5C. cp949 happened to survive only because the character I picked has no 5C trail byte.
Fixed in 7fab731 by trying cp932, cp936, cp949 and cp950 after the locale codepage and latin-1. That works precisely because this reading is never authoritative: it exists only to recover dedup keys, which are ASCII ids, so any codec that manages to parse the line yields the same key. Guessing wrong costs nothing here, where it would have been fatal in the rewrite I removed.
After the fix all four codepages recover both keys, refuse the duplicate, accept the genuinely new record, leave the shard byte-identical, and append pure ASCII.
| "encoding": "utf-8", | ||
| "errors": "replace", |
There was a problem hiding this comment.
Force pip children to emit UTF-8 before decoding
When uv is unavailable and these installers select sys.executable -m pip on a Windows ANSI locale, the Python child emits redirected output in its locale code page while this newly decodes it as UTF-8. A non-ASCII install path or error such as C:\Users\Jürgen\... is therefore replaced in the captured diagnostics. Fresh evidence after the earlier subprocess-alias fix is that the command builders at _install_package_wheel_first and _ensure_flash_linear_attention_unconditional explicitly choose the Python fallback, while utils.child_stdio.utf8_child_env() documents and fixes this exact parent/child mismatch; apply it to these worker subprocess environments as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Verified and fixed in 7fab731. All three installer calls do run sys.executable -m pip (worker.py:352, 597, 845) and none of them passed an env, so the child inherited the ANSI locale while the parent decoded UTF-8. _run_kwargs and both _sp.run calls now go through utf8_child_env().
The HIP branch still works: it copies from _run_kwargs["env"], so its HIPCC_COMPILE_FLAGS_APPEND is added on top of the UTF-8 env rather than replacing it.
Two tests in test_training_worker_flash_attn.py asserted that no env kwarg was passed, using that as a stand-in for no HIP flag being injected. Since the env is now always passed, they assert the flag directly instead: absent entirely on CUDA, and equal to the user own value on the respects-user-gcc-dir path, which is what those tests were guarding. The rest of that file behaves exactly as before, verified by diffing the failure set against the unmodified branch.
That completes the sweep this thread started: llama_cpp, model_config, transformers_version, wheel_utils, update_flow and now the training worker.
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…o studio-utf8-text-io
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3b2624ff22
ℹ️ 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".
| continue | ||
| target, key = node.value, node.slice | ||
| if isinstance(target, ast.Name) and target.id == name: | ||
| if isinstance(key, ast.Constant) and key.value == "encoding": | ||
| return True |
There was a problem hiding this comment.
Verify encoding assignments precede the subprocess call
When an encoding assignment occurs after the splatted call or only inside one conditional branch, this module-wide search still returns true and suppresses the offender. Fresh evidence after the earlier later-assignment exemption is kw = {"text": True}; run(cmd, **kw); kw["encoding"] = "utf-8", which passes the guard even though the subprocess still uses the locale encoding; associate the assignment with the relevant call and control-flow path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced the mechanism, but not the harm, so declining this one.
Running the guard's own _offenders() over your exact snippet confirms kw = {"text": True} / run(cmd, **kw) / kw["encoding"] = "utf-8" is not flagged, and neither is the branch-only variant nor a same-named kw assigned in a different function.
Then I walked all 333 sources _studio_sources() actually scans, using the guard's own helpers. The only two splatted text-mode kwargs dicts are core/training/worker.py:385 and utils/ssm_runtime.py:254, and both carry "encoding" inside the literal, so _text_mode_dict() returns False and _encoding_assigned_later() is never reached. No backend source contains an x["encoding"] = ... store at all, so the exemption is not load-bearing anywhere and no offender is slipping past it.
That leaves a test guard that is loose for a code shape the repo does not contain, rather than a miss on code that exists. Adding control-flow analysis to it is churn I would rather not carry here.
| for keyword in node.keywords: | ||
| if keyword.arg is None and isinstance(keyword.value, ast.Dict): | ||
| if _text_mode_dict(keyword.value): | ||
| found.append(keyword.value) |
There was a problem hiding this comment.
Restrict inline kwargs checks to subprocess-like calls
Fresh evidence after the earlier dict-scanning fix is that an unrelated call such as render(**{"text": True}) still enters this branch and is reported as subprocess configuration. Because the test scans every runtime source, any legitimate keyword API with an inline text=True mapping will fail CI despite performing no text I/O; check the callee or a known subprocess-helper path before flagging the dictionary.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed the branch is callee-agnostic: render(**{"text": True}) does get flagged. That part is deliberate rather than accidental, because these kwargs dicts are usually splatted through a helper, so the subprocess name is not visible at the call site. Checking the callee would defeat the case the branch exists for.
On the claimed harm, that CI would redden: it would not. The guard scans 333 backend sources, and the only inline **{...} literals in any of them are three TrainingRunSummary(**{...}) calls in routes/training_history.py, none of which carry a "text" key. _studio_sources() also skips tests/, so the fixtures in this file are never scanned either. So there is no false positive today and nothing fails.
That makes this a hypothetical ergonomics cost on a test, not a correctness bug in shipped code, so I am leaving the branch as is.
| reading = _read_line(raw, _locale_encoding()) | ||
| data = reading.as_utf8 if reading.as_utf8 is not None else reading.as_legacy | ||
| self._data = data if isinstance(data, dict) else {} |
There was a problem hiding this comment.
Reject damaged UTF-8 checkpoint data before legacy fallback
When a current UTF-8 checkpoint has one invalid byte inside an otherwise valid cursor string, _read_line fails UTF-8 but successfully parses the whole document as Latin-1, so this installs a mojibaked cursor into _data. The scraper then sends that invalid cursor in its next GraphQL request and can no longer resume; before this change, the decode failure reset the checkpoint and allowed a safe deduplicated restart. Treat this fallback result as corrupt unless there is reliable legacy provenance or validate the checkpoint's ASCII cursor values.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and worse than described. Fixed in 4d8e68c.
Reproduced end to end. A checkpoint that is valid UTF-8 apart from one 0x96 inside issues_cursor fails the UTF-8 read, parses whole under latin-1, and lands Y3Vyc29yOnYyOpK0MjA\x96Mi0wMi0xNlQ... in _data. I sent that exact cursor to the live GraphQL API: GitHub answers HTTP 200 with "repository": null and INVALID_CURSOR_ARGUMENTS. gh_client.graphql() sees no RATE_LIMITED entry, so it logs and returns the partial document. scrape_issues() then reads zero nodes and an empty pageInfo, writes issues_cursor = None, and because hasNextPage is absent it also writes issues_done = True. Every later resume returns early on done and makes no request at all, so the remainder of the stream is lost silently, not merely un-resumable. Driving the same damaged file through the pre-PR StateStore pages normally and scrapes the records.
The fallback also turns out never to help here. A checkpoint holds only base64 cursors and booleans, so if a single-byte reading of one were all ASCII the UTF-8 read would already have succeeded. It can therefore only ever contribute non-ASCII, which is exactly the mojibake case. Written out under cp1252, cp932 or cp1251 a real checkpoint is byte-identical to the UTF-8 one, so nothing legacy is given up.
StateStore now reads UTF-8 only and resets otherwise. _scan_existing() keeps its codepage reading, since shard records genuinely do carry non-ASCII. Regression test covers all three: healthy, codepage-written, and damaged.
A checkpoint holds nothing but base64 cursors and booleans, so one written by an older locale-encoded release is byte-identical to a UTF-8 one and already reads back. The codepage fallback can therefore only ever contribute non-ASCII: if a single-byte reading of the file were all ASCII, the UTF-8 read would have succeeded first. So the only file it changes the answer for is a damaged one, and there it turns a safe reset into a resume on a mojibaked cursor. GitHub answers that with INVALID_CURSOR_ARGUMENTS at HTTP 200, gh_client returns the partial document, and the scraper reads zero nodes and an empty pageInfo, which marks the stream done. Every later resume then skips it entirely. Reading UTF-8 only restores the earlier behaviour of dropping a checkpoint that will not decode, which re-scrapes from the first page while the writers dedup the replay. The shard scan below keeps its codepage reading; those records do carry non-ASCII.
_tilelang_platform_supported() returns False off Linux, so _ensure_tilelang_backend returns before the install and the subprocess mock these six assert on is never called. They fail on macOS runners for that reason alone. The rest of the file already carries this marker; these were missed.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 00ae2ffb13
ℹ️ 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".
| try: | ||
| return json.loads(raw.decode(encoding)) | ||
| except (UnicodeDecodeError, LookupError, ValueError): |
There was a problem hiding this comment.
Treat parser recursion as malformed JSON
When a checkpoint or JSONL shard contains an excessively nested JSON document, json.loads raises RecursionError, which is not covered by this exception tuple. _parse is called outside any broader exception handler in both StateStore.__init__ and JsonlWriter._scan_existing, so one damaged record can now abort scraper startup instead of being discarded or skipped as malformed, as the previous catch-all behavior did. Catch RecursionError here as another parse failure.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and it is a regression this branch introduced. The catch-all this replaced was except Exception, and RecursionError is a RuntimeError, so it was caught before and is not now.
Reproduced with the real classes over a checkpoint and a shard whose first line is a deeply nested document, followed by two healthy records:
base (studio-umlaut-chat-encoding) |
head c2a21b5a5 |
|
|---|---|---|
StateStore(checkpoint) |
ok, {} (damaged checkpoint dropped) |
RecursionError out of __init__ |
JsonlWriter(shard) |
ok, keys ['id:1', 'id:2'] |
RecursionError out of __init__ |
The depth needed is lower than it looks on modern CPython. sys.setrecursionlimit no longer moves it from 3.12 on, since the _json.c Py_EnterRecursiveCall guard is bounded by the C recursion limit, so the threshold is fixed at ~9999 on 3.13 and ~9998 on 3.12. On 3.9, which requires-python = ">=3.9,<3.15" still allows, it follows sys.getrecursionlimit() and is 995. Measured on each, no setrecursionlimit call needed. This is the same under-documented failure mode as python/cpython#135835, which reports json.loads('[' * 9999) verbatim.
Fixed in ddf5156 by adding RecursionError to the tuple, which is what _parse's own contract already promised: nesting json.loads will not descend is a parse failure like any other. Regression test test_an_unparseably_nested_document_is_discarded_not_raised drives both callers and probes the depth at runtime rather than hardcoding it, so it holds across versions and micro versions. It fails with the RecursionError before the change and passes after, and the shard's healthy records still yield their dedup keys, so the resume does not re-fetch them.
| if name == "open" and isinstance(node.func, ast.Name): | ||
| if _mode_is_binary(node) or _has_keyword(node, "encoding"): | ||
| continue | ||
| found.append(f"{path.name}:{node.lineno}: open() without encoding") |
There was a problem hiding this comment.
Include os.fdopen in the encoding guard
The new guard only recognizes a bare open(...) or an attribute literally named open, so text streams created with os.fdopen(...) remain unchecked even though they also default to the locale encoding. There are already unencoded runtime examples in utils/transformers_version.py:2131 and utils/mlx_repair.py:257; their current payloads happen to be ASCII, but this leaves the advertised regression guard unable to detect non-ASCII data later being written through those existing paths.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct on both halves. _call_name returns func.attr for an attribute, so os.fdopen(fd, "w") yields "fdopen" and misses both open branches; a probe file containing an unencoded os.fdopen returned no offenders at all. And the two call sites are exact on head: utils/transformers_version.py:2131 and utils/mlx_repair.py:257, both mode "w", both unencoded. os.fdopen is documented as an alias of the open() built-in accepting the same arguments, so text mode takes the same locale.getencoding() default.
You are right that neither is a live bug, which is why this is P3. But the gap already cost this branch something concrete: the whole diff to mlx_repair.py is pinning the subprocess.run at :293 to UTF-8, and the unencoded os.fdopen sits 36 lines above it in the same call chain. The guard walked past it. Separately, transformers_version.py's swap lock reader _read_swap_lock is pinned to utf-8-sig while its writer was still on the codepage, which is exactly the asymmetry this guard exists to forbid.
So I took it, in ddf5156. Measured the blast radius first: across all 333 scanned sources the widened guard flags exactly those two lines and nothing else. Every other locale-defaulting constructor is either absent from the runtime tree or already encoded, including all seven tempfile.NamedTemporaryFile calls (six binary, the one text call already names UTF-8).
Fixed rather than exempted. The guard has no suppression mechanism, so an exemption would cost more machinery than the fix, and both payloads are ASCII today so the output is byte-identical: json.dumps defaults to ensure_ascii = True, and PEP 440 versions are ASCII.
The widening also closes a positional-encoding hole the bare open() branch already had: _open_has_encoding now accepts encoding at argument index 3, so open(p, "w", 1, "utf-8") and os.fdopen(fd, "w", 1, "utf-8") are no longer false positives. test_the_guard_sees_os_fdopen covers both directions, flagging bare and default-mode calls while leaving binary, keyword-encoded and positionally-encoded ones alone. It fails with set() before the change and passes after.
Two different gates, because the production code has two. The causal-conv1d and flash-linear-attention installers bail out on sys.platform == 'win32' alone and run everywhere else including macOS, so those cases get not_on_windows; marking them linux_only would skip tests that legitimately pass off Linux. The DRM and KFD readers return early unless platform.system() is Linux, and their fixtures build a fake sysfs tree needing PCI addresses like 0000:00:02.0 as directory names, which Windows cannot represent, so those get linux_only. The two visible-utilization cases failed for a different reason: on Windows get_visible_gpu_utilization takes the AMD adapter branch ahead of the torch fallback under test, and probing it imports torch, which the runner lacks. Stubbing that branch empty leaves every other platform unchanged.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c2a21b5a55
ℹ️ 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".
| (tmp_path / "modeling_custom.py").write_text(source, encoding = "utf-8") | ||
| # newline = "" pins the bytes on disk: Windows would otherwise translate the line | ||
| # ends, so the read back would differ by \r for a reason unrelated to encoding. | ||
| (tmp_path / "modeling_custom.py").write_text(source, encoding = "utf-8", newline = "") |
There was a problem hiding this comment.
Keep this test compatible with Python 3.9
When the backend tests run under Python 3.9, this call raises TypeError: Path.write_text() got an unexpected keyword argument 'newline', because pathlib.Path.write_text() only gained newline in Python 3.10. The project declares Python 3.9 support in pyproject.toml, so use an API available there, such as open(..., newline="", encoding="utf-8"), to avoid breaking the supported-version test suite.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in bb7fa45. pyproject declares requires-python >=3.9,<3.15, and Path.write_text only grew the newline argument in 3.10, so this raised TypeError on the lowest supported version. It was the only such call in the suite. Rewritten as open(path, "w", encoding = "utf-8", newline = "") with a with block, which takes the argument on every supported version and pins the bytes on disk the same way, so the intent of not letting Windows translate the line ends is unchanged. 361 encoding tests pass.
json.loads answers nesting it cannot descend with RecursionError, a RuntimeError, so _parse let it escape where the catch-all it replaced discarded the record. Both callers run _parse outside any further handler, so one damaged checkpoint or shard line aborted the scraper at startup. The encoding guard also missed os.fdopen, which is open() on a descriptor and takes the same locale default in text mode. It flags exactly the two text-mode calls that were left unencoded; the swap lock file's reader was already pinned to UTF-8 while its writer still used the codepage.
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Path.write_text() only grew newline in 3.10, and pyproject declares requires-python >=3.9, so this raised TypeError there. open() takes the same argument on every supported version and pins the bytes on disk the same way.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bb7fa45861
ℹ️ 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".
| if isinstance(target, ast.Name) and target.id == name: | ||
| if isinstance(key, ast.Constant) and key.value == "encoding": | ||
| return True |
There was a problem hiding this comment.
Restrict encoding assignments to before the splatted call
When a kwargs dictionary is used without an encoding and the same variable is assigned name["encoding"] only after the subprocess call—or inside an unrelated function—this module-wide AST search still returns true, so _splatted_kwargs_offenders silently accepts the unsafe call. The guard should associate the assignment with the same scope and ensure it executes before the relevant splat.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The mechanism is real but nothing reaches it, which is the same finding as the earlier item on this exemption. Re-scanned at head: _studio_sources() returns 302 files, and across all of them there are zero x["encoding"] = ... subscript stores, so _encoding_assigned_later never returns True and cannot exempt anything, in or out of order, in or out of scope. The only two splatted text-mode kwargs dicts are worker.py:385 and ssm_runtime.py:254, and both carry "encoding" inside the literal, so _text_mode_dict already returns False before the exemption is consulted. Making it scope- and order-aware means a per-scope symbol table plus statement-order and branch reachability analysis inside a test-only guard, to close a path that is provably never taken. Not worth the machinery here.
| def _is_subprocess_call(node: ast.Call, names: set[str]) -> bool: | ||
| func = node.func | ||
| if not isinstance(func, ast.Attribute) or func.attr not in _SUBPROCESS_CALLS: | ||
| return False | ||
| value = func.value | ||
| return isinstance(value, ast.Name) and value.id in names |
There was a problem hiding this comment.
Track subprocess calls routed through callable aliases
When a subprocess call is routed through a callable alias, this predicate rejects it because its AST function is a Name, not an Attribute. For example, both changed calls in utils/wheel_utils.py::install_wheel invoke the run parameter whose default is subprocess.run; removing either encoding would therefore pass the new guard. Track imported, assigned, and parameter-default aliases so these existing installer calls remain protected.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and it reproduces on the two calls you named. install_wheel takes run: Callable[...] = subprocess.run and invokes it as a bare Name at wheel_utils.py:204 and :218, so _is_subprocess_call bailed on the isinstance(func, ast.Attribute) check. Deleting only those two encoding = "utf-8" lines and re-running _offenders returned an empty list, while the same deletion on an attribute-form call is flagged, so the guard was silent on exactly the calls this PR added the encoding to. Fixed in 17266ba: _subprocess_aliases() collects names bound to a subprocess callable by from subprocess import ..., by assignment, and by parameter default, and _is_subprocess_call now matches a Name call against that set. The same deletion is now flagged at both lines. Added test_the_guard_follows_subprocess_through_an_alias covering the three binding forms, plus an encoding-carrying call and a same-named non-subprocess function that must stay unflagged.
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
afd0612
into
studio-umlaut-chat-encoding
* Studio: read model text as utf-8 so umlauts survive on Windows Chat rejects or mangles non-ASCII on Windows: "ä ö ü" in a prompt, a chat template, or a model path comes back as mojibake, or the load dies with UnicodeDecodeError. open() and Path.read_text() fall back to locale.getencoding() when no encoding is passed. On Windows that is the ANSI codepage (cp1252, cp932, cp1251, ... by system locale), never UTF-8. Hugging Face writes these files as raw UTF-8, so every read of one decodes with the wrong codec: - tokenizer_config.json, which holds the chat template. Templates routinely carry -> arrows, smart quotes and CJK, so this is the common path into chat - config.json and adapter_config.json - modules.json, Ollama manifests, and the .py sources the remote-code scanner reads before a model is allowed to load The llama-server and embedding-server stdout readers have the same problem via subprocess(text = True); they now decode utf-8 with errors = "replace" so a stray byte cannot kill a log reader. Encoding arguments only, no logic changes. tests/test_chat_text_encoding.py covers a config.json and a chat template holding umlauts, arrows and CJK, plus the remote-code scanner reading a source file with umlauts. Those pass anywhere the locale is already UTF-8, so a fourth test re-runs the readers under -X warn_default_encoding and fails on any platform if an encoding argument goes missing again. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: name utf-8 explicitly on the remaining text I/O, with an AST guard (#7465) * Studio: name utf-8 explicitly on the remaining text I/O Follow-up to the model-text reads in #7467, covering the rest of the backend: system probes (nvidia-smi, amd-smi, powershell, git, node), package installers, /proc and /sys readers, and internal marker files (pid, install id, bootstrap password, Colab credentials). Same reason as #7467. open(), Path.read_text()/write_text() and subprocess(text = True) fall back to locale.getencoding(), which on Windows is the ANSI codepage rather than UTF-8. These paths are mostly ASCII today, so this is hardening, not a live bug. Encoding arguments only, no logic changes. Adds tests/test_text_io_encoding.py: an AST guard walking every backend source and asserting text I/O names its encoding, so the class of bug cannot creep back in one call at a time. 275 files. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Catch aliased subprocess and positional Path.open, migrate legacy JSONL The guard only matched a receiver literally named subprocess, so worker.py's `import subprocess as _sp` hid three text = True installs that decode pip output with the ANSI codepage. It also skipped any .open() with more than one positional argument, though Path.open takes buffering/encoding/errors/newline positionally. Resuming a scrape written by an older release is the other half: those JSONL lines are in the locale codepage, so the UTF-8 preload raised, the dedup keys were silently forgotten and duplicates were appended to a now mixed-encoding file. Decode with the locale codepage as fallback and rewrite as UTF-8 before the append handle opens, since Windows cannot replace a file it holds open. * Stream the JSONL preload and keep a torn line from relabelling the shard Reading the whole shard to migrate it was wrong twice over. These files reach gigabytes on a large scrape, so the preload now streams line by line and the rewrite streams through a temp file. Worse, one interrupted append used to condemn the file: the whole-file UTF-8 decode failed, every byte was retried as cp1252, and the rewrite persisted mojibake over records that were fine. A line now counts as legacy only if the locale codepage both decodes it and yields valid JSON, which a torn UTF-8 line does not. Damaged lines are skipped and copied through byte for byte. When the rewrite cannot be written at all, the append handle opens with the legacy encoding rather than mixing UTF-8 into the file. install_wheel takes run = subprocess.run as a parameter, so the guard cannot see it. Both wheel installs there now name their encoding. * Decide the shard's encoding from the file, not one line at a time Some byte strings parse both ways. cp1251 `Р°` is D0 B0, which is also valid UTF-8 for `а`, so a UTF-8-first parse quietly showed the wrong text instead of migrating it. A line now yields both readings, and the file decides. Any line that parses under the codepage but not as UTF-8 is unambiguous evidence, and ambiguous lines then follow that verdict, which is enough for any real shard: ordinary Cyrillic or Japanese prose is invalid UTF-8 several times per line. Keys for ambiguous lines are re-derived from the legacy reading during the rewrite. A shard is undecidable only if every line is ambiguous, and nothing can tell those apart. latin-1 is also tried after the locale codepage, so a scrape carried from Windows to a UTF-8 machine still has a reading rather than none. Requiring valid JSON, not just a decode, keeps that from claiming torn lines. * Weigh the whole shard, and never lose a record on the fallback path One structurally valid JSON line carrying a stray 0x96 parses as cp1252, so a single-line verdict let it relabel a healthy shard and mojibake every good record in it. Each line with non-ASCII bytes now votes: parsing only under the codepage is evidence for legacy, parsing as UTF-8 is evidence against, since codepage text rarely forms valid multibyte UTF-8. Ties leave the file alone. When the migration cannot be written the append handle uses the legacy codepage, and errors = "replace" quietly turned characters it cannot hold into question marks while write() still reported success. That path now escapes to \uXXXX instead, which is ASCII, so every codepage holds it and json.loads returns the exact characters. Nothing needs replacing, so errors = "strict" is safe. stream_installer runs sys.executable, so its output is now decoded as UTF-8 by utf8_child_env rather than read as the ANSI codepage. * Only rewrite a shard we can attribute, and append ASCII when we cannot latin-1 was doing too much work. It reads any byte, so it gave a moved shard a reading, but it is the right text only for cp1252: cp1251 Привет came back as Ïðèâåò and the rewrite made that permanent. The codepage is now trusted only when it is the locale's, and an untrusted reading is never written back. That leaves three cases where the file holds bytes UTF-8 cannot read and we are not converting it: no codepage to attribute it to, ambiguous lines outvoting the unambiguous ones, and a preload that could not read the file at all. All three used to append UTF-8 into it. They now append pure ASCII, which every ASCII-compatible codepage stores identically, so the file keeps decoding exactly as it did and no record is lost. Keys from the two readings are also kept apart. A damaged line in a healthy shard was marked seen through its codepage reading, so the retry that would have replaced the unreadable record was refused as a duplicate. * Let the flash-attn install stub take the kwargs the installer now passes _run_kwargs gained encoding and errors, so the one stub in this file that spelled its signature out rejected the call. The other four here already take **kwargs; this one now matches. * Do not let a stuck temp file mask the migration failure unlink() on the failure path could raise in its own right, on a stale .utf8.tmp directory or a temp another process holds. That escaped the constructor instead of returning False, so the caller never reached the ASCII append fallback that keeps the shard single-encoding. The pip fallback in install_wheel also spawns a Python child, so it gets utf8_child_env like the probe above it already had. The uv and nvidia-smi children are native binaries, where PYTHONIOENCODING would do nothing. * Stop converting legacy shards; the encoding that wrote them is unknowable trusted only ever meant that the bytes parse under this machine's codepage, which for a single-byte codepage is nearly always true. A cp1251 shard opened on a cp1252 Windows box decodes cleanly and would have been rewritten with Привет as Ïðèâåò. That is the fourth way this rewrite could corrupt a shard, and the common cause is that a file's encoding cannot be recovered from its bytes. So the rewrite is gone. The shard is left exactly as found, and appends are pure ASCII whenever it holds bytes UTF-8 cannot read, which is what actually delivered the no-mixed-encoding guarantee the rewrite was added for. Dedup keys still come from whichever reading parses, since ids are ASCII either way. This also removes the temp file, so there is no longer any file mode or ACL to carry across. * Scan the sandbox shim; it is shipped code, not a build artifact sandbox_site is on the sandboxed child's PYTHONPATH for every Python run (tools.py:332, 2660), so excluding it let two unannotated text calls through in code we ship. Both read and write the remap sidecar, which holds file paths. The exclusion list is meant for build output only, so the directory comes off it and the two calls name their encoding. * Force the worker's pip children to UTF-8, and read DBCS keys with a DBCS codec The three installer calls run sys.executable -m pip with an inherited environment, so the parent decoded UTF-8 while the child emitted the ANSI codepage. They now go through utf8_child_env like the other Python children. Two tests asserted no env kwarg was passed as a stand-in for no HIP flag being injected. They now assert the flag itself, which is the guarantee they were written for and does not depend on how the env is delivered. Separately, latin-1 cannot stand in for a double-byte codepage while recovering dedup keys: cp932 表 is 95 5C, and the trail byte reads as a JSON backslash, so the record failed to parse and its id was forgotten, appending a duplicate on resume. cp932, cp936, cp949 and cp950 are tried too. The reading is still only ever used for keys, which are ASCII and identical whichever codec parses. * Require more than one legacy line before trusting its dedup keys A shard whose valid records are all ASCII casts no UTF-8 votes, so a single damaged line won the vote by itself, its key was remembered, and the retry that would have replaced the unreadable record was refused. One such line is genuinely undecidable: a legacy record with one accented character and an ASCII record with one stray byte are the same shape. Reading it as damage costs a duplicate; reading it as legacy loses the record for good. Only one of those is recoverable, so it is now read as damage. A real legacy shard has a legacy line for every record carrying an umlaut, so its dedup is unaffected. * Append ASCII whenever the shard already holds non-ASCII bytes The gate asked whether any line was undecodable as UTF-8, which misses a shard where every legacy line happens to be valid UTF-8 too. A cp1251 shard of Р° records is bytes D0 B0 throughout, so appending 世界 as UTF-8 left a file where cp1251 reads the old records correctly and the new one as mojibake, and UTF-8 does the reverse. No single decoding recovered the whole scrape. The gate is now simply whether the shard holds any non-ASCII byte at all, which covers both cases and is easier to reason about: if what is already there reads differently under different encodings, do not add more bytes that do. Appending ASCII costs only \uXXXX escapes, which json.loads turns back into the exact characters, and it leaves the new record correct under either reading. * Skip the two Linux-gated flash-attn tests off Linux _should_try_runtime_flash_attn_install ends in sys.platform.startswith( "linux"), and the threshold test one line above already asserts exactly that, so the two tests that drive _ensure_flash_attn_for_long_context past the gate cannot pass anywhere else: the call returns before it reports a status. They were written on Linux and only surface once the suite actually runs on Windows or macOS, where both fail on an empty status list. This PR is about making the backend behave on Windows, so its own suite should be runnable there. * Fail closed when a KFD topology node does not decode This PR pins that read to utf-8, which turns an undecodable byte into UnicodeDecodeError. That is a ValueError, not an OSError, so it slips past the handler one line below and escapes a helper whose docstring promises to fail closed on any unreadable node. The caller would then lose the whole HIP-order map on a machine that has AMD GPUs, and the reason the helper fails closed is that dropping a node shifts every later ordinal and lets a similar-capacity GPU pass the total-size guard while showing another card's usage. Widening the handler is the same one-line change main already made in #7487, so the two agree and the eventual merge is clean. * Tighten the comments added in this branch * Treat an undecodable marker and undecodable metadata as malformed, not fatal Two more places where pinning the decode changed the failure mode. A UnicodeDecodeError is a ValueError, so neither `except OSError` nor `except (JSONDecodeError, OSError)` catches it, and both sites had a documented fallback that stopped being reached. An undecodable .transport marker used to read as an unknown value, and the caller then safely purged and restarted the partial download. It now aborts prepare_cache_for_transport instead, so the transfer fails rather than retrying. Undecodable .meta.json used to fall back to the file's own name, the same way invalid JSON does. It now aborts URI construction for the entire unstructured seed, so one corrupt byte in original_filename takes out the whole dataset. Both handlers are widened, matching the KFD fix earlier on this branch. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Widen two more decode guards, and pin the kernel installer's pipe Same shape as the ones already fixed here: the read was pinned to UTF-8 while the handler around it still only catches OSError, and UnicodeDecodeError is a ValueError. hf_cache_snapshot_dir answers whether a model is already on disk, and the offline embedding checks turn a raise into a 500. A torn refs/main used to decode into a nonsense commit and miss the snapshot dir; it now skips that cache root and keeps looking. _remove_pid_file runs first in _graceful_shutdown, so a corrupt studio.pid raising there abandoned the inference, export, training and tunnel children the rest of that function exists to kill. ssm_runtime's source-build path builds its subprocess kwargs in a dict and splats them through _run_with_heartbeat, so neither the encoding guard nor the earlier sweep saw the text = True in it: pip's output was still decoded with the Windows ANSI codepage, where a non-ASCII path or a compiler diagnostic mojibakes or raises over an install that was going fine. It now pins the same utf-8/replace pair install_wheel uses, and the HIP branch extends that env rather than replacing it. The guard learned the dict-literal shape and reddens on the old code (ssm_runtime.py:253). * Tighten the comments around the UTF-8 text I/O pins Collapse the multi-line rationales added with the encoding pins down to a line or two each, drop what the code already says, and use one wording for the repeated child-env note. * Do not let an unreadable bootstrap password stop startup, and narrow the kwargs guard ensure_default_admin calls _load_bootstrap_password for every existing admin and the lifespan calls that with no handler, so pinning the decode turned a damaged or pre-pin .bootstrap_password file into a backend that will not start. We write that file ourselves in UTF-8, so a byte that will not decode belongs to a file whose plaintext is worthless anyway; it now reads as no bootstrap password, the same answer as an absent file. A readable one still loads. The new kwargs check also judged every dict literal in the tree, so an unrelated payload carrying "text": True would have been reported as subprocess configuration with a misleading message, and a dict that fills in its encoding on a later line would have been reported too. It now only judges a dict that actually reaches a call, either splatted through a name or written at the call site, and treats a later kw["encoding"] assignment as satisfying it. The ssm_runtime shape it was written for is still caught, and a test pins both directions. * Stop reading a UTF-8 record a second time _read_line always parsed the line under the codepage as well, even when it had already read as UTF-8. Both callers take the UTF-8 reading when there is one and never look at the other, so on a healthy shard the second parse is pure waste, and this file reads all of one on every resume of a scrape it expects to reach gigabytes. Measured on 200,000 records, 76 MB: 1.96s before, 0.81s after, so the double reading was costing 2.8x. The early return is limited to a record, since the key lookup deliberately falls through to the codepage reading when UTF-8 yields something that is not one. A line UTF-8 cannot read still tries the codepage, latin-1 and the double-byte encodings as before, which is what the second reading is for. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Pin the scanned source fixture's line endings test_remote_code_scan_reads_non_ascii_sources compared a file's contents against the string it wrote, but wrote it in text mode, so Windows translated the line ends on the way out and the read back differed by a carriage return. That is the writer's doing, not the encoding the test is about, and it was the one failure on the Windows runner that belonged to this branch. The fixture now writes with newline = "" so the bytes on disk are the string on every platform. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Trim the newer comments to their point Shorten the widened-guard and state store notes added since the last pass, and collapse the line-ending note on the scanned source fixture. * Read the scraper checkpoint as UTF-8 only, never as a codepage A checkpoint holds nothing but base64 cursors and booleans, so one written by an older locale-encoded release is byte-identical to a UTF-8 one and already reads back. The codepage fallback can therefore only ever contribute non-ASCII: if a single-byte reading of the file were all ASCII, the UTF-8 read would have succeeded first. So the only file it changes the answer for is a damaged one, and there it turns a safe reset into a resume on a mojibaked cursor. GitHub answers that with INVALID_CURSOR_ARGUMENTS at HTTP 200, gh_client returns the partial document, and the scraper reads zero nodes and an empty pageInfo, which marks the stream done. Every later resume then skips it entirely. Reading UTF-8 only restores the earlier behaviour of dropping a checkpoint that will not decode, which re-scrapes from the first page while the writers dedup the replay. The shard scan below keeps its codepage reading; those records do carry non-ASCII. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Gate the remaining tilelang install tests to Linux _tilelang_platform_supported() returns False off Linux, so _ensure_tilelang_backend returns before the install and the subprocess mock these six assert on is never called. They fail on macOS runners for that reason alone. The rest of the file already carries this marker; these were missed. * Gate the Windows-incompatible worker and ROCm tests Two different gates, because the production code has two. The causal-conv1d and flash-linear-attention installers bail out on sys.platform == 'win32' alone and run everywhere else including macOS, so those cases get not_on_windows; marking them linux_only would skip tests that legitimately pass off Linux. The DRM and KFD readers return early unless platform.system() is Linux, and their fixtures build a fake sysfs tree needing PCI addresses like 0000:00:02.0 as directory names, which Windows cannot represent, so those get linux_only. The two visible-utilization cases failed for a different reason: on Windows get_visible_gpu_utilization takes the AMD adapter branch ahead of the torch fallback under test, and probing it imports torch, which the runner lacks. Stubbing that branch empty leaves every other platform unchanged. * Treat unparseable JSON nesting as a parse failure, and guard os.fdopen json.loads answers nesting it cannot descend with RecursionError, a RuntimeError, so _parse let it escape where the catch-all it replaced discarded the record. Both callers run _parse outside any further handler, so one damaged checkpoint or shard line aborted the scraper at startup. The encoding guard also missed os.fdopen, which is open() on a descriptor and takes the same locale default in text mode. It flags exactly the two text-mode calls that were left unencoded; the swap lock file's reader was already pinned to UTF-8 while its writer still used the codepage. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Write the non-ASCII source fixture without a 3.10-only argument Path.write_text() only grew newline in 3.10, and pyproject declares requires-python >=3.9, so this raised TypeError there. open() takes the same argument on every supported version and pins the bytes on disk the same way. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Tighten encoding comments * Follow subprocess calls through callable aliases in the encoding guard --------- Co-authored-by: Unsloth <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: danielhanchen <[email protected]> --------- Co-authored-by: Unsloth <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: danielhanchen <[email protected]>
Stacked on #7467, review that one first. This branch is the remainder of the same cleanup, split out so the umlaut fix stays small and reviewable.
Scope
#7467 covers the reads that carry model text, which is the live bug users hit. This one covers everything else in the backend:
nvidia-smi,amd-smi,powershell,git,node,wslpathuv pip,pip, prebuilt update flow, wheel probes, mlx repair/procand/sysreadersMostly ASCII today, so this is hardening rather than a live bug. Encoding arguments only, no logic changes.
The guard
tests/test_text_io_encoding.pywalks every backend source withastand asserts thatopen(),Path.open(),Path.read_text()/write_text()andsubprocess(text = True)all name an encoding. One test per file, so a regression points at the exact file and line.This is the part worth keeping. The bug in #7467 and #6489 did not arrive in one commit, it accumulated one unannotated call at a time.
Review raised that the guard skipped shipped plugins and did not recognise
Path.open(). Both were right and both are fixed: the skip list is now build artifacts only, andPath.open()is matched by its signature (at most one positional argument, and onlymode/buffering/encoding/errors/newlinekeywords) sofitz.open(stream = ...)andav.open(..., metadata_errors = ...)are not false positives.The widened guard then found two real bugs:
data-designer-github-repo-seedwrites JSONL withensure_ascii = Falsethrough an unencodedPath.open("a"), so a repo named世界raisedUnicodeEncodeErrorand aborted scrapingdata-designer-unstructured-seedread an upload's.meta.jsonwithout an encoding, and that file holdsoriginal_filename. UploadingBücher.pdflost the name, and the handler catches onlyJSONDecodeError/OSError, so theUnicodeDecodeErrorwould have propagatedFull backend suite before and after gives an identical failure set.