File size: 26,133 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
"""Partial saved geometry can diagnose local failures, never certify a house."""
import copy
import json
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch

from engine import feedback, geometry_validation
from engine import repair_execution, run_chain


class PartialGeometryRepairsTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        self.root = Path(self.temp.name).resolve()
        self.manifest = dict(scene_id='partial_fixture',
            floor_plan=dict(rooms=[dict(room_id='room', bounds_m=[0, 0, 20, 20])]),
            entities=[dict(entity_id=eid, room_id='room', role=eid,
                asset_id='asset-' + eid, center_xy_m=[float(i + 1), 1.],
                yaw_deg=0., base_z_m=0., dimensions_m=[1., 1., 1.])
                for i, eid in enumerate(('chair', 'table', 'open_mesh'))])
        self.request = dict(schema='rhg.scene_request.v1', mode='locked',
            task_kind='scene_generation', task_text='Retain the full scene inventory.',
            entities=copy.deepcopy(self.manifest['entities']),
            furniture=[dict(entity_id=e['entity_id'], asset_id=e['asset_id'])
                       for e in self.manifest['entities']])
        self.diagnostic = dict(code='collision', entity_ids=['chair', 'table'],
            message='Saved physical solids interpenetrate', collision_object='table',
            overlap_volume_m3=.1)
        self.config = dict(schema='rhg.frontier-chain-config.v1',
            manifest=str(self.write('manifest.json', self.manifest)),
            request=str(self.write('request.json', self.request)),
            geometry_validation={},
            repair_execution=dict(enabled=True, max_attempts=2, total_timeout_s=30),
            generation=dict(command=[sys.executable, '-c',
                'import json,pathlib,sys; m=json.load(open(sys.argv[1])); '
                'r=json.load(open(sys.argv[3])); '
                'm["entities"][0]["center_xy_m"][0] += bool(r.get("repair")); '
                '(pathlib.Path(sys.argv[2])/"generated.json").write_text(json.dumps(m))',
                '{manifest}', '{attempt_dir}', '{request}'],
                manifest_output='generated.json', timeout_s=5,
                native_search_required=False))

    def write(self, name, data):
        path = self.root / name
        path.write_text(json.dumps(data))
        return path

    def evidence(self, manifest=None, *, diagnostics=True):
        manifest = manifest or self.manifest
        evidence = dict(schema=geometry_validation.SCHEMA, status='pending', complete=False,
            geometry_passed=False, inputs_unchanged=True,
            manifest_fingerprint=geometry_validation.fingerprint(manifest),
            physical_qualified=False, whole_task_acceptance=False,
            contact_tolerance_m=1e-5,
            pending_fields=['non_solid_mesh:unrelated_open_surface'],
            diagnostics=[copy.deepcopy(self.diagnostic)] if diagnostics else [],
            entity_readbacks={e['entity_id']: dict(center_xy_m=e['center_xy_m'],
                yaw_deg=e['yaw_deg'], base_z_m=0., dimensions_m=e['dimensions_m'],
                world_bbox_m=[[e['center_xy_m'][0]-.5, .5, 0.],
                              [e['center_xy_m'][0]+.5, 1.5, 1.]])
                for e in manifest['entities']},
            pair_checks=[dict(left='chair', right='table', passed=False, complete=True, status='measured',
                             method='manifold3d_solid_intersection', overlap_volume_m3=.1)] if diagnostics else [],
            contact_checks=[dict(entity_id=eid, support_entity_id=None, passed=True,
                                 complete=True, status='measured', pending_fields=[],
                                 support_type='floor', method='bottom_vertices_and_face_centroids',
                                 gaps_m=[0.], sample_count=1)
                            for eid in ('chair', 'table')] + [dict(entity_id='open_mesh',
                                passed=None, complete=False, status='pending',
                                pending_fields=['solid_geometry:open_mesh'])])
        evidence['entity_checks'] = {eid: dict(solid_complete=eid != 'open_mesh',
            contact_complete=eid != 'open_mesh', contact_passed=True if eid != 'open_mesh' else None)
            for eid in ('chair', 'table', 'open_mesh')}
        return self.bind_evidence_files(manifest, evidence)

    def bind_evidence_files(self, manifest, evidence):
        fingerprint = geometry_validation.fingerprint(manifest)
        scene = self.write(fingerprint + '.scene', dict(fixture_only=True))
        meshes = self.write(fingerprint + '.meshes', dict(fixture_only=True))
        pins = {str(path): run_chain.digest(path) for path in (scene, meshes)}
        evidence.update(scene_sha256=pins[str(scene)], input_sha256=pins,
            provenance=dict(evidence.get('provenance') or {}, scene_path=str(scene), scene_sha256=pins[str(scene)],
                            mesh_path=str(meshes), mesh_sha256=pins[str(meshes)]))
        return evidence

    def test_runtime_policy_is_compiled_and_original_template_stays_bound(self):
        template = self.write('runtime-template.json', dict(preserve=dict(values=[1, 2])))
        original = template.read_bytes()
        self.config['geometry_validation'] = dict(enabled=False)
        self.config['wholehouse'] = dict(material_policy=dict(pins=dict(
            interior_wall=dict(material_id='native-wall'),
            door_family=dict(family_id='native-doors'))))
        self.config['generation']['runtime_template'] = str(template)
        result = run_chain.run_chain(self.write('config.json', self.config),
                                      self.root / 'chain', execute=True)
        self.assertTrue(result['output_contract_passed'], result)
        runtime_path = self.root / 'chain/attempt_01/runtime.json'
        runtime = run_chain.load(runtime_path)
        self.assertEqual(runtime.get('wall_material_id'), 'native-wall')
        self.assertEqual(runtime.get('door_family_id'), 'native-doors')
        self.assertEqual(runtime['preserve'], dict(values=[1, 2]))
        self.assertEqual(template.read_bytes(), original)
        self.assertEqual(result['input_sha256'][str(template.resolve())], run_chain.digest(template))
        self.assertEqual(result['input_sha256'][str(runtime_path.resolve())], run_chain.digest(runtime_path))

    def measure(self, config, manifest_path, output, *, timeout_s):
        output.mkdir()
        manifest = run_chain.load(manifest_path)
        evidence = self.evidence(manifest,
            diagnostics=manifest['entities'][0]['center_xy_m'][0] == 1.)
        evidence.update(manifest_sha256=run_chain.digest(manifest_path),
            result_path=str(output / 'result.json'))
        evidence['input_sha256'][str(manifest_path)] = run_chain.digest(manifest_path)
        run_chain.save(output / 'result.json', evidence)
        return evidence

    def execute(self):
        # Exercise the real controller in-process so only the expensive mesh
        # measurement boundary is substituted. Generation uses a real process.
        def chain_command(command, cwd, log_path, timeout):
            run_chain.run_chain(command[command.index('--config') + 1],
                command[command.index('--output') + 1], execute=True)
            return dict(timed_out=False, cleanup_passed=True, exit_code=1)

        with patch.object(geometry_validation, 'validate_generated_scene', side_effect=self.measure), \
                patch.object(repair_execution, 'execute_command', side_effect=chain_command):
            return repair_execution.execute_repairs(self.write('config.json', self.config),
                                                     self.root / 'output', execute=True)

    def test_pending_receipt_retains_measured_failures_without_acceptance(self):
        with patch.object(geometry_validation, 'validate_generated_scene', side_effect=self.measure):
            result = run_chain.run_chain(self.write('config.json', self.config),
                                          self.root / 'chain', execute=True)
        review = run_chain.load(self.root / 'chain/attempt_01/output_review.json')
        self.assertEqual(review['diagnostics'], [self.diagnostic])
        self.assertTrue(result['geometry_provenance_current'])
        self.assertFalse(result['geometry_complete'])
        self.assertFalse(result['geometry_current'])
        self.assertFalse(result['geometry_passed'])
        self.assertFalse(result['output_contract_passed'])

    def test_partial_collision_retries_and_preserves_unrelated_open_entity(self):
        result = self.execute()
        self.assertEqual(result['count'], 2, result)
        self.assertTrue(result['preservation_verified'], result)
        self.assertEqual(result['status'], 'generation_completed_pending_geometry_review')
        first = run_chain.load(self.root / 'output/round_01/attempt_01/generated.json')
        second = run_chain.load(self.root / 'output/round_02/attempt_01/generated.json')
        self.assertEqual(first['entities'][2], second['entities'][2])
        self.assertFalse(result['geometry_passed'])
        self.assertFalse(result['output_contract_passed'])
        self.assertFalse(result['whole_task_acceptance'])
        self.assertTrue(result['geometry_requested'])
        self.assertTrue(result['geometry_provenance_current'])
        self.assertFalse(result['geometry_complete'])
        self.assertEqual(result['geometry_validation']['manifest_fingerprint'],
                         geometry_validation.fingerprint(second))
        self.assertEqual(result['geometry_validation']['manifest_sha256'],
                         result['output_manifest_sha256'])
        self.assertEqual(result['history'][0]['failure_record']['geometry_label'], 'failure')
        self.assertEqual(result['history'][0]['repair_record']['action'], 'planned')
        self.assertEqual(result['history'][1]['repair_record']['outcome'], 'preservation_verified')

    def test_pending_without_failures_is_unknown_in_failure_record(self):
        self.manifest['entities'][0]['center_xy_m'][0] = 2.
        self.write('manifest.json', self.manifest)
        result = self.execute()
        self.assertEqual(result['count'], 1, result)
        record = result['history'][0]['failure_record']
        self.assertEqual(record['geometry_label'], 'unknown')
        self.assertFalse(record['accepted_training_positive'])

    def test_dependency_on_unmeasured_open_entity_blocks_retry(self):
        self.manifest['entities'][2]['parent_entity_id'] = 'chair'
        self.write('manifest.json', self.manifest)
        result = self.execute()
        self.assertEqual(result['count'], 1, result)
        self.assertEqual(result['status'], 'manual_review_required', result)

    def test_local_preservation_accepts_current_partial_evidence(self):
        plan = feedback.plan_repair(self.manifest, self.request, [self.diagnostic])
        after = copy.deepcopy(self.manifest)
        after['entities'][0]['center_xy_m'][0] += 1
        receipt = feedback.verify_preservation(self.manifest, after, plan,
                                               geometry_evidence=self.evidence(after))
        self.assertTrue(receipt['preservation_verified'], receipt)
        self.assertEqual(receipt['geometry_scope_entity_ids'], ['chair', 'table'])
        self.assertFalse(receipt['whole_task_acceptance'])

    def test_local_preservation_never_allows_global_asset_changes(self):
        plan = feedback.plan_repair(self.manifest, self.request, [self.diagnostic])
        after = copy.deepcopy(self.manifest)
        after['entities'][2]['asset_id'] = 'different-asset'
        receipt = feedback.verify_preservation(self.manifest, after, plan,
                                               geometry_evidence=self.evidence(after))
        self.assertFalse(receipt['passed'])

    def test_scoped_evidence_fails_closed(self):
        for mutation in (
            lambda e: e.update(manifest_fingerprint='0' * 64),
            lambda e: e.update(inputs_unchanged=False),
            lambda e: e.update(status='failed'),
            lambda e: e.update(pair_checks=[]),
            lambda e: e['pair_checks'][0].update(passed=True),
            lambda e: e['pair_checks'][0].update(complete=False, status='pending'),
            lambda e: e['pair_checks'][0].update(overlap_volume_m3=0.),
            lambda e: e['contact_checks'].pop(1),
            lambda e: e['contact_checks'][0].update(complete=False, status='pending'),
            lambda e: e['entity_readbacks']['chair'].update(yaw_deg=90.),
        ):
            evidence = self.evidence()
            mutation(evidence)
            with self.subTest(evidence=evidence):
                self.assertFalse(feedback.geometry_scope_supported(self.manifest, evidence,
                    ['chair', 'table'], diagnostics=[self.diagnostic]))

    def test_unknown_or_unmeasured_diagnostics_never_authorize_partial_repair(self):
        for code in ('unknown_failure', 'out_of_bounds', 'support_contact_invalid'):
            diagnostic = dict(self.diagnostic, code=code)
            evidence = self.evidence()
            evidence['diagnostics'] = [diagnostic]
            self.assertFalse(feedback.geometry_scope_supported(self.manifest, evidence,
                ['chair', 'table'], diagnostics=[diagnostic]))

    def test_scope_hashes_inputs_once_for_many_entities_and_diagnostics(self):
        evidence = self.evidence()
        with patch.object(geometry_validation, '_file_sha256',
                          wraps=geometry_validation._file_sha256) as hashes:
            self.assertTrue(feedback.geometry_scope_supported(self.manifest, evidence,
                ['chair', 'table'], diagnostics=[self.diagnostic] * 8))
        self.assertEqual(hashes.call_count, len(evidence['input_sha256']))

    def test_mutated_scene_bytes_cannot_authorize_scoped_repair(self):
        evidence = self.evidence()
        Path(evidence['provenance']['scene_path']).write_text('changed fixture scene')
        self.assertFalse(feedback.geometry_scope_supported(self.manifest, evidence,
            ['chair', 'table'], diagnostics=[self.diagnostic]))

    def test_measured_support_failure_can_authorize_only_its_covered_scope(self):
        evidence = self.evidence()
        diagnostic = dict(code='support_contact_invalid', entity_ids=['chair'],
                          support_entity_id=None, message='Measured support gap.')
        evidence['diagnostics'] = [diagnostic]
        evidence['contact_checks'][0].update(passed=False, gaps_m=[.02])
        evidence['entity_checks']['chair']['contact_passed'] = False
        self.assertTrue(feedback.geometry_scope_supported(self.manifest, evidence,
            ['chair'], diagnostics=[diagnostic]))
        evidence['contact_checks'][0].update(passed=None, status='pending', complete=False)
        self.assertFalse(feedback.geometry_scope_supported(self.manifest, evidence,
            ['chair'], diagnostics=[diagnostic]))

    def test_native_rotation_can_use_partial_current_scoped_readbacks(self):
        from engine.tests.test_feedback import NativePreservationTests
        native = NativePreservationTests()
        native.setUp()
        native.manifest['entities'][0]['world_bbox_m'] = [[1.8, 1.8, 0.], [2.2, 2.2, .7]]
        after = native.rotated()
        after['entities'][0]['world_bbox_m'] = [[2.2, 1.8, 0.], [2.6, 2.2, .7]]
        row = after['entities'][0]
        evidence = dict(schema=geometry_validation.SCHEMA, status='pending', complete=False,
            geometry_passed=False, inputs_unchanged=True,
            manifest_fingerprint=geometry_validation.fingerprint(after),
            physical_qualified=False, whole_task_acceptance=False,
            entity_readbacks=dict(plant=dict(world_bbox_m=row['world_bbox_m'],
                center_xy_m=row.get('actual_center_xy_m', row['center_xy_m']),
                dimensions_m=row['dimensions_m'], base_z_m=0., yaw_deg=row['yaw_deg'])),
            contact_tolerance_m=1e-5,
            entity_checks=dict(plant=dict(solid_complete=True, contact_complete=True, contact_passed=True)),
            contact_checks=[dict(entity_id='plant', support_entity_id=None, passed=True,
                support_type='floor', method='bottom_vertices_and_face_centroids', gaps_m=[0.], sample_count=1,
                status='measured', complete=True, pending_fields=[])])
        evidence = self.bind_evidence_files(after, evidence)
        receipt = feedback.verify_preservation(native.manifest, after, native.plan(),
                                               geometry_evidence=evidence)
        self.assertTrue(receipt['preservation_verified'], receipt)
        self.assertFalse(receipt['geometry_complete'])
        self.assertFalse(receipt['whole_task_acceptance'])

    def test_forged_partial_pass_is_never_overall_acceptance(self):
        measure = self.measure

        def forged(*args, **kwargs):
            evidence = measure(*args, **kwargs)
            evidence['geometry_passed'] = True
            run_chain.save(evidence['result_path'], evidence)
            return evidence

        self.manifest['entities'][0]['center_xy_m'][0] = 2.
        self.write('manifest.json', self.manifest)
        with patch.object(geometry_validation, 'validate_generated_scene', side_effect=forged):
            result = run_chain.run_chain(self.write('config.json', self.config),
                                          self.root / 'chain', execute=True)
        self.assertFalse(result['geometry_passed'])
        self.assertFalse(result['output_contract_passed'])
        self.assertEqual(result['status'], 'generation_completed_pending_geometry_review')

    def test_real_measured_collision_survives_unrelated_open_geometry(self):
        from engine.tests.test_geometry_validation import box
        meshes = [box('floor', [0, 0, -.2], [10, 10, 0]),
                  box('chair', [1, 1, 0], [2, 2, 1], 'chair'),
                  box('table', [1.9, 1, 0], [2.9, 2, 1], 'table'),
                  box('open', [5, 5, 0], [6, 6, 1], 'open_mesh')]
        meshes[-1]['triangles'].pop()
        manifest = copy.deepcopy(self.manifest)
        for row, center in zip(manifest['entities'], ([1.5, 1.5], [2.4, 1.5], [5.5, 5.5])):
            row['center_xy_m'] = center
        # An open part with no collision proxy stays pending (unresolvable geometry).
        with patch.object(geometry_validation, '_proxy_solid', return_value=(None, None)):
            audit = geometry_validation.audit_meshes(manifest,
                dict(world_vertices=True, meshes=meshes), {})
        evidence = self.bind_evidence_files(manifest, dict(audit,
            schema=geometry_validation.SCHEMA, status='pending',
            inputs_unchanged=True, manifest_fingerprint=geometry_validation.fingerprint(manifest),
            physical_qualified=False, whole_task_acceptance=False))
        self.assertFalse(evidence['complete'])
        collision = next(d for d in evidence['diagnostics'] if d['code'] == 'collision')
        self.assertTrue(feedback.geometry_scope_supported(manifest, evidence,
            ['chair', 'table'], diagnostics=[collision]))
        self.assertFalse(feedback.geometry_scope_supported(manifest, evidence,
            ['chair', 'table', 'open_mesh'], diagnostics=[collision]))

    def test_flags_without_typed_contact_measurements_do_not_authorize_repairs(self):
        for mutation in (
            lambda c: c.pop('method'), lambda c: c.pop('gaps_m'),
            lambda c: c.update(support_type='suspended'),
            lambda c: c.update(method='unsupported_proxy'),
            lambda c: c.update(gaps_m=[float('nan')]),
            lambda c: c.update(sample_count=True),
            lambda c: c.update(passed=False),
        ):
            evidence = self.evidence()
            mutation(evidence['contact_checks'][0])
            with self.subTest(contact=evidence['contact_checks'][0]):
                self.assertFalse(feedback.geometry_scope_supported(self.manifest, evidence,
                    ['chair', 'table'], diagnostics=[self.diagnostic]))
        evidence = self.evidence()
        evidence['entity_checks']['chair']['contact_passed'] = False
        self.assertFalse(feedback.geometry_scope_supported(self.manifest, evidence,
            ['chair', 'table'], diagnostics=[self.diagnostic]))

    def test_unmeasured_support_failure_does_not_trigger_second_attempt(self):
        measure = self.measure
        def unmeasured(*args, **kwargs):
            evidence = measure(*args, **kwargs)
            evidence['diagnostics'] = [dict(code='support_contact_invalid', entity_ids=['chair'],
                support_entity_id=None, message='Unmeasured support flag')]
            evidence['contact_checks'][0] = dict(entity_id='chair', support_entity_id=None,
                passed=False, status='measured', complete=True, pending_fields=[])
            evidence['entity_checks']['chair']['contact_passed'] = False
            run_chain.save(evidence['result_path'], evidence)
            return evidence
        self.measure = unmeasured
        result = self.execute()
        self.assertEqual(result['count'], 1, result)
        self.assertEqual(result['status'], 'manual_review_required')
        self.assertFalse(result['preservation_verified'])

    def test_duplicate_or_contradictory_collision_pairs_fail_closed(self):
        for update in ({}, dict(passed=True, overlap_volume_m3=0.),
                       dict(left='table', right='chair')):
            evidence = self.evidence()
            evidence['pair_checks'].append(dict(evidence['pair_checks'][0], **update))
            with self.subTest(update=update):
                self.assertFalse(feedback.geometry_scope_supported(self.manifest, evidence,
                    ['chair', 'table'], diagnostics=[self.diagnostic]))
        evidence = self.evidence()
        evidence['pair_checks'][0]['method'] = 'saved_mesh_aabb_separation'
        self.assertFalse(feedback.geometry_scope_supported(self.manifest, evidence,
            ['chair', 'table'], diagnostics=[self.diagnostic]))

    def test_complete_preservation_evidence_rechecks_scene_and_export_bytes(self):
        plan = feedback.plan_repair(self.manifest, self.request, [self.diagnostic])
        after = copy.deepcopy(self.manifest)
        after['entities'][0]['center_xy_m'][0] += .1
        for key in ('scene_path', 'mesh_path'):
            evidence = self.evidence(after)
            evidence.update(status='measured', complete=True)
            Path(evidence['provenance'][key]).write_bytes(b'changed')
            with self.subTest(key=key):
                self.assertFalse(feedback.verify_preservation(self.manifest, after, plan,
                    geometry_evidence=evidence)['preservation_verified'])

    def test_missing_ray_hit_is_a_measured_support_failure(self):
        evidence = self.evidence()
        diagnostic = dict(code='support_contact_invalid', entity_ids=['chair'],
            support_entity_id=None, message='Actual ray had no hit')
        evidence['diagnostics'] = [diagnostic]
        evidence['contact_checks'][0].update(passed=False, gaps_m=[None])
        evidence['entity_checks']['chair']['contact_passed'] = False
        self.assertTrue(feedback.geometry_scope_supported(self.manifest, evidence,
            ['chair'], diagnostics=[diagnostic]))

    def test_real_floor_surface_and_inset_measurements_remain_supported(self):
        from engine.tests.test_geometry_validation import box, entity
        for kind in ('surface', 'inset'):
            rows = [entity('table', [0, 0, 0], [2, 2, 1]),
                    entity('cup', [.2, .2, 1], [.8, .8, 1.4], 'table')]
            rows[1]['support_type'] = kind
            manifest = dict(floor_plan=dict(rooms=[dict(room_id='room')]), entities=rows)
            payload = dict(world_vertices=True, meshes=[
                box('floor', [-3, -3, -.2], [3, 3, 0]),
                box('table', [0, 0, 0], [2, 2, 1], 'table'),
                box('cup', [.2, .2, 1], [.8, .8, 1.4], 'cup')])
            audit = geometry_validation.audit_meshes(manifest, payload, {})
            evidence = self.bind_evidence_files(manifest, dict(audit,
                schema=geometry_validation.SCHEMA, status='pending', inputs_unchanged=True,
                manifest_fingerprint=geometry_validation.fingerprint(manifest),
                physical_qualified=False, whole_task_acceptance=False))
            with self.subTest(kind=kind):
                self.assertTrue(feedback.geometry_scope_supported(manifest, evidence, ['table', 'cup']))

    def test_real_wall_nominal_gap_requires_bound_receipt_without_widening(self):
        from engine.tests.test_support_installation_contract import SupportInstallationContractTests
        wall = SupportInstallationContractTests()
        wall.setUp()
        self.addCleanup(wall.doCleanups)
        scene = self.write('wall.scene', dict(fixture_only=True))
        wall.payload['source_blend_sha256'] = run_chain.digest(scene)
        receipt = wall.receipt()
        manifest = dict(floor_plan=copy.deepcopy(wall.plan), entities=[wall.row])
        audit = geometry_validation.audit_meshes(manifest, wall.payload, {})
        evidence = self.bind_evidence_files(manifest, dict(audit,
            schema=geometry_validation.SCHEMA, status='pending', inputs_unchanged=True,
            manifest_fingerprint=geometry_validation.fingerprint(manifest),
            physical_qualified=False, whole_task_acceptance=False))
        evidence['input_sha256'][str(receipt.resolve())] = run_chain.digest(receipt)
        self.assertTrue(feedback.geometry_scope_supported(manifest, evidence, ['cabinet']))
        evidence['contact_checks'][0]['gaps_m'][0] += .0001
        self.assertFalse(feedback.geometry_scope_supported(manifest, evidence, ['cabinet']))


if __name__ == '__main__':
    unittest.main()