Files
NODEDC_MISSION_CORE/simulation/semantic-learning/admission_store.py
T
DCCONSTRUCTIONS 25dc0a1b44 feat(semantics): add portable annotation, learning and review contracts
Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
2026-10-29 09:10:00 +03:00

516 lines
22 KiB
Python

"""Pinned, task-specific supervision over a frozen review corpus (Worker only).
Explicit reviewed pixel runs and source-vector ranges; no automatic rasterization
of edited geometry, inferred background, label fitting or media copying.
"""
import argparse
import json
import math
import shutil
import tempfile
from datetime import datetime
from pathlib import Path, PurePosixPath
from corpus_store import Corpus, checked_file, load_json, sha256
from dataset_store import checksum, confined, digest, write
PLAN_SCHEMA = "missioncore.semantic-admission-plan/v1"
DECISION_SCHEMA = "missioncore.semantic-admission-decision/v1"
SCHEMA = "missioncore.semantic-supervision/v1"
TASKS = {"observed_paint", "contextual_map"}
MAX_RECORD = 2 * 1024**2
MAX_RELEASE = 64 * 1024**2
MAX_DECISIONS = 2048
MAX_PIXELS = 4 * 1024**2
def text(value):
if not isinstance(value, str) or not value.strip() or len(value) > 2048:
raise ValueError("Explicit bounded review text required")
return value
def keys(value, expected):
if not isinstance(value, dict) or set(value) != set(expected.split()):
raise ValueError("Unsupported or missing review fields")
def bounded(value):
if len(json.dumps(value, allow_nan=False).encode()) > MAX_RECORD:
raise ValueError("Review record budget exceeded")
return value
def revision_policy(rows):
if not isinstance(rows, list) or not 1 <= len(rows) <= MAX_DECISIONS:
raise ValueError("Explicit selected source revisions required")
result = {}
for row in rows:
keys(row, "world_sha256 revision annotation_sha256")
for value in row.values():
sha256(value)
world = row["world_sha256"]
if world in result:
raise ValueError("Select exactly one annotation revision per source world")
result[world] = row
return result
def selected(reference, policy):
source = reference["source"]
identity = {k: source[k] for k in ("world_sha256", "revision", "annotation_sha256")}
if policy.get(identity["world_sha256"]) != identity:
raise ValueError("Sample does not belong to the selected annotation revision")
def view_key(value):
keys(value, "sample_id view")
sha256(value["sample_id"])
name = text(value["view"])
if PurePosixPath(name).name != name or any(c in name for c in "\\:"):
raise ValueError("Unsafe view identity")
return value["sample_id"], name
def input_view(corpus, anchor, value, policy, verify_media):
sample_id, view = view_key(value)
reference = corpus.reference(sample_id)
selected(reference, policy)
if any(reference[k] != anchor[k] for k in ("source", "physical_group", "split")):
raise ValueError("Context must share source revision, physical group and split")
folder = PurePosixPath(reference["sample"]).parent
camera_name, rgb_name = str(folder / "cameras.json"), str(folder / (view + ".png"))
with corpus.open_member(reference, camera_name) as stream:
raw = stream.read(MAX_RECORD + 1)
if len(raw) > MAX_RECORD:
raise ValueError("Camera metadata budget exceeded")
cameras = json.loads(raw)
matches = [c for c in cameras["views"] if c["id"] == view]
if len(matches) != 1 or rgb_name not in reference["members"]:
raise ValueError("Input must bind exactly one raw view and camera")
camera = matches[0]
dimensions(camera["size"])
if verify_media:
with corpus.open_member(reference, rgb_name):
pass # Checks bytes; does not decode or copy the image.
return dict(
sample_id=sample_id,
view=view,
rgb=dict(name=rgb_name, **reference["members"][rgb_name]),
camera=camera,
camera_sha256=digest(camera),
cameras_member=dict(name=camera_name, **reference["members"][camera_name]),
coordinates=text(cameras["coordinates"]),
pixel_convention=text(cameras["pixel_convention"]),
)
def dimensions(size):
if (
not isinstance(size, list)
or len(size) != 2
or any(type(v) is not int or v <= 0 for v in size)
or size[0] * size[1] > MAX_PIXELS
):
raise ValueError("Invalid or oversized review raster")
return size
def pixel_runs(value, size):
"""Integer image indices: [row, first_column, exclusive_end_column]."""
width, height = dimensions(size)
occupied = []
for kind in ("paint", "background", "unknown"):
runs = value[kind]
if not isinstance(runs, list) or runs != sorted(runs):
raise ValueError("Pixel runs must be ordered")
for run in runs:
if (
not isinstance(run, list)
or len(run) != 3
or any(type(v) is not int for v in run)
or not 0 <= run[0] < height
or not 0 <= run[1] < run[2] <= width
):
raise ValueError("Pixel run outside its declared view")
occupied.append(run)
occupied.sort()
if any(a[0] == b[0] and a[2] > b[1] for a, b in zip(occupied, occupied[1:], strict=False)):
raise ValueError("Conflicting or duplicated reviewed pixels")
return {k: value[k] for k in ("paint", "background", "unknown")}
def pixel_target(view):
"""One loss target: 255 ignore, 0 explicit background, 1 observed paint.
No class is assigned to the complement of the reviewed runs. This bytearray
is generated on demand; a trainer must preserve ignore_index=255.
"""
width, height = dimensions(view["size"])
runs = pixel_runs(view, view["size"])
target = bytearray([255]) * (width * height)
for kind, label in (("paint", 1), ("background", 0)):
for row, start, end in runs[kind]:
target[row * width + start : row * width + end] = bytes([label]) * (end - start)
return target
def fragments(feature, ranges):
"""Preserve exact line segments, selecting only explicitly reviewed intervals."""
geometry = feature["geometry"]
if geometry["type"] not in {"LineString", "Polygon"}:
raise ValueError("Unsupported source vector geometry")
paths = (
[geometry["coordinates"]] if geometry["type"] == "LineString" else geometry["coordinates"]
)
if not isinstance(ranges, list) or not ranges or ranges != sorted(ranges):
raise ValueError("Explicit ordered vector ranges required")
result = []
for span in ranges:
if (
not isinstance(span, list)
or len(span) != 4
or any(type(v) is not int for v in span[:2])
or any(type(v) not in (int, float) or not math.isfinite(v) for v in span[2:])
):
raise ValueError("Invalid vector range")
path, segment, lo, hi = span
if (
not 0 <= path < len(paths)
or not 0 <= segment < len(paths[path]) - 1
or not 0 <= lo < hi <= 1
):
raise ValueError("Vector range outside source geometry")
if feature["properties"].get("editor_curves", {}).get(str(path)):
raise ValueError("Curved paths need an explicit curve-aware target contract")
a, b = paths[path][segment : segment + 2]
if any(
len(p) != 3 or any(type(v) not in (int, float) or not math.isfinite(v) for v in p)
for p in (a, b)
):
raise ValueError("Finite scene-local XYZ required")
if a[:2] == b[:2]:
raise ValueError("Degenerate planar source segment")
result.append(
[
a if lo == 0 else [x + lo * (y - x) for x, y in zip(a, b, strict=True)],
b if hi == 1 else [x + hi * (y - x) for x, y in zip(a, b, strict=True)],
]
)
return result
def compile_decision(corpus, decision, policy, *, verify_media=False):
bounded(decision)
keys(
decision,
"schema_version sample_id reviewer reviewed_utc reason inputs "
"observed_paint contextual_map",
)
if decision["schema_version"] != DECISION_SCHEMA:
raise ValueError("Unsupported admission decision")
keys(decision["reviewer"], "id kind")
text(decision["reviewer"]["id"])
if decision["reviewer"]["kind"] not in {"human", "assistant"}:
raise ValueError("Explicit reviewer kind required; rules are not reviewers")
text(decision["reason"])
stamp = datetime.fromisoformat(decision["reviewed_utc"])
if stamp.tzinfo is None:
raise ValueError("Review time must include a timezone")
reference = corpus.reference(decision["sample_id"])
selected(reference, policy)
if not 1 <= len(decision["inputs"]) <= 16:
raise ValueError("Select one to sixteen bounded context views")
inputs = {}
for value in decision["inputs"]:
key = view_key(value)
if key in inputs:
raise ValueError("Duplicate input view")
inputs[key] = input_view(corpus, reference, value, policy, verify_media)
review = corpus.review(reference)
features = {f["id"]: f for f in review["active_candidates"]}
pixels, vectors, excluded, spans = [], [], [], {}
seen_views = set()
for record in decision["observed_paint"]:
keys(record, "view paint background unknown")
view = text(record["view"])
key = (reference["id"], view)
if key not in inputs or view in seen_views:
raise ValueError("Pixel target needs a unique included source view")
seen_views.add(view)
size = inputs[key]["camera"]["size"]
runs = pixel_runs(record, size)
pixels.append(dict(view=view, size=size, **runs, ignore_index=255))
for record in decision["contextual_map"]:
keys(record, "feature_id geometry_sha256 ranges state evidence support reason")
text(record["reason"])
feature = features.get(record["feature_id"])
if feature is None:
raise ValueError("Unknown or rejected feature cannot become a target")
if digest(feature["geometry"]) != sha256(record["geometry_sha256"]):
raise ValueError("Reviewed source geometry changed")
if record["state"] not in {"confirmed", "weak", "unknown"} or record["evidence"] not in {
"observed",
"context",
"rule",
"unknown",
}:
raise ValueError("Unknown vector evidence or review state")
support = [view_key(v) for v in record["support"]]
if len(support) != len(set(support)) or any(v not in inputs for v in support):
raise ValueError("Every evidence view must be present in model inputs")
if record["state"] == "confirmed" and (
not support or record["evidence"] not in {"observed", "context"}
):
raise ValueError("A rule or unknown evidence cannot confirm a vector target")
coordinates = fragments(feature, record["ranges"])
for path, segment, lo, hi in record["ranges"]:
key = (feature["id"], path, segment)
existing = spans.setdefault(key, [])
if any(max(lo, a) < min(hi, b) for a, b in existing):
raise ValueError("Conflicting or duplicated reviewed vector ranges")
existing.append((lo, hi))
target = dict(
**record,
semantic_class=text(feature["properties"]["class"]),
fragments=coordinates,
completeness="reviewed-ranges-only",
supervised_axes=["x", "y"],
z_supervision=False,
)
(vectors if record["state"] == "confirmed" else excluded).append(target)
return bounded(
dict(
sample_id=reference["id"],
source=reference["source"],
physical_group=reference["physical_group"],
split=reference["split"],
reviewer=decision["reviewer"],
reviewed_utc=decision["reviewed_utc"],
reason=decision["reason"],
inputs=list(inputs.values()),
observed_paint=pixels,
contextual_map=vectors,
excluded_vectors=excluded,
background_from_absence=False,
vector_completeness="reviewed-ranges-only",
)
)
def active(record, task):
if task == "contextual_map":
return bool(record[task])
return any(v["paint"] or v["background"] for v in record[task])
def build(store, plan, destination):
"""Publish a new immutable sidecar; original corpus and datasets stay untouched."""
store = Path(store).resolve()
keys(plan, "schema_version corpus revisions decisions")
if plan["schema_version"] != PLAN_SCHEMA:
raise ValueError("Unsupported admission plan")
policy = revision_policy(plan["revisions"])
destination = confined(store, destination)
if destination.exists():
raise ValueError("Supervision version already exists")
if not 1 <= len(plan["decisions"]) <= MAX_DECISIONS:
raise ValueError("Review release decision budget exceeded")
with Corpus(store, plan["corpus"]["path"], plan["corpus"]["sha256"]) as corpus:
protected = [
corpus.root,
*[confined(store, d["path"]) for d in corpus.manifest["datasets"]],
]
for entry in plan["decisions"]:
keys(entry, "path sha256")
path = confined(store, entry["path"])
if checksum(path) != sha256(entry["sha256"]):
raise ValueError("Pinned review decision changed")
protected.append(path)
if any(destination.is_relative_to(p) or p.is_relative_to(destination) for p in protected):
raise ValueError("Supervision output overlaps immutable input")
destination.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix=".supervision-", dir=destination.parent) as tmp:
stage = Path(tmp)
(stage / "decisions").mkdir()
records, used = {}, 0
geometry_identities = {}
counts = {
s: {t: 0 for t in sorted(TASKS)}
for s in ("train", "validation", "test", "regression")
}
for entry in plan["decisions"]:
source = confined(store, entry["path"])
decision = load_json(source, MAX_RECORD)
if checksum(source) != entry["sha256"]:
raise ValueError("Decision changed during compilation")
compiled = compile_decision(corpus, decision, policy, verify_media=True)
for target in compiled["contextual_map"] + compiled["excluded_vectors"]:
key = (compiled["source"]["world_sha256"], target["feature_id"])
prior = geometry_identities.setdefault(key, target["geometry_sha256"])
if prior != target["geometry_sha256"]:
raise ValueError("Conflicting source geometry across review windows")
identity = compiled["sample_id"]
if identity in records:
raise ValueError("Conflicting decisions for the same sample")
name = f"decisions/{identity}.json"
write(stage / name, decision)
used += (stage / name).stat().st_size
if used > MAX_RELEASE:
raise ValueError("Supervision release byte budget exceeded")
records[identity] = dict(
path=name, compiled_sha256=digest(compiled), split=compiled["split"]
)
for task in TASKS:
counts[compiled["split"]][task] += active(compiled, task)
for name in ("admission_store.py", "corpus_store.py", "dataset_store.py"):
shutil.copyfile(Path(__file__).with_name(name), stage / name)
manifest = dict(
schema_version=SCHEMA,
corpus=plan["corpus"],
revisions=plan["revisions"],
plan_sha256=digest(plan),
records=records,
counts=counts,
files={
p.relative_to(stage).as_posix(): dict(
sha256=checksum(p), bytes=p.stat().st_size
)
for p in sorted(stage.rglob("*"))
if p.is_file()
},
)
if sum(s["bytes"] for s in manifest["files"].values()) > MAX_RELEASE:
raise ValueError("Supervision release byte budget exceeded")
if len(json.dumps(manifest).encode()) > 8 * 1024**2:
raise ValueError("Supervision manifest budget exceeded")
write(stage / "supervision.json", manifest)
destination.mkdir()
try:
for name in [*manifest["files"], "supervision.json"]:
target = destination / name
target.parent.mkdir(exist_ok=True)
(stage / name).replace(target)
except BaseException:
shutil.rmtree(destination)
raise
return dict(
path=destination.relative_to(store).as_posix(),
sha256=checksum(destination / "supervision.json"),
counts=counts,
)
class Supervision:
"""Lazily compile reviewed targets; training access always uses the train split."""
def __init__(self, store, release, expected_sha256):
self.store = Path(store).resolve()
self.root = confined(self.store, release)
if checksum(self.root / "supervision.json") != sha256(expected_sha256):
raise ValueError("Pinned supervision release changed")
self.manifest = load_json(self.root / "supervision.json")
if self.manifest["schema_version"] != SCHEMA:
raise ValueError("Unsupported supervision release")
for name, spec in self.manifest["files"].items():
checked_file(self.root, name, spec)
self.policy = revision_policy(self.manifest["revisions"])
pointer = self.manifest["corpus"]
self.corpus = Corpus(self.store, pointer["path"], pointer["sha256"])
def __enter__(self):
return self
def __exit__(self, *args):
self.corpus.close()
def batches(self, task, split, batch_size=8):
if task not in TASKS:
raise ValueError("Select an explicit supervision task")
batch, size = [], 0
for references in self.corpus.batches(split, batch_size):
for reference in references:
spec = self.manifest["records"].get(reference["id"])
if spec is None:
continue
name = spec["path"]
decision = load_json(
checked_file(self.root, name, self.manifest["files"][name]), MAX_RECORD
)
compiled = compile_decision(self.corpus, decision, self.policy)
if digest(compiled) != spec["compiled_sha256"]:
raise ValueError("Supervision differs from its pinned review")
if not active(compiled, task):
continue
# Consumer sees only this task's targets, not another task's geometry
# disguised as visible paint. Provenance is bookkeeping, not a model input.
example = dict(
sample_id=reference["id"],
source=compiled["source"],
physical_group=compiled["physical_group"],
split=split,
task=task,
inputs=compiled["inputs"],
targets=[v for v in compiled[task] if v["paint"] or v["background"]]
if task == "observed_paint"
else compiled[task],
supervision_scope="reviewed-pixels-only"
if task == "observed_paint"
else "reviewed-vector-ranges-only",
background_from_absence=False,
training_eligible=(split == "train"),
review_sha256=spec["compiled_sha256"],
)
length = len(json.dumps(example).encode())
if length > MAX_RECORD:
raise ValueError("Example metadata budget exceeded")
if batch and (len(batch) >= batch_size or size + length > MAX_RECORD):
yield batch
batch, size = [], 0
batch.append(example)
size += length
if batch:
yield batch
def open_image(self, value):
"""Open a bound raw RGB descriptor from an example, with a fresh hash check."""
reference = self.corpus.reference(value["sample_id"])
selected(reference, self.policy)
view_key({"sample_id": value["sample_id"], "view": value["view"]})
name = str(PurePosixPath(reference["sample"]).parent / (value["view"] + ".png"))
if name not in reference["members"] or value["rgb"] != dict(
name=name, **reference["members"][name]
):
raise ValueError("Input is not the bound raw RGB view")
return self.corpus.open_member(reference, name)
def training_batches(self, task, batch_size=8):
yield from self.batches(task, "train", batch_size)
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
make = commands.add_parser("build")
make.add_argument("store", type=Path)
make.add_argument("plan", type=Path)
make.add_argument("destination")
inspect = commands.add_parser("inspect")
inspect.add_argument("store", type=Path)
inspect.add_argument("release")
inspect.add_argument("sha256")
args = parser.parse_args()
if args.command == "build":
result = build(args.store, load_json(args.plan), args.destination)
else:
with Supervision(args.store, args.release, args.sha256) as reader:
result = dict(
counts=reader.manifest["counts"], tasks=sorted(TASKS), model_trained=False
)
print(json.dumps(result))
if __name__ == "__main__":
main()