Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
388 lines
15 KiB
Python
388 lines
15 KiB
Python
"""Frozen multi-area corpus: lazy views, source integrity and growth isolation."""
|
|
|
|
import copy
|
|
import importlib.util
|
|
import json
|
|
import sqlite3
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from test_semantic_delivery import ds
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
@pytest.fixture
|
|
def corpus(monkeypatch):
|
|
monkeypatch.setitem(sys.modules, "dataset_store", ds)
|
|
spec = importlib.util.spec_from_file_location(
|
|
"corpus_store_test", ROOT / "simulation/semantic-learning/corpus_store.py"
|
|
)
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
return module
|
|
|
|
|
|
def dataset(store, name, world, *, count=3, split_group=None, revision="a" * 64):
|
|
root = store / "datasets" / name
|
|
root.mkdir(parents=True)
|
|
samples = []
|
|
for i in range(count):
|
|
folder = root / f"sample-{i}"
|
|
folder.mkdir()
|
|
(folder / "top.rgb.bin").write_bytes(b"synthetic-top")
|
|
(folder / "oblique.rgb.bin").write_bytes(b"synthetic-oblique")
|
|
ds.write(folder / "camera.json", dict(projection="orthographic", metric_scale=0.1))
|
|
feature = dict(id="edited", properties=dict(review_status="accepted"))
|
|
ds.write(
|
|
folder / "labels.json",
|
|
dict(
|
|
original_element=[],
|
|
proposed_element=[feature],
|
|
projections={
|
|
"top": [dict(feature_id="edited")],
|
|
"oblique": [dict(feature_id="edited")],
|
|
},
|
|
),
|
|
)
|
|
ds.write(
|
|
folder / "sample.json",
|
|
dict(
|
|
members=[p.relative_to(root).as_posix() for p in sorted(folder.iterdir())],
|
|
training_eligible=False,
|
|
complete_regions=[],
|
|
revision=revision,
|
|
split_group=split_group or world,
|
|
),
|
|
)
|
|
samples.append(f"sample-{i}/sample.json")
|
|
ds.write(
|
|
root / "dataset.json",
|
|
dict(
|
|
schema_version=ds.SCHEMA,
|
|
training_eligible=False,
|
|
revision=revision,
|
|
world_sha256=world,
|
|
split_group=split_group or world,
|
|
annotation_sha256="c" * 64,
|
|
samples=samples,
|
|
files={
|
|
p.relative_to(root).as_posix(): dict(sha256=ds.checksum(p), bytes=p.stat().st_size)
|
|
for p in root.rglob("*")
|
|
if p.is_file()
|
|
},
|
|
),
|
|
)
|
|
return dict(path=root.relative_to(store).as_posix(), sha256=ds.checksum(root / "dataset.json"))
|
|
|
|
|
|
def group(name, split, *worlds):
|
|
return dict(id=name, split=split, worlds=list(worlds))
|
|
|
|
|
|
def plan(corpus, datasets, groups, **kw):
|
|
return dict(schema_version=corpus.PLAN_SCHEMA, datasets=datasets, groups=groups, **kw)
|
|
|
|
|
|
def refs(reader, split="train", **kw):
|
|
return [r for batch in reader.batches(split, **kw) for r in batch]
|
|
|
|
|
|
def opened(corpus, root, receipt):
|
|
return corpus.Corpus(root, receipt["path"], receipt["sha256"])
|
|
|
|
|
|
def test_batches_keep_all_views_and_do_not_promote_editor_acceptance(corpus, tmp_path):
|
|
a = dataset(tmp_path, "a", "a" * 64)
|
|
b = dataset(tmp_path, "b", "b" * 64)
|
|
frozen = corpus.build(
|
|
tmp_path,
|
|
plan(
|
|
corpus,
|
|
[a, b],
|
|
[
|
|
group("area-a", "train", "a" * 64),
|
|
group("area-b", "test", "b" * 64),
|
|
],
|
|
),
|
|
"corpora/v1",
|
|
)
|
|
with opened(corpus, tmp_path, frozen) as reader:
|
|
batches = list(reader.batches("train", batch_size=2))
|
|
assert [len(b) for b in batches] == [2, 1]
|
|
assert {r["dataset"] for b in batches for r in b} == {a["path"]}
|
|
assert len(refs(reader, "test")) == 3
|
|
reference = batches[0][0]
|
|
assert len(reference["members"]) == 4
|
|
viewed = reader.review(reference)
|
|
assert set(viewed["views"]) == {"top", "oblique"}
|
|
assert viewed["approved_targets"] == viewed["background_targets"] == []
|
|
assert viewed["training_eligible"] is False
|
|
name = next(n for n in reference["members"] if n.endswith("top.rgb.bin"))
|
|
with reader.open_member(reference, name) as stream:
|
|
assert stream.read() == b"synthetic-top"
|
|
assert stream.closed
|
|
|
|
|
|
def test_same_area_scans_and_revisions_share_split(corpus, tmp_path):
|
|
a = dataset(tmp_path, "a", "a" * 64)
|
|
revision = dataset(tmp_path, "a2", "a" * 64, revision="e" * 64)
|
|
other_scan = dataset(tmp_path, "b", "b" * 64)
|
|
frozen = corpus.build(
|
|
tmp_path,
|
|
plan(
|
|
corpus,
|
|
[a, revision, other_scan],
|
|
[
|
|
group("same-physical-area", "validation", "a" * 64, "b" * 64),
|
|
],
|
|
),
|
|
"corpora/v1",
|
|
)
|
|
with opened(corpus, tmp_path, frozen) as reader:
|
|
assert not refs(reader, "train")
|
|
rows = refs(reader, "validation")
|
|
assert len(rows) == 9
|
|
assert {r["physical_group"] for r in rows} == {"same-physical-area"}
|
|
|
|
|
|
def test_ambiguous_groups_and_related_source_groups_fail(corpus, tmp_path):
|
|
a = dataset(tmp_path, "a", "a" * 64, split_group="c" * 64)
|
|
b = dataset(tmp_path, "b", "b" * 64, split_group="c" * 64)
|
|
with pytest.raises(ValueError, match="multiple physical"):
|
|
corpus.build(
|
|
tmp_path,
|
|
plan(
|
|
corpus,
|
|
[a],
|
|
[
|
|
group("a", "train", "a" * 64),
|
|
group("b", "test", "a" * 64),
|
|
],
|
|
),
|
|
"corpora/bad",
|
|
)
|
|
with pytest.raises(ValueError, match="split_group"):
|
|
corpus.build(
|
|
tmp_path,
|
|
plan(
|
|
corpus,
|
|
[a, b],
|
|
[
|
|
group("a", "train", "a" * 64),
|
|
group("b", "test", "b" * 64),
|
|
],
|
|
),
|
|
"corpora/bad",
|
|
)
|
|
assert not (tmp_path / "corpora/bad").exists()
|
|
assert not list((tmp_path / "corpora").glob(".corpus-*"))
|
|
|
|
|
|
def test_adding_unlisted_data_does_not_change_pinned_corpus(corpus, tmp_path, monkeypatch):
|
|
a = dataset(tmp_path, "a", "a" * 64)
|
|
frozen = corpus.build(
|
|
tmp_path, plan(corpus, [a], [group("a", "train", "a" * 64)]), "corpora/v1"
|
|
)
|
|
with opened(corpus, tmp_path, frozen) as reader:
|
|
before = refs(reader)
|
|
dataset(tmp_path, "unlisted", "b" * 64)
|
|
monkeypatch.setattr(Path, "rglob", lambda *a, **k: pytest.fail("Reader scanned the store"))
|
|
with opened(corpus, tmp_path, frozen) as reader:
|
|
assert refs(reader) == before
|
|
assert ds.checksum(tmp_path / "corpora/v1/corpus.json") == frozen["sha256"]
|
|
|
|
|
|
def test_growth_preserves_old_data_and_split_assignments(corpus, tmp_path):
|
|
a = dataset(tmp_path, "a", "a" * 64)
|
|
policy = [group("a", "train", "a" * 64)]
|
|
old = corpus.build(tmp_path, plan(corpus, [a], policy), "corpora/v1")
|
|
b = dataset(tmp_path, "b", "b" * 64)
|
|
new_policy = policy + [group("b", "test", "b" * 64)]
|
|
expanded = plan(corpus, [a, b], new_policy, parent=old)
|
|
new = corpus.build(tmp_path, expanded, "corpora/v2")
|
|
with opened(corpus, tmp_path, old) as first, opened(corpus, tmp_path, new) as second:
|
|
assert refs(first) == refs(second)
|
|
assert len(refs(second, "test")) == 3
|
|
bad = copy.deepcopy(expanded)
|
|
bad["groups"][0]["split"] = "test"
|
|
with pytest.raises(ValueError, match="prior physical"):
|
|
corpus.build(tmp_path, bad, "corpora/v3")
|
|
bad = copy.deepcopy(expanded)
|
|
bad["datasets"] = [b]
|
|
with pytest.raises(ValueError, match="discard"):
|
|
corpus.build(tmp_path, bad, "corpora/v3")
|
|
|
|
|
|
def test_reader_does_not_open_media_until_requested_and_detects_tampering(
|
|
corpus, tmp_path, monkeypatch
|
|
):
|
|
a = dataset(tmp_path, "a", "a" * 64)
|
|
frozen = corpus.build(
|
|
tmp_path, plan(corpus, [a], [group("a", "train", "a" * 64)]), "corpora/v1"
|
|
)
|
|
with opened(corpus, tmp_path, frozen) as reader:
|
|
original_open = Path.open
|
|
with monkeypatch.context() as scoped:
|
|
|
|
def no_media(path, *args, **kwargs):
|
|
if path.suffix == ".bin":
|
|
pytest.fail("Unexpected media read")
|
|
return original_open(path, *args, **kwargs)
|
|
|
|
scoped.setattr(Path, "open", no_media)
|
|
reference = refs(reader)[0]
|
|
reader.review(reference)
|
|
name = next(n for n in reference["members"] if n.endswith("top.rgb.bin"))
|
|
(tmp_path / a["path"] / name).write_bytes(b"X" * len(b"synthetic-top"))
|
|
with pytest.raises(ValueError, match="member changed"), reader.open_member(reference, name):
|
|
pass
|
|
|
|
|
|
def test_reference_and_index_identity_cannot_be_substituted(corpus, tmp_path):
|
|
a = dataset(tmp_path, "a", "a" * 64)
|
|
frozen = corpus.build(
|
|
tmp_path, plan(corpus, [a], [group("a", "train", "a" * 64)]), "corpora/v1"
|
|
)
|
|
with pytest.raises(ValueError, match="manifest changed"):
|
|
corpus.Corpus(tmp_path, frozen["path"], "0" * 64)
|
|
with opened(corpus, tmp_path, frozen) as reader:
|
|
row = refs(reader)[0]
|
|
row["split"] = "test"
|
|
with pytest.raises(ValueError, match="Reference"):
|
|
reader.review(row)
|
|
with (tmp_path / "corpora/v1/index.sqlite3").open("ab") as f:
|
|
f.write(b"corruption")
|
|
with pytest.raises(ValueError, match="member changed"):
|
|
opened(corpus, tmp_path, frozen)
|
|
|
|
|
|
def test_relocated_store_works_with_bundled_reader_cli(corpus, tmp_path):
|
|
root = tmp_path / "original"
|
|
a = dataset(root, "a", "a" * 64)
|
|
frozen = corpus.build(root, plan(corpus, [a], [group("a", "train", "a" * 64)]), "corpora/v1")
|
|
moved = tmp_path / "relocated store"
|
|
root.rename(moved)
|
|
with opened(corpus, moved, frozen) as reader:
|
|
assert len(refs(reader)) == 3
|
|
result = subprocess.run(
|
|
[
|
|
sys.executable,
|
|
"-B",
|
|
str(moved / "corpora/v1/corpus_store.py"),
|
|
"inspect",
|
|
str(moved),
|
|
frozen["path"],
|
|
frozen["sha256"],
|
|
"--split",
|
|
"train",
|
|
"--limit",
|
|
"2",
|
|
],
|
|
check=True,
|
|
capture_output=True,
|
|
text=True,
|
|
cwd=tmp_path,
|
|
)
|
|
data = json.loads(result.stdout)
|
|
assert data["total"] == 3 and len(data["samples"]) == 2
|
|
|
|
|
|
def test_batch_byte_budget_and_invalid_requests(corpus, tmp_path, monkeypatch):
|
|
a = dataset(tmp_path, "a", "a" * 64)
|
|
frozen = corpus.build(
|
|
tmp_path, plan(corpus, [a], [group("a", "train", "a" * 64)]), "corpora/v1"
|
|
)
|
|
with opened(corpus, tmp_path, frozen) as reader:
|
|
size = len(json.dumps(refs(reader)[0], sort_keys=True, allow_nan=False).encode())
|
|
monkeypatch.setattr(corpus, "MAX_BATCH_BYTES", size * 2 - 1)
|
|
assert [len(b) for b in reader.batches("train", batch_size=128)] == [1, 1, 1]
|
|
for split, count in [("all", 8), ("train", 0), ("train", 129), ("train", True)]:
|
|
with pytest.raises(ValueError):
|
|
list(reader.batches(split, count))
|
|
assert not refs(reader, physical_group="not-present")
|
|
|
|
|
|
def test_refuses_overwrite_unsafe_paths_and_unknown_sources(corpus, tmp_path):
|
|
a = dataset(tmp_path, "a", "a" * 64)
|
|
p = plan(corpus, [a], [group("a", "train", "a" * 64)])
|
|
corpus.build(tmp_path, p, "corpora/v1")
|
|
for destination in ["corpora/v1", "datasets/a/corpus", "../escape", "/tmp/escape"]:
|
|
with pytest.raises(ValueError):
|
|
corpus.build(tmp_path, p, destination)
|
|
with pytest.raises(ValueError, match="Missing physical"):
|
|
corpus.build(
|
|
tmp_path, plan(corpus, [a], [group("unknown", "train", "b" * 64)]), "corpora/v2"
|
|
)
|
|
with pytest.raises(ValueError, match="Duplicate corpus dataset"):
|
|
corpus.build(tmp_path, plan(corpus, [a, a], p["groups"]), "corpora/v2")
|
|
|
|
|
|
def test_collection_member_paths_and_source_geometry_remain_bound(corpus, tmp_path):
|
|
from test_semantic_review_reader import collection, labels
|
|
|
|
root = tmp_path / "datasets" / "collection"
|
|
original = labels()
|
|
collection(root, [original, original])
|
|
entry = dict(path="datasets/collection", sha256=ds.checksum(root / "dataset.json"))
|
|
frozen = corpus.build(
|
|
tmp_path,
|
|
plan(corpus, [entry], [group("same-area", "regression", "b" * 64)]),
|
|
"corpora/v1",
|
|
)
|
|
with opened(corpus, tmp_path, frozen) as reader:
|
|
rows = refs(reader, "regression")
|
|
assert len(rows) == 2
|
|
assert {r["sample"] for r in rows} == {"part-000/sample.json", "part-001/sample.json"}
|
|
for row in rows:
|
|
reviewed = reader.review(row)
|
|
assert reviewed["original"] == original["original_element"]
|
|
assert reviewed["active_candidates"][0] == original["proposed_element"][0]
|
|
assert reviewed["rejected_history"] == [original["proposed_element"][1]]
|
|
with reader.open_member(row, row["labels"]) as stream:
|
|
assert json.load(stream) == original
|
|
|
|
|
|
def test_index_capacity_failure_cleans_only_own_scratch(corpus, tmp_path, monkeypatch):
|
|
a = dataset(tmp_path, "a", "a" * 64)
|
|
p = plan(corpus, [a], [group("a", "train", "a" * 64)])
|
|
old = corpus.build(tmp_path, p, "corpora/v1")
|
|
monkeypatch.setattr(corpus, "MAX_INDEX_BYTES", 4096)
|
|
with pytest.raises(ValueError, match="capacity exhausted"):
|
|
corpus.build(tmp_path, p, "corpora/v2")
|
|
assert not (tmp_path / "corpora/v2").exists()
|
|
assert not list((tmp_path / "corpora").glob(".corpus-*"))
|
|
with opened(corpus, tmp_path, old) as reader:
|
|
assert len(refs(reader)) == 3
|
|
assert ds.checksum(tmp_path / a["path"] / "dataset.json") == a["sha256"]
|
|
|
|
|
|
def test_unbound_sqlite_sidecars_cannot_override_pinned_index(corpus, tmp_path):
|
|
a = dataset(tmp_path, "a", "a" * 64)
|
|
frozen = corpus.build(
|
|
tmp_path, plan(corpus, [a], [group("a", "train", "a" * 64)]), "corpora/v1"
|
|
)
|
|
index = tmp_path / "corpora/v1/index.sqlite3"
|
|
# A WAL is outside the published manifest. Even a pending valid SQLite
|
|
# transaction must not contribute unbound rows to the frozen corpus.
|
|
db = sqlite3.connect(index)
|
|
try:
|
|
db.execute("PRAGMA journal_mode=WAL")
|
|
# WAL mode changes the main header; pin this consistent mode before the
|
|
# separate sidecar transaction, to exercise the reader's WAL isolation.
|
|
manifest_path = tmp_path / "corpora/v1/corpus.json"
|
|
manifest = ds.read(manifest_path)
|
|
manifest["files"]["index.sqlite3"]["sha256"] = ds.checksum(index)
|
|
ds.write(manifest_path, manifest)
|
|
frozen["sha256"] = ds.checksum(manifest_path)
|
|
db.execute("UPDATE samples SET split='test'")
|
|
db.commit()
|
|
assert ds.checksum(index) == manifest["files"]["index.sqlite3"]["sha256"]
|
|
with opened(corpus, tmp_path, frozen) as reader:
|
|
assert len(refs(reader, "train")) == 3
|
|
assert not refs(reader, "test")
|
|
finally:
|
|
db.close()
|