Skip to content

Official Codebase of 3DCodeVerse

Python

cleanup: B2+B3 — proc.read_json_or_none + JSONL helpers (iter_jsonl_lines / read_jsonl_lenient / append_jsonl_line)

gaoypeng041a1d7e481a
diff --git a/harness/bench/_jsonl.py b/harness/bench/_jsonl.py
index a8cafc12..01e86483 100644
--- a/harness/bench/_jsonl.py
+++ b/harness/bench/_jsonl.py
@@ -21,6 +21,8 @@ from typing import TypeVar
from pydantic import BaseModel
+from codeverse.proc import iter_jsonl_lines
+
log = logging.getLogger(__name__)
T = TypeVar("T", bound=BaseModel)
@@ -29,18 +31,14 @@ T = TypeVar("T", bound=BaseModel)
def read_jsonl[T: BaseModel](path: Path, model: type[T]) -> list[T]:
"""Parse ``path`` as one ``model`` per line, skipping unparseable lines with a
warning. Missing file → ``[]``."""
- if not Path(path).is_file():
- return []
rows: list[T] = []
bad = 0
- for i, line in enumerate(Path(path).read_text(encoding="utf-8", errors="replace").splitlines()):
- if not line.strip():
- continue
+ for i, line in iter_jsonl_lines(path):
try:
rows.append(model.model_validate_json(line))
except Exception as e: # a truncated/corrupt row must not cost us the good ones
bad += 1
- log.warning("%s:%d unreadable, skipping (%s: %s)", path, i + 1, type(e).__name__, str(e)[:120])
+ log.warning("%s:%d unreadable, skipping (%s: %s)", path, i, type(e).__name__, str(e)[:120])
if bad:
log.warning("%s: skipped %d unreadable line(s), kept %d", path, bad, len(rows))
return rows
diff --git a/harness/bench/complexity_report.py b/harness/bench/complexity_report.py
index 396600cf..785b10b8 100644
--- a/harness/bench/complexity_report.py
+++ b/harness/bench/complexity_report.py
@@ -30,6 +30,7 @@ from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parents[0].parent))
+from codeverse.proc import read_json_or_none # noqa: E402
from codeverse.spatial.complexity import COMPLEXITY_WEIGHTS, ComplexityVector, band_of # noqa: E402
CRITERIA = (
@@ -55,11 +56,7 @@ class Row(dict):
so the CSV/JSON writers stay trivial."""
-def _read_json(p: Path) -> dict[str, Any] | None:
- try:
- return json.loads(p.read_text())
- except (OSError, ValueError):
- return None
+_read_json = read_json_or_none
def _vector_for(run: Path, best: dict[str, Any] | None) -> ComplexityVector | None:
diff --git a/harness/codeverse/agents/transcript.py b/harness/codeverse/agents/transcript.py
index bcd8383e..24331804 100644
--- a/harness/codeverse/agents/transcript.py
+++ b/harness/codeverse/agents/transcript.py
@@ -15,6 +15,8 @@ from typing import Any
from pydantic import BaseModel
+from codeverse.proc import append_jsonl_line, read_jsonl_lenient
+
class Trajectory:
"""Append-only writer for one agent session's files."""
@@ -66,10 +68,7 @@ class Trajectory:
def append(self, kind: str, **data: Any) -> None:
"""Append one JSONL turn: ``{"t": epoch, "kind": kind, **data}``."""
- rec = {"t": round(time.time(), 3), "kind": kind, **data}
- line = json.dumps(rec, ensure_ascii=False, default=str)
- with self._lock, self.transcript_path.open("a") as fh:
- fh.write(line + "\n")
+ append_jsonl_line(self.transcript_path, {"t": round(time.time(), 3), "kind": kind, **data}, self._lock)
def write_result(self, result: BaseModel, **extra: Any) -> Path:
"""Write ``result.json`` = AgentResult fields + any extra diagnostics."""
@@ -78,6 +77,4 @@ class Trajectory:
return self.write_json("result.json", data)
def read_transcript(self) -> list[dict[str, Any]]:
- if not self.transcript_path.is_file():
- return []
- return [json.loads(ln) for ln in self.transcript_path.read_text().splitlines() if ln.strip()]
+ return read_jsonl_lenient(self.transcript_path)
diff --git a/harness/codeverse/cli/_judge.py b/harness/codeverse/cli/_judge.py
index 7ef9e92d..6399a345 100644
--- a/harness/codeverse/cli/_judge.py
+++ b/harness/codeverse/cli/_judge.py
@@ -21,6 +21,7 @@ from codeverse.contracts.artifacts import BuildResult, RenderSet, RenderView
from codeverse.contracts.common import TRACK_INFO
from codeverse.contracts.plan import AcceptanceItem
from codeverse.contracts.run import RoundRecord, RunRecord
+from codeverse.proc import read_json_or_none
from codeverse.workspace import Workspace
@@ -47,14 +48,9 @@ def rubric_for(rec: RunRecord, rnd: RoundRecord, override: str | None) -> str:
def plan_summary_for(ws: Workspace) -> str:
"""Track-agnostic plan digest from plan.json (same fields the tracks summarise)."""
- if not ws.plan_path.is_file():
- return ""
- try:
- data = json.loads(ws.plan_path.read_text())
- except ValueError:
- return ""
+ data = read_json_or_none(ws.plan_path)
plan_digest = C.lazy("codeverse.judges.calibration", "plan_digest")
- return plan_digest(data)
+ return plan_digest(data) if data else ""
def previous_judgment(ws: Workspace, rec: RunRecord, index: int) -> Any:
diff --git a/harness/codeverse/cli/main.py b/harness/codeverse/cli/main.py
index 3bdec569..7078cae6 100644
--- a/harness/codeverse/cli/main.py
+++ b/harness/codeverse/cli/main.py
@@ -29,6 +29,7 @@ from codeverse.cli.tools_cmd import tools
from codeverse.config import get_settings
from codeverse.contracts.common import TRACK_LANGUAGES, Budget, Language, Track
from codeverse.contracts.spec import Constraints, ReferenceImage, RunOptions, Spec
+from codeverse.proc import read_json_or_none
app = typer.Typer(
name="3dcv",
@@ -740,9 +741,8 @@ def _render_round_or_refuse(ws, round_index: int | None) -> int:
def _best_round_of_record(ws) -> int | None:
"""``record.best_round``, or None when there is no readable record yet."""
- try:
- rec = json.loads(ws.record_path.read_text())
- except (OSError, ValueError, AttributeError):
+ rec = read_json_or_none(ws.record_path)
+ if rec is None:
return None
best = rec.get("best_round")
return best if isinstance(best, int) else None
diff --git a/harness/codeverse/cli/skills_cmd.py b/harness/codeverse/cli/skills_cmd.py
index 2e4bdff9..e41527f9 100644
--- a/harness/codeverse/cli/skills_cmd.py
+++ b/harness/codeverse/cli/skills_cmd.py
@@ -16,6 +16,7 @@ from typing import Annotated
import typer
from codeverse.cli._fmt import console, err_console
+from codeverse.proc import read_jsonl_lenient
skills_app = typer.Typer(invoke_without_command=True, help="The skill library: list / show / validate / read-rate report.")
@@ -129,11 +130,7 @@ def report(
rows: list[dict] = []
for p in sorted(Path(runs_dir).rglob("telemetry/skills.jsonl")):
- for line in p.read_text().splitlines():
- try:
- rows.append(json.loads(line))
- except json.JSONDecodeError:
- continue
+ rows.extend(read_jsonl_lenient(p))
if not rows:
err_console.print(f"[yellow]no telemetry/skills.jsonl under {runs_dir}[/] (was CV3D_SKILLS on?)")
raise typer.Exit(code=1)
diff --git a/harness/codeverse/cost/ledger.py b/harness/codeverse/cost/ledger.py
index 64b8febe..ca1a081d 100644
--- a/harness/codeverse/cost/ledger.py
+++ b/harness/codeverse/cost/ledger.py
@@ -42,6 +42,7 @@ from codeverse.models.pricing import (
price_provenance,
unit_prices,
)
+from codeverse.proc import iter_jsonl_lines
log = logging.getLogger(__name__)
@@ -352,16 +353,12 @@ def load_ledger(path: str | Path) -> list[CallCost]:
if found is None:
return []
p = found
- if not p.is_file():
- return []
rows: list[CallCost] = []
- for i, line in enumerate(p.read_text(encoding="utf-8", errors="replace").splitlines()):
- if not line.strip():
- continue
+ for i, line in iter_jsonl_lines(p):
try:
rows.append(CallCost.model_validate_json(line))
except Exception as e: # pragma: no cover - defensive
- log.debug("cost ledger %s:%d unreadable: %s", p, i + 1, e)
+ log.debug("cost ledger %s:%d unreadable: %s", p, i, e)
return rows
diff --git a/harness/codeverse/cost/reconstruct.py b/harness/codeverse/cost/reconstruct.py
index cd4a1bcd..d9a52da4 100644
--- a/harness/codeverse/cost/reconstruct.py
+++ b/harness/codeverse/cost/reconstruct.py
@@ -28,10 +28,8 @@ Double-counting rules (same order as the row sources):
from __future__ import annotations
-import json
import logging
import re
-from collections.abc import Iterator
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
@@ -39,6 +37,7 @@ from typing import Any
from codeverse.contracts.common import Usage
from codeverse.cost.ledger import price_call
from codeverse.cost.types import CallCost, Role, Stage, role_for_stage, stage_for_label
+from codeverse.proc import read_json_or_none, read_jsonl_lenient
log = logging.getLogger(__name__)
@@ -47,27 +46,11 @@ _AGGREGATE_EVENTS = frozenset({"round.done", "run.done", "texture.done"})
def _read_json(path: Path) -> dict[str, Any]:
- try:
- data = json.loads(path.read_text(errors="replace"))
- except (OSError, ValueError):
- return {}
- return data if isinstance(data, dict) else {}
+ return read_json_or_none(path, errors="replace") or {}
-def _read_jsonl(path: Path) -> Iterator[dict[str, Any]]:
- try:
- text = path.read_text(errors="replace")
- except OSError:
- return
- for line in text.splitlines():
- if not line.strip():
- continue
- try:
- row = json.loads(line)
- except ValueError:
- continue
- if isinstance(row, dict):
- yield row
+def _read_jsonl(path: Path) -> list[dict[str, Any]]:
+ return read_jsonl_lenient(path, dicts_only=True)
def _usage(d: Any) -> Usage:
diff --git a/harness/codeverse/events.py b/harness/codeverse/events.py
index 09f283ac..3c80133e 100644
--- a/harness/codeverse/events.py
+++ b/harness/codeverse/events.py
@@ -6,13 +6,14 @@ tests read. Keep payloads small (paths + numbers, not file contents).
from __future__ import annotations
-import json
import logging
import threading
import time
from pathlib import Path
from typing import Any
+from codeverse.proc import append_jsonl_line, read_jsonl_lenient
+
log = logging.getLogger(__name__)
@@ -25,10 +26,7 @@ class EventLog:
def emit(self, event: str, **data: Any) -> None:
"""Append one event. ``event`` is the event name (e.g. ``round.start``);
``data`` may use any keys, including ``kind``."""
- rec = {"t": round(time.time(), 3), "event": event, **data}
- line = json.dumps(rec, default=str, ensure_ascii=False)
- with self._lock, self.path.open("a") as fh:
- fh.write(line + "\n")
+ append_jsonl_line(self.path, {"t": round(time.time(), 3), "event": event, **data}, self._lock)
def read(self) -> list[dict[str, Any]]:
"""Read the log, skipping unparseable lines with a debug log.
@@ -37,15 +35,4 @@ class EventLog:
leaves a partial trailing line — and a killed run is exactly when someone
types ``3dcv status``. A truncated last line must never lose the rest of
the file (same contract as ``cost.ledger.load_ledger``)."""
- if not self.path.is_file():
- return []
- out: list[dict[str, Any]] = []
- text = self.path.read_text(encoding="utf-8", errors="replace")
- for i, line in enumerate(text.splitlines()):
- if not line.strip():
- continue
- try:
- out.append(json.loads(line))
- except ValueError as e:
- log.debug("events %s:%d unreadable: %s", self.path, i + 1, e)
- return out
+ return read_jsonl_lenient(self.path, log=log)
diff --git a/harness/codeverse/flywheel/telemetry.py b/harness/codeverse/flywheel/telemetry.py
index 69ec60f9..8a191d06 100644
--- a/harness/codeverse/flywheel/telemetry.py
+++ b/harness/codeverse/flywheel/telemetry.py
@@ -38,7 +38,7 @@ from codeverse.contracts.run import (
SettingsSnapshot,
StageCost,
)
-from codeverse.proc import write_json_atomic, write_text_atomic
+from codeverse.proc import read_json_or_none, write_json_atomic, write_text_atomic
from codeverse.workspace import Workspace
log = logging.getLogger(__name__)
@@ -300,14 +300,6 @@ def cost_summary(record: RunRecord, rows: list[dict[str, Any]]) -> CostSummary:
)
-def read_json(path: Path) -> dict[str, Any] | None:
- try:
- data = json.loads(path.read_text())
- except (OSError, ValueError):
- return None
- return data if isinstance(data, dict) else None
-
-
# --------------------------------------------------------------------------- io
def write_usage_jsonl(path: Path, rows: list[dict[str, Any]]) -> Path:
return write_text_atomic(path, "".join(json.dumps(r, ensure_ascii=False, default=str) + "\n" for r in rows))
@@ -358,8 +350,8 @@ def load_telemetry(ws: Workspace, record: RunRecord | None = None) -> RunTelemet
"""``record.telemetry`` when present, else the files under ``telemetry/``, else None."""
if record is not None and record.telemetry is not None:
return record.telemetry
- cost = read_json(ws.cost_path)
- settings = read_json(ws.settings_path)
+ cost = read_json_or_none(ws.cost_path)
+ settings = read_json_or_none(ws.settings_path)
if cost is None and settings is None:
return None
try:
diff --git a/harness/codeverse/flywheel/trajectories.py b/harness/codeverse/flywheel/trajectories.py
index 0fb39b8f..ba7fcfb9 100644
--- a/harness/codeverse/flywheel/trajectories.py
+++ b/harness/codeverse/flywheel/trajectories.py
@@ -19,7 +19,6 @@ right before the session (nearest one not after the first transcript event);
from __future__ import annotations
-import json
import subprocess
from pathlib import Path
from typing import Any
@@ -27,6 +26,7 @@ from typing import Any
from pydantic import BaseModel, Field
from codeverse.flywheel import _git
+from codeverse.proc import read_jsonl_lenient
from codeverse.workspace import Workspace
BUILD_TOOLS = frozenset({"build", "run_build"})
@@ -116,16 +116,7 @@ class _Replay:
def read_events(transcript: Path) -> list[dict[str, Any]]:
- out = []
- for line in transcript.read_text(errors="replace").splitlines():
- line = line.strip()
- if not line:
- continue
- try:
- out.append(json.loads(line))
- except ValueError:
- continue
- return out
+ return read_jsonl_lenient(transcript)
def mine_trajectory(ws: Workspace, traj_dir: Path) -> list[TrajectoryRepair]:
diff --git a/harness/codeverse/gallery/index.py b/harness/codeverse/gallery/index.py
index 4c5c37ee..d683a521 100644
--- a/harness/codeverse/gallery/index.py
+++ b/harness/codeverse/gallery/index.py
@@ -12,7 +12,6 @@ and the gallery must still render. Nothing in this module raises for one bad ru
from __future__ import annotations
-import json
import time
from pathlib import Path
@@ -28,6 +27,7 @@ from codeverse.flywheel.record import (
from codeverse.flywheel.sample import gate_error_summary, telemetry_digest
from codeverse.gallery.labels import humanize_view
from codeverse.gallery.model import GalleryIndex, RootSection, RoundRow, RunEntry, RunLink
+from codeverse.proc import read_json_or_none
from codeverse.workspace import Workspace
#: run roots the CLI defaults to when the user names none
@@ -196,10 +196,7 @@ _CX_AXES = ("part_count", "assembly_depth", "tri_count", "materials",
def _measurement_complexity(ws: Workspace) -> dict | None:
"""The complexity block sitting in ``artifacts/measurement.json`` — how a run
finished before the record carried its own block (and after any re-measure)."""
- try:
- data = json.loads((ws.root / "artifacts" / "measurement.json").read_text())
- except (OSError, ValueError):
- return None
+ data = read_json_or_none(ws.root / "artifacts" / "measurement.json") or {}
block = (data.get("extra") or {}).get("complexity")
return block if isinstance(block, dict) else None
@@ -257,10 +254,7 @@ def entry_from_record(battery: str, ws: Workspace, rec: RunRecord) -> RunEntry:
def _spec_fields(run_dir: Path) -> dict[str, str]:
"""Prompt / track / language straight from spec.json — a run with no record yet
still deserves a readable card (and spec.json can be half-written too)."""
- try:
- spec = json.loads((run_dir / "spec.json").read_text())
- except (OSError, ValueError):
- return {}
+ spec = read_json_or_none(run_dir / "spec.json") or {}
return {k: str(spec.get(k) or "") for k in ("prompt", "track", "language")}
diff --git a/harness/codeverse/languages/threejs/lint.py b/harness/codeverse/languages/threejs/lint.py
index c48f17c3..4fbb6220 100644
--- a/harness/codeverse/languages/threejs/lint.py
+++ b/harness/codeverse/languages/threejs/lint.py
@@ -8,7 +8,6 @@ that every planned part has a file and is assembled by ``object.js``.
from __future__ import annotations
-import json
import re
import subprocess
import time
@@ -18,6 +17,7 @@ from codeverse.config import get_settings
from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
from codeverse.contracts.plan import StaticPlan
from codeverse.conventions import to_pascal, to_snake
+from codeverse.proc import read_json_or_none
from codeverse.workspace import Workspace
GATE = "lint:threejs"
@@ -152,15 +152,13 @@ def _exports(src: str) -> set[str]:
def _load_plan(ws: Workspace) -> StaticPlan | None:
- if not ws.plan_path.is_file():
+ data = read_json_or_none(ws.plan_path)
+ if data is None or "parts" not in data or "joints" in data:
return None
try:
- data = json.loads(ws.plan_path.read_text())
- if isinstance(data, dict) and "parts" in data and "joints" not in data:
- return StaticPlan.model_validate(data)
- except (ValueError, OSError):
+ return StaticPlan.model_validate(data)
+ except ValueError:
return None
- return None
def lint_workspace(ws: Workspace) -> GateReport:
diff --git a/harness/codeverse/proc.py b/harness/codeverse/proc.py
index 9092b72b..8700fd72 100644
--- a/harness/codeverse/proc.py
+++ b/harness/codeverse/proc.py
@@ -1,8 +1,9 @@
"""Subprocess + atomic-JSON primitives shared across the harness.
One home for the run-a-child-process pattern (own process group, wall-clock
-timeout, group kill, captured output) and the tmp+rename JSON write. Peer of
-``workspace.py``; stdlib-only — imports nothing from ``codeverse`` so wrappers,
+timeout, group kill, captured output), the tmp+rename JSON write, and the
+tolerant JSON / JSONL readers every "best effort" side-car consumer needs. Peer
+of ``workspace.py``; stdlib-only — imports nothing from ``codeverse`` so wrappers,
spatial helpers and agents can all use it without layering back-edges.
``languages/_common.py`` currently carries the same helpers for its runtime
@@ -13,12 +14,13 @@ from __future__ import annotations
import contextlib
import json
+import logging
import os
import signal
import subprocess
import threading
import time
-from collections.abc import Callable, Mapping
+from collections.abc import Callable, Iterator, Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -162,3 +164,87 @@ def write_json_atomic(path: Path, data: Any) -> None:
(``RunState.load`` refuses to guess). Last writer to rename still wins.
"""
write_text_atomic(path, json.dumps(data, indent=2, ensure_ascii=False, default=str))
+
+
+# ------------------------------------------------------------------ tolerant reads
+def read_json_or_none(path: Path | str, *, errors: str | None = None) -> dict[str, Any] | None:
+ """Parse ``path`` as a JSON object; ``None`` when absent, unreadable, malformed
+ or not a dict at the top level.
+
+ The one tolerant reader behind every "use it if it is there" side-car: it
+ replaced identical ``try: json.loads(read_text()) except (OSError, ValueError)``
+ copies in ``flywheel/telemetry.read_json``, ``bench/complexity_report._read_json``,
+ ``gallery/index._measurement_complexity`` / ``_spec_fields``,
+ ``cli/main._best_round_of_record``, ``runlock._holder``,
+ ``languages/threejs/lint._load_plan``, ``cost/reconstruct._read_json``,
+ ``spatial/_render_common.read_json`` and ``cli/_judge.plan_summary_for`` — all
+ the same algorithm, differing only in whether they also checked ``isinstance(dict)``
+ (which every caller then relied on anyway). Strict readers that must raise on
+ a corrupt input (``Workspace.read_json``, ``judges/calibration._read_json``)
+ deliberately do NOT use this.
+
+ ``errors`` is ``read_text``'s decode policy (``"replace"`` for files another
+ process may still be writing). Reads UTF-8, the encoding :func:`write_json_atomic`
+ writes.
+ """
+ try:
+ data = json.loads(Path(path).read_text(encoding="utf-8", errors=errors))
+ except (OSError, ValueError):
+ return None
+ return data if isinstance(data, dict) else None
+
+
+def iter_jsonl_lines(path: Path | str) -> Iterator[tuple[int, str]]:
+ """``(line_no, line)`` for every non-blank line of a JSONL file, 1-based.
+
+ Missing file → nothing; decoded UTF-8 with ``errors="replace"`` so one bad byte
+ (or a SIGKILL mid-append) costs at most that line. Shared by
+ :func:`read_jsonl_lenient` and by the model-validating readers that keep their own
+ per-line parse (``cost/ledger.load_ledger``, ``bench/_jsonl.read_jsonl``).
+ """
+ p = Path(path)
+ if not p.is_file():
+ return
+ for i, line in enumerate(p.read_text(encoding="utf-8", errors="replace").splitlines()):
+ if line.strip():
+ yield i + 1, line
+
+
+def read_jsonl_lenient(
+ path: Path | str, *, log: logging.Logger | None = None, dicts_only: bool = False
+) -> list[Any]:
+ """Every parseable JSON line of ``path``; unparseable lines are skipped (debug-logged
+ to ``log`` when given), ``dicts_only`` also drops non-object rows.
+
+ Replaced the same skip-bad-lines loop in ``events.EventLog.read``,
+ ``cost/reconstruct._read_jsonl``, ``flywheel/trajectories.read_events``,
+ ``cli/skills_cmd`` (skills report) and ``agents/transcript.read_transcript`` —
+ a truncated last line must never lose the rest of the file (the contract
+ ``cost.ledger.load_ledger`` has always had).
+ """
+ out: list[Any] = []
+ for i, line in iter_jsonl_lines(path):
+ try:
+ row = json.loads(line)
+ except ValueError as e:
+ if log is not None:
+ log.debug("%s:%d unreadable: %s", path, i, e)
+ continue
+ if dicts_only and not isinstance(row, dict):
+ continue
+ out.append(row)
+ return out
+
+
+def append_jsonl_line(path: Path | str, rec: Any, lock: threading.Lock) -> None:
+ """Append ``rec`` as one JSON line under ``lock`` (``ensure_ascii=False``,
+ ``default=str`` so paths / enums / datetimes serialise).
+
+ Replaced the identical bodies of ``events.EventLog.emit`` and
+ ``agents/transcript.Trajectory.append``. ``cost/ledger.CostLedger.append`` is NOT
+ a copy — it mkdirs, flushes and swallows OSError ("flushed on write") — and keeps
+ its own.
+ """
+ line = json.dumps(rec, ensure_ascii=False, default=str)
+ with lock, Path(path).open("a", encoding="utf-8") as fh:
+ fh.write(line + "\n")
diff --git a/harness/codeverse/runlock.py b/harness/codeverse/runlock.py
index d8788124..3538967f 100644
--- a/harness/codeverse/runlock.py
+++ b/harness/codeverse/runlock.py
@@ -25,6 +25,8 @@ from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
+from codeverse.proc import read_json_or_none
+
LOCK_NAME = "run.lock"
@@ -59,9 +61,8 @@ def _holder(path: Path) -> dict | None:
An unreadable or truncated lock is treated as stale rather than fatal: a crashed
process must never leave a run permanently unenterable.
"""
- try:
- rec = json.loads(path.read_text())
- except (OSError, ValueError):
+ rec = read_json_or_none(path)
+ if rec is None:
return None
pid = rec.get("pid")
if not isinstance(pid, int) or not _alive(pid):
diff --git a/harness/codeverse/spatial/_render_common.py b/harness/codeverse/spatial/_render_common.py
index dd3fb428..52e54f90 100644
--- a/harness/codeverse/spatial/_render_common.py
+++ b/harness/codeverse/spatial/_render_common.py
@@ -14,13 +14,13 @@ Nothing in here talks to node — see ``spatial.node.run_node`` (objects) and
from __future__ import annotations
-import json
from collections.abc import Sequence
from pathlib import Path
from typing import Any
from codeverse.config import get_settings
from codeverse.conventions import ViewPreset
+from codeverse.proc import read_json_or_none
from codeverse.spatial.sheet import contact_sheet
@@ -42,13 +42,7 @@ def view_specs(views: Sequence[ViewPreset]) -> list[dict[str, Any]]:
def read_json(path: Path | str) -> dict[str, Any]:
"""Parse a driver side-car (views.json / metrics.json); ``{}`` when absent."""
- p = Path(path)
- if not p.is_file():
- return {}
- try:
- return json.loads(p.read_text())
- except (OSError, ValueError):
- return {}
+ return read_json_or_none(path) or {}
def build_sheet(images: Sequence[tuple[str, str | Path]], out: Path | str) -> str | None:
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index f01e32f0..2c119e12 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -83,7 +83,9 @@ codeverse/
runlock.py ONE writer per run dir — a PID lock that names its holder so a
human can kill that one run and not every run on the box
proc.py stdlib-only subprocess + atomic-JSON primitives (run_subprocess w/ group kill +
- preexec_fn, kill_group, tail, write_json_atomic) — shared by languages/spatial/cli
+ preexec_fn, kill_group, tail, write_json_atomic) and the tolerant readers/writer
+ (read_json_or_none, iter_jsonl_lines, read_jsonl_lenient, append_jsonl_line) —
+ shared by languages/spatial/cli/cost/flywheel/gallery/bench
fanout.py bounded parallel fan-out (fan_out, split_results, FanOutReport) — shared by
tracks/judges/texturing/bench
models/ ChatModel; gemini_convert.py anthropic_convert.py openai_convert.py
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index 7e7d3a83..234288c6 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -37,6 +37,11 @@ get_settings().backends(planner=..., generator=..., judge=..., captioner=...) ->
from codeverse.proc import ProcResult, run_subprocess, kill_group, tail, write_json_atomic
run_subprocess(cmd, *, cwd, timeout_s, env=None, stdin_text=None, preexec_fn=None) -> ProcResult
# own session/process group, group-kill on timeout, never raises on rc != 0; stdlib-only module
+from codeverse.proc import read_json_or_none, iter_jsonl_lines, read_jsonl_lenient, append_jsonl_line
+read_json_or_none(path, *, errors=None) -> dict | None # None when absent / unreadable / malformed / not a dict
+iter_jsonl_lines(path) -> Iterator[tuple[int, str]] # (1-based line_no, line); missing file -> nothing; blanks skipped
+read_jsonl_lenient(path, *, log=None, dicts_only=False) -> list # bad lines skipped (debug-logged when `log` given)
+append_jsonl_line(path, rec, lock) -> None # one json.dumps(ensure_ascii=False, default=str) line under `lock`
```
`Spec.options` is plan-hash safe (`plan_stage_inputs` whitelists spec fields).
`Workspace.write_json` delegates to `proc.write_json_atomic`.
diff --git a/harness/tests/core/test_proc.py b/harness/tests/core/test_proc.py
index f6e246d1..cd3e0476 100644
--- a/harness/tests/core/test_proc.py
+++ b/harness/tests/core/test_proc.py
@@ -10,7 +10,17 @@ import threading
import time
from pathlib import Path
-from codeverse.proc import ProcResult, kill_group, run_subprocess, tail, write_json_atomic
+from codeverse.proc import (
+ ProcResult,
+ append_jsonl_line,
+ iter_jsonl_lines,
+ kill_group,
+ read_json_or_none,
+ read_jsonl_lenient,
+ run_subprocess,
+ tail,
+ write_json_atomic,
+)
def test_run_subprocess_captures_output(tmp_path: Path):
@@ -232,3 +242,28 @@ def test_write_json_atomic_round_trips(tmp_path: Path):
write_json_atomic(out, {"a": 1})
assert json.loads(out.read_text()) == {"a": 1}
assert [p.name for p in out.parent.iterdir()] == ["x.json"]
+
+
+def test_read_json_or_none_is_none_unless_a_dict_parses(tmp_path: Path):
+ assert read_json_or_none(tmp_path / "missing.json") is None
+ (tmp_path / "bad.json").write_text("{not json")
+ assert read_json_or_none(tmp_path / "bad.json") is None
+ (tmp_path / "list.json").write_text("[1, 2]")
+ assert read_json_or_none(tmp_path / "list.json") is None
+ (tmp_path / "ok.json").write_bytes(b'{"a": "caf\xc3\xa9", "b": "\xff"}')
+ assert read_json_or_none(tmp_path / "ok.json") is None # undecodable byte -> ValueError
+ assert read_json_or_none(tmp_path / "ok.json", errors="replace") == {"a": "café", "b": "\ufffd"}
+
+
+def test_jsonl_helpers_round_trip_and_skip_bad_lines(tmp_path: Path):
+ p = tmp_path / "log.jsonl"
+ assert list(iter_jsonl_lines(p)) == [] and read_jsonl_lenient(p) == []
+ lock = threading.Lock()
+ append_jsonl_line(p, {"k": "é", "p": tmp_path}, lock) # default=str for the Path
+ append_jsonl_line(p, [1, 2], lock)
+ with p.open("ab") as fh: # what a SIGKILL mid-append leaves behind
+ fh.write(b'\n{"k": "b\xff\n{"k": "tr')
+ assert [i for i, _ in iter_jsonl_lines(p)] == [1, 2, 4, 5] # 1-based, blank line 3 skipped
+ rows = read_jsonl_lenient(p)
+ assert rows == [{"k": "é", "p": str(tmp_path)}, [1, 2]]
+ assert read_jsonl_lenient(p, dicts_only=True) == rows[:1]