Files

453 lines
17 KiB
Python

"""Worker-only bounded inbox and portable, hash-verified sample manifests (stdlib)."""
import hashlib
import json
import os
import shutil
import sqlite3
from pathlib import Path, PurePosixPath
SCHEMA = "missioncore.semantic-dataset/v1"
MAX_JOB = 24 * 1024**2
MAX_DATASET = 512 * 1024**2
def digest(value):
return hashlib.sha256(
json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()
).hexdigest()
def checksum(path):
with Path(path).open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def write(path, value):
path = Path(path)
raw = json.dumps(value, ensure_ascii=False, allow_nan=False).encode()
tmp = path.with_suffix(".tmp")
with tmp.open("wb") as stream:
stream.write(raw)
stream.flush()
os.fsync(stream.fileno())
os.replace(tmp, path)
def read(path):
return json.loads(Path(path).read_text(encoding="utf-8"))
def confined(root, name):
rel = PurePosixPath(name)
if (
not rel.parts
or rel.is_absolute()
or ".." in rel.parts
or "\\" in name
or ":" in name
or rel.as_posix() != name
):
raise ValueError("Unsafe dataset member")
path = root.joinpath(*rel.parts)
if path.is_symlink() or not path.resolve().is_relative_to(root.resolve()):
raise ValueError("Dataset member escaped root")
return path
def verify(root):
root = Path(root)
manifest = read(root / "dataset.json")
if manifest["schema_version"] == "missioncore.semantic-collection/v1":
if (
manifest.get("training_eligible") is not False
or not 1 <= len(manifest["shards"]) <= 256
):
raise ValueError("Invalid collection review policy")
total = count = 0
expected = {"dataset.json", *manifest["files"]}
for name, spec in manifest["files"].items():
p = confined(root, name)
if p.stat().st_size != spec["bytes"] or checksum(p) != spec["sha256"]:
raise ValueError("Collection file changed")
total += spec["bytes"]
for name, spec in manifest["shards"].items():
child = confined(root, name)
if read(child / "dataset.json")["schema_version"] != SCHEMA:
raise ValueError("Nested collections forbidden")
result = verify(child)
if result != spec:
raise ValueError("Collection shard changed")
count += result["sample_count"]
total += result["bytes"]
expected.update(p.relative_to(root).as_posix() for p in child.rglob("*") if p.is_file())
if (
total > 4 * 1024**3
or {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()} != expected
):
raise ValueError("Collection size or membership changed")
return dict(
sha256=checksum(root / "dataset.json"),
sample_count=count,
bytes=total,
training_eligible=False,
)
if manifest["schema_version"] != SCHEMA or manifest["training_eligible"] is not False:
raise ValueError("Unsupported dataset review policy")
total = 0
for name, spec in manifest["files"].items():
path = confined(root, name)
total += spec["bytes"]
if (
total > MAX_DATASET
or path.stat().st_size != spec["bytes"]
or checksum(path) != spec["sha256"]
):
raise ValueError("Dataset integrity check failed: " + name)
actual = {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()}
if actual != set(manifest["files"]) | {"dataset.json"}:
raise ValueError("Unmanifested dataset contents")
for sample in manifest["samples"]:
row = read(confined(root, sample))
for name in row["members"]:
if name not in manifest["files"]:
raise ValueError("Unbound sample member")
if row["training_eligible"] or row["complete_regions"]:
raise ValueError("Unreviewed edit cannot provide training ground truth")
return {
"sha256": checksum(root / "dataset.json"),
"sample_count": len(manifest["samples"]),
"bytes": total,
"training_eligible": False,
}
def review_labels(labels):
"""Separate retained history from current candidates. Neither is training truth.
Editor 'accepted' is a map review status, not per-view training admission.
Projection flags/opaque pixels likewise do not prove visual evidence.
"""
features = labels["proposed_element"]
by_id = {f["id"]: f for f in features}
if len(by_id) != len(features):
raise ValueError("Duplicate feature identity in review sample")
active, rejected = [], []
for f in features:
status = f["properties"].get("review_status", "unreviewed")
if status not in {"unreviewed", "accepted", "rejected"}:
raise ValueError("Unknown map review status")
(rejected if status == "rejected" else active).append(f)
active_ids = {f["id"] for f in active}
views = {}
for name, projections in labels["projections"].items():
if any(p["feature_id"] not in by_id for p in projections):
raise ValueError("Projection references an unknown feature")
views[name] = dict(
candidate_projections=[p for p in projections if p["feature_id"] in active_ids],
rejected_projections=[p for p in projections if p["feature_id"] not in active_ids],
evidence="unreviewed",
approved_targets=[],
complete_regions=[],
training_eligible=False,
)
return dict(
original=labels["original_element"],
active_candidates=active,
rejected_history=rejected,
approved_targets=[],
background_targets=[],
views=views,
training_eligible=False,
)
def sample_records(root):
"""Yield bound context/member references; never decode or collect image arrays."""
root = Path(root)
verify(root)
manifest = read(root / "dataset.json")
children = (
[(name, confined(root, name)) for name in manifest["shards"]]
if manifest["schema_version"] == "missioncore.semantic-collection/v1"
else [("", root)]
)
annotation = manifest.get("annotation_sha256")
for prefix, child in children:
shard = read(child / "dataset.json")
for key in ("world_sha256", "revision", "split_group"):
if not shard.get(key) or shard[key] != manifest.get(key):
raise ValueError("Review shard source identity mismatch: " + key)
annotation = annotation or shard.get("annotation_sha256")
if not annotation or annotation != shard.get("annotation_sha256"):
raise ValueError("Review shard annotation identity mismatch")
source = {
k: shard[k] for k in ("world_sha256", "revision", "annotation_sha256", "split_group")
}
for name in shard["samples"]:
sample = read(confined(child, name))
label_name = str(PurePosixPath(name).with_name("labels.json"))
if label_name not in sample["members"]:
raise ValueError("Sample has no bound labels")
if (
sample["revision"] != shard["revision"]
or sample["split_group"] != shard["split_group"]
):
raise ValueError("Sample source identity mismatch")
yield dict(
source=source,
sample=str(PurePosixPath(prefix) / name),
labels=str(PurePosixPath(prefix) / label_name),
sample_spec=shard["files"][name],
members={
str(PurePosixPath(prefix) / member): shard["files"][member]
for member in sample["members"]
},
)
def review_samples(root):
"""Read verified portable observations without merging history into targets."""
root = Path(root)
for row in sample_records(root):
yield dict(
source=row["source"],
sample=row["sample"],
labels=row["labels"],
**review_labels(read(confined(root, row["labels"]))),
)
def review_index(root):
"""Small relative-path index. Existing datasets remain immutable; no RGB copy."""
root = Path(root)
source = None
samples, active, rejected, identities = [], set(), set(), {}
for row in review_samples(root):
source = row["source"]
partitions = {}
for key, ids in (("active_candidates", active), ("rejected_history", rejected)):
partitions[key] = [f["id"] for f in row[key]]
for f in row[key]:
identity = digest(f)
if f["id"] in identities and identities[f["id"]] != identity:
raise ValueError("Feature changed between review windows")
identities[f["id"]] = identity
ids.add(f["id"])
samples.append(
dict(
sample=row["sample"],
labels=row["labels"],
**partitions,
views={
name: dict(
evidence="unreviewed",
approved_targets=[],
complete_regions=[],
training_eligible=False,
)
for name in row["views"]
},
approved_targets=[],
background_targets=[],
training_eligible=False,
)
)
if source is None:
raise ValueError("Empty review dataset")
if active & rejected:
raise ValueError("Conflicting feature lifecycle between windows")
return dict(
schema_version="missioncore.semantic-review-index/v1",
dataset_sha256=checksum(root / "dataset.json"),
reader_sha256=checksum(__file__),
source=source,
samples=samples,
active_candidate_ids=sorted(active),
rejected_history_ids=sorted(rejected),
approved_targets=[],
background_targets=[],
training_eligible=False,
)
class Store:
def __init__(
self, root, *, quota=20 * 1024**3, reserve=12 * 1024**3, research_quota=8 * 1024**3
):
self.root, self.quota, self.reserve = Path(root), quota, reserve
self.research_quota = research_quota
self.root.mkdir(parents=True, exist_ok=True)
for folder in ("inbox", "datasets", "work", "sources", "logs"):
(self.root / folder).mkdir(exist_ok=True)
self.db = sqlite3.connect(self.root / "queue.sqlite3")
self.db.execute("PRAGMA synchronous=FULL")
self.db.execute("""CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY, identity TEXT NOT NULL, state TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
receipt TEXT NOT NULL, error TEXT, acknowledged TEXT)""")
self.db.commit()
def capacity(self, additional):
# Historical research has its own finite allowance. It must not consume
# the dataset admission budget, nor disappear from all accounting.
research_roots = {
"experiments",
"agent-reviews",
"audits",
"archives",
"reviews",
"verification",
}
used = research = 0
for p in self.root.rglob("*"):
if not p.is_file():
continue
if p.relative_to(self.root).parts[0] in research_roots:
research += p.stat().st_size
else:
used += p.stat().st_size
if research > self.research_quota:
raise RuntimeError("Worker research storage quota reached; close completed experiments")
if (
used + additional > self.quota
or shutil.disk_usage(self.root).free < self.reserve + additional
):
raise RuntimeError("Worker learning storage quota/reserve reached")
def accept(self, envelope):
exported = envelope["annotation"]
package = exported["package"]
identity = exported["sha256"]
if identity != digest(package):
raise ValueError("Annotation checksum mismatch")
revision = package["revision"]
if len(revision) != 64 or any(c not in "0123456789abcdef" for c in revision):
raise ValueError("Invalid revision identity")
if (
package["world_sha256"] != envelope["world"]["sha256"]
or package["world_sha256"] != envelope["source"]["world_sha256"]
):
raise ValueError("Source does not belong to annotation world")
parent = None
for row in package["revisions"]:
if (
row["parent"] != parent
or digest({k: v for k, v in row.items() if k != "revision"}) != row["revision"]
):
raise ValueError("Annotation history changed")
parent = row["revision"]
if parent != revision or digest(package["model"]) != package["model_sha256"]:
raise ValueError("Annotation baseline changed")
previous = self.db.execute("SELECT identity FROM jobs WHERE id=?", (revision,)).fetchone()
if previous:
if previous[0] != identity:
raise ValueError("Conflicting annotation identity")
return revision
raw_size = len(json.dumps(envelope).encode())
if raw_size > MAX_JOB:
raise ValueError("Annotation exceeds inbox limit")
if (
self.db.execute(
"SELECT count(*) FROM jobs WHERE state NOT IN ('draft-ready','failed')"
).fetchone()[0]
>= 20
):
raise RuntimeError("Worker learning queue is full")
self.capacity(raw_size + 1024**2)
path = self.root / "inbox" / (revision + ".json")
if path.exists() and read(path) != envelope:
raise ValueError("Conflicting recovered inbox item")
write(path, envelope) # Durable file first; a crash before SQL is safe to replay.
receipt = dict(
state="received", package_sha256=identity, dataset_sha256=None, sample_count=0
)
with self.db:
self.db.execute(
"INSERT INTO jobs(id,identity,state,receipt) VALUES(?,?,?,?)",
(revision, identity, "received", json.dumps(receipt)),
)
return revision
def update(self, key, state, result=None, error=None):
identity = self.db.execute("SELECT identity FROM jobs WHERE id=?", (key,)).fetchone()[0]
receipt = dict(
state=state,
package_sha256=identity,
dataset_sha256=result["sha256"] if result else None,
sample_count=result["sample_count"] if result else 0,
)
with self.db:
self.db.execute(
"UPDATE jobs SET state=?,receipt=?,error=? WHERE id=?",
(state, json.dumps(receipt), error, key),
)
return receipt
def next(self):
row = self.db.execute(
"SELECT id,attempts FROM jobs WHERE state IN ('received','building') "
"ORDER BY rowid LIMIT 1"
).fetchone()
if not row:
return None
key, attempts = row
destination = self.root / "datasets" / key
if destination.exists():
try:
result = verify(destination)
except (ValueError, OSError, KeyError) as exc:
self.update(key, "failed", error="Published integrity failure: " + str(exc)[:1000])
else:
self.update(key, "draft-ready", result)
return None
if attempts >= 3:
self.update(key, "failed", error="Interrupted three times; explicit repair required")
return None
with self.db:
self.db.execute("UPDATE jobs SET attempts=attempts+1 WHERE id=?", (key,))
self.update(key, "building")
return key
def publish(self, key, staging):
result = verify(staging)
destination = self.root / "datasets" / key
if destination.exists():
if verify(destination) != result:
raise ValueError("Published dataset is immutable")
else:
os.replace(staging, destination)
self.update(key, "draft-ready", result)
return result
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Verify a portable semantic review dataset")
parser.add_argument("dataset", type=Path)
parser.add_argument(
"--review-index", type=Path, help="Write a separate review index, never training labels"
)
args = parser.parse_args()
if args.review_index:
destination = args.review_index.resolve()
if destination.is_relative_to(args.dataset.resolve()) or destination.exists():
raise ValueError("Review index must be new and outside the immutable dataset")
index = review_index(args.dataset)
write(destination, index)
print(
json.dumps(
dict(
samples=len(index["samples"]),
active=len(index["active_candidate_ids"]),
rejected=len(index["rejected_history_ids"]),
approved=0,
dataset_sha256=index["dataset_sha256"],
training_eligible=False,
)
)
)
else:
print(json.dumps(verify(args.dataset)))