Skip to content

Official Codebase of 3DCodeVerse

Python

addons: one hash loop, VOXEL_RES goes, the gallery rescan is locked and happens once per ?runs=; comments point at eval/

gaoypenge7d791dffaa1
diff --git a/harness/codeverse3d/addons/__init__.py b/harness/codeverse3d/addons/__init__.py
index 77a62ad0..58b5f441 100644
--- a/harness/codeverse3d/addons/__init__.py
+++ b/harness/codeverse3d/addons/__init__.py
@@ -7,7 +7,7 @@
* ``calibration`` judge repeatability / calibration over recorded runs
(``python -m codeverse3d.addons.calibration``)
* ``skill_targets`` each skill bundle's falsifiable claim, measured (``3dcode skills …``,
- ``bench/skill_targets.py``)
+ ``eval/bench/skill_targets.py``)
The boundary is one-way and pinned by ``tests/core/test_addons_boundary.py``: an addon may
import anything in ``codeverse3d``; outside ``codeverse3d.cli`` nothing in ``codeverse3d`` imports an
diff --git a/harness/codeverse3d/addons/dataset/export.py b/harness/codeverse3d/addons/dataset/export.py
index 10b38518..6530569b 100644
--- a/harness/codeverse3d/addons/dataset/export.py
+++ b/harness/codeverse3d/addons/dataset/export.py
@@ -2,7 +2,7 @@
``export_samples(runs_dir, out_dir)`` writes one sample folder per run (see
``sample.py`` for the layout), records every file it wrote — sha256 each — in
-``<out>/dataset_manifest.json`` (``flywheel/manifest.py``) and builds the text
+``<out>/dataset_manifest.json`` (:func:`write_manifest`, below) and builds the text
index FROM those manifest entries, never from a directory rescan (so repeated
exports into the same folder stay consistent and nothing the selection did not
choose can leak into the index):
diff --git a/harness/codeverse3d/addons/dataset/quality.py b/harness/codeverse3d/addons/dataset/quality.py
index 4a2f3482..4d3d66b9 100644
--- a/harness/codeverse3d/addons/dataset/quality.py
+++ b/harness/codeverse3d/addons/dataset/quality.py
@@ -9,14 +9,13 @@ from __future__ import annotations
import hashlib
import re
from collections import defaultdict
-from collections.abc import Iterable, Mapping
+from collections.abc import Callable, Iterable, Mapping
from typing import Any, Literal
from pydantic import BaseModel, Field
_COMMENT = re.compile(r"^\s*(#|//|\*|/\*).*$")
_TRAILING_COMMENT = re.compile(r"\s+(#|//).*$")
-VOXEL_RES = 16
def normalise_code(text: str) -> str:
@@ -32,32 +31,27 @@ def normalise_code(text: str) -> str:
return "\n".join(out)
-def code_fingerprint(files: Mapping[str, str | bytes]) -> str:
- """Order-independent sha256 over ``(path, normalised code)`` pairs."""
+def _digest(files: Mapping[str, str | bytes], content: Callable[[str | bytes], bytes]) -> str:
+ """Order-independent sha256 over ``path \0 content(data) \0`` for every file."""
h = hashlib.sha256()
for path in sorted(files):
- data = files[path]
- text = data.decode("utf-8", errors="replace") if isinstance(data, bytes) else data
- h.update(path.encode())
- h.update(b"\0")
- h.update(normalise_code(text).encode())
- h.update(b"\0")
+ for part in (path.encode(), content(files[path])):
+ h.update(part)
+ h.update(b"\0")
return h.hexdigest()
+def code_fingerprint(files: Mapping[str, str | bytes]) -> str:
+ """Order-independent sha256 over ``(path, normalised code)`` pairs."""
+ return _digest(files, lambda data: normalise_code(
+ data.decode("utf-8", errors="replace") if isinstance(data, bytes) else data).encode())
+
+
def code_sha256(files: Mapping[str, str | bytes]) -> str:
"""Order-independent sha256 over the RAW ``(path, bytes)`` pairs — the
exact-content counterpart of :func:`code_fingerprint` (no normalisation,
no lossy decode)."""
- h = hashlib.sha256()
- for path in sorted(files):
- data = files[path]
- raw = data.encode("utf-8") if isinstance(data, str) else data
- h.update(path.encode())
- h.update(b"\0")
- h.update(raw)
- h.update(b"\0")
- return h.hexdigest()
+ return _digest(files, lambda data: data.encode("utf-8") if isinstance(data, str) else data)
# ===================================================================== quality
diff --git a/harness/codeverse3d/addons/dataset/refine.py b/harness/codeverse3d/addons/dataset/refine.py
index cc7fe303..1e6bcd56 100644
--- a/harness/codeverse3d/addons/dataset/refine.py
+++ b/harness/codeverse3d/addons/dataset/refine.py
@@ -139,7 +139,7 @@ _LAYOUT_DIRS = frozenset(BATTERY_MARKERS)
def _identity(root: Path, found: Any) -> tuple[str, str]:
"""``(battery, run)`` for a run, taken from where it PHYSICALLY lives.
- ``bench/out``'s batteries symlink each other's cells (54 of 239 runs are reachable
+ ``eval/bench/out``'s batteries symlink each other's cells (54 of 239 runs are reachable
twice), so labelling by the path a scan happened to reach first credits a run to a
battery it never ran in."""
try:
@@ -157,7 +157,7 @@ def transitions(runs_dir: Path | str, *, threshold: float = MIN_PREFERENCE_DELTA
drops: Counter[str] | None = None) -> Iterator[RefineTransition]:
"""Every exportable refine transition under ``runs_dir``; every one that is not is counted.
- A run reachable through more than one path (54 of 239 under ``bench/out``, where the
+ A run reachable through more than one path (54 of 239 under ``eval/bench/out``, where the
batteries symlink each other's cells) is exported once, under the battery it physically
lives in."""
drops = drops if drops is not None else Counter()
diff --git a/harness/codeverse3d/addons/dataset/sample.py b/harness/codeverse3d/addons/dataset/sample.py
index 277c907d..8ed01088 100644
--- a/harness/codeverse3d/addons/dataset/sample.py
+++ b/harness/codeverse3d/addons/dataset/sample.py
@@ -292,7 +292,7 @@ def build_meta(
gates = gate_error_summary(rnd)
n_gate_errors = sum(gates.values())
# difficulty next to quality: a tier-A five-box stool and a tier-A machine are
- # not the same training sample (docs/COMPLEXITY.md)
+ # not the same training sample (eval/docs/COMPLEXITY.md)
cx = record.extra.get("complexity") or (round_complexity(rnd) if rnd is not None else None)
name = ""
if record.plan is not None:
diff --git a/harness/codeverse3d/addons/gallery/detail.py b/harness/codeverse3d/addons/gallery/detail.py
index e19ff11f..2c7fd93b 100644
--- a/harness/codeverse3d/addons/gallery/detail.py
+++ b/harness/codeverse3d/addons/gallery/detail.py
@@ -226,7 +226,7 @@ def _complexity_panel(entry: RunEntry, rec: RunRecord) -> str:
if isinstance(trail, list) and len(trail) > 1:
rows.append(_kv("by round", " → ".join(f"{float(x):.2f}" for x in trail)))
note = ("<p class='xs faint'>objective complexity of the delivered artifact "
- "(codeverse3d/spatial/complexity.py) — difficulty, not quality; see docs/COMPLEXITY.md</p>")
+ "(codeverse3d/spatial/complexity.py) — difficulty, not quality; see eval/docs/COMPLEXITY.md</p>")
return _panel("complexity", f"<div class='kvs'>{''.join(rows)}</div>{note}", anchor="complexity")
diff --git a/harness/codeverse3d/addons/gallery/index.py b/harness/codeverse3d/addons/gallery/index.py
index 1883d3ea..302a7243 100644
--- a/harness/codeverse3d/addons/gallery/index.py
+++ b/harness/codeverse3d/addons/gallery/index.py
@@ -211,7 +211,7 @@ def _complexity(ws: Workspace, rec: RunRecord) -> tuple[float | None, str, dict[
"""``(index, band, axes)`` of the delivered artifact: the record's own
complexity block, else the best round's measurement, else the measurement
file on disk. A run built before the complexity vector existed has none
- (``bench/complexity_report.py`` recomputes those from the GLB)."""
+ (``eval/bench/complexity_report.py`` recomputes those from the GLB)."""
from codeverse3d.record.record import complexity_block
try:
@@ -294,7 +294,7 @@ def entry_for_dir(battery: str, run_dir: Path, *, slug: str | None = None) -> Ru
def _pending_direct_children(root: Path, found: set[Path]) -> list[Path]:
"""Direct children with a spec.json but no record.json yet — a bench mid-write
still deserves a readable (pending) card. Only DIRECT children qualify: a run is
- otherwise gated on record.json exactly like ``flywheel.record.is_run_dir``, because
+ otherwise gated on record.json exactly like ``record.record.is_run_dir``, because
accepting spec-only directories during descent counted every nested ``eval/``
judge workspace of a battery cell as a phantom run."""
if not root.is_dir():
diff --git a/harness/codeverse3d/addons/gallery/page.py b/harness/codeverse3d/addons/gallery/page.py
index 1cd93505..23b8215a 100644
--- a/harness/codeverse3d/addons/gallery/page.py
+++ b/harness/codeverse3d/addons/gallery/page.py
@@ -149,7 +149,7 @@ def render_index(index: GalleryIndex, urls: UrlMaker, *, title: str = "3dcode ga
flt: dict[str, str] | None = None, sort: str = "score", view: str = "cards",
note: str = "", extra_html: str = "") -> str:
"""The whole index page as one HTML document. ``extra_html`` (already
- escaped markup, e.g. bench/report.py's stats tables) goes under the summary strip."""
+ escaped markup, e.g. eval/bench/report.py's stats tables) goes under the summary strip."""
flt = {k: (flt or {}).get(k, "") for k in FILTER_KEYS}
all_entries = index.entries()
selected = [e for e in all_entries if match(e, flt)]
diff --git a/harness/codeverse3d/addons/gallery/server.py b/harness/codeverse3d/addons/gallery/server.py
index bac44403..7ce9a544 100644
--- a/harness/codeverse3d/addons/gallery/server.py
+++ b/harness/codeverse3d/addons/gallery/server.py
@@ -122,10 +122,13 @@ class GalleryApp:
self.index = build_index(self.roots)
# ----------------------------------------------------------------- helpers
- def _entry(self, battery: str, slug: str) -> RunEntry | None:
- entry = self.index.find(battery, slug)
- if entry is None: # a run created since the last scan
- self.index = build_index(self.roots)
+ def _entry(self, battery: str, slug: str, *, rescan: bool = True) -> RunEntry | None:
+ index = self.index
+ entry = index.find(battery, slug)
+ if entry is None and rescan: # a run created since the last scan
+ with self._lock: # one scan at a time, and a waiter never replaces a newer index
+ if self.index is index:
+ self.index = build_index(self.roots)
entry = self.index.find(battery, slug)
return entry
@@ -137,26 +140,28 @@ class GalleryApp:
return sort_entries([e for e in self.index.entries() if match(e, flt)], query.get("sort", "score"))
def picked(self, keys: list[str]) -> tuple[list[RunEntry], list[str]]:
- """``(entries, unknown_keys)`` for ``battery/slug`` keys, in the order given."""
- found, missing = [], []
+ """``(entries, unknown_keys)`` for ``battery/slug`` keys, in the order given — with at
+ most ONE re-scan, however many keys are unknown (it was one full scan per key)."""
+ found, missing, scanned = [], [], False
for key in keys:
battery, _, slug = key.partition("/")
- entry = self._entry(battery, slug) if slug else None
+ entry = self._entry(battery, slug, rescan=not scanned) if slug else None
if entry is None:
missing.append(key)
+ scanned = scanned or bool(slug)
else:
found.append(entry)
return found, missing
def _picked(self, query: dict[str, str]) -> tuple[list[RunEntry], UrlMaker, str]:
- """What ``?runs=`` names, capped, with a note about anything dropped."""
+ """What ``?runs=`` names, capped BEFORE any lookup, with a note about anything dropped."""
self.refresh()
keys = parse_keys(query.get("runs", ""))
- entries, missing = self.picked(keys)
notes = []
- if len(entries) > MAX_COMPARE:
- notes.append(f"showing the first {MAX_COMPARE} of {len(entries)} selected runs")
- entries = entries[:MAX_COMPARE]
+ if len(keys) > MAX_COMPARE:
+ notes.append(f"showing the first {MAX_COMPARE} of {len(keys)} selected runs")
+ keys = keys[:MAX_COMPARE]
+ entries, missing = self.picked(keys)
if missing:
notes.append("unknown: " + ", ".join(missing[:6]))
return entries, self.urls, " · ".join(notes)
diff --git a/harness/codeverse3d/addons/skill_targets.py b/harness/codeverse3d/addons/skill_targets.py
index 8cea17ff..043be123 100644
--- a/harness/codeverse3d/addons/skill_targets.py
+++ b/harness/codeverse3d/addons/skill_targets.py
@@ -10,7 +10,7 @@ Three rules the rows obey:
* **Deterministic only.** Every row is read from a gate report, a build result or a
measured artefact — never from the judge. An 8-prompt A/A of the judged score gave
- paired sd 0.202 and needs ~408 paired prompts to resolve +0.02 (``docs/EVAL.md`` §8);
+ paired sd 0.202 and needs ~408 paired prompts to resolve +0.02 (``eval/docs/EVAL.md`` §8);
a skills A/B read out on ``score`` at n=8 is a coin toss. These do not carry that
variance.
* **One owner per quantity.** ``contract/instance_bbox`` belongs to
@@ -20,7 +20,7 @@ Three rules the rows obey:
deterministic instrument can see says so here rather than borrowing a judged
criterion and calling it evidence.
-``bench/skill_targets.py`` is the readout; ``tests/skills/test_targets.py`` pins the
+``eval/bench/skill_targets.py`` is the readout; ``tests/skills/test_targets.py`` pins the
rows against the live gate vocabulary and against each bundle's own frontmatter.
"""
@@ -81,7 +81,7 @@ TARGETS: tuple[Target, ...] = (
kinds=("connectivity/interpenetration",),
languages=OBJECT_LANGS,
why="the plain count of penetrating pairs is the strongest single predictor of "
- "assembly_fit (r = -0.258, docs/COMPLEXITY.md §6) and the bundle exists to lower it",
+ "assembly_fit (r = -0.258, eval/docs/COMPLEXITY.md §6) and the bundle exists to lower it",
),
Target(
skill="c3d-bbox-contract",
@@ -141,7 +141,7 @@ TARGETS: tuple[Target, ...] = (
languages=("cadquery",),
why="the bundle's own framing is 'the kernel rules that decide whether the script "
"builds at all'; an OCC kernel refusal is a build failure, not a gate finding",
- caveat="no baseline exists: bench/out holds zero graded cadquery runs.",
+ caveat="no baseline exists: eval/bench/out holds zero graded cadquery runs.",
),
Target(
skill="c3d-threejs-forms",
@@ -153,7 +153,7 @@ TARGETS: tuple[Target, ...] = (
languages=("threejs",),
why="the bundle's distinct claim is the traps that make a threejs part silently ship "
"nothing (bevel_depth 0, no computeVertexNormals); the contract gate calls that a missing part",
- caveat="no baseline exists: bench/out holds zero graded threejs runs.",
+ caveat="no baseline exists: eval/bench/out holds zero graded threejs runs.",
),
Target(
skill="c3d-scene-composition",
diff --git a/harness/tests/flywheel_cli/test_run_identity.py b/harness/tests/flywheel_cli/test_run_identity.py
index 0ba309eb..e6a41974 100644
--- a/harness/tests/flywheel_cli/test_run_identity.py
+++ b/harness/tests/flywheel_cli/test_run_identity.py
@@ -1,6 +1,6 @@
"""Run identity (RunId): the slug rule, and that nested batteries no longer collide.
-The real bench/out tree holds 396 run dirs with only 169 distinct basenames — 211 are
+The real eval/bench/out tree holds 396 run dirs with only 169 distinct basenames — 211 are
literally ``run`` (compare_backends ``cells/<id>/<arm>/run``, ab_plan
``arms/<arm>/cells/<id>/<slug>/run``). Keying anything on ``ws.root.name`` therefore
made exports rmtree each other, blew the SQLite PRIMARY KEY, collapsed gallery entries
diff --git a/harness/tests/gallery/test_server.py b/harness/tests/gallery/test_server.py
index 9b8e39d8..6f2b2598 100644
--- a/harness/tests/gallery/test_server.py
+++ b/harness/tests/gallery/test_server.py
@@ -177,6 +177,53 @@ def test_no_reload_still_finds_a_new_run_by_url(gallery_tree: dict[str, Path]):
assert app.route("/run/runs/late_arrival").status == 200
+def test_unknown_compare_keys_cost_one_rescan_not_one_each(gallery_tree: dict[str, Path],
+ monkeypatch: pytest.MonkeyPatch):
+ """``?runs=`` with N unknown keys ran N full scans of every root, and capped the keys
+ only after looking every one of them up."""
+ import codeverse3d.addons.gallery.server as server
+
+ app = GalleryApp([gallery_tree["runs"]])
+ real, scans = server.build_index, []
+ monkeypatch.setattr(server, "build_index", lambda roots: scans.append(1) or real(roots))
+ entries, missing = app.picked(["runs/nope_a", "runs/nope_b", "runs/wooden_chair_ab12cd34"])
+ assert len(scans) == 1 and missing == ["runs/nope_a", "runs/nope_b"] and len(entries) == 1
+ _, _, note = app._picked({"runs": ",".join(f"runs/nope_{i}" for i in range(20))})
+ assert len(scans) == 2 and note.startswith(f"showing the first {server.MAX_COMPARE} of 20 selected runs")
+
+
+def test_a_waiting_rescan_never_replaces_a_newer_index(gallery_tree: dict[str, Path],
+ monkeypatch: pytest.MonkeyPatch):
+ """The rescan-on-miss assigned ``self.index`` without the lock, so a slow, older scan
+ could land after a newer one and put a stale index back."""
+ import codeverse3d.addons.gallery.server as server
+
+ app = GalleryApp([gallery_tree["runs"]])
+ real, scans = server.build_index, []
+ monkeypatch.setattr(server, "build_index", lambda roots: scans.append(1) or real(roots))
+
+ class _Lock: # a lock that says when a caller starts waiting for it
+ def __init__(self) -> None:
+ self.inner, self.waiting = threading.Lock(), threading.Event()
+
+ def __enter__(self) -> None:
+ self.waiting.set()
+ self.inner.acquire()
+
+ def __exit__(self, *exc: object) -> None:
+ self.inner.release()
+
+ app._lock = lock = _Lock()
+ lock.inner.acquire() # another thread is mid-rescan ...
+ t = threading.Thread(target=app.picked, args=(["runs/brand_new"],))
+ t.start()
+ assert lock.waiting.wait(5)
+ app.index = newer = real(app.roots) # ... and publishes a newer index
+ lock.inner.release()
+ t.join(5)
+ assert scans == [] and app.index is newer
+
+
# --------------------------------------------------------------------------- over a real socket
def test_over_a_loopback_socket(app: GalleryApp):
httpd = make_server(app, DEFAULT_HOST, 0)
diff --git a/harness/tests/judges/test_detail_anchors.py b/harness/tests/judges/test_detail_anchors.py
index 61a7d3a2..23ec881f 100644
--- a/harness/tests/judges/test_detail_anchors.py
+++ b/harness/tests/judges/test_detail_anchors.py
@@ -1,6 +1,6 @@
"""The geometry-detail anchors must stay *countable*.
-The corpus study (docs/COMPLEXITY.md) found geometry_detail to be the weakest
+The corpus study (eval/docs/COMPLEXITY.md) found geometry_detail to be the weakest
criterion (static mean 0.667, 2 of 44 runs at ≥ 0.9) and, worse, almost blind to
objective geometry: r = +0.05 against the complexity index and +0.19 against
feature density. The fix was to make the anchors count REFINEMENT KINDS and
diff --git a/harness/tests/judges/test_prompt_builder.py b/harness/tests/judges/test_prompt_builder.py
index 5065512b..9dad2403 100644
--- a/harness/tests/judges/test_prompt_builder.py
+++ b/harness/tests/judges/test_prompt_builder.py
@@ -206,7 +206,7 @@ def test_a_passed_connectivity_gate_tells_the_judge_a_seam_is_not_daylight():
# ===================================================================== the contact ledger (2026-08-30)
-#: the connectivity gate's ledger for a real p90 round — bench/out/codex_tiers_v3/cells/
+#: the connectivity gate's ledger for a real p90 round — eval/bench/out/codex_tiers_v3/cells/
#: cmp_hard_violin/harness_codex_gpt-5.6-sol r00 (16 parts, 26 contacts), re-run through
#: ``check_connectivity(planned_edges=planned_joins(plan, measurement))`` on 2026-08-30.
#: 23 overlaps, one open planned join (the tailpiece never reaches the endpin button).
@@ -240,7 +240,7 @@ CONTRACT_FAIL = GateReport(gate="contract", passed=False, findings=[
def test_ledger_turns_penetration_warn_prose_into_one_measured_line():
- """The audit (docs/EVAL.md §6): 110 of 237 interpenetration flags cited only WARNs the rubric
+ """The audit (eval/docs/EVAL.md §6): 110 of 237 interpenetration flags cited only WARNs the rubric
says to ignore; same images with the gate text removed flipped 13 of 24. The eleven
'interpenetrate by' sentences of this round become one measured line, ERRORs stay."""
from codeverse3d.judges.prompt_builder import gates_section
diff --git a/harness/tests/threejs_render/test_cli_flush.py b/harness/tests/threejs_render/test_cli_flush.py
index c63caf0e..567ea569 100644
--- a/harness/tests/threejs_render/test_cli_flush.py
+++ b/harness/tests/threejs_render/test_cli_flush.py
@@ -7,7 +7,7 @@ the pipe buffer was cut mid-JSON and the caller saw no parsable last line.
Measured 2026-09-06 on the starter scene, `probe_scene.mjs --compile`: written to a file
the summary is 10 462 bytes and parses; through a pipe it was **exactly 8192** and did not.
That is the real mechanism behind every "driver output lost" and "[?] scene did not boot"
-in `bench/out/scene_baseline` / `scene_textures` — it depends on how big the census is, not
+in `eval/bench/out/scene_baseline` / `scene_textures` — it depends on how big the census is, not
on how busy the machine is, which is why it read as weather for two batteries. In
`scene_textures/japanese_garden` it cost the round all three repair attempts and the
texture use the arm existed to measure.
diff --git a/harness/tests/threejs_render/test_render_retry.py b/harness/tests/threejs_render/test_render_retry.py
index f8e11409..d1541d13 100644
--- a/harness/tests/threejs_render/test_render_retry.py
+++ b/harness/tests/threejs_render/test_render_retry.py
@@ -54,7 +54,7 @@ def test_real_failure_is_not_retried(tmp_path, monkeypatch):
assert calls == [100]
-# The string below is verbatim from bench/out/scene_baseline (2026-09-05): with the box
+# The string below is verbatim from eval/bench/out/scene_baseline (2026-09-05): with the box
# at load 93 and swap full, Chrome reaped the render tab and every driver reported it
# this way. "detached frame" was not in TRANSIENT_MARKERS, so the object path did not
# retry it either — it only ever matched the "Target closed" spelling.