Skip to content

Official Codebase of 3DCodeVerse

Python

models: a planner wrote a NUL escape where it meant the glyphs x and +/-, and it killed a codex cell four stages later

gaoypengcf94dc29e749
diff --git a/harness/codeverse/agents/watchdog.py b/harness/codeverse/agents/watchdog.py
index 6b2b4d0c..8b685f0f 100644
--- a/harness/codeverse/agents/watchdog.py
+++ b/harness/codeverse/agents/watchdog.py
@@ -126,6 +126,7 @@ def run_with_watchdog(
dirs = list(activity_dirs) if activity_dirs is not None else [cwd / "src"]
tracker = ActivityTracker()
t0 = time.monotonic()
+ _reject_control_chars(cmd, cwd)
proc = subprocess.Popen(
list(cmd), cwd=str(cwd), env=dict(env) if env is not None else None,
stdin=subprocess.PIPE if stdin is not None else subprocess.DEVNULL,
@@ -173,3 +174,23 @@ def run_with_watchdog(
rc=rc, stdout="\n".join(out), stderr="\n".join(err), duration_s=time.monotonic() - t0,
timed_out=bool(killed), killed_reason=killed, stdout_lines=out, stderr_lines=err,
)
+
+
+def _reject_control_chars(cmd: Sequence[str], cwd: object) -> None:
+ """Fail with an argv position and an excerpt instead of a bare "embedded null byte".
+
+ ``subprocess.Popen`` raises ``ValueError: embedded null byte`` naming nothing at all —
+ not the argument, not the offset, not the value. On 2026-08-24 that cost an hour to
+ trace back to five ``\\u0000`` escapes a planner had written into plan.json four stages
+ earlier (see ``schema_utils.strip_control_chars``, which is the actual cure). This is
+ the backstop: if one ever leaks again, the error says where.
+ """
+ for i, arg in enumerate(cmd):
+ text = str(arg)
+ j = text.find("\x00")
+ if j != -1:
+ raise ValueError(
+ f"argv[{i}] contains a NUL at offset {j} of {len(text)} — a model almost "
+ f"certainly emitted \\u0000 in structured output and it was not sanitised "
+ f"(cwd={cwd}). Context: {text[max(0, j - 60):j + 40]!r}"
+ )
diff --git a/harness/codeverse/models/schema_utils.py b/harness/codeverse/models/schema_utils.py
index cbf549c2..65c3eff7 100644
--- a/harness/codeverse/models/schema_utils.py
+++ b/harness/codeverse/models/schema_utils.py
@@ -291,6 +291,36 @@ def _first_balanced(text: str, opener: str = "{", closer: str = "}") -> str | No
return None
+#: C0 control characters that are never legitimate inside a model's text field. TAB,
+#: LF and CR are kept — they carry meaning in a description or a code snippet.
+_CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
+#: what a stripped control character is replaced BY. A space, not "": the observed case
+#: was a model writing \u0000 where it meant a glyph it could not encode ("0.078 × 0.300"
+#: -> "0.078 \x00 0.300"), and deleting the byte would silently fuse "0.078" and "0.300"
+#: into a different number. A space keeps the text honest and readable.
+_CONTROL_SUB = " "
+
+
+def strip_control_chars(value: Any) -> Any:
+ """Recursively replace C0 control characters in every string of a parsed JSON value.
+
+ A model can emit ``\u0000`` — it is legal JSON, pydantic accepts it, and the harness
+ persists it happily. It then detonates far away: on 2026-08-24 a gemini-3.7-flash
+ plan carried five of them (written where the model meant ``×`` and ``±``), survived
+ validation and ``plan.json``, and killed all four generation tasks of a codex cell
+ four stages later with ``ValueError: embedded null byte`` out of ``subprocess.Popen``
+ — an error naming no file, no field and no value. Sanitising at ingestion is the
+ only place that covers every model, every track and every downstream consumer.
+ """
+ if isinstance(value, str):
+ return _CONTROL_RE.sub(_CONTROL_SUB, value)
+ if isinstance(value, dict):
+ return {k: strip_control_chars(v) for k, v in value.items()}
+ if isinstance(value, list):
+ return [strip_control_chars(v) for v in value]
+ return value
+
+
def parse_json_lenient(text: str) -> Any:
"""Parse JSON from model text tolerating code fences, leading prose and
trailing chatter. Tries: whole text → fenced block → first balanced {...}
@@ -314,14 +344,14 @@ def parse_json_lenient(text: str) -> Any:
last_err: Exception | None = None
for cand in candidates:
try:
- return json.loads(cand)
+ return strip_control_chars(json.loads(cand))
except json.JSONDecodeError as exc:
last_err = exc
# tolerate trailing commas
fixed = re.sub(r",\s*([}\]])", r"\1", cand)
if fixed != cand:
try:
- return json.loads(fixed)
+ return strip_control_chars(json.loads(fixed))
except json.JSONDecodeError:
pass
raise JsonParseError(f"no JSON value found: {last_err} — head={s[:120]!r}")
diff --git a/harness/tests/models/test_control_chars.py b/harness/tests/models/test_control_chars.py
new file mode 100644
index 00000000..0da53229
--- /dev/null
+++ b/harness/tests/models/test_control_chars.py
@@ -0,0 +1,71 @@
+"""Control characters in model output (codeverse/models/schema_utils.strip_control_chars).
+
+Regression (2026-08-24): a gemini-3.7-flash plan emitted five ``\\u0000`` escapes where the
+model meant glyphs it could not encode — "0.078 × 0.300 × 0.240 m" became
+"0.078 \\x00 0.300 \\x00 0.240 m", and "0.240 m ± 0.005 m" became "0.240 m \\x00 0.005 m".
+That is legal JSON, so it passed the parser, passed pydantic validation, and was written to
+plan.json. It detonated four stages later in a codex cell: every generation task died with
+``ValueError: embedded null byte`` raised by subprocess.Popen, an error naming no file, no
+field and no value. The whole cell was lost.
+"""
+
+from __future__ import annotations
+
+import json
+
+from codeverse.models.schema_utils import parse_json_lenient, strip_control_chars
+
+THE_REAL_PAYLOAD = (
+ '{"summary": "Overall envelope is 0.078 \\u0000 0.300 \\u0000 0.240 m",'
+ ' "acceptance": [{"text": "height is 0.240 m \\u0000 0.005 m"}]}'
+)
+
+
+def test_the_plan_that_killed_a_cell_now_parses_clean():
+ out = parse_json_lenient(THE_REAL_PAYLOAD)
+ blob = json.dumps(out)
+ assert "\x00" not in blob and "\\u0000" not in blob
+ # a space, never deletion: "0.078" and "0.300" must not fuse into "0.0780.300"
+ assert out["summary"] == "Overall envelope is 0.078 0.300 0.240 m"
+ assert out["acceptance"][0]["text"] == "height is 0.240 m 0.005 m"
+
+
+def test_every_string_in_a_nested_structure_is_cleaned():
+ dirty = {"a": "x\x00y", "b": ["p\x07q", {"c": "r\x1bs"}], "n": 3, "ok": None, "t": True}
+ assert strip_control_chars(dirty) == {
+ "a": "x y", "b": ["p q", {"c": "r s"}], "n": 3, "ok": None, "t": True}
+
+
+def test_tab_newline_and_carriage_return_survive():
+ """They carry meaning in a description or an embedded code snippet."""
+ keep = "def f():\n\tx = 1\r\n"
+ assert strip_control_chars(keep) == keep
+
+
+def test_ordinary_unicode_is_untouched():
+ """Only C0 controls go. The glyphs the model FAILED to write are perfectly fine
+ when it writes them properly, and so is every other non-ASCII character."""
+ text = "0.078 × 0.300 m ± 0.005 — café 日本語 🔧"
+ assert strip_control_chars(text) == text
+
+
+def test_a_null_byte_can_no_longer_reach_a_subprocess_argv():
+ """The end-to-end property: what comes out of the parser is safe to exec with."""
+ import subprocess
+
+ out = parse_json_lenient(THE_REAL_PAYLOAD)
+ # would raise ValueError("embedded null byte") before the fix
+ proc = subprocess.run(["printf", "%s", out["summary"]], capture_output=True, text=True, check=True)
+ assert "0.078" in proc.stdout and "\x00" not in proc.stdout
+
+
+def test_the_subprocess_backstop_names_the_offender(tmp_path):
+ """If a NUL ever leaks again, the error must say WHERE — the bare
+ "embedded null byte" from Popen names no argument, offset or value."""
+ import pytest
+
+ from codeverse.agents.watchdog import run_with_watchdog
+
+ poisoned = "harness_instructions: envelope is 0.078 \x00 0.300 m"
+ with pytest.raises(ValueError, match=r"argv\[2\] contains a NUL at offset \d+"):
+ run_with_watchdog(["echo", "ok", poisoned], cwd=tmp_path, env=None, soft_timeout_s=5)