Skip to content

Commit d04df74

Browse files
authored
Merge pull request #10084 from loopx-project/codex/c1-utf8-prefetch-byte-cap-20261203
Keep rendered prefetch text within its UTF-8 byte limit
2 parents a833f27 + 5b02d32 commit d04df74

2 files changed

Lines changed: 54 additions & 10 deletions

File tree

‎loopx/control_plane/turn_driver/epoch_prefetch_io.py‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
"""
88
from __future__ import annotations
99

10+
import codecs
1011
from collections.abc import Mapping
1112
from contextlib import closing
1213
from dataclasses import dataclass
@@ -66,14 +67,18 @@ def _normalize_json_object(value: object) -> dict[str, object] | None:
6667
return normalized
6768

6869

69-
def _utf8_prefix(data: bytes, max_bytes: int) -> tuple[str, bool]:
70-
if len(data) <= max_bytes:
71-
return data.decode("utf-8", errors="replace"), False
72-
clipped = data[:max_bytes]
73-
# Back off past any split UTF-8 continuation bytes so output stays valid text.
74-
while clipped and (clipped[-1] & 0xC0) == 0x80:
75-
clipped = clipped[:-1]
76-
return clipped.decode("utf-8", errors="replace"), True
70+
def _utf8_prefix(data: bytes | bytearray, max_bytes: int, *, truncated: bool = False) -> tuple[str, bool]:
71+
if len(data) > max_bytes:
72+
data = data[:max_bytes]
73+
truncated = True
74+
# A byte cap may split a valid character. Replace incomplete input only at real EOF.
75+
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
76+
text = decoder.decode(data, final=not truncated)
77+
encoded = text.encode("utf-8")
78+
if len(encoded) <= max_bytes:
79+
return text, truncated
80+
# Replacement characters can expand malformed bytes beyond the delivery limit.
81+
return encoded[:max_bytes].decode("utf-8", errors="ignore"), True
7782

7883

7984
def _terminate_process_group(process: subprocess.Popen[bytes]) -> None:
@@ -201,8 +206,7 @@ def run_bounded_prefetch_subprocess(
201206
process.stderr.close()
202207

203208
latency_ms = max(0, int(round((time.monotonic() - start) * 1000)))
204-
output_text, utf8_truncated = _utf8_prefix(bytes(stdout_kept), max_output_bytes)
205-
truncated = truncated or utf8_truncated
209+
output_text, truncated = _utf8_prefix(stdout_kept, max_output_bytes, truncated=truncated)
206210
stderr_text = stderr_kept.decode("utf-8", errors="replace").strip()
207211
error_observation: str | None = None
208212
if timed_out:
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""Byte limits apply to the UTF-8 text delivered by an optional epoch prefetch."""
2+
import sys
3+
4+
import pytest
5+
6+
from loopx.control_plane.turn_driver.epoch_prefetch_io import _utf8_prefix, run_bounded_prefetch_subprocess
7+
8+
9+
@pytest.mark.parametrize(
10+
("raw", "cap", "expected", "was_truncated"),
11+
[
12+
("界".encode(), 3, "界", False),
13+
("界x".encode(), 3, "界", True),
14+
("ab界z".encode(), 4, "ab", True),
15+
("a🎯z".encode(), 2, "a", True),
16+
("a🎯z".encode(), 3, "a", True),
17+
("a🎯z".encode(), 4, "a", True),
18+
("a🎯z".encode(), 5, "a🎯", True),
19+
(b"ab\xff", 3, "ab", True),
20+
(b"\xff", 3, "\ufffd", False),
21+
(b"ab\xe7", 6, "ab\ufffd", False),
22+
(b"", 0, "", False),
23+
],
24+
)
25+
def test_decode_prefetch_output(raw, cap, expected, was_truncated):
26+
kept = bytearray(raw[:cap])
27+
text, truncated = _utf8_prefix(kept, cap, truncated=len(raw) > cap)
28+
assert (text, truncated) == (expected, was_truncated)
29+
assert len(text.encode("utf-8")) <= cap
30+
31+
32+
@pytest.mark.skipif(sys.platform == "win32", reason="The prefetch pipe selector requires POSIX file descriptors")
33+
def test_runner_reports_raw_count_when_a_utf8_character_crosses_the_cap(tmp_path):
34+
path = tmp_path / "source.txt"
35+
path.write_bytes("ab界z".encode("utf-8"))
36+
probe = run_bounded_prefetch_subprocess(["cat", str(path)], timeout_ms=2000, max_output_bytes=4)
37+
assert probe["exit_code"] == 0
38+
assert probe["prefetched_output"] == "ab"
39+
assert probe["truncated"] is True
40+
assert probe["raw_bytes_read"] == 6

0 commit comments

Comments
 (0)