File size: 42,366 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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
"""Contract tests for planning only; no solver, experiment, or GPU imports."""

import copy
import importlib
import json
import math
import unittest


POSE_PREFERENCES = (
    "preferred_center_xy_m", "preferred_yaw_deg", "installation_height_m",
)
SUPPORT_ALIASES = ("supported_by_entity_id", "support_entity_id", "parent_entity_id")


def row_bytes(row):
    return json.dumps(row, separators=(",", ":"), allow_nan=False).encode("utf-8")


def inputs():
    entities = []
    for index, entity_id in enumerate(
        ("table", "tray", "cup", "chair", "stool", "lamp", "table_10")
    ):
        entities.append({
            "entity_id": entity_id, "room_id": "living", "role": entity_id,
            "layout_slot_id": entity_id + "_slot", "center_xy_m": [index, 2.0],
            "yaw_deg": 90.0, "base_z_m": 0.0, "dimensions_m": [1.0, 1.0, 0.7],
            "source_dimensions_m": [1.0, 1.0, 0.7], "uniform_scale": 1.0,
            "asset_id": "source:" + entity_id, "asset_sha256": "sha:" + entity_id,
            "canonical_transform": {"scale": [1, 1, 1]}, "wall_anchor": "N",
            "opaque": {"original": "  keep\\nbytes  ", "number": 1.0},
        })
    entities[1]["supported_by_entity_id"] = "table"
    entities[2]["support_entity_id"] = "tray"
    entities[3]["front_target_entity_id"] = "table"
    manifest = {
        "schema": "example.manifest.v1",
        "floor_plan": {"rooms": [{"room_id": "living", "bounds_m": [0, 0, 10, 8]}]},
        "entities": entities,
        "source_assets": [{"asset_id": "source:table", "path": "/source/original.usd"}],
    }
    definitions = []
    for entity in entities:
        definition = {key: copy.deepcopy(value) for key, value in entity.items()
                      if key in ("entity_id", "room_id", "role", "layout_slot_id",
                                 "wall_anchor", "supported_by_entity_id",
                                 "support_entity_id", "front_target_entity_id")}
        definition.update(preferred_center_xy_m=copy.deepcopy(entity["center_xy_m"]),
                          preferred_yaw_deg=entity["yaw_deg"],
                          installation_height_m=entity["base_z_m"])
        definitions.append(definition)
    request = {
        "schema": "rhg.scene_request.v1", "mode": "pool",
        "task_kind": "scene_generation", "task_text": "Keep every entity and relation.",
        "task": {"arbitrary": ["untouched", {"source": "original"}]},
        "furniture": [{"entity_id": e["entity_id"],
                       "candidate_asset_ids": [e["asset_id"], e["asset_id"] + ":other"],
                       "preferred_candidate_record_ids": ["record:original"],
                       "evidence": {"source_dimensions_m": e["source_dimensions_m"]}}
                      for e in entities],
        "entities": definitions,
        "relations": [{"kind": "near", "subject": "stool", "object": "chair",
                       "maximum_m": 2.0}],
        "search": {"max_nodes_per_room": 80000},
    }
    diagnostics = [{"code": "collision", "entity_ids": ["table"],
                    "message": "Explicit IDs determine the repair, not this prose."}]
    return manifest, request, diagnostics


class FeedbackTests(unittest.TestCase):
    def setUp(self):
        try:
            self.feedback = importlib.import_module("engine.feedback")
        except ModuleNotFoundError as exc:
            if exc.name not in ("engine",
                                "engine.feedback"):
                raise
            self.fail("The additive feedback API has not been implemented")
        self.manifest, self.request, self.diagnostics = inputs()

    def plan(self, **kwargs):
        return self.feedback.plan_repair(
            self.manifest, self.request, self.diagnostics, **kwargs)

    def verify(self, after, plan=None):
        return self.feedback.verify_preservation(self.manifest, after, plan or self.plan())

    def test_support_front_and_relation_transitive_closure(self):
        plan = self.plan()
        self.assertEqual(plan["schema"], "rhg.frontier.repair-plan.v1")
        self.assertEqual(plan["status"], "repair_planned")
        self.assertEqual(plan["directly_conflicting_entity_ids"], ["table"])
        self.assertEqual(plan["resample_entity_ids"], ["table", "tray", "cup", "chair", "stool"])
        self.assertEqual(plan["preserved_entity_ids"], ["lamp", "table_10"])
        self.assertEqual(plan["attempt_index"], 1)
        self.assertEqual(plan["next_attempt_index"], 2)

    def test_dependencies_are_downstream_only(self):
        self.diagnostics[0]["entity_ids"] = ["cup"]
        self.assertEqual(self.plan()["resample_entity_ids"], ["cup"])
        self.diagnostics[0]["entity_ids"] = ["stool"]
        self.assertEqual(self.plan()["resample_entity_ids"], ["stool"])

    def test_both_support_aliases_and_request_dependencies_are_used(self):
        self.request["entities"][5]["support_entity_id"] = "cup"
        self.manifest["entities"][5]["supported_by_entity_id"] = "cup"
        self.assertIn("lamp", self.plan()["resample_entity_ids"])

    def test_parent_entity_alias_preserves_transitive_support_chain(self):
        for rows in (self.manifest["entities"], self.request["entities"]):
            rows[1]["parent_entity_id"] = rows[1].pop("supported_by_entity_id")
        original = copy.deepcopy((self.manifest, self.request, self.diagnostics))
        plan = self.plan()
        self.assertEqual(plan["resample_entity_ids"],
                         ["table", "tray", "cup", "chair", "stool"])
        self.assertEqual(plan["preserved_entity_ids"], ["lamp", "table_10"])
        for index in (1, 2):
            for key in POSE_PREFERENCES:
                self.assertNotIn(key, plan["next_request"]["entities"][index])
        self.assertEqual(plan["next_request"]["entities"][1]["parent_entity_id"], "table")
        self.assertEqual((self.manifest, self.request, self.diagnostics), original)
        self.diagnostics[0]["entity_ids"] = ["tray"]
        self.assertEqual(self.plan()["resample_entity_ids"], ["tray", "cup"])

    def test_support_aliases_work_from_each_input_collection(self):
        for collection in ("manifest", "entities", "furniture"):
            for alias in SUPPORT_ALIASES:
                with self.subTest(collection=collection, alias=alias):
                    manifest, request, diagnostics = inputs()
                    del manifest["entities"][1]["supported_by_entity_id"]
                    del request["entities"][1]["supported_by_entity_id"]
                    rows = manifest["entities"] if collection == "manifest" else request[collection]
                    rows[1][alias] = "table"
                    plan = self.feedback.plan_repair(manifest, request, diagnostics)
                    self.assertIn("tray", plan["resample_entity_ids"])
                    self.assertIn("cup", plan["resample_entity_ids"])

    def test_agreeing_support_aliases_and_nulls_are_accepted_without_rewriting(self):
        self.manifest["entities"][1].update(support_entity_id="table", parent_entity_id="table")
        self.request["entities"][1].update(support_entity_id=None, parent_entity_id="table")
        self.request["furniture"][1].update(parent_entity_id="table")
        plan = self.plan()
        self.assertIn("cup", plan["resample_entity_ids"])
        self.assertIsNone(plan["next_request"]["entities"][1]["support_entity_id"])
        self.assertEqual(plan["next_request"]["entities"][1]["parent_entity_id"], "table")

    def test_contradictory_support_aliases_within_rows_are_rejected(self):
        for collection in ("manifest", "entities", "furniture"):
            for first, second in (("supported_by_entity_id", "support_entity_id"),
                                  ("supported_by_entity_id", "parent_entity_id"),
                                  ("support_entity_id", "parent_entity_id")):
                with self.subTest(collection=collection, aliases=(first, second)):
                    manifest, request, diagnostics = inputs()
                    rows = manifest["entities"] if collection == "manifest" else request[collection]
                    rows[1].pop("supported_by_entity_id", None)
                    rows[1].update({first: "table", second: "lamp"})
                    original = copy.deepcopy((manifest, request, diagnostics))
                    with self.assertRaisesRegex(ValueError, "[Cc]ontradictory support"):
                        self.feedback.plan_repair(manifest, request, diagnostics)
                    self.assertEqual((manifest, request, diagnostics), original)

    def test_support_aliases_must_agree_across_manifest_and_request_rows(self):
        for collection in ("entities", "furniture"):
            for alias in SUPPORT_ALIASES:
                with self.subTest(collection=collection, alias=alias):
                    manifest, request, diagnostics = inputs()
                    request[collection][1].pop("supported_by_entity_id", None)
                    request[collection][1][alias] = "lamp"
                    with self.assertRaisesRegex(ValueError, "[Cc]ontradictory support"):
                        self.feedback.plan_repair(manifest, request, diagnostics)

    def test_every_support_alias_rejects_invalid_unknown_and_self_references(self):
        for alias in SUPPORT_ALIASES:
            for parent in ("", "  ", False, 0, [], {}, "absent", "tray"):
                with self.subTest(alias=alias, parent=parent):
                    manifest, request, diagnostics = inputs()
                    del manifest["entities"][1]["supported_by_entity_id"]
                    del request["entities"][1]["supported_by_entity_id"]
                    manifest["entities"][1][alias] = parent
                    with self.assertRaises(ValueError):
                        self.feedback.plan_repair(manifest, request, diagnostics)

    def test_relations_in_manifest_and_declared_dependencies_are_used(self):
        self.manifest["relations"] = [{"kind": "faces", "subject": "lamp", "object": "cup"}]
        self.manifest["entities"][6]["attributes"] = {"depends_on": ["lamp"]}
        self.assertEqual(self.plan()["resample_entity_ids"],
                         [e["entity_id"] for e in self.manifest["entities"]])

    def test_functional_cycles_terminate_without_whole_house_fallback(self):
        self.request["relations"].append({"kind": "faces", "subject": "table", "object": "chair"})
        self.assertEqual(self.plan()["preserved_entity_ids"], ["lamp", "table_10"])

    def test_slot_front_target_resolves_explicit_slot_in_same_room(self):
        del self.manifest["entities"][3]["front_target_entity_id"]
        del self.request["entities"][3]["front_target_entity_id"]
        self.request["entities"][3]["face_target_slot_id"] = "table_slot"
        self.assertIn("chair", self.plan()["resample_entity_ids"])

    def test_three_entity_relations_include_both_subject_and_object_dependents(self):
        self.request["relations"] = [{"kind": "opposite_seats", "subject": "chair",
                                      "object": "stool", "target": "lamp"}]
        self.diagnostics[0]["entity_ids"] = ["lamp"]
        self.assertEqual(self.plan()["resample_entity_ids"], ["chair", "stool", "lamp"])

    def test_compiled_structured_layout_dependencies_are_used(self):
        self.manifest["entities"][5]["_layout_parent_id"] = "cup"
        self.manifest["entities"][6]["_layout_targets"] = ["lamp"]
        self.assertEqual(self.plan()["preserved_entity_ids"], [])

    def test_direct_ids_deduplicated_in_inventory_order_not_message_tokens(self):
        self.diagnostics = [{"code": "collision", "entity_ids": ["table_10", "table_10"],
                             "message": "table tray chair lamp are mentioned incidentally"},
                            {"code": "contact", "entity_ids": ["cup"], "message": "table"}]
        plan = self.plan()
        self.assertEqual(plan["directly_conflicting_entity_ids"], ["cup", "table_10"])
        self.assertEqual(plan["resample_entity_ids"], ["cup", "table_10"])

    def test_next_request_drops_only_affected_pose_preferences(self):
        self.request["furniture"][0]["preferred_yaw_deg"] = 90.0
        expected = copy.deepcopy(self.request)
        affected = {"table", "tray", "cup", "chair", "stool"}
        for collection in ("entities", "furniture"):
            for row in expected[collection]:
                if row["entity_id"] in affected:
                    for key in POSE_PREFERENCES:
                        row.pop(key, None)
        plan = self.plan()
        actual = copy.deepcopy(plan["next_request"])
        metadata = actual.pop("repair")
        actual.pop("search_constraints")
        self.assertEqual(row_bytes(actual), row_bytes(expected))
        self.assertEqual(metadata["resample_entity_ids"], plan["resample_entity_ids"])
        self.assertEqual(metadata["requested_preserved_entity_ids"], ["lamp", "table_10"])
        self.assertFalse(metadata["preservation_enforced"])
        self.assertFalse(metadata["physical_qualified"])
        self.assertFalse(metadata["whole_task_acceptance"])
        for old, new in zip(self.request["entities"][-2:], actual["entities"][-2:]):
            self.assertEqual(row_bytes(old), row_bytes(new))

    def test_planning_and_returned_values_do_not_mutate_inputs(self):
        original = copy.deepcopy((self.manifest, self.request, self.diagnostics))
        plan = self.plan()
        self.assertEqual((self.manifest, self.request, self.diagnostics), original)
        plan["next_request"]["furniture"][0]["candidate_asset_ids"].append("other")
        plan["next_request"]["task"]["arbitrary"].append("other")
        plan["diagnostics"][0]["entity_ids"].append("lamp")
        self.assertEqual((self.manifest, self.request, self.diagnostics), original)

    def test_preservation_is_requested_and_no_acceptance_is_claimed(self):
        plan = self.plan()
        self.assertFalse(plan["preservation_enforced"])
        self.assertFalse(plan["preservation_verified"])
        self.assertIn("requested", plan["preservation_note"].lower())
        self.assertFalse(plan["physical_qualified"])
        self.assertFalse(plan["whole_task_acceptance"])
        self.assertEqual(plan["physical_execution"], "not_run")
        self.assertEqual(len(plan["source_manifest_sha256"]), 64)
        self.assertEqual(len(plan["source_request_sha256"]), 64)

    def test_empty_diagnostics_produce_no_attempt_even_at_budget(self):
        self.diagnostics = []
        plan = self.plan(attempt_index=3, max_attempts=3)
        self.assertEqual(plan["status"], "no_repair_needed")
        self.assertIsNone(plan["next_request"])
        self.assertIsNone(plan["next_attempt_index"])
        self.assertEqual(plan["resample_entity_ids"], [])
        self.assertEqual(len(plan["preserved_entity_ids"]), 7)
        self.assertFalse(plan["whole_task_acceptance"])

    def test_unlocalized_or_mixed_diagnostics_require_manual_review(self):
        for diagnostics in (
            [{"code": "solver_error", "entity_ids": [], "message": "table collision"}],
            self.diagnostics + [{"code": "solver_error", "entity_ids": [], "message": "unknown"}],
        ):
            with self.subTest(diagnostics=diagnostics):
                self.diagnostics = diagnostics
                plan = self.plan()
                self.assertEqual(plan["status"], "manual_review_required")
                self.assertEqual(plan["resample_entity_ids"], [])
                self.assertEqual(len(plan["preserved_entity_ids"]), 7)
                self.assertIsNone(plan["next_request"])

    def test_missing_ids_still_require_manual_review_at_budget(self):
        self.diagnostics[0]["entity_ids"] = []
        self.assertEqual(self.plan(attempt_index=3)["status"], "manual_review_required")

    def test_budget_counts_completed_attempts_and_never_asserts_infeasibility(self):
        self.assertEqual(self.plan(attempt_index=2, max_attempts=3)["next_attempt_index"], 3)
        for attempt in (3, 4):
            with self.subTest(attempt=attempt):
                plan = self.plan(attempt_index=attempt, max_attempts=3)
                self.assertEqual(plan["status"], "budget_exhausted")
                self.assertEqual(plan["resample_entity_ids"], [])
                self.assertIsNone(plan["next_request"])
                self.assertFalse(plan["mathematical_infeasibility_proven"])
                self.assertFalse(plan["physical_qualified"])

    def test_invalid_attempt_budget_rejected(self):
        for kwargs in ({"attempt_index": 0}, {"attempt_index": True},
                       {"attempt_index": 1.0}, {"max_attempts": 0},
                       {"max_attempts": False}, {"max_attempts": "3"}):
            with self.subTest(kwargs=kwargs), self.assertRaises(ValueError):
                self.plan(**kwargs)

    def test_invalid_diagnostics_and_unknown_explicit_ids_rejected(self):
        for diagnostics in (None, {}, ["error"], [{}],
                            [{"code": "bad", "entity_ids": []}],
                            [{"code": "", "entity_ids": [], "message": "bad"}],
                            [{"code": "bad", "entity_ids": "table", "message": "bad"}],
                            [{"code": "bad", "entity_ids": [None], "message": "bad"}],
                            [{"code": "bad", "entity_ids": ["absent"], "message": "bad"}]):
            with self.subTest(diagnostics=diagnostics), self.assertRaises(ValueError):
                self.feedback.plan_repair(self.manifest, self.request, diagnostics)

    def test_invalid_inventory_room_and_references_rejected(self):
        mutations = [
            lambda m, r: m["entities"].append(copy.deepcopy(m["entities"][0])),
            lambda m, r: r["furniture"].pop(),
            lambda m, r: r["entities"].pop(),
            lambda m, r: r["entities"].append(copy.deepcopy(r["entities"][0])),
            lambda m, r: m["entities"][0].update(entity_id=1),
            lambda m, r: m["entities"][0].update(room_id="absent"),
            lambda m, r: m["entities"][1].update(supported_by_entity_id="absent"),
            lambda m, r: r["entities"][1].update(support_entity_id="absent"),
            lambda m, r: m["entities"][1].update(front_target_entity_id="absent"),
            lambda m, r: r["relations"][0].update(subject="absent"),
            lambda m, r: r["relations"][0].pop("object"),
            lambda m, r: r["relations"][0].pop("kind"),
            lambda m, r: r.update(relations="not rows"),
            lambda m, r: r["entities"][0].update(face_target_slot_id="absent"),
            lambda m, r: m["entities"][0].update(attributes={"depends_on": ["absent"]}),
            lambda m, r: m["floor_plan"]["rooms"].append(copy.deepcopy(m["floor_plan"]["rooms"][0])),
            lambda m, r: r.update(floor_plan_sha256="wrong"),
            lambda m, r: r.update(floor_plan={"rooms": []}),
            lambda m, r: r.update(task_kind="robot_execution"),
            lambda m, r: r["entities"][0].update(room_id="absent"),
            lambda m, r: r["relations"][0].update(target="absent"),
            lambda m, r: m["entities"][0].update(front_target_entity_id="table"),
        ]
        for index, mutation in enumerate(mutations):
            with self.subTest(index=index), self.assertRaises(ValueError):
                manifest, request, diagnostics = inputs()
                mutation(manifest, request)
                self.feedback.plan_repair(manifest, request, diagnostics)

    def test_invalid_json_and_geometry_rejected(self):
        mutations = [
            lambda m, r: m["entities"][0].update(center_xy_m=[float("nan"), 2]),
            lambda m, r: m["entities"][0].update(dimensions_m=[1, -1, 1]),
            lambda m, r: m["entities"][0].update(yaw_deg=True),
            lambda m, r: r["entities"][0].update(preferred_center_xy_m=[1]),
            lambda m, r: r["entities"][0].update(installation_height_m="zero"),
            lambda m, r: r.update(opaque={1: "not a JSON object key"}),
            lambda m, r: r.update(opaque=object()),
            lambda m, r: r["furniture"][0].update(candidate_asset_ids=[]),
            lambda m, r: r["furniture"][0].update(candidate_asset_ids=["a", "a"]),
            lambda m, r: r.update(mode="unknown"),
            lambda m, r: r.update(schema="unknown"),
            lambda m, r: r.update(task_text="  "),
        ]
        for index, mutation in enumerate(mutations):
            with self.subTest(index=index), self.assertRaises(ValueError):
                manifest, request, diagnostics = inputs()
                mutation(manifest, request)
                self.feedback.plan_repair(manifest, request, diagnostics)

    def test_joint_request_without_projected_entities_and_locked_assets_supported(self):
        del self.request["entities"]
        self.request["mode"] = "locked"
        for row in self.request["furniture"]:
            row["asset_id"] = row.pop("candidate_asset_ids")[0]
        plan = self.plan()
        self.assertEqual(plan["status"], "repair_planned")
        self.assertEqual(plan["next_request"]["furniture"], self.request["furniture"])
        self.assertNotIn("entities", plan["next_request"])

    def test_successful_preservation_check_allows_only_affected_pose_changes(self):
        after = copy.deepcopy(self.manifest)
        after["entities"][0].update(center_xy_m=[3.0, 4.0], yaw_deg=180.0)
        result = self.verify(after)
        self.assertEqual(result["schema"], "rhg.frontier.preservation-verification.v1")
        self.assertTrue(result["passed"])
        self.assertTrue(result["preservation_verified"])
        self.assertEqual(result["changed_entity_ids"], ["table"])
        self.assertEqual(result["errors"], [])
        self.assertFalse(result["physical_qualified"])
        self.assertFalse(result["whole_task_acceptance"])

    def test_preservation_verifier_never_mutates_inputs_or_plan(self):
        plan = self.plan()
        after = copy.deepcopy(self.manifest)
        originals = copy.deepcopy((self.manifest, after, plan))
        self.verify(after, plan)
        self.assertEqual((self.manifest, after, plan), originals)

    def test_preserved_entity_record_compares_serialized_bytes_including_types(self):
        for key, value in (("yaw_deg", 0.0), ("opaque", {"original": "changed"}),
                           ("center_xy_m", [5, 2])):
            with self.subTest(key=key):
                after = copy.deepcopy(self.manifest)
                after["entities"][5][key] = value
                result = self.verify(after)
                self.assertFalse(result["passed"])
                self.assertIn("preserved_entity_changed", [e["code"] for e in result["errors"]])

    def test_no_silent_entity_deletion_addition_or_duplication(self):
        for change in ("delete_affected", "delete_preserved", "add", "duplicate"):
            with self.subTest(change=change):
                after = copy.deepcopy(self.manifest)
                if change == "delete_affected":
                    after["entities"].pop(0)
                elif change == "delete_preserved":
                    after["entities"].pop()
                else:
                    new = copy.deepcopy(after["entities"][0])
                    if change == "add":
                        new["entity_id"] = "new"
                    after["entities"].append(new)
                self.assertFalse(self.verify(after)["passed"])

    def test_dimensions_source_assets_and_structure_frozen_even_for_affected(self):
        for key, value in (("dimensions_m", [0.9, 1, 0.7]),
                           ("source_dimensions_m", [0.9, 1, 0.7]),
                           ("uniform_scale", 0.5), ("asset_id", "source:replacement"),
                           ("asset_sha256", "changed"),
                           ("canonical_transform", {"scale": [0.5, 0.5, 0.5]}),
                           ("support_entity_id", "lamp")):
            with self.subTest(key=key):
                after = copy.deepcopy(self.manifest)
                after["entities"][0][key] = value
                self.assertFalse(self.verify(after)["passed"])
        for key in ("dimensions_m", "asset_id"):
            with self.subTest(deleted=key):
                after = copy.deepcopy(self.manifest)
                del after["entities"][0][key]
                self.assertFalse(self.verify(after)["passed"])

    def test_floor_plan_and_top_level_source_assets_frozen(self):
        for key in ("floor_plan", "source_assets"):
            with self.subTest(key=key):
                after = copy.deepcopy(self.manifest)
                after[key] = {} if key == "floor_plan" else []
                self.assertFalse(self.verify(after)["passed"])

    def test_wrong_baseline_and_forged_plan_partition_are_rejected(self):
        plan = self.plan()
        baseline = copy.deepcopy(self.manifest)
        baseline["entities"][0]["yaw_deg"] = 30.0
        self.assertFalse(self.feedback.verify_preservation(baseline, baseline, plan)["passed"])
        for mutation in (
            lambda p: p["preserved_entity_ids"].remove("lamp"),
            lambda p: p["resample_entity_ids"].append("lamp"),
            lambda p: p["resample_entity_ids"].append("absent"),
            lambda p: p.update(schema="unknown"),
            lambda p: p.update(status="manual_review_required"),
        ):
            with self.subTest(mutation=mutation):
                changed = copy.deepcopy(plan)
                mutation(changed)
                self.assertFalse(self.verify(copy.deepcopy(self.manifest), changed)["passed"])

    def test_verification_reports_invalid_payloads_without_success(self):
        for after in (None, {}, {"entities": ["bad"], "floor_plan": {}},
                      {"entities": [], "floor_plan": {}}):
            with self.subTest(after=after):
                result = self.verify(after)
                self.assertFalse(result["passed"])
                self.assertTrue(result["errors"])
                self.assertFalse(result["physical_qualified"])
                self.assertFalse(result["whole_task_acceptance"])

    def test_verifier_malformed_plan_types_produce_structured_failure(self):
        for value in ([], {}, None, 1, False):
            with self.subTest(value=value):
                plan = self.plan()
                plan["status"] = value
                result = self.feedback.verify_preservation(self.manifest, self.manifest, plan)
                self.assertFalse(result["passed"])
                self.assertTrue(result["errors"])

    def test_no_deletion_of_affected_pose_fields(self):
        after = copy.deepcopy(self.manifest)
        del after["entities"][0]["center_xy_m"]
        result = self.verify(after)
        self.assertFalse(result["passed"])
        self.assertIn("pose_field_deleted", [e["code"] for e in result["errors"]])

    def test_record_key_order_is_preserved_but_inventory_list_order_can_change(self):
        after = copy.deepcopy(self.manifest)
        after["entities"].reverse()
        self.assertTrue(self.verify(after)["passed"])
        after = copy.deepcopy(self.manifest)
        after["entities"][5] = dict(reversed(list(after["entities"][5].items())))
        self.assertFalse(self.verify(after)["passed"])


class NativePreservationTests(unittest.TestCase):
    def setUp(self):
        self.feedback = importlib.import_module('engine.feedback')
        rows = []
        for eid, x in (('plant', 2.), ('fixed', 4.)):
            access = [x-.2, 2.2, x+.2, 2.8]
            evidence = dict(pool_candidate_key='record-' + eid, release_sha256='d'*64)
            rows.append(dict(entity_id=eid, room_id='living', role='plant', asset_id='native-' + eid,
                asset_sha256='a'*64, runtime_sha256='b'*64, canonical_path='/sealed/' + eid + '.glb',
                dimensions_m=[.4,.4,.7], source_dimensions_m=[.4,.4,.7], uniform_scale=1.,
                center_xy_m=[x,2.], yaw_deg=0., base_z_m=0., contract_yaw_deg=0.,
                canonical_front_axis='+Y', world_front_vector_xy=[math.cos(math.pi/2), 1.],
                wall_anchor='W', placement_side='W', style_attribute_consumption=evidence,
                operation_space_xy_m=list(access), front_clearance_box_xy_m=list(access),
                wall_fit_correction_xy_m=[0.,0.], wall_fit_remaining_gap_m=0.,
                selected_support_surface=None, measured_wall_mount=None,
                real_dimension_layout=dict(schema='rhg.joint_native_pose.v1', center_xy_m=[x,2.],
                    yaw_deg=0., contract_yaw_deg=0., dimensions_m=[.4,.4,.7], uniform_scale=1.,
                    wall_anchor='W', access_box_xy_m=list(access), companion_placements=[],
                    delta_xy_m=[0.,0.], dimensions_authority='measured_source', attribute_consumption=evidence)))
        self.manifest = dict(scene_id='house', entities=rows,
            floor_plan=dict(rooms=[dict(room_id='living', bounds_m=[0.,0.,8.,8.])]),
            task_kind='scene_generation', task_text='Retain the house.',
            joint_request=dict(sha256='1'*64, task_text='Retain the house.', mode='locked', relations=[],
                effective_policies=dict(search=dict(grid_step_m=.4), support_region_policy='mesh_union')),
            fixed_layout_real_asset_binding=dict(source_scene='/round_01/layout/house',
                uniform_scale_only=True, preserve_source_materials=True, binding_phase='final',
                final_binding_passed=True, selection_policy='content_diverse_v1'),
            joint_layout_constraint_evidence=dict(shell_input_path='/round_01/windows.json',
                shell_input_sha256='c'*64, door_swing_keepouts=[], wall_mesh_bounds=[0,0,8,8],
                floor_body_geometry_index=dict(path='/sealed/floor.json', sha256='e'*64)))
        self.request = dict(schema='rhg.scene_request.v1', mode='locked', task_text='Retain the house.',
            furniture=[dict(entity_id=row['entity_id'], asset_id=row['asset_id']) for row in rows])
        self.diagnostics = [dict(code='access_blocked', entity_ids=['plant'], message='Measured obstruction.')]

    def plan(self):
        return self.feedback.plan_repair(self.manifest, self.request, self.diagnostics)

    def moved(self):
        after = copy.deepcopy(self.manifest)
        row = after['entities'][0]
        row['center_xy_m'][0] += .4
        row['real_dimension_layout']['center_xy_m'][0] += .4
        row['real_dimension_layout']['delta_xy_m'] = [.4,0.]
        row['wall_fit_correction_xy_m'] = [.4,0.]
        for box in (row['operation_space_xy_m'], row['front_clearance_box_xy_m'],
                    row['real_dimension_layout']['access_box_xy_m']):
            box[0] += .4
            box[2] += .4
        return after

    def rotated(self):
        writer = importlib.import_module('engine.source.scripts.'
            'internal.scene_generation.real_assets.real_dimension_layout')
        after = copy.deepcopy(self.manifest)
        row = after['entities'][0]
        pose = copy.deepcopy(row['real_dimension_layout'])
        pose.update(center_xy_m=[2.4,2.], yaw_deg=90., contract_yaw_deg=90.,
                    delta_xy_m=[.4,0.], access_box_xy_m=[1.6,1.8,2.2,2.2])
        writer.apply_placement(row, pose)
        row['operation_space_xy_m'] = list(pose['access_box_xy_m'])
        return after

    def test_native_plan_selects_explicit_profile_and_allows_only_execution_provenance(self):
        plan = self.plan()
        self.assertEqual(plan.get('preservation_profile'), 'native_joint_binding_v1')
        after = copy.deepcopy(self.manifest)
        after['joint_request']['sha256'] = '2'*64
        after['fixed_layout_real_asset_binding']['source_scene'] = '/round_02/layout/house'
        after['joint_layout_constraint_evidence']['shell_input_path'] = '/round_02/windows.json'
        self.assertTrue(self.feedback.verify_preservation(self.manifest, after, plan)['passed'])

    def test_missing_profile_keeps_strict_default(self):
        plan = self.plan()
        plan.pop('preservation_profile', None)
        after = copy.deepcopy(self.manifest)
        after['joint_request']['sha256'] = '2'*64
        self.assertFalse(self.feedback.verify_preservation(self.manifest, after, plan)['passed'])

    def test_partial_native_marker_does_not_enable_profile(self):
        self.manifest['fixed_layout_real_asset_binding']['final_binding_passed'] = False
        self.assertEqual(self.plan().get('preservation_profile', 'strict'), 'strict')

    def test_native_pose_and_derived_placement_must_move_together(self):
        result = self.feedback.verify_preservation(self.manifest, self.moved(), self.plan())
        self.assertTrue(result['passed'], result)

    def test_pose_change_cannot_reuse_populated_blender_world_readback(self):
        readback = dict(world_bbox_m=[[1.8,1.8,0.],[2.2,2.2,.7]],
            visual_footprint_polygon_xy_m=[[1.8,1.8],[2.2,1.8],[2.2,2.2],[1.8,2.2]],
            actual_center_xy_m=[2.,2.], applied_world_front_vector_xy=[0.,1.])
        for field in [None, *readback]:
            with self.subTest(field=field):
                fields = readback if field is None else {field: readback[field]}
                self.manifest['entities'][0].update(copy.deepcopy(fields))
                after = self.rotated() if field == 'applied_world_front_vector_xy' else self.moved()
                result = self.feedback.verify_preservation(self.manifest, after, self.plan())
                self.assertFalse(result['passed'], result)
                self.assertIn('invalid_native_pose_evidence', [e['code'] for e in result['errors']])
                for key in fields:
                    self.manifest['entities'][0].pop(key)

    def test_blender_readback_allows_verified_xyz_translation(self):
        self.manifest['entities'][0].update(world_bbox_m=[[1.8,1.8,0.],[2.2,2.2,.7]],
            visual_footprint_polygon_xy_m=[[1.8,1.8],[2.2,1.8],[2.2,2.2],[1.8,2.2]],
            actual_center_xy_m=[2.,2.], applied_world_front_vector_xy=[0.,1.])
        after = self.moved()
        after['entities'][0].update(base_z_m=.3,
            world_bbox_m=[[2.2,1.8,.3],[2.6,2.2,1.]],
            visual_footprint_polygon_xy_m=[[2.2,1.8],[2.6,1.8],[2.6,2.2],[2.2,2.2]],
            actual_center_xy_m=[2.4,2.])
        plan = self.plan()
        original = copy.deepcopy((self.manifest, after, plan))
        result = self.feedback.verify_preservation(self.manifest, after, plan)
        self.assertTrue(result['passed'], result)
        self.assertEqual((self.manifest, after, plan), original)
        for field in ('world_bbox_m', 'visual_footprint_polygon_xy_m', 'actual_center_xy_m'):
            for value in (self.manifest['entities'][0][field], None, []):
                with self.subTest(field=field, value=value):
                    stale = copy.deepcopy(after)
                    stale['entities'][0][field] = copy.deepcopy(value)
                    self.assertFalse(self.feedback.verify_preservation(self.manifest, stale, plan)['passed'])
        for field, value in (('asset_sha256', 'f'*64), ('dimensions_m', [.5,.4,.7]),
                             ('selected_support_surface', dict(surface_z_world_m=.7))):
            with self.subTest(field=field):
                changed = copy.deepcopy(after)
                changed['entities'][0][field] = value
                self.assertFalse(self.feedback.verify_preservation(self.manifest, changed, plan)['passed'])

    def test_blender_xy_readback_allows_verified_rotation_without_bbox(self):
        self.manifest['entities'][0].update(
            visual_footprint_polygon_xy_m=[[1.8,1.8],[2.2,1.8],[2.2,2.2],[1.8,2.2]],
            actual_center_xy_m=[2.05,2.], applied_world_front_vector_xy=[0.,1.])
        after = self.rotated()
        after['entities'][0].update(
            visual_footprint_polygon_xy_m=[[2.6,1.8],[2.6,2.2],[2.2,2.2],[2.2,1.8]],
            actual_center_xy_m=[2.4,2.05], applied_world_front_vector_xy=[-1.,0.])
        plan = self.plan()
        result = self.feedback.verify_preservation(self.manifest, after, plan)
        self.assertTrue(result['passed'], result)
        for field in ('visual_footprint_polygon_xy_m', 'actual_center_xy_m',
                      'applied_world_front_vector_xy'):
            with self.subTest(field=field):
                stale = copy.deepcopy(after)
                stale['entities'][0][field] = copy.deepcopy(self.manifest['entities'][0][field])
                self.assertFalse(self.feedback.verify_preservation(self.manifest, stale, plan)['passed'])
        self.manifest['entities'][0]['world_bbox_m'] = [[1.8,1.8,0.],[2.2,2.2,.7]]
        after['entities'][0]['world_bbox_m'] = [[2.2,1.8,0.],[2.6,2.2,.7]]
        self.assertFalse(self.feedback.verify_preservation(self.manifest, after, self.plan())['passed'])

    def test_unchanged_pose_hash_replay_preserves_populated_blender_readback(self):
        self.manifest['entities'][0].update(world_bbox_m=[[1.8,1.8,0.],[2.2,2.2,.7]],
            visual_footprint_polygon_xy_m=[[1.8,1.8],[2.2,1.8],[2.2,2.2],[1.8,2.2]],
            actual_center_xy_m=[2.,2.], applied_world_front_vector_xy=[0.,1.])
        after = copy.deepcopy(self.manifest)
        after['joint_request']['sha256'] = '2'*64
        result = self.feedback.verify_preservation(self.manifest, after, self.plan())
        self.assertTrue(result['passed'], result)

    def test_source_local_footprint_stays_frozen_during_native_pose_change(self):
        self.manifest['entities'][0]['source_visual_footprint_polygon_xy_m'] = [
            [-.2,-.2],[.2,-.2],[.2,.2],[-.2,.2]]
        after = self.moved()
        self.assertTrue(self.feedback.verify_preservation(self.manifest, after, self.plan())['passed'])
        after['entities'][0]['source_visual_footprint_polygon_xy_m'][0][0] = -.3
        self.assertFalse(self.feedback.verify_preservation(self.manifest, after, self.plan())['passed'])

    def test_actual_native_placement_writer_can_translate_and_rotate(self):
        result = self.feedback.verify_preservation(self.manifest, self.rotated(), self.plan())
        self.assertTrue(result['passed'], result)

    def test_native_contact_evidence_is_not_silently_carried_to_a_new_pose(self):
        for field in ('selected_support_surface', 'derived_support_relation', 'floor_cover_contact_evidence'):
            with self.subTest(field=field):
                self.manifest['entities'][0][field] = dict(evidence_sha256='f'*64)
                result = self.feedback.verify_preservation(self.manifest, self.moved(), self.plan())
                self.assertFalse(result['passed'], result)
                self.assertIn('invalid_native_pose_evidence', [e['code'] for e in result['errors']])
                self.manifest['entities'][0].pop(field)

    def test_native_verification_is_read_only_and_tolerates_binder_key_order(self):
        after = self.moved()
        after['entities'][1] = dict(reversed(list(after['entities'][1].items())))
        plan = self.plan()
        original = copy.deepcopy((self.manifest, after, plan))
        self.assertTrue(self.feedback.verify_preservation(self.manifest, after, plan)['passed'])
        self.assertEqual((self.manifest, after, plan), original)

    def test_stale_or_inconsistent_derived_geometry_is_rejected(self):
        for field in ('real_dimension_layout', 'operation_space_xy_m', 'front_clearance_box_xy_m',
                      'wall_fit_correction_xy_m'):
            with self.subTest(field=field):
                after = self.moved()
                after['entities'][0][field] = copy.deepcopy(self.manifest['entities'][0][field])
                result = self.feedback.verify_preservation(self.manifest, after, self.plan())
                self.assertFalse(result['passed'])
        after = copy.deepcopy(self.manifest)
        after['entities'][0]['yaw_deg'] = 90.
        self.assertFalse(self.feedback.verify_preservation(self.manifest, after, self.plan())['passed'])

    def test_native_profile_keeps_unknown_metadata_requirements_and_source_identity_frozen(self):
        mutations = [
            lambda m: m['joint_request'].update(task_text='Different task'),
            lambda m: m['joint_request'].update(relations=[dict(kind='near', subject='plant', object='fixed')]),
            lambda m: m['joint_request']['effective_policies']['search'].update(grid_step_m=.8),
            lambda m: m['joint_request'].update(sha256='malformed'),
            lambda m: m['fixed_layout_real_asset_binding'].update(final_binding_passed=False),
            lambda m: m['joint_layout_constraint_evidence'].update(shell_input_sha256='f'*64),
            lambda m: m['joint_layout_constraint_evidence'].update(door_swing_keepouts=[{}]),
            lambda m: m.update(unrecognized_metadata='new'),
            lambda m: m['entities'][0].update(asset_sha256='f'*64),
            lambda m: m['entities'][0].update(dimensions_m=[.2,.2,.7]),
            lambda m: m['entities'][0]['real_dimension_layout'].update(unrecognized='new'),
            lambda m: m['entities'][1]['real_dimension_layout'].update(delta_xy_m=[1.,0.]),
        ]
        for index, mutate in enumerate(mutations):
            with self.subTest(index=index):
                after = self.moved()
                mutate(after)
                self.assertFalse(self.feedback.verify_preservation(self.manifest, after, self.plan())['passed'])

    def test_native_profile_must_be_recognized_and_match_final_binding(self):
        plan = self.plan()
        plan['preservation_profile'] = 'ignore_metadata'
        self.assertFalse(self.feedback.verify_preservation(self.manifest, self.manifest, plan)['passed'])
        plan['preservation_profile'] = 'native_joint_binding_v1'
        self.manifest['fixed_layout_real_asset_binding']['final_binding_passed'] = False
        self.assertFalse(self.feedback.verify_preservation(self.manifest, self.manifest, plan)['passed'])

    def test_pose_change_cannot_reuse_unhandled_world_contact_evidence(self):
        self.manifest['entities'][0]['measured_wall_mount'] = dict(surface_center_world_m=[2.,2.,.7])
        self.assertFalse(self.feedback.verify_preservation(self.manifest, self.moved(), self.plan())['passed'])


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