File size: 14,567 Bytes
1b3d8c0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | #!/usr/bin/env python3
"""Validate the explicitly registered F sequence insertion supplement.
Strict validation binds media and metadata to a captured immutable Hub inventory.
Prepublication validation is explicitly unbound and cannot authorize publication.
The ordinary dated fragment validator and its RecNN contract remain unchanged.
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import re
from pathlib import Path, PurePosixPath
REGISTRY_PATH = 'Standard_Time_Lapses/Provenance/Sequence_Insertions/registry.json'
MANIFEST_PATH = 'Standard_Time_Lapses/Provenance/Sequence_Insertions/2026-10-29-F/sequence.json'
F_LABEL = '2026-10-25.0938.BallpointPen.Ink.Paper.9x12'
PREDECESSOR_PATH = 'Standard_Time_Lapses/Provenance/2026-10-29/fragment_sequence_relationships.csv'
PREDECESSOR_SHA256 = 'd930bd171220403df10247cb3c05cb7ad431689c7bfcd0e4ec7e3c11ec9f232d'
PREDECESSOR_REVISION = '4f563085afacfc454496ac2d61606614268b2cb8'
EVIDENCE = {'membership': 'owner-confirmed', 'order': 'visual-inference-with-device-metadata-corroboration', 'gapless_capture': 'not-established'}
HASH_RE = re.compile(r'^[0-9a-f]{64}$')
REVISION_RE = re.compile(r'^[0-9a-f]{40}$')
RECORD_RE = re.compile(r'^tla-[0-9a-f]{16}$')
LETTERED_RE = re.compile(r'\.Rec\d+[a-zA-Z]+\.mp4$')
MEMBER_KEYS = {'record_id', 'file_path', 'sha256', 'hub_xet_hash', 'size_bytes', 'sequence_position'}
MANIFEST_KEYS = {'schema_version', 'fragment_set_label', 'source_hub_revision', 'predecessor', 'additions', 'members', 'sequence_completeness', 'evidence', 'notes'}
def matches(pattern, value):
return isinstance(value, str) and pattern.fullmatch(value) is not None
def positive_int(value):
return type(value) is int and value > 0
def read_json(path):
return json.loads(path.read_text(encoding='utf-8-sig'))
def read_csv(path):
with path.open(encoding='utf-8-sig', newline='') as handle:
reader = csv.DictReader(handle)
if not reader.fieldnames:
raise ValueError('CSV header is missing')
return list(reader)
def safe_path(root, value):
if not isinstance(value, str) or not value or '\\' in value:
raise ValueError('invalid repository path')
relative = PurePosixPath(value)
if relative.is_absolute() or any(p in ('..', '.') for p in relative.parts) or ':' in value:
raise ValueError('unsafe repository path')
path = root.joinpath(*relative.parts).resolve()
if not path.is_relative_to(root.resolve()):
raise ValueError('repository path escapes root')
return path
def unique_index(rows, field, errors, label):
result = {}
if not isinstance(rows, list):
errors.append(f'{label}: expected a list')
return result
for row in rows:
if not isinstance(row, dict) or not isinstance(row.get(field), str) or not row[field]:
errors.append(f'{label}: invalid {field}')
continue
value = row[field]
if value in result:
errors.append(f'{label}: duplicate {field}: {value}')
result[value] = row
return result
def validate_insertions(root: Path, metadata: Path, *, inventory=None,
prepublication=False, bind_inventory=True):
"""Return errors and validated sequences; never return partial membership.
bind_inventory=False is for the metadata loader's local structural check.
It still requires real remote identities; only prepublication=True permits
a null source revision and null Xet identities for the declared additions.
"""
errors = []
sequences = []
level = ('prepublication_unbound' if prepublication else
'pinned_repository_inventory' if bind_inventory else 'structural_and_metadata_only')
result = {'verification_level': level, 'inventory_binding_checked': False,
'sequences': sequences, 'errors': errors}
try:
registry = read_json(root / REGISTRY_PATH)
metadata_rows = read_csv(metadata)
by_id = unique_index(metadata_rows, 'record_id', errors, 'metadata')
unique_index(metadata_rows, 'file_name', errors, 'metadata')
if (not isinstance(registry, dict) or set(registry) != {'schema_version', 'sequences'}
or type(registry.get('schema_version')) is not int or registry['schema_version'] != 1
or not isinstance(registry.get('sequences'), list) or not registry['sequences']):
raise ValueError('registry must contain schema_version 1 and a nonempty sequences list')
if bind_inventory and not prepublication and not isinstance(inventory, dict):
errors.append('strict validation requires an actual pinned repository inventory')
seen_labels, seen_paths, registered_ids = set(), set(), set()
for entry in registry['sequences']:
if not isinstance(entry, dict) or set(entry) != {'manifest_path', 'sha256'}:
errors.append('invalid registry entry'); continue
path = safe_path(root, entry['manifest_path'])
if entry['manifest_path'] != MANIFEST_PATH:
errors.append('unregistered insertion manifest path'); continue
if entry['manifest_path'] in seen_paths:
errors.append('duplicate active insertion version'); continue
seen_paths.add(entry['manifest_path'])
raw = path.read_bytes()
if not matches(HASH_RE, entry['sha256']) or hashlib.sha256(raw).hexdigest() != entry['sha256']:
errors.append('registry manifest SHA-256 mismatch'); continue
manifest = json.loads(raw)
if not isinstance(manifest, dict) or set(manifest) != MANIFEST_KEYS:
errors.append('invalid sequence manifest fields'); continue
if type(manifest['schema_version']) is not int or manifest['schema_version'] != 1:
errors.append('invalid sequence schema_version')
label = manifest['fragment_set_label']
if label != F_LABEL:
errors.append('unregistered fragment_set_label'); continue
if label in seen_labels:
errors.append('duplicate active sequence for fragment_set_label'); continue
seen_labels.add(label)
if manifest['sequence_completeness'] != 'unknown' or manifest['evidence'] != EVIDENCE:
errors.append('insertion evidence/completeness contract differs')
if not isinstance(manifest['notes'], str) or not manifest['notes'].strip():
errors.append('sequence notes must be nonblank')
revision = manifest['source_hub_revision']
if not matches(REVISION_RE, revision) and not (prepublication and revision is None):
errors.append('source_hub_revision must be an immutable commit')
expected_predecessor = {'path': PREDECESSOR_PATH, 'sha256': PREDECESSOR_SHA256,
'source_hub_revision': PREDECESSOR_REVISION}
if manifest['predecessor'] != expected_predecessor:
errors.append('predecessor differs from the immutable registered F receipt')
predecessor = root / PREDECESSOR_PATH
if hashlib.sha256(predecessor.read_bytes()).hexdigest() != PREDECESSOR_SHA256:
errors.append('historical predecessor bytes changed'); continue
old = [row for row in read_csv(predecessor) if row['object_role'] == 'canonical_fragment' and row['fragment_set_label'] == F_LABEL]
old.sort(key=lambda row: int(row['sequence_position']))
old_ids = [row['record_id'] for row in old]
additions = manifest['additions']
if (not isinstance(additions, list) or len(additions) != 2
or not all(matches(RECORD_RE, item) for item in additions)
or len(set(additions)) != 2 or any(item in old_ids for item in additions)):
errors.append('additions must declare exactly two new unique record IDs'); continue
members = manifest['members']
members_by_id = unique_index(members, 'record_id', errors, 'members')
if not isinstance(members, list) or any(not isinstance(m, dict) for m in members):
errors.append('members must be objects'); continue
for field in ('file_path', 'sha256'):
unique_index(members, field, errors, 'members')
bound_xet = [m.get('hub_xet_hash') for m in members if isinstance(m.get('hub_xet_hash'), str)]
if len(bound_xet) != len(set(bound_xet)):
errors.append('members contain duplicate Xet identities')
expected_ids = old_ids[:3] + additions + old_ids[3:]
if [m.get('record_id') for m in members] != expected_ids:
errors.append('members must preserve all nine predecessor objects in order and insert only Rec03a/Rec03b after Rec03')
for old_member in old:
member = members_by_id.get(old_member['record_id'], {})
for field in MEMBER_KEYS - {'sequence_position'}:
expected = int(old_member[field]) if field == 'size_bytes' else old_member[field]
if member.get(field) != expected:
errors.append(f"{old_member['record_id']}: predecessor {field} changed or missing")
for record_id, suffix in zip(additions, ('03a', '03b')):
if members_by_id.get(record_id, {}).get('file_path') != f'Standard_Time_Lapses/{F_LABEL}.Rec{suffix}.mp4':
errors.append('unregistered insertion suffix or path')
for position, member in enumerate(members, 1):
record_id = member.get('record_id')
if set(member) != MEMBER_KEYS:
errors.append('invalid member field contract')
if not matches(RECORD_RE, record_id):
errors.append('invalid member record_id'); continue
if type(member.get('sequence_position')) is not int or member['sequence_position'] != position:
errors.append(f'{record_id}: sequence_position differs from explicit order')
if not positive_int(member.get('size_bytes')) or not matches(HASH_RE, member.get('sha256')):
errors.append(f'{record_id}: invalid size or SHA-256')
pending = prepublication and record_id in additions and member.get('hub_xet_hash') is None
if not pending and not matches(HASH_RE, member.get('hub_xet_hash')):
errors.append(f'{record_id}: invalid or unbound Xet identity')
row = by_id.get(record_id, {})
expected_metadata = {'file_name': member.get('file_path'), 'hub_xet_hash': '' if pending else member.get('hub_xet_hash'),
'size_bytes': str(member.get('size_bytes')), 'date': '2026-10-25', 'time': '09:38',
'work_id': '', 'acquisition_protocol_version': 'standard-2026-08-27'}
for field, expected in expected_metadata.items():
if field not in row or row[field] != expected:
errors.append(f'{record_id}: metadata {field} differs from registered sequence')
registered_ids.update(additions)
if bind_inventory and not prepublication and isinstance(inventory, dict):
validate_inventory(inventory, revision, metadata, members, errors)
result['inventory_binding_checked'] = True
sequences.append(manifest)
for row in metadata_rows:
if LETTERED_RE.search(row.get('file_name', '')) and row.get('record_id') not in registered_ids:
errors.append(f"{row.get('record_id')}: unregistered lettered Rec suffix")
except (OSError, ValueError, TypeError, KeyError, UnicodeError) as exc:
errors.append(f'unable to validate sequence insertions: {exc}')
if errors:
result['sequences'] = []
return result
def validate_inventory(inventory, revision, metadata, members, errors):
if inventory.get('sha') != revision:
errors.append('inventory commit differs from source_hub_revision')
files = inventory.get('validationFiles')
receipt = files.get('metadata.csv') if isinstance(files, dict) else None
data = metadata.read_bytes()
if (not isinstance(receipt, dict) or receipt.get('repoCommit') != revision
or receipt.get('sha256') != hashlib.sha256(data).hexdigest()
or type(receipt.get('size')) is not int or receipt['size'] != len(data)):
errors.append('metadata.csv is not bound to exact pinned repository bytes')
siblings = unique_index(inventory.get('siblings'), 'rfilename', errors, 'inventory')
for member in members:
remote = siblings.get(member.get('file_path'), {})
lfs = remote.get('lfs')
if not isinstance(lfs, dict):
lfs = {}
if (type(remote.get('size')) is not int or remote['size'] != member.get('size_bytes')
or lfs.get('sha256') != member.get('sha256')
or remote.get('xetHash') != member.get('hub_xet_hash')
or remote.get('repoCommit') != revision):
errors.append(f"{member.get('record_id')}: pinned repository media identity differs or is absent")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--root', type=Path, default=Path('.'))
parser.add_argument('--metadata', type=Path, required=True)
parser.add_argument('--repo-inventory-json', type=Path)
parser.add_argument('--prepublication', action='store_true', help='local-only preparation; never publishable validation')
args = parser.parse_args()
try:
inventory = read_json(args.repo_inventory_json) if args.repo_inventory_json else None
result = validate_insertions(args.root, args.metadata, inventory=inventory, prepublication=args.prepublication)
except (OSError, ValueError, UnicodeError) as exc:
result = {'errors': [f'unable to read inventory: {exc}'], 'sequences': []}
print(json.dumps(result, indent=2))
raise SystemExit(bool(result['errors']))
if __name__ == '__main__':
main()
|