File size: 28,709 Bytes
719b488
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Independent acceptance gate for the 3D-FRONT export.

This script never imports convert_3dfront or unify_3dfront and never reuses
their record builders. Everything it checks is either recounted from the two
published JSON files or recomputed from the raw house JSON with a second,
deliberately different implementation for the two that carry real algorithms
(gift-wrapping instead of monotone chain for the hull, a hand-written scanner
instead of the regex for the room type), so that a shared bug cannot hide behind
itself. furniture_size and furniture_position are transcriptions, not
independent derivations: they gate the wiring, not the axis order. There is no
independent area
computation any more, because room_area_m2 is no longer computed from geometry:
it is the raw scene.room[].size scalar, and it is gated against that scalar in
both directions.

Any failed gate exits non-zero.

Usage:
    python kits/verify_3dfront.py --data-dir data \
        --room json_room.json --merged multiroom/json_multi_merged.json
"""

from __future__ import annotations

import argparse
import json
import math
import random
import sys
from collections import Counter
from pathlib import Path

# --------------------------------------------------------------------------
# Acceptance baselines (measured on the raw houses, see README.md)
# --------------------------------------------------------------------------

BASELINES = {
    "room_scenes": 56129,
    "merged_scenes": 6813,
    "merged_room_total": 56129,
    "placements_room_view": 533837,
    "placements_merged_view": 533837,
    # Direct counts of the raw scene.room[].size values, no geometry involved:
    # 33,116 rooms state a positive area. Everything else is null -- 4,695 rooms
    # state 0 and 18,318 carry no size key at all. 33,116 + 23,013 = 56,129.
    "area_from_source": 33116,
    "area_null": 23013,
    "boundary_convex_hull": 50903,
    "boundary_null": 5226,
    "room_height_non_null": 49799,
    "room_height_null": 6330,
    # room_type is the raw scene.room[].type string normalised through IL3D's
    # table plus IL3D's own split rule. Every one of the 56,129 rooms states a
    # type, so nothing is null. Pinned from the 2026-09-03 full run; check_samples
    # additionally re-derives room_type from raw with an independent scanner.
    "room_type_non_null": 56129,
    "room_type_null": 0,
    # furniture_category is furniture[].category and nothing else; model_info.json
    # belongs to 3D-FUTURE and disagrees with it on 39% of the placements where
    # both exist. furniture_size is furniture[].size or the flat furniture[].bbox
    # -- one quantity under two keys, identical to the last digit over the 2,387
    # definitions carrying both -- times children[].scale. Both counts changed with those decisions
    # and are pinned from the first full run under them.
    # 236,352 of the 533,837 placements (44.3%) reference a furniture uid the
    # house does not define, so they carry no category and no extent at all.
    "category_non_null": 46124,
    "category_null": 487713,
    "size_non_null": 182794,
    "size_null": 351043,
    "position_non_null": 533432,
    "position_null": 405,
    "rotation_no_tilt": 527710,
    # 6,127 records have null x/y: 5,695 retain yaw and 432 also have null z.
    # This bucket combines tilted placements and unusable source quaternions;
    # the converter counts those two cases separately.
    "rotation_tilt": 6127,
    "rotation_tilt_yaw_null": 432,
    # Opening totals interact with the "fewer than four footprint points" filter
    # (audit: Door 678, Window 579, BayWindow 1911 such meshes, dropped before
    # grouping). If the observed
    # numbers differ, the filter interaction must be resolved before release --
    # do not quietly relax the gate.
    "doors_total": 28731,
    # 47,671 = 23,638 Window + 24,033 BayWindow. Six fewer than the briefing's
    # 47,677 because a group whose 2D hull collapses to under four points cannot
    # produce a profile polygon and is now rejected instead of published:
    # opening_Window_group_hull_under_four 1 + opening_BayWindow_... 5 = 6. Exact,
    # so the delta is resolved rather than relaxed.
    "windows_total": 47671,
}

# The four bulk geometry arrays, and nothing else. "material" and "materialList"
# used to be in this set by mistake: on a mesh, material is a uid string, not
# geometry. No mesh record is published at all now -- only the type strings, in
# source_fields.mesh_types -- so this gate is what proves no geometry leaked in.
FORBIDDEN_KEYS = {"xyz", "faces", "normal", "uv"}

# Exact key order, checked with == so an added or dropped field fails the gate.
# These are the root README schema blocks verbatim, plus source_fields for the
# source fields the schema has no slot for. source_fields holds exactly ten keys,
# each one a source field that says something about the layout and that no schema
# field consumed -- three on the room, seven on a placement. Both lists are
# asserted below, per room and per placement, not merely described here.
CORE_ROOM_KEYS = [
    "room_id", "room_index", "room_type", "room_type_source", "room_boundary",
    "room_boundary_type", "room_area_m2", "room_height", "coordinate_system",
    "doors", "windows", "furniture_quantity", "furniture", "source_fields",
]
CORE_FURNITURE_KEYS = [
    "furniture_category", "furniture_instance_id", "furniture_position",
    "furniture_rotation", "furniture_size", "source_fields",
]
# The twelve root README scene keys, in the README's own order.
CORE_SCENE_KEYS = [
    "scene_id", "sample_id", "dataset", "source_dataset", "source_subset",
    "room_count", "total_area", "building_style", "description",
    "description_source", "provenance", "rooms",
]
ROOM_SOURCE_FIELD_KEYS = ["extension_door", "mesh_types", "scene_boundingBox"]
FURNITURE_SOURCE_FIELD_KEYS = [
    "jid", "title", "bbox", "sourceCategoryId", "valid", "replace_bbox",
    "parentJid",
]

# IL3D's table restated, not imported: this script never imports the converter.
ROOM_TYPE_TABLE = {
    "Aisle": "aisle", "Balcony": "balcony", "BathRoom": "bathroom",
    "BedRoom": "bedroom", "CloakRoom": "cloakroom",
    "DiningRoom": "dining room", "ElderlyRoom": "elderly room",
    "Garage": "garage", "KidsRoom": "kids room", "Kitchen": "kitchen",
    "LaundryRoom": "laundry room", "Library": "library",
    "LivingDiningRoom": "living dining room", "LivingRoom": "living room",
    "OfficeRoom": "office", "OtherRoom": "other room",
    "RecreationRoom": "recreation room", "StorageRoom": "storage room",
}


# --------------------------------------------------------------------------
# Independent geometry (different algorithms on purpose)
# --------------------------------------------------------------------------


def hull_gift_wrapping(points):
    """Jarvis march. Independent of the monotone chain used by the converter."""
    pts = sorted(set(points))
    if len(pts) < 3:
        return pts
    start = pts[0]
    hull, current = [], start
    while True:
        hull.append(current)
        candidate = pts[0] if pts[0] != current else pts[1]
        for p in pts:
            if p == current:
                continue
            cross = ((candidate[0] - current[0]) * (p[1] - current[1])
                     - (candidate[1] - current[1]) * (p[0] - current[0]))
            # Collinearity needs the same tolerance the converter uses (1e-12).
            # A floor edge sampled at even spacing -- e.g. Bathroom-54893 of house
            # 0003d406, whose bottom edge carries a vertex at x=1.1575 exactly
            # between x=0.7575 and x=1.5575 -- is collinear in exact arithmetic but
            # evaluates to a cross of ~1e-19 in floating point. Testing cross == 0
            # made this march keep that mid-edge vertex while the monotone chain
            # dropped it, and the two hulls then disagreed on a room that is not
            # actually ambiguous. The algorithms stay different; only the
            # degeneracy threshold is shared.
            if cross < -1e-12:
                candidate = p
            elif abs(cross) <= 1e-12:
                far = ((p[0] - current[0]) ** 2 + (p[1] - current[1]) ** 2)
                near = ((candidate[0] - current[0]) ** 2 + (candidate[1] - current[1]) ** 2)
                if far > near:
                    candidate = p
        current = candidate
        if current == start:
            return hull
        if len(hull) > len(pts):
            raise RuntimeError("gift wrapping did not terminate")


def room_type_scan(raw):
    r"""The converter's normalisation, scanned by hand instead of by regex.

    convert_3dfront.py splits with re.findall(r"[A-Z][a-z]*|[a-z]+|\d+"); this
    walks the string. Same partition, different code.
    """
    if not isinstance(raw, str) or not raw.strip():
        return None
    if raw in ROOM_TYPE_TABLE:
        return ROOM_TYPE_TABLE[raw]
    words, current, kind = [], "", None
    for ch in raw:
        if "A" <= ch <= "Z":
            starts, k = True, "alpha"
        elif "a" <= ch <= "z":
            starts, k = kind != "alpha", "alpha"
        elif "0" <= ch <= "9":
            starts, k = kind != "digit", "digit"
        else:
            starts, k = True, None
        if starts and current:
            words.append(current)
            current = ""
        current = current + ch if k else ""
        kind = k
    if current:
        words.append(current)
    return " ".join(words).lower() if words else raw.lower()


def vec3(value):
    return (isinstance(value, list) and len(value) == 3
            and all(isinstance(v, (int, float)) and math.isfinite(float(v))
                    for v in value))


def size_from_raw(child, defn):
    """furniture_size re-derived from raw: asset extent x placement scale."""
    defn = defn or {}
    base = None
    for key in ("size", "bbox"):
        if vec3(defn.get(key)):
            base = [float(v) for v in defn[key]]
            break
    if base is None or not vec3(child.get("scale")):
        return None
    scale = [abs(float(v)) for v in child["scale"]]
    width, height, length = base[0] * scale[0], base[1] * scale[1], base[2] * scale[2]
    if any((not math.isfinite(v)) or v <= 0.0 for v in (width, height, length)):
        return None
    out = {"width": round(width, 6), "length": round(length, 6),
           "height": round(height, 6)}
    return None if any(v <= 0.0 for v in out.values()) else out


def same_ring(a, b, tol=1e-6):
    """Compare two rings ignoring start offset and winding direction."""
    if len(a) != len(b):
        return False
    n = len(a)
    for direction in (b, list(reversed(b))):
        for shift in range(n):
            rotated = direction[shift:] + direction[:shift]
            if all(abs(p[0] - q[0]) <= tol and abs(p[1] - q[1]) <= tol
                   for p, q in zip(a, rotated)):
                return True
    return False


# --------------------------------------------------------------------------
# Streaming readers
# --------------------------------------------------------------------------


def iter_json_array(path):
    """Yield the top-level objects of a large JSON array without loading it."""
    decoder = json.JSONDecoder()
    buffer = ""
    started = False
    with open(path, encoding="utf-8") as handle:
        for line in handle:
            stripped = line.strip()
            if not started:
                if stripped.startswith("["):
                    started = True
                    stripped = stripped[1:].strip()
                    if not stripped:
                        continue
                else:
                    continue
            if stripped in ("]", ""):
                continue
            buffer += stripped
            while buffer:
                buffer = buffer.lstrip(", \t")
                if not buffer or buffer[0] == "]":
                    buffer = ""
                    break
                try:
                    obj, end = decoder.raw_decode(buffer)
                except ValueError:
                    break
                yield obj
                buffer = buffer[end:]
    if buffer.strip(" ,]\n"):
        raise ValueError(f"{path}: trailing content could not be parsed")


def scan_forbidden(node, path, findings):
    """Publication allowlist: no raw mesh arrays, no local absolute paths.

    Every node of every merged scene, no sampling. The room view is not scanned
    separately: its room objects are asserted equal to the merged ones.
    """
    if isinstance(node, dict):
        for key, value in node.items():
            if key in FORBIDDEN_KEYS:
                findings.append(f"{path}.{key}: forbidden raw-geometry key")
            scan_forbidden(value, f"{path}.{key}", findings)
    elif isinstance(node, list):
        for index, value in enumerate(node):
            scan_forbidden(value, f"{path}[{index}]", findings)
    elif isinstance(node, str):
        if node.startswith("/Users/") or node.startswith("/home/"):
            findings.append(f"{path}: local absolute path leaked")


# --------------------------------------------------------------------------
# Gate 1 + 2 + 5: recount the published files, check invariants, cross-view
# --------------------------------------------------------------------------


def walk_views(room_path, merged_path, sample_size, rng):
    """Single parallel pass over both views.

    The room view is ordered house-by-house and room-by-room, the merged view
    house-by-house, so the two can be zipped without holding either in memory.
    """
    stats = Counter()
    failures = []
    scene_ids_room, scene_ids_merged = set(), set()
    furniture_ids = set()
    reservoir = []
    seen_rooms = 0
    forbidden = []

    room_iter = iter_json_array(room_path)
    for merged in iter_json_array(merged_path):
        stats["merged_scenes"] += 1
        scene_ids_merged.add(merged["scene_id"])
        if merged["room_count"] != len(merged["rooms"]):
            failures.append(f"{merged['scene_id']}: room_count != len(rooms)")
        scan_forbidden(merged, merged["scene_id"], forbidden)

        known_areas = [r["room_area_m2"] for r in merged["rooms"]
                       if r["room_area_m2"] is not None]
        expected_total = round(sum(known_areas), 6) if known_areas else None
        if merged["total_area"] != expected_total:
            failures.append(f"{merged['scene_id']}: total_area != sum(room_area_m2)")

        room_ids = [r["room_id"] for r in merged["rooms"]]
        if len(set(room_ids)) != len(room_ids):
            failures.append(f"{merged['scene_id']}: duplicate room_id inside scene")

        for index, room in enumerate(merged["rooms"]):
            stats["merged_room_total"] += 1
            try:
                single = next(room_iter)
            except StopIteration:
                failures.append("room view ended before the merged view")
                return stats, failures, reservoir, forbidden

            stats["room_scenes"] += 1
            scene_ids_room.add(single["scene_id"])

            # --- cross-view identity (this is what B1 protects) --------------
            if single["room_count"] != 1 or len(single["rooms"]) != 1:
                failures.append(f"{single['scene_id']}: room view must hold exactly one room")
                single_room = None
            else:
                single_room = single["rooms"][0]
                if single_room != room:
                    failures.append(f"{single['scene_id']}: room object differs between views")
            if list(single.keys()) != CORE_SCENE_KEYS:
                failures.append(f"{single['scene_id']}: scene key order/set differs from contract")
            expected_id = f"{merged['scene_id']}::{room['room_id']}"
            if single["scene_id"] != expected_id:
                failures.append(f"{single['scene_id']}: scene_id != {expected_id}")

            # --- field presence and order -----------------------------------
            if list(room.keys()) != CORE_ROOM_KEYS:
                failures.append(f"{single['scene_id']}: room key order/set differs from contract")
            if list(room["source_fields"].keys()) != ROOM_SOURCE_FIELD_KEYS:
                failures.append(f"{single['scene_id']}: room source_fields key order/set differs")

            # interiorgs_agg.py:182 gives sill_height to windows only.
            if any(d["sill_height"] is not None for d in room["doors"]):
                failures.append(f"{single['scene_id']}: door carries a sill_height")

            # --- recount ----------------------------------------------------
            btype = room["room_boundary_type"]
            stats["boundary_convex_hull" if btype == "floor_mesh_convex_hull"
                  else "boundary_null" if btype is None else f"boundary_other:{btype}"] += 1
            stats["room_height_non_null" if room["room_height"] is not None
                  else "room_height_null"] += 1
            stats["area_null" if room["room_area_m2"] is None
                  else "area_from_source"] += 1
            stats["room_type_non_null" if room["room_type"] is not None
                  else "room_type_null"] += 1
            stats["doors_total"] += len(room["doors"])
            stats["windows_total"] += len(room["windows"])
            if room["furniture_quantity"] != len(room["furniture"]):
                failures.append(f"{single['scene_id']}: furniture_quantity != len(furniture)")

            # Counted from each file separately, but what actually gates the two
            # views against each other is the deep equality above; these two can
            # only diverge on a run that already failed there.
            stats["placements_merged_view"] += len(room["furniture"])
            if single_room is not None:
                stats["placements_room_view"] += len(single_room["furniture"])

            for item in room["furniture"]:
                if list(item.keys()) != CORE_FURNITURE_KEYS:
                    failures.append(f"{single['scene_id']}: furniture key order differs")
                if list(item["source_fields"].keys()) != FURNITURE_SOURCE_FIELD_KEYS:
                    failures.append(
                        f"{single['scene_id']}: furniture source_fields key order/set differs")
                furniture_ids.add(item["furniture_instance_id"])
                stats["category_non_null" if item["furniture_category"] is not None
                      else "category_null"] += 1
                stats["size_non_null" if item["furniture_size"] is not None
                      else "size_null"] += 1
                stats["position_non_null" if item["furniture_position"] is not None
                      else "position_null"] += 1
                rot = item["furniture_rotation"]
                if rot["x"] is None and rot["y"] is None:
                    stats["rotation_tilt"] += 1
                    if rot["z"] is None:
                        stats["rotation_tilt_yaw_null"] += 1
                else:
                    stats["rotation_no_tilt"] += 1

            seen_rooms += 1
            if len(reservoir) < sample_size:
                reservoir.append(single)
            else:
                j = rng.randrange(seen_rooms)
                if j < sample_size:
                    reservoir[j] = single

    if next(room_iter, None) is not None:
        failures.append("room view has more records than the merged view")
    if len(scene_ids_room) != stats["room_scenes"]:
        failures.append("duplicate scene_id in json_room.json")
    if len(scene_ids_merged) != stats["merged_scenes"]:
        failures.append("duplicate scene_id in the merged view")
    if len(furniture_ids) != stats["placements_merged_view"]:
        failures.append("duplicate furniture_instance_id across the dataset")
    return stats, failures, reservoir, forbidden


# --------------------------------------------------------------------------
# Gate 3 + 4: recompute sampled rooms from the raw house JSON
# --------------------------------------------------------------------------


def recompute_room(house_path, source_room_id):
    """Rebuild from raw everything the sampled gate compares against.

    Boundary, room_type, and per-placement position / category / size. Nothing
    here reads the published files, and nothing imports the converter.
    """
    with open(house_path, encoding="utf-8") as handle:
        data = json.load(handle)
    mesh_by_uid = {m["uid"]: m for m in data.get("mesh", []) if m.get("uid") is not None}
    # First definition wins, the way the converter indexes them.
    furniture_by_uid = {}
    for defn in data.get("furniture", []):
        uid = defn.get("uid")
        if uid is not None and uid not in furniture_by_uid:
            furniture_by_uid[uid] = defn

    room = next((r for r in (data.get("scene") or {}).get("room", []) or []
                 if r.get("instanceid") == source_room_id), None)
    if room is None:
        return None

    floor_xy = []
    positions, categories, sizes = {}, {}, {}
    for child in room.get("children", []):
        instanceid = child.get("instanceid") or ""
        if instanceid.startswith("furniture/"):
            defn = furniture_by_uid.get(child.get("ref"))
            pos = child.get("pos")
            if vec3(pos):
                positions[instanceid] = {
                    "x": round(float(pos[0]), 6),
                    "y": round(-float(pos[2]), 6),
                    "z": round(float(pos[1]), 6),
                }
            else:
                positions[instanceid] = None
            categories[instanceid] = (defn or {}).get("category") or None
            sizes[instanceid] = size_from_raw(child, defn)
            continue
        mesh = mesh_by_uid.get(child.get("ref"))
        if mesh is not None and mesh.get("type") == "Floor":
            xyz = mesh.get("xyz") or []
            floor_xy.extend((float(xyz[i]), -float(xyz[i + 2]))
                            for i in range(0, len(xyz) - 2, 3))

    hull = hull_gift_wrapping(floor_xy) if floor_xy else []
    boundary = ([[round(p[0], 6), round(p[1], 6)] for p in hull]
                if len(hull) >= 3 else None)
    return {"boundary": boundary, "positions": positions,
            "categories": categories, "sizes": sizes,
            "source_area": room.get("size"),
            "room_type": room_type_scan(room.get("type"))}


def check_samples(house_dir, samples, failures, stats):
    for scene in samples:
        room = scene["rooms"][0]
        # str.removeprefix is 3.9+; the project env is 3.8, so slice it.
        house_uid = scene["scene_id"].split("::")[0]
        if house_uid.startswith("3dfront_"):
            house_uid = house_uid[len("3dfront_"):]
        recomputed = recompute_room(house_dir / f"{house_uid}.json",
                                    scene["provenance"]["source_room_id"])
        stats["sampled_rooms"] += 1
        if recomputed is None:
            failures.append(f"{scene['scene_id']}: source room not found in raw house")
            continue

        if (recomputed["boundary"] is None) != (room["room_boundary"] is None):
            failures.append(f"{scene['scene_id']}: boundary presence differs from raw")
        elif recomputed["boundary"] is not None:
            if not same_ring(room["room_boundary"], recomputed["boundary"]):
                failures.append(f"{scene['scene_id']}: recomputed hull differs")

        # room_type carries no pinned baseline yet, so this is what gates it: the
        # published string must equal the one an independent scanner derives from
        # raw scene.room[].type.
        if room["room_type"] != recomputed["room_type"]:
            failures.append(
                f"{scene['scene_id']}: room_type {room['room_type']!r} "
                f"!= {recomputed['room_type']!r} re-derived from raw")

        # room_area_m2 is the raw scene.room[].size scalar or nothing. Both
        # directions are gated: a published value must equal the raw one, and a
        # null must be backed by a raw value that is absent or non-positive -- so
        # this can never quietly swallow a room that did state an area.
        raw = recomputed["source_area"]
        raw_positive = (isinstance(raw, (int, float)) and not isinstance(raw, bool)
                        and math.isfinite(raw) and raw > 0)
        if room["room_area_m2"] is not None:
            if not raw_positive or abs(room["room_area_m2"] - round(float(raw), 6)) > 1.5e-6:
                failures.append(
                    f"{scene['scene_id']}: room_area_m2 {room['room_area_m2']} "
                    f"!= raw scene.room[].size {raw}")
        elif raw_positive and round(float(raw), 6) > 0:
            failures.append(
                f"{scene['scene_id']}: room_area_m2 null but raw size is {raw}")

        # Conservation: every furniture placement of the room must be published,
        # with the position the raw pos maps to. The raw placement id is the tail
        # of furniture_instance_id, so a dropped or duplicated placement fails
        # here even though no source object is retained any more. recomputed
        # carries None for a placement whose raw pos is unusable, so a position
        # that was dropped while the source had one fails the same comparison.
        def raw_id(item):
            return item["furniture_instance_id"].split("::", 1)[-1]

        published = [raw_id(f) for f in room["furniture"]]
        if len(published) != len(set(published)):
            failures.append(f"{scene['scene_id']}: duplicate placement ids in one room")
        if set(published) != set(recomputed["positions"]):
            failures.append(f"{scene['scene_id']}: furniture placement set differs from raw")
        # category and size have no pinned baseline either; like room_type they
        # are gated per sampled placement against a re-derivation from raw.
        for item in room["furniture"]:
            sid = raw_id(item)
            stats["sampled_placements"] += 1
            if item["furniture_position"] != recomputed["positions"].get(sid):
                failures.append(f"{scene['scene_id']}/{sid}: position differs")
            if item["furniture_category"] != recomputed["categories"].get(sid):
                failures.append(f"{scene['scene_id']}/{sid}: furniture_category differs from raw")
            if item["furniture_size"] != recomputed["sizes"].get(sid):
                failures.append(f"{scene['scene_id']}/{sid}: furniture_size differs from raw")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data-dir", type=Path, default=Path("data"))
    parser.add_argument("--room", type=Path, default=Path("json_room.json"))
    parser.add_argument("--merged", type=Path,
                        default=Path("multiroom/json_multi_merged.json"))
    parser.add_argument("--sample", type=int, default=300,
                        help="rooms recomputed from raw house JSON")
    parser.add_argument("--seed", type=int, default=0)
    parser.add_argument("--subset", action="store_true",
                        help="skip absolute count baselines (smoke runs)")
    args = parser.parse_args()

    rng = random.Random(args.seed)
    stats, failures, samples, forbidden = walk_views(
        args.room, args.merged, args.sample, rng)
    check_samples(args.data_dir / "3D-FRONT", samples, failures, stats)
    failures.extend(forbidden)

    baseline_report = {}
    if not args.subset:
        for key, expected in BASELINES.items():
            actual = stats.get(key, 0)
            if expected is None:
                # Not yet measured on a full run. Reported so the number can be
                # pinned, but it cannot gate anything until it is.
                baseline_report[key] = {"expected": None, "actual": actual,
                                        "ok": None, "note": "unpinned"}
                continue
            baseline_report[key] = {"expected": expected, "actual": actual,
                                    "ok": actual == expected}
            if actual != expected:
                failures.append(f"baseline {key}: expected {expected}, got {actual}")

    report = {
        "counts": dict(sorted(stats.items())),
        "baselines": baseline_report,
        "failures": failures[:50],
        "failure_count": len(failures),
        "verdict": "PASS" if not failures else "FAIL",
    }
    print(json.dumps(report, ensure_ascii=False, indent=2))
    return 0 if not failures else 1


if __name__ == "__main__":
    sys.exit(main())