File size: 40,410 Bytes
3f15e9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
#!/usr/bin/env python3
"""Run one configuration-driven scene collection job.

Exit codes: 0 success; 1 build/normalize; 2 prepare or config/I/O error;
3 execute; 4 no scene; 5 package; 6 render; 7 insufficient disk.
"""
from __future__ import annotations

import argparse
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
import math
import os
from pathlib import Path
import shlex
import shutil
import socket
import subprocess
import sys
import tempfile
import time
from typing import Iterable


CODE_ROOT = Path(__file__).resolve().parents[2]
COLLECTION_ROOT = Path(__file__).resolve().parent
WORKFLOW = CODE_ROOT / "scene_workflow.py"
SELECTOR = COLLECTION_ROOT / "select_scene_manifest.py"
PACKAGER = COLLECTION_ROOT / "package_scene.py"
AUDIT_RENDERER = CODE_ROOT / "engine" / "real_test" / "render_wholehouse.py"
REQUIRED_CONFIG = (
    "blender", "rootfs", "runtime_template", "collision_frame_mappings",
    "prepared_asset_pool", "supplemental_prepared_pool", "prepared_cache",
    "retrieval_index", "appearance_index", "attribute_release", "mdl_sdk_root",
    "mdl_sdk_python", "material_artifact_index", "artifact_cache_root", "digest_cache",
)
DEFAULT_DESCRIPTION = "生成完整住宅场景。"
DEFAULT_PRESENTATION_VIEWS = ("diagnostic_top", "diagnostic_living_human_view")
POLICY_ENV = frozenset({
    "RHG_ENVELOPE_LAYOUT", "RHG_LAYOUT_RULES", "RHG_DOOR_LEAF_FALLBACK_POLICY",
    "RHG_RECOVERY_SEARCH_BUDGET_POLICY", "RHG_LAYOUT_RECOVERY_POLICY",
    "RHG_SUPPORT_COLLISION_OMISSION_POLICY", "RHG_EARLY_OMISSION_MIN_ATTEMPTS",
    "RHG_RECOVERY_SOLVE_CAP_S", "RHG_RECOVERY_MAX_ATTEMPTS", "RHG_RECOVERY_MAX_ELAPSED_S",
    "RHG_ROOM_SEARCH_BUDGETS", "RHG_FLOOR_COVER_COLLISION_OMISSION",
    "RHG_PENETRATION_TOLERANCE_M", "RHG_COMPACT_KITCHEN",
})
_ZSTD_WARNING_EMITTED = False


def min_free_gb(value=None) -> float:
    try:
        result = 30.0 if value in (None, "") else float(value)
    except (TypeError, ValueError) as exc:
        raise ValueError("min_free_gb must be a nonnegative finite number") from exc
    if not math.isfinite(result) or result < 0:
        raise ValueError("min_free_gb must be a nonnegative finite number")
    return result


def disk_space_problem(paths: Iterable[Path], minimum_gb: float, *, usage=None) -> str | None:
    usage = usage or shutil.disk_usage
    for path in paths:
        existing = path
        while not existing.exists() and existing != existing.parent:
            existing = existing.parent
        try:
            free = usage(existing).free / (1024 ** 3)
        except OSError as exc:
            return f"cannot check disk space for {path}: {exc}"
        if free < minimum_gb:
            return f"{path}: {free:.2f} GiB free < {minimum_gb:g} GiB required"
    return None


def _retention_log(log: Path, message: str) -> None:
    message = f"{iso_now()} {message}\n"
    try:
        with (log / "run_dir_retention.log").open("a", encoding="utf-8") as stream:
            stream.write(message)
    except OSError:
        try:
            print(message, end="", file=sys.stderr)
        except OSError:
            pass


def _retain_run_dir(case: Path, log: Path, retention: str, *, success: bool) -> None:
    global _ZSTD_WARNING_EMITTED
    temporary = None
    try:
        if retention == "keep" or not case.is_dir():
            return
        if retention == "delete_on_success" and success:
            shutil.rmtree(case)
            _retention_log(log, f"deleted successful run directory {case}")
            return
        zstd = shutil.which("zstd")
        if not zstd:
            if not _ZSTD_WARNING_EMITTED:
                _retention_log(log, "warning: zstd unavailable; keeping run directories")
                _ZSTD_WARNING_EMITTED = True
            return
        archive = case.parent / (case.name + ".tar.zst")
        fd, name = tempfile.mkstemp(prefix=archive.name + ".", suffix=".tmp", dir=case.parent)
        temporary = Path(name)
        os.close(fd)
        with (log / "run_dir_retention.log").open("a", encoding="utf-8") as stream:
            command = ["tar", "-C", str(case.parent), "-I", shlex.join([zstd, "-T4", "-3"]),
                       "-cf", str(temporary), "--", case.name]
            result = subprocess.run(command, stdout=stream, stderr=subprocess.STDOUT, check=False)
            if result.returncode != 0:
                raise RuntimeError(f"tar returned {result.returncode}")
            result = subprocess.run([zstd, "-t", "-q", str(temporary)], stdout=stream,
                                    stderr=subprocess.STDOUT, check=False)
            if result.returncode != 0:
                raise RuntimeError(f"zstd validation returned {result.returncode}")
        temporary.replace(archive)
        shutil.rmtree(case)
        _retention_log(log, f"compressed run directory to {archive}")
    except Exception as exc:
        # Retention is best effort, including when the log filesystem is full.
        _retention_log(log, f"run directory retention failed for {case}: {exc}; original retained if present")
    finally:
        if temporary is not None:
            try:
                temporary.unlink(missing_ok=True)
            except OSError as exc:
                _retention_log(log, f"temporary archive cleanup failed: {exc}")


def digest(path: Path) -> str:
    value = hashlib.sha256()
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            value.update(block)
    return value.hexdigest()


def iso_now() -> str:
    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())


def load_config(path: Path) -> dict:
    try:
        raw = json.loads(path.read_text(encoding="utf-8"))
    except OSError as exc:
        raise ValueError(f"cannot read config {path}: {exc}") from exc
    except json.JSONDecodeError as exc:
        raise ValueError(f"config is not valid JSON: {path}: {exc}") from exc
    if not isinstance(raw, dict):
        raise ValueError("host config must be a JSON object")
    sys.dont_write_bytecode = True
    sys.path.insert(0, str(CODE_ROOT))
    from rhg_paths import resolve
    try:
        config = resolve(raw)
    except ValueError as exc:
        raise ValueError(f"cannot expand host config {path}: {exc}") from exc
    missing = [name for name in REQUIRED_CONFIG
               if not isinstance(config.get(name), str) or not config[name].strip()]
    if missing:
        raise ValueError("host config missing required fields: " + ", ".join(missing))
    if not isinstance(config.get("environment", {}), dict):
        raise ValueError("host config field environment must be an object")
    _validate_floorplan_config(config)
    if config.get("run_dir_retention", "compress") not in ("compress", "keep", "delete_on_success"):
        raise ValueError("run_dir_retention must be compress, keep, or delete_on_success")
    min_free_gb(config.get("min_free_gb"))
    return config


def _as_int(value, name: str, default: int) -> int:
    if value is None or value == "":
        return default
    try:
        result = int(value)
    except (TypeError, ValueError) as exc:
        raise ValueError(f"config field {name} must be an integer") from exc
    if result <= 0:
        raise ValueError(f"config field {name} must be positive")
    return result


def _as_float(value, name: str, default: float) -> float:
    if value is None or value == "":
        return default
    try:
        result = float(value)
    except (TypeError, ValueError) as exc:
        raise ValueError(f"config field {name} must be a number") from exc
    if result <= 0:
        raise ValueError(f"config field {name} must be positive")
    return result


def _as_bool(value, name: str, default: bool) -> bool:
    if value is None or value == "":
        return default
    if isinstance(value, bool):
        return value
    if isinstance(value, (int, float)) and value in (0, 1):
        return bool(value)
    if isinstance(value, str):
        normalized = value.strip().casefold()
        if normalized in {"true", "yes", "on", "1"}:
            return True
        if normalized in {"false", "no", "off", "0"}:
            return False
    raise ValueError(f"config field {name} must be a boolean")


def _as_rate(value, name: str, default: float) -> float:
    if value is None or value == "":
        return default
    try:
        result = float(value)
    except (TypeError, ValueError) as exc:
        raise ValueError(f"config field {name} must be a number between 0 and 1") from exc
    if not 0 <= result <= 1:
        raise ValueError(f"config field {name} must be between 0 and 1")
    return result


def _presentation_views(config: dict) -> list[str] | None:
    if "presentation_views" not in config:
        return list(DEFAULT_PRESENTATION_VIEWS)
    value = config.get("presentation_views")
    if value is None or value == "":
        return None
    if isinstance(value, str):
        value = [] if not value.strip() else value.split(",")
    if not isinstance(value, (list, tuple)):
        raise ValueError("config field presentation_views must be a list of names or null")
    views = [str(item).strip() for item in value]
    if any(not view for view in views):
        raise ValueError("config field presentation_views must not contain empty names")
    return views


def _audit_render_sampled(case_id: str, audit_render: bool, audit_sample_rate: float) -> bool:
    if audit_render or audit_sample_rate >= 1:
        return True
    if audit_sample_rate <= 0:
        return False
    bucket = int(hashlib.sha256(case_id.encode("utf-8")).hexdigest()[:16], 16)
    return bucket / float(1 << 64) < audit_sample_rate


def _audit_time_budget_s(config: dict, device: str) -> float:
    default = 900.0 if device == "GPU" else 1800.0
    return _as_float(config.get("audit_time_budget_s"), "audit_time_budget_s", default)


def _presentation_deadline_s(config: dict) -> float:
    return _as_float(config.get("presentation_deadline_s"), "presentation_deadline_s", 900.0)


def _safe_case_id(value: str) -> str:
    if not value or Path(value).name != value or value in {".", ".."}:
        raise ValueError("case-id must be a simple directory name")
    return value


def _optional_path(value, name: str) -> str | None:
    if value is None or value == "":
        return None
    if not isinstance(value, (str, Path)):
        raise ValueError(f"config field {name} must be a path")
    return str(Path(value).expanduser().resolve())


def _validate_floorplan_config(config: dict) -> None:
    library = _optional_path(config.get("library"), "library")
    rplan_seeds = _optional_path(config.get("rplan_seeds"), "rplan_seeds")
    if library and rplan_seeds and library != rplan_seeds:
        raise ValueError("config fields library and rplan_seeds refer to different floorplan libraries")


def _select_floorplan_library(config: dict, override: Path | None) -> str:
    _validate_floorplan_config(config)
    command_line = _optional_path(override, "library")
    configured = _optional_path(config.get("library"), "library")
    legacy = _optional_path(config.get("rplan_seeds"), "rplan_seeds")
    selected = command_line or configured or legacy
    if not selected:
        raise ValueError("host config must provide library or rplan_seeds")
    return selected


def _floorplan_library_metadata(path: str) -> dict:
    resolved = Path(path).expanduser().resolve()
    metadata = {"path": str(resolved), "sha256": None}
    if not resolved.is_file():
        return metadata
    metadata["sha256"] = digest(resolved)
    try:
        payload = json.loads(resolved.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return metadata
    plans = payload.get("plans") if isinstance(payload, dict) else None
    if isinstance(plans, list):
        metadata["plan_count"] = len(plans)
        if len(plans) == 1 and isinstance(plans[0], dict):
            metadata["single_plan_id"] = plans[0].get("plan_id")
    return metadata


def _build_shell_plan_id(case: Path) -> str | None:
    manifest_path = case / "layout" / "fullhome_asset_v16_000" / "composition_manifest.runtime.json"
    if not manifest_path.is_file():
        return None
    payload = json.loads(manifest_path.read_text(encoding="utf-8"))
    plan_id = payload.get("floor_plan", {}).get("plan_id")
    return str(plan_id) if plan_id not in (None, "") else None


def _taskset(command: Iterable[str], cpus: str | None) -> list[str]:
    command = [str(item) for item in command]
    if cpus and shutil.which("taskset"):
        return ["taskset", "-c", str(cpus), *command]
    return command


def _env(config: dict, *, case_id: str, case: Path, log: Path, gpu: str | None,
         library: str, cache: Path) -> dict[str, str]:
    environment = {str(key): str(value) for key, value in os.environ.items()}
    for key in POLICY_ENV | {"RHG_REVIEW_PYTHON", "RHG_REVIEW_SITE",
                             "RHG_LIBRARY_ROOT", "RHG_ASSET_LIBRARY_ROOT"}:
        environment.pop(key, None)
    environment.update({
        "PYTHONDONTWRITEBYTECODE": "1",
        "PYTHONUNBUFFERED": "1",
        "RHG_BLENDER": str(config["blender"]),
        "RHG_ROOTFS": str(config["rootfs"]),
        "RHG_RPLAN_SEEDS": str(library),
        "RHG_DIGEST_CACHE": str(config["digest_cache"]),
        "RHG_JOB_TAG": f"collection_{case_id}",
        "TMPDIR": str(log / "TMPDIR"),
        "XDG_CACHE_HOME": str(log / "XDG_CACHE_HOME"),
        "CUDA_CACHE_PATH": str(log / "CUDA_CACHE_PATH"),
        "TORCH_HOME": str(log / "TORCH_HOME"),
        "PYTHONPATH": os.pathsep.join((str(CODE_ROOT / "engine" / "supervisor_site"),
                                        str(CODE_ROOT / "engine"), str(CODE_ROOT))),
        "CUDA_VISIBLE_DEVICES": "" if gpu in (None, "") else str(gpu),
    })
    asset_library_root = _optional_path(config.get("asset_library_root"), "asset_library_root")
    if asset_library_root:
        environment["RHG_LIBRARY_ROOT"] = asset_library_root
    if config.get("review_python"):
        environment["RHG_REVIEW_PYTHON"] = str(config["review_python"])
    if config.get("review_site"):
        environment["RHG_REVIEW_SITE"] = str(config["review_site"])
    for key, value in config.get("environment", {}).items():
        if value is None:
            continue
        environment[str(key)] = str(value)
    environment.setdefault("RHG_CASE_DIR", str(case))
    return environment


def _workflow_base() -> list[str]:
    return [sys.executable, "-B", "-u", str(WORKFLOW)]


def build_commands(config: dict, *, case_id: str, seed: int, case: Path,
                   dataset: Path, log: Path, worker_meta: Path, library: str,
                   device: str, gpu: str | None, cpus: str | None) -> dict[str, list[str]]:
    description = str(config.get("description") or DEFAULT_DESCRIPTION)
    build = _workflow_base() + [
        "build-shell", "--case", str(case), "--rootfs", str(config["rootfs"]),
        "--seed", str(seed), "--blender", str(config["blender"]),
        "--description", description,
    ]
    prepare = _workflow_base() + [
        "prepare", "--case", str(case), "--seed", str(seed),
        "--rootfs", str(config["rootfs"]),
        "--runtime-template", str(config["runtime_template"]),
        "--collision-frame-mappings", str(config["collision_frame_mappings"]),
        "--prepared-asset-pool", str(config["prepared_asset_pool"]),
        "--supplemental-prepared-pool", str(config["supplemental_prepared_pool"]),
        "--prepared-cache", str(config["prepared_cache"]),
        "--retrieval-index", str(config["retrieval_index"]),
        "--appearance-index", str(config["appearance_index"]),
        "--attribute-release", str(config["attribute_release"]),
        "--mdl-sdk-root", str(config["mdl_sdk_root"]),
        "--mdl-sdk-python", str(config["mdl_sdk_python"]),
        "--material-artifact-index", str(config["material_artifact_index"]),
        "--artifact-cache-root", str(config["artifact_cache_root"]),
    ]
    profile = config.get("residential_profile")
    if profile:
        prepare += ["--residential-profile", str(profile),
                    "--retrieval-rounds", str(_as_int(config.get("retrieval_rounds"), "retrieval_rounds", 8)),
                    "--preparation-budget", str(_as_int(config.get("preparation_budget"), "preparation_budget", 64))]
    execute = _workflow_base() + ["execute", "--case", str(case)]
    select = [sys.executable, "-B", str(SELECTOR), str(case)]
    package = [sys.executable, "-B", str(PACKAGER), "--case", str(case),
               "--dataset", str(dataset), "--worker-meta", str(worker_meta),
               "--manifest", "<selected-manifest>"]
    audit = [str(config["blender"]), "--background", "--python-exit-code", "1",
             "--python", str(AUDIT_RENDERER), "--", "--scene", "<scene-dir>",
             "--output", "<dataset>/renders/audit", "--device", device,
             "--diagnostic-overviews"]
    if device == "GPU":
        audit += ["--gpu-backend", str(config.get("audit_gpu_backend") or "CUDA"), "--samples", "8"]
    else:
        audit += ["--samples", "4"]
    audit += ["--time-budget-s", str(_audit_time_budget_s(config, device))]
    render = _workflow_base() + ["render", "--case", str(case),
                                 "--output", "<dataset>/renders/presentation",
                                 "--samples", str(_as_int(config.get("presentation_samples"),
                                                           "presentation_samples", 32)),
                                 "--device", device, "--blender", str(config["blender"])]
    if device == "GPU":
        render += ["--gpu-backend", str(config.get("presentation_gpu_backend") or "CUDA")]
    render += ["--deadline-s", str(_presentation_deadline_s(config))]
    presentation_views = _presentation_views(config)
    if presentation_views:
        render += ["--views", ",".join(presentation_views)]
    for key, option in (("presentation_width", "--width"), ("presentation_height", "--height")):
        if config.get(key) not in (None, ""):
            render += [option, str(config[key])]
    return {name: _taskset(command, cpus) for name, command in {
        "build_shell": build, "prepare": prepare, "execute": execute,
        "select": select, "package": package, "render_audit": audit,
        "render_presentation": render,
    }.items()}


def normalize_scene_input(case: Path, description: str) -> None:
    manifest_path = case / "layout" / "fullhome_asset_v16_000" / "composition_manifest.runtime.json"
    scene_input = case / "scene_input.json"
    if not manifest_path.is_file() or not scene_input.is_file():
        return
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    floor_plan = manifest.get("floor_plan", {})
    labels = {"living_room": "客厅", "dining_room": "餐厅", "kitchen": "厨房",
              "bathroom": "卫生间", "balcony": "阳台", "study": "书房"}
    rooms = floor_plan.get("rooms", [])
    bedrooms = sum("bedroom" in str(room.get("room_type", "")) for room in rooms)
    names = []
    for room in rooms:
        room_type = room.get("room_type")
        if room_type in labels and labels[room_type] not in names:
            names.append(labels[room_type])
    normalized = json.loads(scene_input.read_text(encoding="utf-8"))
    normalized["description"] = f"{description.rstrip('。')},{bedrooms}室,包含{'、'.join(names)}。"
    normalized["normalized_for_shell"] = True
    scene_input.write_text(json.dumps(normalized, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def _git_head() -> str | None:
    try:
        result = subprocess.run(["git", "-C", str(CODE_ROOT), "rev-parse", "HEAD"],
                                text=True, capture_output=True, check=False)
    except OSError:
        return None
    return result.stdout.strip() if result.returncode == 0 else None


def _integrity_result() -> dict:
    checker = CODE_ROOT / "tools" / "release" / "check_source_integrity.py"
    if not checker.is_file():
        return {"available": False}
    result = subprocess.run([sys.executable, str(checker), "--root", str(CODE_ROOT)],
                            cwd=CODE_ROOT, text=True, capture_output=True, check=False)
    try:
        value = json.loads(result.stdout)
    except json.JSONDecodeError:
        value = {"returncode": result.returncode, "stdout": result.stdout, "stderr": result.stderr}
    value["returncode"] = result.returncode
    return value


def _write_meta(path: Path, *, config_path: Path, config: dict, case_id: str, seed: int,
                library: str, case: Path, commands: dict[str, list[str]], device: str,
                gpu: str | None, cpus: str | None, audit_render_sampled: bool,
                presentation_views: list[str] | None,
                selected_plan_id: str | None = None) -> None:
    git_head = _git_head()
    data = {
        "schema": "rhg.collection_worker_meta.v1",
        "case_id": case_id,
        "seed": seed,
        "library": library,
        "floorplan_library": dict(_floorplan_library_metadata(library),
                                   selected_plan_id=selected_plan_id),
        "asset_library_root": _optional_path(config.get("asset_library_root"), "asset_library_root"),
        "selected_plan_id": selected_plan_id,
        "code_root": str(CODE_ROOT),
        "tree_root": str(CODE_ROOT),
        "git_head": git_head,
        "git_rev_parse_head": git_head,
        "source_integrity": _integrity_result(),
        "config_path": str(config_path.resolve()),
        "config_sha256": digest(config_path),
        "host": socket.gethostname(),
        "device": device,
        "gpu": gpu,
        "cpus": cpus,
        "started_at": iso_now(),
        "commands": {key: [str(item) for item in value] for key, value in commands.items()},
        "all_commands": [{"stage": key, "argv": [str(item) for item in value]}
                         for key, value in commands.items()],
        "environment_overrides": {str(key): str(value) for key, value in config.get("environment", {}).items()},
        "description": config.get("description") or DEFAULT_DESCRIPTION,
        "residential_profile": config.get("residential_profile") or None,
        "retrieval_rounds": _as_int(config.get("retrieval_rounds"), "retrieval_rounds", 8)
        if config.get("residential_profile") else None,
        "preparation_budget": _as_int(config.get("preparation_budget"), "preparation_budget", 64)
        if config.get("residential_profile") else None,
        "presentation_samples": _as_int(config.get("presentation_samples"), "presentation_samples", 32),
        "audit_time_budget_s": _audit_time_budget_s(config, device),
        "presentation_deadline_s": _presentation_deadline_s(config),
        "audit_render": _as_bool(config.get("audit_render"), "audit_render", False),
        "audit_sample_rate": _as_rate(config.get("audit_sample_rate"), "audit_sample_rate", 0.0),
        "audit_render_sampled": audit_render_sampled,
        "render_parallel": _as_bool(config.get("render_parallel"), "render_parallel", True),
        "presentation_views": presentation_views,
    }
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def _write_marker(log: Path, name: str, content: str = "failed\n") -> None:
    (log / name).write_text(content, encoding="utf-8")


def _skip_stage(name: str, *, log: Path) -> None:
    timestamp = iso_now() + "\n"
    (log / f"{name}.started").write_text(timestamp, encoding="utf-8")
    (log / f"{name}.log").write_text("skipped\n", encoding="utf-8")
    (log / f"{name}.rc").write_text("skipped\n", encoding="utf-8")
    (log / f"{name}.finished").write_text(iso_now() + "\n", encoding="utf-8")


def _sync_build_aliases(log: Path) -> None:
    for suffix in ("started", "log", "rc", "finished"):
        source = log / f"build_shell.{suffix}"
        target = log / f"build-shell.{suffix}"
        if source.is_file():
            target.write_bytes(source.read_bytes())


def _run_stage(name: str, command: list[str], *, log: Path, env: dict[str, str], cwd: Path) -> int:
    (log / f"{name}.started").write_text(iso_now() + "\n", encoding="utf-8")
    with (log / f"{name}.log").open("w", encoding="utf-8") as stream:
        try:
            result = subprocess.run(command, cwd=cwd, env=env, stdout=stream, stderr=subprocess.STDOUT,
                                    check=False)
            rc = int(result.returncode)
        except OSError as exc:
            stream.write(str(exc) + "\n")
            rc = 127
    (log / f"{name}.rc").write_text(str(rc) + "\n", encoding="utf-8")
    (log / f"{name}.finished").write_text(iso_now() + "\n", encoding="utf-8")
    if name == "build_shell":
        _sync_build_aliases(log)
    return rc


def _run_capture(name: str, command: list[str], *, log: Path, env: dict[str, str], cwd: Path) -> tuple[int, str]:
    (log / f"{name}.started").write_text(iso_now() + "\n", encoding="utf-8")
    try:
        result = subprocess.run(command, cwd=cwd, env=env, capture_output=True, text=True, check=False)
        output = (result.stdout or "") + (result.stderr or "")
        rc = int(result.returncode)
    except OSError as exc:
        output = str(exc) + "\n"
        rc = 127
    (log / f"{name}.log").write_text(output, encoding="utf-8")
    (log / f"{name}.rc").write_text(str(rc) + "\n", encoding="utf-8")
    (log / f"{name}.finished").write_text(iso_now() + "\n", encoding="utf-8")
    if name == "build_shell":
        _sync_build_aliases(log)
    return rc, output


def _last_json(output: str) -> dict:
    for line in reversed([line.strip() for line in output.splitlines() if line.strip()]):
        try:
            value = json.loads(line)
        except json.JSONDecodeError:
            continue
        if isinstance(value, dict):
            return value
    raise ValueError("command did not produce a JSON object")


def _presentation_output_ok(path: Path) -> bool:
    if not (path / "render_summary.json").is_file():
        return False
    return any(item.is_file() and item.suffix.casefold() in {".png", ".jpg", ".jpeg", ".webp", ".exr"}
               for item in path.rglob("*"))


def dry_run(commands: dict[str, list[str]], *, log: Path, env: dict[str, str], explicit: dict,
            audit_render: bool, audit_sample_rate: float, audit_render_sampled: bool,
            render_parallel: bool, presentation_views: list[str] | None) -> None:
    log.mkdir(parents=True, exist_ok=True)
    lines = [
        "# dry-run; no commands executed",
        f"# audit_render={'true' if audit_render else 'false'}",
        f"# audit_sample_rate={audit_sample_rate}",
        f"# audit_render_sampled={'true' if audit_render_sampled else 'false'}",
        f"# render_parallel={'true' if render_parallel else 'false'}",
        f"# render_mode={'parallel' if render_parallel else 'sequential'}",
        "# presentation_views=" + (",".join(presentation_views) if presentation_views is not None else "all"),
        shlex.join(["env", *[
            f"{key}={value}" for key, value in sorted(env.items())
            if key in {"RHG_BLENDER", "RHG_ROOTFS", "RHG_RPLAN_SEEDS", "RHG_LIBRARY_ROOT",
                       "RHG_ASSET_LIBRARY_ROOT", "RHG_DIGEST_CACHE",
                       "TMPDIR", "XDG_CACHE_HOME", "CUDA_CACHE_PATH", "TORCH_HOME",
                       "CUDA_VISIBLE_DEVICES", "RHG_REVIEW_PYTHON", "RHG_REVIEW_SITE"}
        ]])
    ]
    if explicit:
        lines.append(shlex.join(["env", *[f"{key}={value}" for key, value in sorted(explicit.items())]]))
    lines += [shlex.join(commands[name]) for name in (
        "build_shell", "prepare", "execute", "select", "package")]
    if audit_render_sampled:
        lines.append(shlex.join(commands["render_audit"]))
    else:
        audit_command = commands["render_audit"]
        try:
            budget = audit_command[audit_command.index("--time-budget-s") + 1]
        except (ValueError, IndexError):
            budget = "configured"
        lines.append(f"# render_audit: skipped; --time-budget-s {budget}")
    lines.append(shlex.join(commands["render_presentation"]))
    (log / "dry_run_commands.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")


def collect(args: argparse.Namespace) -> int:
    config_path = Path(args.config).resolve()
    config = load_config(config_path)
    case_id = _safe_case_id(args.case_id)
    case = CODE_ROOT / "engine" / "runs" / case_id
    log = Path(args.log_root).resolve() / case_id
    result = None
    try:
        result = _collect(args, config)
        return result
    except Exception as exc:
        if not args.dry_run:
            try:
                log.mkdir(parents=True, exist_ok=True)
                if not (log / "FAILED").exists():
                    _write_marker(log, "FAILED", f"collector_error: {exc}\n")
            except OSError:
                pass
        raise
    finally:
        if not args.dry_run:
            # Both renderers still read the run directory after PACKAGE_SUCCESS.
            _retain_run_dir(case, log, config.get("run_dir_retention", "compress"), success=result == 0)


def _collect(args: argparse.Namespace, config: dict) -> int:
    config_path = Path(args.config).resolve()
    case_id = _safe_case_id(args.case_id)
    dataset = Path(args.dataset).resolve()
    log = Path(args.log_root).resolve() / case_id
    case = CODE_ROOT / "engine" / "runs" / case_id
    library = _select_floorplan_library(config, args.library)
    selected_plan_id = None
    device = "GPU" if args.gpu not in (None, "") else "CPU"
    audit_render = _as_bool(config.get("audit_render"), "audit_render", False)
    audit_sample_rate = _as_rate(config.get("audit_sample_rate"), "audit_sample_rate", 0.0)
    audit_render_sampled = _audit_render_sampled(case_id, audit_render, audit_sample_rate)
    render_parallel = _as_bool(config.get("render_parallel"), "render_parallel", True)
    presentation_views = _presentation_views(config)
    commands = build_commands(config, case_id=case_id, seed=args.seed, case=case,
                              dataset=dataset, log=log, worker_meta=log / "worker_meta.json",
                              library=library, device=device, gpu=args.gpu, cpus=args.cpus)
    env = _env(config, case_id=case_id, case=case, log=log, gpu=args.gpu, library=library,
               cache=Path(config["digest_cache"]))
    if args.dry_run:
        dry_run(commands, log=log, env=env, explicit=config.get("environment", {}),
                audit_render=audit_render, audit_sample_rate=audit_sample_rate,
                audit_render_sampled=audit_render_sampled, render_parallel=render_parallel,
                presentation_views=presentation_views)
        return 0

    minimum = min_free_gb(getattr(args, "min_free_gb", None)
                          if getattr(args, "min_free_gb", None) is not None else config.get("min_free_gb"))
    problem = disk_space_problem((case.parent, log.parent), minimum)
    if problem:
        print(f"collect_one: insufficient_disk: {problem}", file=sys.stderr)
        try:
            log.mkdir(parents=True, exist_ok=True)
            _write_marker(log, "FAILED", "insufficient_disk\n")
        except OSError as exc:
            print(f"collect_one: cannot write FAILED: {exc}", file=sys.stderr)
        return 7

    log.mkdir(parents=True, exist_ok=True)
    case.mkdir(parents=True, exist_ok=True)
    for key in ("TMPDIR", "XDG_CACHE_HOME", "CUDA_CACHE_PATH", "TORCH_HOME"):
        Path(env[key]).mkdir(parents=True, exist_ok=True)
    Path(config["digest_cache"]).mkdir(parents=True, exist_ok=True)
    meta_path = log / "worker_meta.json"
    _write_meta(meta_path, config_path=config_path, config=config, case_id=case_id, seed=args.seed,
                library=library, case=case, commands=commands, device=device, gpu=args.gpu, cpus=args.cpus,
                audit_render_sampled=audit_render_sampled, presentation_views=presentation_views)

    rc = _run_stage("build_shell", commands["build_shell"], log=log, env=env, cwd=CODE_ROOT)
    if rc == 0:
        try:
            normalize_scene_input(case, str(config.get("description") or DEFAULT_DESCRIPTION))
        except Exception as exc:
            with (log / "build_shell.log").open("a", encoding="utf-8") as stream:
                stream.write(str(exc) + "\n")
            rc = 1
            (log / "build_shell.rc").write_text("1\n", encoding="utf-8")
            _sync_build_aliases(log)
    if rc == 0:
        try:
            selected_plan_id = _build_shell_plan_id(case)
            library_meta = _floorplan_library_metadata(library)
            if selected_plan_id is not None:
                _write_meta(meta_path, config_path=config_path, config=config, case_id=case_id,
                            seed=args.seed, library=library, case=case, commands=commands,
                            device=device, gpu=args.gpu, cpus=args.cpus,
                            audit_render_sampled=audit_render_sampled,
                            presentation_views=presentation_views,
                            selected_plan_id=selected_plan_id)
            expected_plan_id = library_meta.get("single_plan_id")
            if library_meta.get("plan_count") == 1 and expected_plan_id is not None \
                    and selected_plan_id != expected_plan_id:
                _write_marker(log, "FAILED", "floorplan_mismatch\n")
                return 1
        except (OSError, ValueError, json.JSONDecodeError) as exc:
            with (log / "build_shell.log").open("a", encoding="utf-8") as stream:
                stream.write(f"floorplan verification failed: {exc}\n")
            _write_marker(log, "FAILED", "build_failed\n")
            return 1
    if rc != 0:
        _write_marker(log, "FAILED", "build_failed\n")
        return 1

    rc = _run_stage("prepare", commands["prepare"], log=log, env=env, cwd=CODE_ROOT)
    if rc != 0:
        _write_marker(log, "FAILED", "prepare_failed\n")
        return 2
    rc = _run_stage("execute", commands["execute"], log=log, env=env, cwd=CODE_ROOT)
    if rc != 0:
        _write_marker(log, "FAILED", "execute_failed\n")
        return 3

    select_rc, select_output = _run_capture("select", commands["select"], log=log, env=env, cwd=CODE_ROOT)
    manifest = None
    if select_rc == 0:
        for line in reversed([line.strip() for line in select_output.splitlines() if line.strip()]):
            candidate = Path(line)
            if candidate.is_file():
                manifest = str(candidate)
                break
    if not manifest:
        _write_marker(log, "FAILED", "no_scene\n")
        return 4

    package_command = [item if item != "<selected-manifest>" else manifest for item in commands["package"]]
    commands["package"] = package_command
    _write_meta(meta_path, config_path=config_path, config=config, case_id=case_id, seed=args.seed,
                library=library, case=case, commands=commands, device=device, gpu=args.gpu, cpus=args.cpus,
                audit_render_sampled=audit_render_sampled, presentation_views=presentation_views,
                selected_plan_id=selected_plan_id)
    package_rc, package_output = _run_capture("package", package_command, log=log, env=env, cwd=CODE_ROOT)
    if package_rc != 0:
        _write_marker(log, "FAILED", "package_failed\n")
        return 5
    try:
        package_info = _last_json(package_output)
        destination = Path(package_info["dest"]).resolve()
        scene_dir = Path(package_info["scene_dir"]).resolve()
    except (KeyError, ValueError, TypeError) as exc:
        with (log / "package.log").open("a", encoding="utf-8") as stream:
            stream.write(f"invalid package receipt: {exc}\n")
        _write_marker(log, "FAILED", "package_failed\n")
        return 5
    (log / "PACKAGE_SUCCESS").write_text("package_success\n", encoding="utf-8")
    audit_command = [item.replace("<scene-dir>", str(scene_dir)).replace("<dataset>", str(destination))
                     for item in commands["render_audit"]]
    render_command = [item.replace("<dataset>", str(destination)) for item in commands["render_presentation"]]
    commands["render_audit"] = audit_command
    commands["render_presentation"] = render_command
    _write_meta(meta_path, config_path=config_path, config=config, case_id=case_id, seed=args.seed,
                library=library, case=case, commands=commands, device=device, gpu=args.gpu, cpus=args.cpus,
                audit_render_sampled=audit_render_sampled, presentation_views=presentation_views,
                selected_plan_id=selected_plan_id)
    destination.joinpath("renders").mkdir(parents=True, exist_ok=True)
    (log / "render.started").write_text(iso_now() + "\n", encoding="utf-8")
    if not audit_render_sampled:
        _skip_stage("render_audit", log=log)
        audit_rc = None
        presentation_rc = _run_stage("render_presentation", render_command, log=log, env=env, cwd=CODE_ROOT)
    elif render_parallel:
        with ThreadPoolExecutor(max_workers=2, thread_name_prefix="collection-render") as executor:
            audit_future = executor.submit(_run_stage, "render_audit", audit_command,
                                            log=log, env=env, cwd=CODE_ROOT)
            presentation_future = executor.submit(_run_stage, "render_presentation", render_command,
                                                  log=log, env=env, cwd=CODE_ROOT)
            audit_rc = audit_future.result()
            presentation_rc = presentation_future.result()
    else:
        audit_rc = _run_stage("render_audit", audit_command, log=log, env=env, cwd=CODE_ROOT)
        presentation_rc = _run_stage("render_presentation", render_command, log=log, env=env, cwd=CODE_ROOT)
    if presentation_rc == 0 and not _presentation_output_ok(destination / "renders" / "presentation"):
        with (log / "render_presentation.log").open("a", encoding="utf-8") as stream:
            stream.write("presentation render produced no render_summary.json and image output\n")
        presentation_rc = 1
        (log / "render_presentation.rc").write_text("1\n", encoding="utf-8")
    render_rc = 0 if audit_rc in (None, 0) and presentation_rc == 0 else 6
    (log / "render.log").write_text(json.dumps({
        "audit_rc": audit_rc, "presentation_rc": presentation_rc, "render_rc": render_rc,
    }) + "\n", encoding="utf-8")
    (log / "render.rc").write_text(str(render_rc) + "\n", encoding="utf-8")
    (log / "render.finished").write_text(iso_now() + "\n", encoding="utf-8")
    status = {
        "case_id": case_id,
        "scene_dir": str(scene_dir),
        "dataset_dir": str(destination),
        "generation_status": "geometry_output_passed",
        "render_status": "passed" if render_rc == 0 else "failed",
        "render_rc": render_rc,
        "render_audit_rc": audit_rc,
        "render_presentation_rc": presentation_rc,
    }
    if render_rc == 0:
        (log / "SUCCESS.json").write_text(json.dumps(status, ensure_ascii=False) + "\n", encoding="utf-8")
        return 0
    (log / "RENDER_FAILED.json").write_text(json.dumps(status, ensure_ascii=False) + "\n", encoding="utf-8")
    _write_marker(log, "RENDER_FAILED", "render_failed\n")
    _write_marker(log, "FAILED", "render_failed\n")
    return 6


def parser() -> argparse.ArgumentParser:
    result = argparse.ArgumentParser(description=__doc__)
    result.add_argument("--config", type=Path, required=True)
    result.add_argument("--case-id", required=True)
    result.add_argument("--seed", type=int, required=True)
    result.add_argument("--library", type=Path)
    result.add_argument("--dataset", type=Path, required=True)
    result.add_argument("--log-root", type=Path, required=True)
    result.add_argument("--cpus")
    result.add_argument("--gpu")
    result.add_argument("--min-free-gb", type=float, help="override config disk threshold (GiB)")
    result.add_argument("--dry-run", action="store_true")
    return result


def main(argv=None) -> int:
    try:
        return collect(parser().parse_args(argv))
    except (ValueError, OSError) as exc:
        print(f"collect_one: {exc}", file=sys.stderr)
        return 2


if __name__ == "__main__":
    raise SystemExit(main())