"""Read-only provenance proof for a reviewed ROI; never infer legacy subtypes. The sidecar describes annotation mechanics, not semantic truth. A zero source- unknown count is meaningful only when source_subtypes_known is true. """ import hashlib from admission_store import pixel_runs from dataset_store import digest from region_coverage import roi_bounds def sha(value): return hashlib.sha256(value).hexdigest() def _mask(spans, width, count): mask = bytearray(count) for y, a, b in spans: mask[y * width + a : y * width + b] = bytes([1]) * (b - a) return mask def _difference(spans, mask, width): result = [] for y, a, b in spans: start = None for x in range(a, b): keep = not mask[y * width + x] if keep and start is None: start = x if not keep and start is not None: result.append([y, start, x]) start = None if start is not None: result.append([y, start, b]) return result def audit_unit(packet, record, original, merged, protected=b"", *, merged_sha256): """Validate exact source->merged mechanics and return additive JSON evidence. Prior protected RLE has no trustworthy subtype; it stays explicitly untyped. Missing source_unknown likewise makes this record's unknown untyped. Outside this ROI, original 255 without prior protection is unassigned to this review. The caller still owns source/media binding and independent semantic review. """ size = packet["size"] x0, y0, x1, y1 = roi_bounds(size, packet["roi"]) width, height = size count = width * height if any(not isinstance(v, (bytes, bytearray)) for v in (original, merged, protected)): raise ValueError("Native byte targets and protected mask required") if any(len(v) != count or set(v) - {0, 1, 255} for v in (original, merged)): raise ValueError("Aligned ternary native targets required") if sha(original) != packet["target_sha256"] or sha(merged) != merged_sha256: raise ValueError("Target SHA mismatch") if protected and (len(protected) != count or set(protected) - {0, 1}): raise ValueError("Aligned binary protected mask required") if sha(protected) != packet["protected_sha256"]: raise ValueError("Protected SHA mismatch") if record["view"] != packet["view"]: raise ValueError("Source view mismatch") checked = pixel_runs(record, size) labels = bytearray([3]) * count # 3 = not reviewed; never a class or ignore. for kind, value in (("background", 0), ("paint", 1), ("unknown", 255)): for y, a, b in checked[kind]: if not y0 <= y < y1 or not x0 <= a < b <= x1: raise ValueError("Reviewed spans outside ROI") labels[y * width + a : y * width + b] = bytes([value]) * (b - a) if sum(v != 3 for v in labels) != (x1 - x0) * (y1 - y0): raise ValueError("Incomplete ROI; unassigned is not reviewed unknown") typed = "source_unknown" in record source = pixel_runs( dict(paint=[], background=[], unknown=record.get("source_unknown", [])), size )["unknown"] source_mask = _mask(source, width, count) if any(mark and labels[i] != 255 for i, mark in enumerate(source_mask)): raise ValueError("Source unknown must be within reviewed unknown") automatic = _difference(checked["unknown"], source_mask, width) if typed else [] untyped = [] if typed else checked["unknown"] categories = dict(source_unknown=source, automatic_margin=automatic, untyped_unknown=untyped) # Check the disjoint union independently with the normal RLE validator. union = sorted(span for spans in categories.values() for span in spans) pixel_runs(dict(paint=[], background=[], unknown=union), size) if _mask(union, width, count) != _mask(checked["unknown"], width, count): raise ValueError("Unknown provenance union differs") prior = protected or bytes(count) outside = dict(pixels=0, prior_known=0, prior_protected_untyped=0, unassigned_unknown=0) prior_counts = dict(pixels=0, inside_roi=0, outside_roi=0, remaining_unknown=0) for i, (old, new, value) in enumerate(zip(original, merged, labels, strict=True)): if prior[i]: if old != 255 or new != 255: raise ValueError("Prior protected unknown changed") prior_counts["pixels"] += 1 prior_counts["inside_roi" if value != 3 else "outside_roi"] += 1 prior_counts["remaining_unknown"] += 1 if source_mask[i] and (old != 255 or new != 255): raise ValueError("Source unknown conflicts with accepted labels") if old != 255 and new != old: raise ValueError("Accepted known label changed") expected = value if value in (0, 1) else old if new != expected: raise ValueError("Merged target differs from source-to-merge contract") if value == 3: outside["pixels"] += 1 key = ( "prior_known" if old != 255 else "prior_protected_untyped" if prior[i] else "unassigned_unknown" ) outside[key] += 1 proof = {} for kind, spans in categories.items(): mask = _mask(spans, width, count) counts = dict( pixels=0, remaining_unknown=0, retained_old_paint=0, retained_old_background=0 ) for i, mark in enumerate(mask): if mark: counts["pixels"] += 1 key = { 255: "remaining_unknown", 1: "retained_old_paint", 0: "retained_old_background", }[merged[i]] counts[key] += 1 proof[kind] = dict(runs=spans, mask_sha256=sha(mask), **counts) return dict( schema="missioncore.annotation-provenance/v1", view=record["view"], size=list(size), roi=list(packet["roi"]), original_sha256=sha(original), merged_sha256=sha(merged), protected_sha256=sha(protected), record_sha256=digest(record), source_subtypes_known=typed, categories=proof, prior_protected_untyped=prior_counts, outside_roi=outside, reviewed_pixels=(x1 - x0) * (y1 - y0), labels_changed_by_audit=0, )