"""Separate authored supports from WQZ's measured rug-contact derivation. Evidence verification binds the current source record and file bytes. Current saved geometry must still verify the actual contact before output acceptance. """ import math import hashlib import json from pathlib import Path WALL_GAP_RANGE_M = (0., .01) WALL_GAP_ACCEPTANCE = 'user_authorized_wall_installation_range' def wall_gap_accepted(gap): """Accept 0..10 mm clearance only; negative measured gaps never pass. The 1e-12 upper-end guard covers coordinate subtraction at the inclusive 10 mm endpoint. It is independent of the much larger contact tolerance. """ return (type(gap) in (int, float) and math.isfinite(gap) and gap >= 0. and (gap <= WALL_GAP_RANGE_M[1] or math.isclose(gap, WALL_GAP_RANGE_M[1], rel_tol=0., abs_tol=1e-12))) def _sha256(value): return (isinstance(value, str) and len(value) == 64 and all(c in '0123456789abcdef' for c in value)) def verify_surface_evidence(row, path, sha, *, inputs=None): """Bind measured surface bytes and the exact current candidate identity. Shared by derived support and thin primary-floor contact. This verifies source evidence only; callers must independently measure saved geometry. """ if (not _sha256(sha) or not isinstance(path, str) or not Path(path).is_absolute() or not Path(path).is_file()): raise ValueError('Missing source surface evidence file') evidence = Path(path).resolve(strict=True) raw = evidence.read_bytes() if (hashlib.sha256(raw).hexdigest() != sha or inputs is not None and inputs.get(str(evidence), sha) != sha): raise ValueError('Source surface evidence bytes differ') data = json.loads(raw) if not isinstance(data, dict) or data.get('schema') != 'rhg.layout_surface_feedback.v1': raise ValueError('Invalid source surface evidence schema') records = data.get('records') key = row.get('pool_candidate_key') record = records.get(key) if isinstance(records, dict) and isinstance(key, str) and key else None identity = {key: row.get(key) for key in ('asset_id', 'asset_sha256', 'runtime_sha256', 'canonical_transform')} if (not identity['asset_id'] or identity['canonical_transform'] is None or any(not _sha256(identity[k]) for k in ('asset_sha256', 'runtime_sha256')) or not isinstance(record, dict) or record.get('identity') != identity): raise ValueError('Source surface evidence record differs') if inputs is not None: inputs[str(evidence)] = sha return dict(evidence_path=str(evidence), evidence_sha256=sha, source_identity=identity, pool_candidate_key=key) # Same 10 micrometre contact tolerance as the saved-geometry audit and the solver (support_regions.CONTACT_TOLERANCE_M); 1 micrometre # rejected a rug whose measured plane (0.0199988 m) and saved top (0.0200000 m) differ by 1.2 micrometres. DERIVED_RUG_HEIGHT_TOLERANCE_M = 1e-5 def resolve_support_contract(row, entities, *, payload=None, inputs=None): """Resolve static contact semantics; unresolved mechanisms stay pending. ``installation_gap`` is a nominal wall back gap, never a tolerance. Its external receipt must bind this entity/source and the current exported geometry. The user's wall-only 0..10 mm acceptance range is separate from that nominal receipt; it does not require or fabricate a source receipt. """ identifier = row['entity_id'] parents = [row[k] for k in ('supported_by_entity_id', 'support_entity_id', 'parent_entity_id') if row.get(k) is not None] if (any(not isinstance(p, str) or not p for p in parents) or len(set(parents)) > 1 or set(parents) - entities.keys() or identifier in parents): raise ValueError('Invalid saved support relationship: ' + identifier) parent = next(iter(parents), None) relation = str(row.get('layout_relation', '')).lower() mounted = row.get('layout_slot_id') in { 'kitchen_upper_cabinet', 'kitchen_range_hood', 'bath_mirror', 'master_television'} or any( term in relation for term in ('wall_mounted', 'wall-mounted', 'wall_tv', 'wall_mirror')) explicit = row.get('support_type') # Native "on_top" describes a legacy relation, not its installation mechanism. # Unknown declarations remain explicit so they cannot fall back to floor. if explicit is None and row.get('support_relation') is not None: explicit = row['support_relation'] if explicit == 'on_top': explicit = ('wall' if mounted else 'inset' if row.get('layout_slot_id') == 'kitchen_sink' else 'surface') kind = explicit if explicit is not None else ('wall' if mounted else 'inset' if row.get('layout_slot_id') == 'kitchen_sink' else 'surface' if parent else 'floor') pending = [] if kind not in ('floor', 'surface', 'wall', 'inset', 'suspended', 'multi_support'): pending.append('unsupported_support_type:' + identifier) elif kind in ('suspended', 'multi_support'): pending.append('support_mechanism:' + identifier + ':' + kind) elif kind == 'wall' and row.get('wall_anchor') not in ('E', 'W', 'N', 'S'): pending.append('wall_anchor:' + identifier) elif kind in ('surface', 'inset') and parent is None: pending.append('support_parent:' + identifier) elif kind == 'floor' and parent is not None: pending.append('support_type_parent_conflict:' + identifier) result = dict(support_type=kind, support_entity_id=parent, expected_gap_m=0., pending_fields=pending) if kind == 'wall': result.update(accepted_gap_range_m=list(WALL_GAP_RANGE_M), gap_acceptance=WALL_GAP_ACCEPTANCE) if 'installation_gap' in row: try: gap = row['installation_gap'] if (kind != 'wall' or not isinstance(gap, dict) or set(gap) != {'gap_m', 'evidence_path', 'evidence_sha256'} or type(gap['gap_m']) not in (int, float) or not math.isfinite(gap['gap_m']) or gap['gap_m'] < 0 or not _sha256(gap['evidence_sha256']) or not isinstance(gap['evidence_path'], str) or not Path(gap['evidence_path']).is_absolute()): raise ValueError('Invalid installation gap declaration') path = Path(gap['evidence_path']).resolve(strict=True) raw = path.read_bytes() if hashlib.sha256(raw).hexdigest() != gap['evidence_sha256']: raise ValueError('Installation evidence bytes differ') evidence = json.loads(raw) identity = {key: row.get(key) for key in ( 'asset_id', 'asset_sha256', 'runtime_sha256', 'canonical_transform')} if (not isinstance(evidence, dict) or not isinstance(payload, dict) or evidence.get('schema') != 'rhg.source-installation-gap.v1' or evidence.get('entity_id') != identifier or evidence.get('support_type') != kind or evidence.get('wall_anchor') != row.get('wall_anchor') or type(evidence.get('gap_m')) not in (int, float) or evidence['gap_m'] != gap['gap_m'] or not identity['asset_id'] or identity['canonical_transform'] is None or any(not _sha256(identity[key]) for key in ('asset_sha256', 'runtime_sha256')) or evidence.get('source_identity') != identity or not _sha256(payload.get('source_blend_sha256')) or evidence.get('scene_sha256') != payload['source_blend_sha256'] or evidence.get('mesh_fingerprint') != hashlib.sha256(json.dumps( payload['meshes'], sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest()): raise ValueError('Installation evidence does not match current source/export') names = evidence.get('target_mesh_names') shell_names = [m['name'] for m in payload['meshes'] if m.get('entity_id') is None] if (not isinstance(names, list) or not names or any(not isinstance(n, str) or shell_names.count(n) != 1 for n in names) or len(set(names)) != len(names)): raise ValueError('Installation evidence targets are absent or ambiguous') if inputs is not None: if str(path) in inputs and inputs[str(path)] != gap['evidence_sha256']: raise ValueError('Installation evidence pin differs') inputs[str(path)] = gap['evidence_sha256'] result.update(expected_gap_m=gap['gap_m'], target_mesh_names=list(names), installation_evidence=dict(evidence_path=str(path), evidence_sha256=gap['evidence_sha256'], scene_sha256=evidence['scene_sha256'], mesh_fingerprint=evidence['mesh_fingerprint'])) except (OSError, ValueError, TypeError, KeyError): pending.append('installation_evidence:' + identifier) result['status'] = 'pending' if pending else 'ready' return result def authored_support_parent(row, entities, *, inputs=None, verify_evidence=False): parents = {row[key] for key in ('supported_by_entity_id', 'support_entity_id', 'parent_entity_id') if row.get(key) is not None} if len(parents) > 1: raise ValueError('Conflicting support parents: ' + row['entity_id']) actual = next(iter(parents), None) relation = row.get('derived_support_relation') if relation is None: return actual surface = row.get('selected_support_surface') or {} parent = entities.get(actual, {}) if (not isinstance(relation, dict) or relation.get('source') != 'actual_floor_cover_mesh_and_furniture_bottom_contacts' or relation.get('stage') != 'joint_search_before_freeze' or relation.get('authored_support_parent_entity_id') is not None or relation.get('added_support_parent_entity_id') != actual or relation.get('original_task_relations_retained') is not True or row.get('supported_by_entity_id') or row.get('parent_entity_id') or parent.get('role') not in ('rug', 'carpet') or parent.get('room_id') != row.get('room_id') or surface.get('status') != 'measured' or surface.get('source_region_modified') is not False or surface.get('parent_entity_id') != actual or surface.get('parent_asset_id') != parent.get('asset_id')): raise ValueError('Invalid derived rug support: ' + row['entity_id']) identity = surface.get('parent_source_identity') or {} for key in ('asset_id', 'asset_sha256', 'runtime_sha256'): if not parent.get(key) or identity.get(key) != parent[key]: raise ValueError('Derived rug source identity differs: ' + row['entity_id']) if identity.get('canonical_transform') != parent.get('canonical_transform'): raise ValueError('Derived rug source transform differs: ' + row['entity_id']) sha = surface.get('evidence_sha256') if not isinstance(sha, str) or len(sha) != 64 or any(c not in '0123456789abcdef' for c in sha): raise ValueError('Missing derived rug surface evidence: ' + row['entity_id']) evidence = None if verify_evidence: evidence = Path(verify_surface_evidence(parent, surface.get('evidence_path'), sha, inputs=inputs)['evidence_path']) values = [row.get('base_z_m'), relation.get('original_floor_height_m'), relation.get('vertical_translation_m'), surface.get('surface_z_world_m')] if (any(type(v) not in (int, float) or not math.isfinite(v) for v in values) or values[2] < 0 or abs(values[0]-values[1]-values[2]) > DERIVED_RUG_HEIGHT_TOLERANCE_M or abs(values[0]-values[3]) > DERIVED_RUG_HEIGHT_TOLERANCE_M): raise ValueError('Derived rug height differs: ' + row['entity_id']) if evidence is not None and inputs is not None: inputs[str(evidence)] = sha return None