Skip to content

Official Codebase of 3DCodeVerse

Python

flywheel: publish the index with the tars; drop duplicates on the RAW hash

gaoypenge277596245d1
diff --git a/harness/codeverse/flywheel/captions.py b/harness/codeverse/flywheel/captions.py
index bd4abb77..44bc6e84 100644
--- a/harness/codeverse/flywheel/captions.py
+++ b/harness/codeverse/flywheel/captions.py
@@ -8,7 +8,9 @@
Rules enforced in code: strict JSON schema, no API/class names, no brand names,
each field non-empty. Captions are stored in ``record.extra["captions"]`` (with
-provenance) and ``<ws>/captions.json``; ``record.json`` is rewritten — or, with
+provenance) and ``<ws>/captions.json``; the run is re-packaged (deliverable/ +
+telemetry/ + ``record.json``, so the priced captioner call reaches the run's
+ledger and ``deliverable/captions.json`` exists) — or, with
``out_dir`` (read-only runs), written as a side-car ``<out_dir>/<slug>.json`` that
``export_samples(captions_dir=...)`` picks up.
"""
@@ -160,7 +162,8 @@ def caption_sample(
"""Caption the best round of ``record``.
Default: store into ``record.extra["captions"]`` + ``<ws>/captions.json`` and
- rewrite ``record.json``. With ``out_dir`` the workspace is left untouched and
+ re-package the run (``package_run``: deliverable/, telemetry/, ``record.json``) —
+ a caption changes all three. With ``out_dir`` the workspace is left untouched and
``<out_dir>/<slug>.json`` (captions + provenance) is written instead — ``slug``
should be the run's :class:`~codeverse.contracts.run.RunId` slug; without one the
side-car falls back to the directory basename (flat layouts only: every nested
@@ -208,7 +211,10 @@ def caption_sample(
out.mkdir(parents=True, exist_ok=True)
(out / f"{slug or ws.root.name}.json").write_text(json.dumps(payload, indent=2, ensure_ascii=False))
return caps
+ from codeverse.flywheel.record import package_run
+
ws.write_json(ws.root / "captions.json", payload)
+ package_run(ws, record) # captions.json + cost.json + the manifest all go stale otherwise
ws.write_json(ws.record_path, record)
return caps
diff --git a/harness/codeverse/flywheel/deliverable.py b/harness/codeverse/flywheel/deliverable.py
index 507a9792..323806f7 100644
--- a/harness/codeverse/flywheel/deliverable.py
+++ b/harness/codeverse/flywheel/deliverable.py
@@ -8,8 +8,9 @@ folder can be zipped and sent on its own:
or ``robot.urdf`` + ``meshes/*.glb``, or ``frames/*.png`` + ``preview.gif``;
* ``sheet.png`` — the best round's contact sheet (one picture of the result);
* ``captions.json`` when the run is captioned;
-* ``manifest.json`` — every file with its role, size and sha256 (mirrored into
- ``record.deliverable``).
+* ``manifest.json`` — every OTHER file with its role, size and sha256 (mirrored
+ into ``record.deliverable``). It does not list itself: a file cannot carry its
+ own hash, and the returned object must be exactly what is on disk.
Renders per round, gates, judge verdicts and measurements stay in the evidence
bucket (``artifacts/`` = ``evidence/``); tokens, prices and settings stay in
@@ -35,7 +36,6 @@ log = logging.getLogger(__name__)
MAX_FILE_BYTES = 128 * 1024 * 1024
MAX_TOTAL_BYTES = 512 * 1024 * 1024
-MANIFEST_NAME = "manifest.json"
#: artifact file → role, copied when present (object tracks / articulated / graphics)
_ARTIFACT_ROLES: tuple[tuple[str, str], ...] = (
@@ -176,8 +176,7 @@ def _stable_timestamp(previous: RunDeliverable | None, current: RunDeliverable)
packager (or the migration) is a no-op instead of a diff."""
if previous is None or previous.generated_at is None:
return current.generated_at or datetime.now(UTC)
- same = {(f.path, f.sha256) for f in previous.files if f.role != "manifest"} == {
- (f.path, f.sha256) for f in current.files}
+ same = {(f.path, f.sha256) for f in previous.files} == {(f.path, f.sha256) for f in current.files}
return previous.generated_at if same else (current.generated_at or datetime.now(UTC))
@@ -209,13 +208,8 @@ def build_deliverable(ws: Workspace, record: RunRecord, *, clean: bool = True) -
generated_at=datetime.now(UTC),
)
manifest.generated_at = _stable_timestamp(previous, manifest)
- payload = manifest.model_dump(mode="json")
- write_json_atomic(ws.deliverable_manifest_path, payload)
- manifest.files.append(DeliverableFile(
- path=f"deliverable/{MANIFEST_NAME}", role="manifest",
- bytes=ws.deliverable_manifest_path.stat().st_size,
- sha256=_sha256(ws.deliverable_manifest_path.read_bytes())))
- return manifest
+ write_json_atomic(ws.deliverable_manifest_path, manifest.model_dump(mode="json"))
+ return manifest # exactly what is on disk: len(files) and total_bytes == sum(f.bytes)
def load_deliverable(ws: Workspace, record: RunRecord | None = None) -> RunDeliverable | None:
diff --git a/harness/codeverse/flywheel/export.py b/harness/codeverse/flywheel/export.py
index 2022239b..e08f1793 100644
--- a/harness/codeverse/flywheel/export.py
+++ b/harness/codeverse/flywheel/export.py
@@ -11,9 +11,9 @@ choose can leak into the index):
captions{detailed,instruction,factory}, meta_json, code, tar, byte_start,
byte_len, n_files``) plus queryable extras (``track, language, score, passed,
generator, quality_tier, complexity (+band), gate_errors, cost_usd, rounds, status,
- code_fingerprint, prompt_hash, duplicate_of, has_captions``). ``tar``/``byte_*``
- are filled by ``pack.py``; ``duplicate_of`` by the (code fingerprint, prompt)
- dedupe pass (``""`` = canonical row).
+ code_fingerprint, code_sha256, prompt_hash, duplicate_of, near_duplicate_of,
+ has_captions``). ``tar``/``byte_*`` are filled by ``pack.py``; ``duplicate_of``
+ (raw hash) and ``near_duplicate_of`` (normalised) by the dedupe pass.
* ``<out>/metadata.jsonl`` — same rows, one JSON object per line.
* ``<out>/duplicates.json`` — the duplicate groups found by the last export.
* ``<out>/dataset_manifest.json`` — the generation manifest: the filters, one
@@ -38,6 +38,7 @@ from pydantic import BaseModel, Field
from codeverse.contracts.common import ENTRY_FILE, Language
from codeverse.contracts.run import RunId, RunRecord
from codeverse.flywheel import sample as S
+from codeverse.flywheel._git import CODE_ROOTS
from codeverse.flywheel.dedupe import code_sha256
from codeverse.flywheel.manifest import (
DatasetGenerationManifest,
@@ -180,11 +181,12 @@ def export_samples(
API stability); the best round is chosen by ``record.best_round`` or the
highest judged score. Runs whose best round never built are skipped unless
``include_unbuilt`` (failed runs are still useful for repair pairs, not as
- dataset samples). Normalised duplicates (same
- ``dedupe.code_fingerprint`` — a hash of whitespace/comment-normalised code —
- plus the same prompt) are marked in the index (``duplicate_of``) and, with
- ``drop_duplicates``, left out of it AND of the manifest entries, recorded
- under ``manifest.dropped`` as ``duplicate_of:<id>`` (folders stay on disk).
+ dataset samples). Byte-identical duplicates (same raw ``code_sha256`` + prompt)
+ are marked ``duplicate_of`` and, with ``drop_duplicates``, left out of the index
+ AND of the manifest entries, recorded under ``manifest.dropped`` as
+ ``duplicate_of:<id>`` (folders stay on disk). Normalised duplicates are only
+ MARKED (``near_duplicate_of``) — never dropped: whitespace inside a string
+ literal is not a duplicate.
"""
if not best_round:
raise ValueError("export_samples: only best_round=True is supported")
@@ -324,8 +326,11 @@ def row_for_sample(sample_dir: Path) -> dict[str, Any]:
"rounds": int(meta.get("rounds") or 0),
"status": str(meta.get("status") or ""),
"code_fingerprint": str(meta.get("code_fingerprint") or ""),
+ "code_sha256": code_sha256({rel: (sample_dir / rel).read_bytes()
+ for rel in meta.get("files", []) if rel.split("/")[0] in CODE_ROOTS}),
"prompt_hash": str(meta.get("prompt_hash") or ""),
"duplicate_of": "",
+ "near_duplicate_of": "",
"has_captions": bool(caps.get("detailed")),
}
@@ -372,15 +377,18 @@ def parquet_schema() -> Any:
("rounds", pa.int32()),
("status", pa.string()),
("code_fingerprint", pa.string()),
+ ("code_sha256", pa.string()),
("prompt_hash", pa.string()),
("duplicate_of", pa.string()),
+ ("near_duplicate_of", pa.string()),
("has_captions", pa.bool_()),
]
)
-def write_parquet(rows: list[dict[str, Any]], path: Path) -> Path:
- """One row per sample, in :func:`parquet_schema` order.
+def write_parquet(rows: list[dict[str, Any]], path: Path, *, commit: bool = True) -> Path:
+ """One row per sample, in :func:`parquet_schema` order. ``commit=False`` leaves the
+ file at ``<path>.tmp`` and returns it, so a caller can publish it with other files.
``from_pylist(schema=...)`` DROPS any key the schema does not name, silently: that is
how ``complexity`` / ``complexity_band`` — filled by :func:`row_for_sample`, kept in
@@ -400,14 +408,19 @@ def write_parquet(rows: list[dict[str, Any]], path: Path) -> Path:
table = pa.Table.from_pylist(rows, schema=schema)
tmp = path.with_suffix(".parquet.tmp")
pq.write_table(table, tmp, compression="zstd")
+ if not commit:
+ return tmp
tmp.replace(path)
return path
-def write_jsonl(rows: list[dict[str, Any]], path: Path) -> Path:
+def write_jsonl(rows: list[dict[str, Any]], path: Path, *, commit: bool = True) -> Path:
+ """``commit=False``: leave ``<path>.tmp`` and return it (see :func:`write_parquet`)."""
tmp = path.with_suffix(".jsonl.tmp")
with tmp.open("w") as fh:
for r in rows:
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
+ if not commit:
+ return tmp
tmp.replace(path)
return path
diff --git a/harness/codeverse/flywheel/pack.py b/harness/codeverse/flywheel/pack.py
index 3a9ef3ff..c6908d4a 100644
--- a/harness/codeverse/flywheel/pack.py
+++ b/harness/codeverse/flywheel/pack.py
@@ -5,9 +5,10 @@ the ``tar / byte_start / byte_len / n_files`` locator columns (STORAGE_RULES §3
``export_samples``) — no directory rescan, so a duplicate dropped at export can
never ship and nothing outside the manifest reaches an archive. Every file is
sha256-verified against the manifest as it is added (fail fast, naming the file);
-each archive is written as ``samples-NNN.tar.tmp`` and moved into place only
-after the WHOLE pack loop succeeded, so a failed re-pack leaves the previous
-archives and index untouched.
+the archives AND the two index files are written as ``.tmp`` and moved into place
+in one final loop, so a failure anywhere — including in ``write_parquet`` — leaves
+the previous archives and index untouched. Tars left over from a re-pack that
+produced fewer shards are removed after that loop.
Each sample's files are written consecutively so ``byte_start..+byte_len`` is a
valid sub-tar; ``verify_locators`` round-trips every row.
@@ -132,6 +133,10 @@ def pack_samples(out_dir: Path | str, *, tar_prefix: str = "", max_tar_bytes: in
rep.n_samples += 1
tar.close()
tar = None
+ # the index is published WITH the tars: a failure here used to leave every new
+ # tar in place and the old index pointing into it (byte offsets of a re-pack)
+ tmp_to_final.append((write_parquet(rows, out / PARQUET_NAME, commit=False), out / PARQUET_NAME))
+ tmp_to_final.append((write_jsonl(rows, out / JSONL_NAME, commit=False), out / JSONL_NAME))
done = True
finally:
if not done: # leave the previous archives and index exactly as they were
@@ -141,8 +146,11 @@ def pack_samples(out_dir: Path | str, *, tar_prefix: str = "", max_tar_bytes: in
tmp.unlink(missing_ok=True)
for tmp, final in tmp_to_final:
os.replace(tmp, final)
- rep.parquet = str(write_parquet(rows, out / PARQUET_NAME))
- write_jsonl(rows, out / JSONL_NAME)
+ for stale in out.glob("samples-*.tar"): # a re-pack with fewer shards must leave no dead tar
+ n = stale.name[len("samples-"):-len(".tar")]
+ if n.isdigit() and int(n) >= tar_idx:
+ stale.unlink()
+ rep.parquet = str(out / PARQUET_NAME)
return rep
diff --git a/harness/codeverse/flywheel/quality.py b/harness/codeverse/flywheel/quality.py
index 25844d19..2c7338b9 100644
--- a/harness/codeverse/flywheel/quality.py
+++ b/harness/codeverse/flywheel/quality.py
@@ -1,4 +1,4 @@
-"""Dataset hygiene: quality tiers + normalised-duplicate detection by (code fingerprint, prompt).
+"""Dataset hygiene: quality tiers + duplicate detection by (code hash, prompt).
* ``quality_tier(passed, gate_errors, score)`` → ``A | B | C | D``::
@@ -8,9 +8,12 @@
D everything else (unjudged, failed, low score)
* ``find_duplicates(rows)`` groups index rows with identical
- ``(code_fingerprint, prompt_hash)``; the canonical row of a group is the
+ ``(code_sha256, prompt_hash)`` — RAW bytes. The canonical row of a group is the
best (tier, score, fewest gate errors, captioned, then key order) and every other row gets
- ``duplicate_of = canonical id``.
+ ``duplicate_of = canonical id``. This is the only set anything may DROP.
+* ``find_near_duplicates(rows)`` groups on the NORMALISED ``code_fingerprint``
+ instead and only stamps ``near_duplicate_of``: ``x = "a b"`` and ``x="ab"``
+ normalise the same but are different programs, so they are marked, never removed.
"""
from __future__ import annotations
@@ -42,7 +45,7 @@ def quality_tier(*, passed: bool | None, gate_errors: int, score: float | None)
class DuplicateGroup(BaseModel):
- code_fingerprint: str
+ code_hash: str = Field(description="raw code_sha256 (find_duplicates) or normalised code_fingerprint (near)")
prompt_hash: str
canonical: str = Field(description="sample id kept")
duplicates: list[str] = Field(default_factory=list, description="sample ids marked duplicate_of=canonical")
@@ -60,37 +63,43 @@ def _rank(row: dict[str, Any]) -> tuple:
)
-def find_duplicates(rows: Iterable[dict[str, Any]]) -> list[DuplicateGroup]:
- """Group rows by identical (code_fingerprint, prompt_hash); only groups with ≥ 2 rows are returned.
-
- The fingerprint is of NORMALISED code (``dedupe.normalise_code`` strips comments
- and whitespace), so these are normalised duplicates, not raw-byte-exact ones —
- the raw hash lives in the manifest as ``code_sha256``.
- Rows without a fingerprint are never grouped. The rows are not modified;
- use ``mark_duplicates`` to stamp ``duplicate_of``.
- """
+def _group(rows: Iterable[dict[str, Any]], column: str) -> list[DuplicateGroup]:
+ """Groups of ≥ 2 rows sharing ``(row[column], prompt_hash)``; blank keys never group.
+ The rows are not modified — ``mark_duplicates`` stamps them."""
buckets: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)
for r in rows:
- fp = str(r.get("code_fingerprint") or "")
- if not fp:
+ key = str(r.get(column) or "")
+ if not key:
continue
- buckets[(fp, str(r.get("prompt_hash") or ""))].append(r)
+ buckets[(key, str(r.get("prompt_hash") or ""))].append(r)
groups = []
- for (fp, ph), members in sorted(buckets.items()):
+ for (key, ph), members in sorted(buckets.items()):
if len(members) < 2:
continue
members = sorted(members, key=_rank)
- groups.append(DuplicateGroup(code_fingerprint=fp, prompt_hash=ph, canonical=str(members[0]["id"]),
+ groups.append(DuplicateGroup(code_hash=key, prompt_hash=ph, canonical=str(members[0]["id"]),
duplicates=[str(m["id"]) for m in members[1:]]))
return groups
+def find_duplicates(rows: Iterable[dict[str, Any]]) -> list[DuplicateGroup]:
+ """Exact duplicates: identical RAW ``(code_sha256, prompt_hash)`` — the only DROP set."""
+ return _group(rows, "code_sha256")
+
+
+def find_near_duplicates(rows: Iterable[dict[str, Any]]) -> list[DuplicateGroup]:
+ """Normalised duplicates (``code_fingerprint``) — MARKED as ``near_duplicate_of``, never dropped."""
+ return _group(rows, "code_fingerprint")
+
+
def mark_duplicates(rows: list[dict[str, Any]]) -> list[DuplicateGroup]:
- """Set ``row["duplicate_of"]`` ("" for canonical rows) in place; returns the groups."""
- for r in rows:
- r["duplicate_of"] = ""
+ """Stamp ``duplicate_of`` (raw) and ``near_duplicate_of`` (normalised) in place;
+ returns the exact groups — the only ones a caller may drop."""
groups = find_duplicates(rows)
dup_of = {d: g.canonical for g in groups for d in g.duplicates}
+ near_of = {d: g.canonical for g in find_near_duplicates(rows) for d in g.duplicates}
for r in rows:
- r["duplicate_of"] = dup_of.get(str(r.get("id")), "")
+ rid = str(r.get("id"))
+ r["duplicate_of"] = dup_of.get(rid, "")
+ r["near_duplicate_of"] = near_of.get(rid, "")
return groups
diff --git a/harness/tests/flywheel_cli/test_captions.py b/harness/tests/flywheel_cli/test_captions.py
index ee2982ca..30ed69a0 100644
--- a/harness/tests/flywheel_cli/test_captions.py
+++ b/harness/tests/flywheel_cli/test_captions.py
@@ -53,6 +53,32 @@ def test_caption_sample_stores_and_writes(fake_run):
assert again.extra["captions"]["factory"] == GOOD["factory"]
assert again.extra["captions"]["provenance"]["captioner"] == "fake:fake"
assert again.extra["captions"]["provenance"]["cost_usd"] == pytest.approx(0.001)
+ # a caption changes the hand-over folder too — it used to leave deliverable/,
+ # the manifest, record.deliverable and telemetry/ describing an uncaptioned run
+ assert json.loads((ws.deliverable / "captions.json").read_text())["factory"] == GOOD["factory"]
+ assert again.deliverable is not None and again.telemetry is not None
+ assert "deliverable/captions.json" in {f.path for f in again.deliverable.files}
+
+
+def test_caption_cmd_writes_the_captioner_row_into_the_run_ledger(fake_run, monkeypatch):
+ """`3dcv flywheel caption` joins the run's ledger the way `3dcv judge` does —
+ the captioner's priced call used to go to the per-process log instead."""
+ from typer.testing import CliRunner
+
+ import codeverse.models.registry as R
+ from codeverse.cli.main import app
+ from codeverse.cost.ledger import open_run_ledger
+
+ ws, rec = fake_run
+ ledger = open_run_ledger(ws.root) # the run already keeps one (create=False appends)
+ ledger.path.touch()
+ monkeypatch.setattr(R, "_build_chat_model", lambda _mid: FakeModel([GOOD]))
+ r = CliRunner().invoke(app, ["flywheel", "caption", ws.root.name, "--runs-dir", str(ws.root.parent),
+ "--model", "fake:fake"])
+ assert r.exit_code == 0, r.output
+ rows = [json.loads(ln) for ln in ledger.path.read_text().splitlines() if ln.strip()]
+ assert any(row.get("label") == "captioner" for row in rows), rows
+ assert (ws.deliverable / "captions.json").is_file()
def test_caption_retry_then_fail(fake_run):
diff --git a/harness/tests/flywheel_cli/test_manifest_pack.py b/harness/tests/flywheel_cli/test_manifest_pack.py
index 90e50320..52ff01ae 100644
--- a/harness/tests/flywheel_cli/test_manifest_pack.py
+++ b/harness/tests/flywheel_cli/test_manifest_pack.py
@@ -6,7 +6,8 @@ duplicate, a re-pack truncated the previous valid archive at open, and a planted
``src/meta.json`` (sample folders carry the run's LLM-written src/** tree) could
inject a phantom row. The manifest is now the single source of truth: pack tars
ONLY manifest entries, verifies every byte against the recorded sha256, and
-replaces archives atomically after the whole loop succeeded.
+publishes the archives AND the index in one replace loop after the whole pack
+succeeded (a failure in either window leaves the previous dataset untouched).
"""
from __future__ import annotations
@@ -70,7 +71,7 @@ def test_filtered_runs_are_recorded_as_dropped(runs_dir: Path, tmp_path: Path):
# --------------------------------------------------------------------------- drop-duplicates → pack
def test_drop_duplicates_then_pack_ships_no_duplicate(runs_dir: Path, tmp_path: Path):
out = tmp_path / "ds"
- # the codex run shares prompt + best-round code with the chair → normalised duplicate
+ # the codex run shares prompt + best-round code bytes with the chair → exact duplicate
rep = export_samples(runs_dir, out, drop_duplicates=True)
assert rep.n_exported == 3 and rep.n_indexed == 2 and rep.n_duplicates == 1
m = load_manifest(out)
@@ -99,12 +100,16 @@ def test_pack_without_a_manifest_is_a_hard_error(tmp_path: Path):
load_manifest(out)
-def test_repack_failure_leaves_the_old_tar_and_index_intact(runs_dir: Path, tmp_path: Path):
+def _packed_state(out: Path) -> dict[str, bytes]:
+ return {p.name: p.read_bytes()
+ for p in [*out.glob("samples-*.tar"), out / "metadata.jsonl", out / "metadata.parquet"]}
+
+
+def test_a_failure_inside_the_pack_loop_leaves_the_old_tar_and_index_intact(runs_dir: Path, tmp_path: Path):
out = tmp_path / "ds"
export_samples(runs_dir, out)
pack_samples(out)
- tar_path = out / "samples-000.tar"
- before = {p.name: p.read_bytes() for p in (tar_path, out / "metadata.jsonl", out / "metadata.parquet")}
+ before = _packed_state(out)
# corrupt the recorded hash of a file in the LAST entry: the mismatch fires
# mid-pack, after earlier samples were already added to the new tmp archive
m = load_manifest(out)
@@ -114,13 +119,40 @@ def test_repack_failure_leaves_the_old_tar_and_index_intact(runs_dir: Path, tmp_
write_manifest(m, out)
with pytest.raises(PackError, match=re.escape(rel)):
pack_samples(out)
- assert tar_path.read_bytes() == before["samples-000.tar"] # old archive untouched
- assert (out / "metadata.jsonl").read_bytes() == before["metadata.jsonl"]
- assert (out / "metadata.parquet").read_bytes() == before["metadata.parquet"]
+ assert _packed_state(out) == before # old archives AND index untouched
assert not list(out.glob("*.tmp")) # the half-written tmp tar is cleaned up
assert verify_locators(out) == 3 # the previous pack still round-trips
+def test_a_failure_after_the_pack_loop_publishes_nothing(runs_dir: Path, tmp_path: Path, monkeypatch):
+ """The window the tar loop does NOT cover: every tar is written, then the index
+ write fails. Publishing the tars alone left the OLD index resolving to the new
+ tars' byte offsets — six rows pointing at the wrong bytes, and verify_locators
+ happily passing a corrupt dataset."""
+ import codeverse.flywheel.pack as P
+
+ out = tmp_path / "ds"
+ export_samples(runs_dir, out)
+ pack_samples(out)
+ before = _packed_state(out)
+ monkeypatch.setattr(P, "write_parquet", lambda *a, **k: (_ for _ in ()).throw(OSError("No space left on device")))
+ with pytest.raises(OSError, match="No space left"):
+ pack_samples(out)
+ assert _packed_state(out) == before
+ assert not list(out.glob("*.tmp"))
+ assert verify_locators(out) == 3
+
+
+def test_a_repack_with_fewer_shards_leaves_no_orphan_tar(runs_dir: Path, tmp_path: Path):
+ out = tmp_path / "ds"
+ export_samples(runs_dir, out)
+ assert pack_samples(out, max_tar_bytes=1).tars == ["samples-000.tar", "samples-001.tar", "samples-002.tar"]
+ prep = pack_samples(out) # one shard now: 001/002 are dead bytes the index never names
+ assert prep.tars == ["samples-000.tar"]
+ assert sorted(p.name for p in out.glob("samples-*.tar")) == ["samples-000.tar"]
+ assert verify_locators(out) == 3
+
+
def test_a_tampered_sample_file_fails_fast_and_names_it(runs_dir: Path, tmp_path: Path):
out = tmp_path / "ds"
export_samples(runs_dir, out)
diff --git a/harness/tests/flywheel_cli/test_quality_gallery.py b/harness/tests/flywheel_cli/test_quality_gallery.py
index 59705efb..291ea64f 100644
--- a/harness/tests/flywheel_cli/test_quality_gallery.py
+++ b/harness/tests/flywheel_cli/test_quality_gallery.py
@@ -36,22 +36,45 @@ def test_quality_tier_rule():
assert quality_tier(passed=None, gate_errors=5, score=None) == "D"
-def test_find_and_mark_duplicates():
+def test_only_raw_hash_duplicates_are_dropped_normalised_ones_are_only_marked():
+ """``duplicate_of`` (the DROP set) is keyed on the RAW code_sha256; the normalised
+ fingerprint only ever stamps ``near_duplicate_of`` — row c differs from a/b/e in
+ bytes alone and must survive."""
rows = [
- {"id": "a", "key": "a", "code_fingerprint": "X", "prompt_hash": "p", "quality_tier": "B", "score": 0.8},
- {"id": "b", "key": "b", "code_fingerprint": "X", "prompt_hash": "p", "quality_tier": "A", "score": 0.8},
- {"id": "c", "key": "c", "code_fingerprint": "X", "prompt_hash": "q", "quality_tier": "A", "score": 0.9},
- {"id": "d", "key": "d", "code_fingerprint": "", "prompt_hash": "p", "quality_tier": "A", "score": 0.9},
- {"id": "e", "key": "e", "code_fingerprint": "X", "prompt_hash": "p", "quality_tier": "A", "score": 0.8,
+ {"id": "a", "key": "a", "code_sha256": "R", "code_fingerprint": "X", "prompt_hash": "p", "quality_tier": "B", "score": 0.8},
+ {"id": "b", "key": "b", "code_sha256": "R", "code_fingerprint": "X", "prompt_hash": "p", "quality_tier": "A", "score": 0.8},
+ {"id": "c", "key": "c", "code_sha256": "S", "code_fingerprint": "X", "prompt_hash": "p", "quality_tier": "A", "score": 0.8},
+ {"id": "d", "key": "d", "code_sha256": "R", "code_fingerprint": "X", "prompt_hash": "q", "quality_tier": "A", "score": 0.9},
+ {"id": "e", "key": "e", "code_sha256": "R", "code_fingerprint": "X", "prompt_hash": "p", "quality_tier": "A", "score": 0.8,
"has_captions": True},
+ {"id": "f", "key": "f", "code_sha256": "", "code_fingerprint": "", "prompt_hash": "p", "quality_tier": "A", "score": 0.9},
]
groups = find_duplicates(rows)
assert len(groups) == 1 and groups[0].canonical == "e" and set(groups[0].duplicates) == {"a", "b"}
mark_duplicates(rows)
- assert {r["id"]: r["duplicate_of"] for r in rows} == {"a": "e", "b": "e", "c": "", "d": "", "e": ""}
+ assert {r["id"]: r["duplicate_of"] for r in rows} == {"a": "e", "b": "e", "c": "", "d": "", "e": "", "f": ""}
+ assert {r["id"]: r["near_duplicate_of"] for r in rows} == {"a": "e", "b": "e", "c": "e", "d": "", "e": "", "f": ""}
assert prompt_hash(" a chair ") == prompt_hash("a chair") and len(prompt_hash("x")) == 16
+def test_whitespace_inside_a_string_is_a_near_duplicate_not_a_duplicate(runs_dir: Path, tmp_path: Path):
+ """``LABEL = "a b"`` and ``LABEL="ab"`` normalise identically but are different
+ programs: --drop-duplicates must keep both and only mark them, while the
+ byte-identical chair/codex pair is still dropped."""
+ common = '# round 1\nimport bpy\nLABEL={}\nbpy.ops.mesh.primitive_cube_add(size=2.0)\n'
+ make_fake_run(runs_dir, "stool_spaced", prompt="a stool", code_v2=common.format('"a b"'))
+ make_fake_run(runs_dir, "stool_tight", prompt="a stool", code_v2=common.format('"ab"'))
+ out = tmp_path / "ds"
+ rep = export_samples(runs_dir, out, drop_duplicates=True)
+ rows = {json.loads(ln)["key"]: json.loads(ln) for ln in (out / "metadata.jsonl").read_text().splitlines()}
+ assert {"stool_spaced", "stool_tight"} <= set(rows)
+ assert rows["stool_spaced"]["code_sha256"] != rows["stool_tight"]["code_sha256"]
+ assert rows["stool_spaced"]["code_fingerprint"] == rows["stool_tight"]["code_fingerprint"]
+ assert [rows[k]["duplicate_of"] for k in ("stool_spaced", "stool_tight")] == ["", ""]
+ assert rows["stool_tight"]["near_duplicate_of"] == "3dcodeverse/static_object/blender/stool_spaced"
+ assert "wooden_chair_codex" not in rows and rep.n_duplicates == 1 # byte-identical → dropped
+
+
# --------------------------------------------------------------------------- export extras
@@ -89,8 +112,8 @@ def test_export_meta_tiers_duplicates_and_captions_sidecar(runs_dir: Path, tmp_p
import pyarrow.parquet as pq
table = pq.read_table(out / "metadata.parquet")
- assert {"quality_tier", "gate_errors", "cost_usd", "rounds", "status", "code_fingerprint", "prompt_hash",
- "duplicate_of", "has_captions"} <= set(table.column_names)
+ assert {"quality_tier", "gate_errors", "cost_usd", "rounds", "status", "code_fingerprint", "code_sha256",
+ "prompt_hash", "duplicate_of", "near_duplicate_of", "has_captions"} <= set(table.column_names)
# drop duplicates from the index (folder stays)
rep2 = export_samples(runs_dir, out, captions_dir=side, drop_duplicates=True)
assert rep2.n_indexed == 3 and rep2.n_duplicates == 2 and rep2.tiers == {"A": 2, "C": 1}
diff --git a/harness/tests/flywheel_cli/test_run_layout_cli.py b/harness/tests/flywheel_cli/test_run_layout_cli.py
index c88747ad..163cb82a 100644
--- a/harness/tests/flywheel_cli/test_run_layout_cli.py
+++ b/harness/tests/flywheel_cli/test_run_layout_cli.py
@@ -59,7 +59,10 @@ def test_package_run_builds_deliverable_and_telemetry(fake_run):
assert rec.deliverable is not None and rec.telemetry is not None
d = rec.deliverable
roles = {f.role for f in d.files}
- assert {"code", "model", "sheet", "manifest"} <= roles
+ # the manifest does NOT list itself: no file can carry its own hash, and the
+ # returned object used to have one more file (and a smaller total) than the disk
+ assert {"code", "model", "sheet"} <= roles and "manifest" not in roles
+ assert load_deliverable(ws) == d and d.total_bytes == sum(f.bytes for f in d.files)
assert d.best_round == 1 and d.code_source == "commit"
assert d.entry == "deliverable/src/model.py"
assert (ws.deliverable / "src" / "model.py").read_text().startswith("# round 1")