"""Bounded read-only coverage of the native annotation index, never admission. The caller's catalog must be the already prepared record-id -> candidate mapping. Request entities determine roles; furniture pins do not restrict full-index discovery. Filesystem/SQLite work runs in a disposable process so even stalled NFS I/O cannot hold the calling controller indefinitely. No native engine imports or writes occur. """ from __future__ import annotations import hashlib import json import math import os from pathlib import Path import sqlite3 import subprocess import sys import threading import time WALL_TIMEOUT_S = 1800 QUERY_TIMEOUT_S = float(os.environ.get('RHG_QUERY_TIMEOUT_S', 12)) HASH_MAX_BYTES = 8 * 1024 * 1024 RAW_MAX_BYTES = 128 * 1024 RAW_REPORT_BUDGET = 8 * 1024 * 1024 # Copied from the inspected native unified_asset_catalog.role_name taxonomy; # this is retrieval labeling only, not its semantic/qualification predicates. ROLE_ALIASES = { 'couch':'sofa', 'tv':'television', 'tv_stand':'media_console', 'tv_cabinet':'media_console', 'nightstand':'side_table', 'bedside_table':'side_table', 'bedside':'side_table', 'end_table':'side_table', 'tea_table':'coffee_table', 'bookshelf':'bookcase', 'closet':'wardrobe', 'armoire':'wardrobe', 'kitchen_wall_cabinet':'upper_cabinet', 'wall_cabinet':'upper_cabinet', 'kitchen_upper_cabinet':'upper_cabinet', 'kitchen_range_hood':'range_hood', 'base_cabinet':'kitchen_counter', 'kitchen_base_cabinet':'kitchen_counter', 'dressing_table':'vanity', 'writing_table':'desk', 'work_table':'desk', 'bathroom_sink':'sink', 'washbasin':'sink', 'mug':'cup', 'carpet':'rug', 'stovetop':'cooktop', 'floor_lamp':'lamp', 'table_lamp':'lamp', } REQUIRED_COLUMNS = { 'annotations': {'asset_id','core_complete','generation_eligible','runtime_verified', 'category','reasons_json','record_json'}, 'assets': {'asset_id','asset_kind','normalized_category','source','admission_status', 'dimensions_json','dimension_confidence','quality_tier','record_json'}, 'asset_descriptors': {'asset_id','asset_sha256','source','category','support_type', 'quality_overall','canonical_path','descriptor_json','status'}, 'functional_slots': {'asset_id','slot'}, 'function_tags': {'asset_id','tag'}, 'metadata': {'key','value_json'}, } def _role(value): text = str(value or '').strip().lower().replace('-', '_').replace(' ', '_') if text.endswith('_general'): text = text[:-8] return ROLE_ALIASES.get(text, text) def _candidate_roles(row): values = row.get('catalog_roles') or row.get('annotation_roles') if not values: values = [row.get('canonical_role') or row.get('primary_role') or row.get('semantic') or row.get('role') or row.get('category')] if isinstance(values, str): values = [values] return {_role(v) for v in values if v} def _entity_role(entity): """Mirror native request-role labels without importing its admission rules.""" if entity.get('semantic_key'): return _role(entity['semantic_key']) role = _role(entity.get('role') or entity.get('category')) text = ' '.join(str(entity.get(k,'')) for k in ('procedural_kind','layout_slot_id','asset_pool_key','entity_id')).lower() if role=='sink' and 'kitchen' in text: return 'kitchen_sink' if role=='oven' and 'cooktop' in text: return 'cooktop' for token, key in [('dining_plate','plate'),('bath_counter_bottle','bottle'), ('small_bowl','bowl'),('counter_bowl','bowl'),('upper','upper_cabinet'), ('kitchen_counter','kitchen_counter'),('bookcase','bookcase'), ('vanity','vanity'),('media_console','media_console')]: if token in text: return key return role def _base(path): return {'schema':'rhg.asset_retrieval_audit.v1', 'status':'failed', 'database':{'path':str(path),'sha256':None}, 'source_counts':{}, 'prepared_counts':{}, 'category_counts':{}, 'roles':{}, 'errors':[], 'unverified':['native_admission_not_checked', 'raw_dimensions_not_current_geometry_measurements'], 'scope':'full_annotation_index_vs_supplied_prepared_catalog', 'raw_hits_are_admitted':False} def _size_targets(request, role, entities): furnishing = request.get('constraints', {}).get('furnishing', {}) policy = furnishing.get('suitability', {}) selection = furnishing.get('selection_policy', {}) targets = [] for entity in entities: if _entity_role(entity) != role: continue eid = entity.get('entity_id') target = policy.get('entities', {}).get(eid, {}).get('target_width_m') basis = 'constraints.furnishing.suitability.entities.target_width_m' if target is None: target = selection.get('target_width_m_by_role', {}).get(role, selection.get(role+'_target_width_m')) basis = 'constraints.furnishing.selection_policy' if target is not None: if type(target) not in (int,float) or not math.isfinite(target) or target <= 0: raise ValueError('invalid_size_target: '+str(eid)) targets.append(dict(entity_id=eid,target_width_m=target,basis=basis)) continue if role != 'sofa': continue zone = next((z for z in request.get('furnishing_zones', []) if eid in z.get('entity_ids',[])), None) if zone is None: zone = policy.get('zones',{}).get(entity.get('room_id')) if zone: bounds = zone.get('bounds_xy_m',zone.get('bounds_m')) size = zone.get('dimensions_m') width = bounds[2]-bounds[0] if isinstance(bounds,list) and len(bounds)==4 else ( size[0] if isinstance(size,list) and len(size)>=2 else None) ratio = policy.get('sofa_target_zone_width_ratio',.65) if type(width) not in (int,float) or type(ratio) not in (int,float) or not ( math.isfinite(width) and width>0 and math.isfinite(ratio) and ratio>0): raise ValueError('invalid_sofa_zone_width_or_ratio') targets.append(dict(entity_id=eid,target_width_m=width*ratio, zone_id=zone.get('zone_id'),zone_width_m=width, width_ratio=ratio,width_ratio_assumed='sofa_target_zone_width_ratio' not in policy, basis='declared_functional_zone_width_times_policy_ratio')) else: targets.append(dict(entity_id=eid,target_width_m=2.6, basis='assumed_soft_sofa_target')) return targets def _reap_worker(process): try: process.communicate() finally: for pipe in (process.stdin,process.stdout,process.stderr): if pipe: pipe.close() def _subprocess_timeout(name, default): # This read-only index API stays independent of native engine imports. raw = os.environ.get(name, default) try: value = float(raw) except (TypeError, ValueError, OverflowError): raise ValueError(name + ' must be a finite positive number <= 7200') from None if isinstance(raw, bool) or not math.isfinite(value) or not 0 < value <= 7200: raise ValueError(name + ' must be a finite positive number <= 7200') return value def audit_retrieval(index_path: Path, catalog: dict[str, dict], request: dict, *, limit_per_role=32) -> dict: """Return explicit failed/unverified evidence rather than a false empty success. Limit is 1..256 hits per role and at most 64 requested roles. Counts cover the entire snapshot; hit samples are deterministic asset-id order, not rankings. The worker uses SQLite mode=ro, query_only, no temp tables, and a read transaction. The configurable outer deadline includes path stat, opening, queries and hashing. """ result = _base(index_path) if type(limit_per_role) is not int or not 1 <= limit_per_role <= 256: result['errors'].append('invalid_limit_per_role: expected integer in 1..256') return result try: wall_timeout = _subprocess_timeout('RHG_RETRIEVAL_AUDIT_TIMEOUT_S', WALL_TIMEOUT_S) payload = json.dumps({'path':str(index_path),'catalog':catalog, 'request':request,'limit':limit_per_role}, allow_nan=False) process = subprocess.Popen([sys.executable, '-B', os.path.abspath(__file__), '--worker'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) try: output, error = process.communicate(payload, timeout=wall_timeout) except subprocess.TimeoutExpired: process.kill() # Do not wait synchronously for a kernel task stuck on a hard NFS mount. # Reap and drain pipes in the background if/when that task exits. threading.Thread(target=_reap_worker, args=(process,), daemon=True).start() result['errors'].append('index_io_timeout: worker exceeded wall deadline') result['unverified'].append('database_identity_and_coverage_unavailable') return result if process.returncode: result['errors'].append('audit_worker_failed: '+error[-1000:]) return result return json.loads(output) except (OSError, ValueError, TypeError) as exc: result['errors'].append(type(exc).__name__+': '+str(exc)) return result def _local_filesystem(path): """Hash only a positively identified local filesystem; unknown stays unverified.""" if sys.platform.startswith('linux'): matches = [] for line in Path('/proc/self/mountinfo').read_text().splitlines(): left, right = line.split(' - ', 1) mount = left.split()[4].replace('\\040',' ').replace('\\134','\\') if str(path) == mount or str(path).startswith(mount.rstrip('/')+'/'): matches.append((len(mount), right.split()[0])) kind = max(matches)[1] if matches else '' return kind in {'ext2','ext3','ext4','xfs','btrfs','tmpfs','overlay','zfs'} if sys.platform == 'darwin': # Python's statvfs masks Darwin's MNT_LOCAL bit; inspect the mount table. mounts = subprocess.run(['/sbin/mount'], capture_output=True, text=True, check=True, timeout=_subprocess_timeout('RHG_FILESYSTEM_PROBE_TIMEOUT_S', 600)).stdout matches = [] for line in mounts.splitlines(): if ' on ' not in line or ' (' not in line: continue mount, flags = line.split(' on ',1)[1].rsplit(' (',1) if str(path)==mount or str(path).startswith(mount.rstrip('/')+'/'): matches.append((len(mount), 'local' in flags.rstrip(')').split(', '))) return max(matches)[1] if matches else False return False def _worker(data): path = Path(data['path']).absolute() result = _base(path) try: if not path.is_file(): raise ValueError('missing_index: '+str(path)) path = path.resolve() result['database']['resolved_path'] = str(path) before = path.stat() if path.with_name(path.name+'-wal').exists() or path.with_name(path.name+'-shm').exists(): raise ValueError('unsupported_index_wal_snapshot: supply a quiescent standalone index') result['database'].update(size_bytes=before.st_size, mtime_ns=before.st_mtime_ns) rows = data['catalog'] prepared_ids = {str(c['asset_id']) for c in rows.values() if c.get('asset_id')} result['prepared_counts'] = {'records':len(rows),'distinct_assets':len(prepared_ids)} entities = data['request'].get('entities') if entities is None: entities = data['request'].get('furniture', []) roles = sorted({_entity_role(e) for e in entities} - {''}) if not roles or len(roles) > 64: raise ValueError('invalid_request_roles: expected 1..64 explicit entity roles') deadline = time.monotonic() + QUERY_TIMEOUT_S with sqlite3.connect(path.as_uri()+'?mode=ro', uri=True, timeout=.25) as db: db.execute('PRAGMA query_only=ON') db.execute('PRAGMA trusted_schema=OFF') db.set_progress_handler(lambda: int(time.monotonic() > deadline), 2000) db.execute('BEGIN') schema = db.execute("SELECT type,name,tbl_name,sql FROM sqlite_master ORDER BY type,name LIMIT 129").fetchall() result['database']['schema_objects'] = [dict(zip(('type','name','table','sql'),r)) for r in schema] if len(schema) > 128: raise ValueError('unsupported_index_schema: too many schema objects') tables = {r[1] for r in schema if r[0]=='table'} for table, columns in REQUIRED_COLUMNS.items(): if table not in tables or not columns <= {r[1] for r in db.execute('PRAGMA table_info('+table+')')}: raise ValueError('unsupported_index_schema: missing table/columns '+table) manifest_row = db.execute("SELECT value_json FROM metadata WHERE key='manifest' LIMIT 1").fetchone() manifest = json.loads(manifest_row[0]) if manifest_row else {} if not isinstance(manifest, dict) or manifest.get('schema') != 'rhg.annotation_integration.v1': raise ValueError('unsupported_index_manifest: expected rhg.annotation_integration.v1') result['database']['manifest'] = manifest for table in REQUIRED_COLUMNS: if table == 'metadata': result['source_counts'][table] = {'records':db.execute('SELECT COUNT(*) FROM metadata').fetchone()[0]} else: total, unique = db.execute('SELECT COUNT(*),COUNT(DISTINCT asset_id) FROM '+table).fetchone() result['source_counts'][table] = {'records':total,'distinct_assets':unique} categories = db.execute('SELECT category,COUNT(*) FROM annotations GROUP BY category LIMIT 16385').fetchall() slots = db.execute('SELECT DISTINCT slot FROM functional_slots LIMIT 16385').fetchall() if len(categories)>16384 or len(slots)>16384: raise ValueError('unsupported_index_schema: excessive category/slot cardinality') result['category_counts'] = {str(k):v for k,v in categories} db.create_function('audit_prepared', 1, lambda aid: int(aid in prepared_ids)) raw_budget = RAW_REPORT_BUDGET for role in roles: category_names = [k for k,_ in categories if _role(k)==role] slot_names = [r[0] for r in slots if _role(r[0])==role] # UNION deduplicates slot/category overlap without multiplying tag rows. clauses, params = [], [] for table, field, values in [('annotations','category',category_names), ('functional_slots','slot',slot_names)]: if values: clauses.append('SELECT asset_id FROM '+table+' WHERE '+field+' IN ('+','.join('?' for _ in values)+')') params.extend(values) matches = ' UNION '.join(clauses) or 'SELECT asset_id FROM annotations WHERE 0' cte = 'WITH matched AS ('+matches+') ' total, unique, missing = db.execute(cte+'''SELECT COUNT(*),COUNT(DISTINCT a.asset_id), COALESCE(SUM(NOT audit_prepared(a.asset_id)),0) FROM annotations a JOIN matched m ON a.asset_id=m.asset_id''', params).fetchone() prepared = [c for c in rows.values() if role in _candidate_roles(c)] report = {'raw_records':total,'raw_distinct_assets':unique, 'prepared_records':len(prepared), 'prepared_distinct_assets':len({c['asset_id'] for c in prepared if c.get('asset_id')}), 'missing_distinct_assets':missing,'missing_raw_hits':[], 'hits_truncated':missing>data['limit'], 'match_scope':'canonicalized_annotation_category_or_functional_slot', 'category_values':category_names,'slot_values':slot_names, 'size_targets':_size_targets(data['request'],role,entities), 'size_ranked_unprepared_hits':[]} result['roles'][role] = report raw_rows = db.execute(cte+'''SELECT a.asset_id,a.category, CASE WHEN length(CAST(a.record_json AS BLOB))<=? THEN a.record_json END, a.core_complete,a.generation_eligible,a.runtime_verified FROM annotations a JOIN matched m ON a.asset_id=m.asset_id WHERE NOT audit_prepared(a.asset_id) ORDER BY a.asset_id LIMIT ?''', [*params,RAW_MAX_BYTES,data['limit']]).fetchall() combined = [(row,None) for row in raw_rows] if report['size_targets']: # SQL examines the entire role domain before LIMIT, including # rows beyond the ID sample. JSON1 evaluates metadata only. dim_cte = cte.rstrip()+''', dimensions AS ( SELECT a.*, CASE WHEN json_valid(g.dimensions_json) AND json_type(g.dimensions_json)='array' THEN g.dimensions_json WHEN json_valid(a.record_json) THEN json_extract(a.record_json,'$.dimensions_m') END AS dims, CASE WHEN json_valid(g.dimensions_json) AND json_type(g.dimensions_json)='array' THEN 'assets.dimensions_json' ELSE 'annotations.record_json.dimensions_m' END AS dims_basis FROM annotations a JOIN matched m ON a.asset_id=m.asset_id LEFT JOIN assets g ON g.asset_id=a.asset_id WHERE NOT audit_prepared(a.asset_id)), widths AS (SELECT *, '''+( "json_extract(dims,'$[0]')" if role=='bed' else "max(json_extract(dims,'$[0]'),json_extract(dims,'$[1]'))")+''' AS width_m FROM dimensions WHERE json_valid(dims) AND json_array_length(dims)=3 AND json_type(dims,'$[0]') IN ('integer','real') AND json_extract(dims,'$[0]')>0 AND json_type(dims,'$[1]') IN ('integer','real') AND json_extract(dims,'$[1]')>0 AND json_type(dims,'$[2]') IN ('integer','real') AND json_extract(dims,'$[2]')>0) ''' distances = ['abs(width_m-?)' for _ in report['size_targets']] distance = distances[0] if len(distances)==1 else 'min('+','.join(distances)+')' ranked = db.execute(dim_cte+'''SELECT asset_id,category, CASE WHEN length(CAST(record_json AS BLOB))<=? THEN record_json END, core_complete,generation_eligible,runtime_verified,dims,dims_basis,width_m, '''+distance+''' AS distance_m FROM widths ORDER BY distance_m,asset_id LIMIT ?''', [*params,RAW_MAX_BYTES,*[t['target_width_m'] for t in report['size_targets']], data['limit']]).fetchall() combined.extend((row[:6],row[6:]) for row in ranked) else: report['size_ranking_unverified'] = 'no_declared_width_target_for_role' for (aid,category,raw,complete,eligible,verified), ranking in combined: hit = {'asset_id':aid,'category':category,'admitted':False, 'status':'discovery_only_unprepared','unverified':[], 'index_flags':{'core_complete':complete,'generation_eligible':eligible, 'runtime_verified':verified}} if raw is None or len(raw.encode()) > raw_budget: hit['unverified'].extend(['raw_record_omitted_byte_budget','dimensions_unavailable']) else: raw_budget -= len(raw.encode()) hit['raw_record_json'] = raw hit['raw_record_sha256'] = hashlib.sha256(raw.encode()).hexdigest() try: record = json.loads(raw) if not isinstance(record, dict) or record.get('asset_id') != aid: raise ValueError('raw_record_identity_mismatch') for key in ('source','canonical_path','asset_sha256','runtime_path','runtime_sha256'): if record.get(key) is not None: hit[key] = record[key] dims = record.get('dimensions_m') if isinstance(dims,list) and len(dims)==3 and all( type(v) in (int,float) and math.isfinite(v) and v>0 for v in dims): hit['dimensions_m'] = dims else: hit['unverified'].append('dimensions_unavailable') except (ValueError, TypeError) as exc: hit['unverified'].extend(['invalid_raw_record: '+str(exc),'dimensions_unavailable']) if ranking: dims,basis,width,distance = ranking hit.update(dimensions_m=json.loads(dims),dimensions_basis=basis, metadata_width_m=width,target_distance_m=distance, size_rank_basis='metadata_width_distance_over_full_role_domain') hit['unverified'] = [s for s in hit['unverified'] if s!='dimensions_unavailable'] hit['unverified'].append('metadata_dimensions_unmeasured') report['size_ranked_unprepared_hits'].append(hit) else: report['missing_raw_hits'].append(hit) wal = path.with_name(path.name+'-wal') if wal.exists(): result['unverified'].append('database_sha256_unavailable_wal_snapshot') elif before.st_size > HASH_MAX_BYTES: result['unverified'].append('database_sha256_skipped_size_limit') elif not _local_filesystem(path): result['unverified'].append('database_sha256_skipped_remote_or_unknown_filesystem') else: digest = hashlib.sha256() with path.open('rb') as stream: remaining = HASH_MAX_BYTES+1 while remaining: chunk = stream.read(min(1024*1024,remaining)) if not chunk: break remaining -= len(chunk) digest.update(chunk) if remaining == 0: raise ValueError('database_changed_during_audit: hash byte limit exceeded') result['database']['sha256'] = digest.hexdigest() after = path.stat() if (before.st_size,before.st_mtime_ns,before.st_ino) != (after.st_size,after.st_mtime_ns,after.st_ino): result['database']['sha256'] = None raise ValueError('database_changed_during_audit') result['status'] = 'ok' except (OSError, sqlite3.Error, ValueError, TypeError, KeyError) as exc: result['errors'].append(type(exc).__name__+': '+str(exc)) result['unverified'].append('coverage_incomplete') return result if __name__ == '__main__': if sys.argv[1:] != ['--worker']: raise SystemExit('Library API: audit_retrieval(Path(index), catalog, request)') print(json.dumps(_worker(json.load(sys.stdin)), allow_nan=False))