"""Read source-bound appearance observations from a native attribute release. Standard library only. No prepared-pool filtering, filename inference, asset reads, image hashing or native certification. ``deadline`` is an absolute ``time.monotonic()`` timestamp, shared with the retrieval worker. SQLite work and Python processing check it cooperatively; callers must retain their outer process timeout for an uninterruptible filesystem/NFS operation. Pass the native release path explicitly; no implicit fallback is used. """ from __future__ import annotations import hashlib import json import math from pathlib import Path import re import sqlite3 import time _DIMENSIONS = ('style_tags', 'colors', 'materials', 'shapes') _FACETS = dict(zip(_DIMENSIONS, ('style', 'colors', 'materials', 'shape'))) _USABLE = frozenset(('inferred', 'measured', 'verified')) _EMPTY = frozenset(('unknown', 'unspecified', 'none', 'n/a', 'pending', 'conflict')) _SHAPE_TERMS = { 'round': r'round|circular', 'rectangle': r'rectangle|rectangular', 'oval': r'oval', 'l_shape': r'l[- _]+shap(?:e|ed)', 'three_seater': r'(?:three|3)[- ]+(?:seaters?|seats?|seat[- ]+cushions?)', } _SHAPE_PATTERNS = {name: re.compile(r'(?= deadline: raise TimeoutError('appearance_index_timeout: observations incomplete') def _object(value): return value if isinstance(value, dict) else {} def _list(value): return value if isinstance(value, list) else [] def _text(value): if isinstance(value, str): value = value.strip() if value and value.casefold() not in _EMPTY: return value return None def _usable(value): return isinstance(value, dict) and value.get('status') in _USABLE def _entry_usable(value): return isinstance(value, dict) and ('status' not in value or _usable(value)) def _empty(asset_id, status): return dict(asset_id=asset_id, features={d: [] for d in _DIMENSIONS}, basis={d: [] for d in _DIMENSIONS}, shape_text={}, source_sha256=None, runtime_sha256=None, record_id=None, record_sha256=None, evidence_refs={}, facet_metadata={}, evidence_content_verified=False, status=status) def _normalize(row): aid, rid, sql_source, raw = row try: record = json.loads(raw) except (TypeError, ValueError, UnicodeDecodeError) as exc: raise ValueError(f'appearance_index invalid record_json for {rid!r}') from exc if not isinstance(record, dict): raise ValueError(f'appearance_index record_json must be an object for {rid!r}') raw_bytes = raw.encode('utf-8') if isinstance(raw, str) else raw result = _empty(aid, 'inferred_metadata_not_certified') result.update(record_id=rid, record_sha256=hashlib.sha256(raw_bytes).hexdigest()) identity = _object(record.get('identity')) source = _object(identity.get('source')) runtime = _object(identity.get('runtime')) source_value, runtime_value = _object(source.get('value')), _object(runtime.get('value')) result.update(source_sha256=source_value.get('sha256'), runtime_sha256=runtime_value.get('sha256'), source_identity=source, runtime_identity=runtime, declared_sql_source_sha256=sql_source) registry = _object(record.get('evidence_registry')) result['evidence_refs'] = registry # Appearance inference cannot establish which source/runtime it describes. # Require explicit verified identities; retain all declarations for audit. identity_errors = [] for name, declaration in (('source', source), ('runtime', runtime)): if declaration.get('status') != 'verified': identity_errors.append(f'$.identity.{name}.status') sha = result[name + '_sha256'] if not isinstance(sha, str) or re.fullmatch(r'[0-9a-fA-F]{64}', sha) is None: identity_errors.append(f'$.identity.{name}.value.sha256') if identity_errors: result['status'] = 'source_identity_unverified' result['identity_validation_errors'] = identity_errors return result # Preserve differing declarations, but never use a conflicting binding to # satisfy an entity's hard appearance requirement. if (sql_source and result['source_sha256'] and sql_source != result['source_sha256']): result['status'] = 'source_identity_conflict' return result if ((record.get('asset_id') is not None and record['asset_id'] != aid) or (record.get('record_id') is not None and record['record_id'] != rid)): result['status'] = 'record_identity_conflict' return result attributes = _object(record.get('attributes')) for dimension, facet_name in _FACETS.items(): facet = _object(attributes.get(facet_name)) result['facet_metadata'][dimension] = { key: facet[key] for key in ('status', 'confidence', 'provenance', 'evidence') if key in facet} if not _usable(facet): continue value = _object(facet.get('value')) prefix = '$.attributes.' + facet_name + '.value' if not _entry_usable(value): continue if 'appearance_status' in value and value['appearance_status'] not in _USABLE: continue def add(label, path): label = _text(label) if label is not None: result['features'][dimension].append(label) result['basis'][dimension].append(path) if dimension == 'style_tags': for i, label in enumerate(_list(value.get('labels'))): if not _entry_usable(label): continue score = label.get('score') if type(score) in (int, float) and math.isfinite(score) and score >= .4: add(label.get('name'), f'{prefix}.labels[{i}].name') elif dimension == 'colors': appearance = _object(value.get('rendered_appearance')) if not _entry_usable(appearance): continue for i, entry in enumerate(_list(appearance.get('palette'))): if _entry_usable(entry): add(entry.get('color_name'), f'{prefix}.rendered_appearance.palette[{i}].color_name') elif dimension == 'materials': appearance = _object(value.get('appearance')) if not _entry_usable(appearance): continue for i, entry in enumerate(_list(appearance.get('appearance'))): if _entry_usable(entry): add(entry.get('material_appearance'), f'{prefix}.appearance.appearance[{i}].material_appearance') else: description = value.get('description') if _text(description): result['shape_text']['description'] = description head = _SHAPE_CLAUSE_END.split(description, maxsplit=1)[0] for label, pattern in _SHAPE_PATTERNS.items(): if label == 'three_seater': # Explicit seating count can occur after "with"; # component counts such as legs/pillows never match. matches = (not _NEGATION.search(description[:m.start()]) for m in pattern.finditer(description)) else: # Only the initial subject's adjective is evidence of # overall form. Parts and later clauses are audit only. matches = (_SHAPE_PREFIX.fullmatch(head[:m.start()]) is not None and not _SHAPE_COMPONENT.match(head[m.end():]) for m in pattern.finditer(head)) if any(matches): add(label, prefix + '.description') if 'parts' in value: result['shape_text']['parts'] = value['parts'] result['features'][dimension] = sorted(set(result['features'][dimension])) result['basis'][dimension] = sorted(set(result['basis'][dimension])) evidence_keys = {key for facet in result['facet_metadata'].values() for key in _list(facet.get('evidence')) if isinstance(key, str)} result['unresolved_evidence_refs'] = sorted(evidence_keys - registry.keys()) return result def load_observations(path, asset_ids, deadline=None) -> dict: """Return normalized records keyed by requested asset ID (missing IDs omitted). ``path`` must be the native release's records SQLite, not annotation_index. Each query uses at most 400 bound IDs. Pool/processing status never limits discovery. Duplicate IDs in the request are deduplicated; duplicate *rows* return an ``ambiguous`` entry with empty features and compact ``records`` identities, never an arbitrarily selected source variant. Malformed JSON, schema/IO errors and expired deadlines raise without a partial result. Hashes and evidence URIs are release declarations; only record_sha256 is freshly computed here, over the exact stored record_json UTF-8 bytes. Both identity declarations must have status verified and a 64-hex SHA; otherwise features stay empty with status source_identity_unverified. """ if deadline is None: deadline = time.monotonic() + 30.0 if type(deadline) not in (int, float) or not math.isfinite(deadline): raise ValueError('deadline must be a finite absolute monotonic timestamp') _check_deadline(deadline) if isinstance(asset_ids, (str, bytes)): raise TypeError('asset_ids must be an iterable of asset ID strings') ids = [] seen = set() for aid in asset_ids: _check_deadline(deadline) if not isinstance(aid, str): raise TypeError('asset_ids must contain strings') if aid not in seen: seen.add(aid) ids.append(aid) if not ids: return {} # absolute() does not resolve a symlink or add a separate filesystem stat. uri = Path(path).absolute().as_uri() + '?mode=ro' db = None try: db = sqlite3.connect(uri, uri=True, timeout=min(1.0, max(0.0, deadline-time.monotonic()))) db.execute('PRAGMA query_only=ON') db.execute('PRAGMA trusted_schema=OFF') db.set_progress_handler(lambda: int(time.monotonic() >= deadline), 1000) db.execute('BEGIN') columns = {r[1] for r in db.execute('PRAGMA table_info(records)')} if not {'asset_id', 'record_id', 'source_sha256', 'record_json'} <= columns: raise ValueError('appearance_index schema: expected native records(asset_id, record_id, source_sha256, record_json)') result = {} for offset in range(0, len(ids), 400): _check_deadline(deadline) chunk = ids[offset:offset+400] marks = ','.join('?' for _ in chunk) query = f'SELECT asset_id, record_id, source_sha256, record_json FROM records WHERE asset_id IN ({marks})' for row in db.execute(query, chunk): _check_deadline(deadline) observation = _normalize(row) aid = row[0] if aid not in result: result[aid] = observation else: previous = result[aid] keys = ('record_id', 'record_sha256', 'source_sha256', 'runtime_sha256') if previous['status'] != 'ambiguous': previous = _empty(aid, 'ambiguous') previous['records'] = [{key: result[aid][key] for key in keys}] result[aid] = previous previous['records'].append({key: observation[key] for key in keys}) _check_deadline(deadline) for observation in result.values(): if observation['status'] == 'ambiguous': observation['records'].sort(key=lambda r: str(r['record_id'])) _check_deadline(deadline) return result except sqlite3.Error as exc: if time.monotonic() >= deadline: raise TimeoutError('appearance_index_timeout: observations incomplete') from exc raise ValueError(f'appearance_index read/schema error: {exc}') from exc finally: if db is not None: db.close()