Datasets:
File size: 79,973 Bytes
8ca7ba0 | 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 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 | from __future__ import annotations
import asyncio
import json
import multiprocessing
import os
import re
import signal
import threading
import time
import traceback
import types
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor, as_completed
from copy import deepcopy
from dataclasses import asdict, is_dataclass
from pathlib import Path
from typing import Any
import yaml # type: ignore[import-untyped]
from packages.runtime.gpu_scheduler import DynamicGpuPool
from packages.runtime.scenesmith_skill_policy import (
ManipulandSkillPolicy,
load_scenesmith_skill_policy,
)
from packages.scene_generation.dependency_graph import manipulation_assignments
_PROCESS_START_LOCK = threading.Lock()
_COLLISION_LINE = re.compile(
r"^- (?P<first>.+?) collides with (?P<second>.+?) "
r"\((?P<detail>[^)]*)\)$"
)
def task_support_ids(
context: dict[str, Any], dependency_graph: dict[str, Any] | None = None
) -> set[str]:
if dependency_graph:
planned = manipulation_assignments(dependency_graph)
if planned:
return set(planned)
task = context.get("task", {})
return {
str(predicate["object"])
for predicate in task.get("initial_predicates", [])
if predicate.get("name") in {"on", "supported_by", "inside"}
and predicate.get("object")
}
def serialize_selection(selection: Any) -> dict[str, Any]:
if is_dataclass(selection):
return asdict(selection)
if hasattr(selection, "model_dump"):
return selection.model_dump(mode="json")
if hasattr(selection, "__dict__"):
return deepcopy(vars(selection))
return {"furniture_id": str(selection.furniture_id)}
def maximum_interval_concurrency(timings: list[dict[str, Any]]) -> int:
"""Return measured overlap; queued work without a lease is deliberately excluded."""
events: list[tuple[float, int]] = []
for timing in timings:
started = timing.get("lease_acquired_unix", timing.get("started_unix"))
completed = timing.get("completed_unix")
if not isinstance(started, (int, float)) or not isinstance(completed, (int, float)):
continue
if completed < started:
continue
events.extend(((float(started), 1), (float(completed), -1)))
active = 0
maximum = 0
# End events sort before starts at the same timestamp so touching intervals
# are not reported as concurrent.
for _, delta in sorted(events, key=lambda item: (item[0], item[1])):
active += delta
maximum = max(maximum, active)
return maximum
def evaluate_branch_completion(
additions: dict[str, list[str]], expected_by_furniture: dict[str, list[str]]
) -> tuple[dict[str, dict[str, Any]], list[str]]:
"""Require critical shards to materialize every stable planned entity ID."""
completion = {}
for furniture_id, expected in sorted(expected_by_furniture.items()):
added = additions.get(furniture_id, [])
missing = [
entity_id
for entity_id in expected
if not any(
object_id == entity_id or object_id.startswith(f"{entity_id}_")
for object_id in added
)
]
completion[furniture_id] = {
"expected_entity_ids": expected,
"added_object_ids": added,
"missing_entity_ids": missing,
"passed": not missing,
}
failed = sorted(
furniture_id for furniture_id, report in completion.items() if not report["passed"]
)
return completion, failed
def project_declared_support_chain(
scene: Any,
dependency_graph: dict[str, Any],
*,
contact_gap_m: float = 0.001,
) -> list[dict[str, Any]]:
"""Seat generated children on generated parents before local critique.
SceneSmith extracts support surfaces once when a shard starts, so a deeper
child cannot otherwise see an intermediate parent generated in that shard.
This deterministic pass realizes those DAG edges while preserving x/y/yaw.
"""
if contact_gap_m < 0.0:
raise ValueError("contact_gap_m must be non-negative")
objects = getattr(scene, "objects", {})
if not isinstance(objects, dict):
return []
def matching_object(entity_id: str) -> Any | None:
exact = [
value
for object_id, value in objects.items()
if str(object_id) == entity_id or str(object_id).startswith(f"{entity_id}_")
]
if len(exact) == 1:
return exact[0]
described = [
value
for value in objects.values()
if entity_id.casefold()
in " ".join(
str(getattr(value, field, ""))
for field in ("object_id", "name", "description")
).casefold()
]
return described[0] if len(described) == 1 else None
edges: list[tuple[str, str]] = []
for node in dependency_graph.get("nodes", []):
if not isinstance(node, dict) or node.get("stage") != "manipulation":
continue
entity_id = str(node.get("entity_id") or node.get("node_id") or "")
attributes = (node.get("metadata") or {}).get("attributes") or {}
parent_id = str(attributes.get("supported_by") or "")
if entity_id and parent_id:
edges.append((entity_id, parent_id))
changes: list[dict[str, Any]] = []
# A bounded fixed point handles serialized node orders that are not topological.
for _ in range(max(1, len(edges))):
changed = False
for child_id, parent_id in edges:
child = matching_object(child_id)
parent = matching_object(parent_id)
if child is None or parent is None:
continue
if any(
getattr(item, "bbox_min", None) is None
or getattr(item, "bbox_max", None) is None
for item in (child, parent)
):
continue
child_translation = child.transform.translation().copy()
parent_translation = parent.transform.translation()
# RoomScene serializes bbox coordinates after uniform asset scaling.
# Applying scale_factor again would double-scale HSSD/Objaverse assets.
parent_top = float(parent_translation[2] + float(parent.bbox_max[2]))
child_bottom_offset = float(child.bbox_min[2])
target_z = parent_top + contact_gap_m - child_bottom_offset
previous_z = float(child_translation[2])
if abs(previous_z - target_z) <= 1.0e-6:
continue
child_translation[2] = target_z
child.transform.set_translation(child_translation)
changes.append(
{
"entity_id": child_id,
"parent_entity_id": parent_id,
"object_id": str(getattr(child, "object_id", child_id)),
"previous_z_m": previous_z,
"corrected_z_m": target_z,
"contact_gap_m": contact_gap_m,
}
)
changed = True
if not changed:
break
return changes
def _world_aabb(scene_object: Any) -> tuple[list[float], list[float]] | None:
"""Return an object's conservative world AABB from its local bbox and pose."""
bbox_min = getattr(scene_object, "bbox_min", None)
bbox_max = getattr(scene_object, "bbox_max", None)
transform = getattr(scene_object, "transform", None)
if bbox_min is None or bbox_max is None or transform is None:
return None
try:
rotation = transform.rotation().matrix()
translation = transform.translation()
corners = []
for x in (float(bbox_min[0]), float(bbox_max[0])):
for y in (float(bbox_min[1]), float(bbox_max[1])):
for z in (float(bbox_min[2]), float(bbox_max[2])):
local = (x, y, z)
corners.append(
[
float(translation[axis])
+ sum(
float(rotation[axis][component]) * local[component]
for component in range(3)
)
for axis in range(3)
]
)
except (IndexError, TypeError, ValueError, AttributeError):
return None
return (
[min(corner[axis] for corner in corners) for axis in range(3)],
[max(corner[axis] for corner in corners) for axis in range(3)],
)
def filter_disjoint_collision_report(
report: str,
scene: Any,
*,
tolerance_m: float = 0.003,
) -> tuple[str, list[dict[str, Any]]]:
"""Remove narrow-phase collisions contradicted by world-space broad phase."""
if tolerance_m < 0.0:
raise ValueError("tolerance_m must be non-negative")
objects = getattr(scene, "objects", {})
if not isinstance(objects, dict) or "Collisions (" not in report:
return report, []
removed: list[dict[str, Any]] = []
kept_lines: list[str] = []
collision_header_index: int | None = None
kept_collision_count = 0
in_collision_section = False
for line in report.splitlines():
if line.startswith("Collisions ("):
collision_header_index = len(kept_lines)
kept_lines.append(line)
in_collision_section = True
continue
if in_collision_section and line and not line.startswith("- "):
in_collision_section = False
match = _COLLISION_LINE.match(line) if in_collision_section else None
if match is None:
kept_lines.append(line)
continue
first_id = match.group("first")
second_id = match.group("second")
first_bounds = _world_aabb(objects.get(first_id))
second_bounds = _world_aabb(objects.get(second_id))
if first_bounds is None or second_bounds is None:
kept_collision_count += 1
kept_lines.append(line)
continue
separated_axes = [
axis
for axis in range(3)
if first_bounds[1][axis] < second_bounds[0][axis] - tolerance_m
or second_bounds[1][axis] < first_bounds[0][axis] - tolerance_m
]
if not separated_axes:
kept_collision_count += 1
kept_lines.append(line)
continue
removed.append(
{
"first_object_id": first_id,
"second_object_id": second_id,
"reported_detail": match.group("detail"),
"first_world_aabb": first_bounds,
"second_world_aabb": second_bounds,
"separated_axes": separated_axes,
}
)
if not removed:
return report, []
if collision_header_index is not None:
if kept_collision_count:
kept_lines[collision_header_index] = f"Collisions ({kept_collision_count}):"
else:
del kept_lines[collision_header_index]
remaining_violations = sum(1 for line in kept_lines if line.startswith("- "))
if remaining_violations == 0:
return "No physics violations detected. All objects are properly placed.", removed
for index, line in enumerate(kept_lines):
if line.startswith("Physics violations detected ("):
kept_lines[index] = (
f"Physics violations detected ({remaining_violations} issue(s)):"
)
break
return "\n".join(kept_lines), removed
def protected_manipulation_entities(
dependency_graph: dict[str, Any],
baseline: dict[str, Any],
furniture_id: str,
) -> set[str]:
"""Return stable manipulation IDs owned by one furniture support branch."""
record = (baseline.get("objects") or {}).get(furniture_id, {})
support_candidates = {
furniture_id,
str(record.get("object_id") or ""),
str(record.get("name") or ""),
}
support_candidates.discard("")
branch_nodes: set[str] = set()
for branch in dependency_graph.get("branches", []):
if not isinstance(branch, dict):
continue
root = str(branch.get("root_node_id") or "")
if any(
candidate == root or candidate.startswith(f"{root}_")
for candidate in support_candidates
):
branch_nodes.update(str(item) for item in branch.get("node_ids", []))
return {
str(node.get("entity_id") or node.get("node_id"))
for node in dependency_graph.get("nodes", [])
if isinstance(node, dict)
and node.get("stage") == "manipulation"
and str(node.get("node_id")) in branch_nodes
}
def prioritize_manipuland_selections(
selections: list[Any],
object_descriptions: dict[str, str],
critical_support_ids: set[str],
*,
max_contextual_supports: int,
max_items_per_critical_support: int,
max_items_per_contextual_support: int,
) -> tuple[list[Any], dict[str, Any]]:
"""Keep task supports plus a bounded amount of contextual clutter."""
matched_supports: dict[str, str] = {}
critical = []
contextual = []
for selection in selections:
furniture_id = str(selection.furniture_id)
description = object_descriptions.get(furniture_id, "").casefold()
matched = next(
(
support_id
for support_id in sorted(critical_support_ids)
if support_id.casefold() in description
or support_id.casefold().replace("_", " ") in description
),
None,
)
if matched is None:
contextual.append(selection)
else:
matched_supports[matched] = furniture_id
critical.append(selection)
unresolved = sorted(critical_support_ids - set(matched_supports))
fallback = bool(critical_support_ids and unresolved)
chosen = list(selections) if fallback else [*critical, *contextual[:max_contextual_supports]]
critical_furniture = set(matched_supports.values())
capped = []
for selection in chosen:
copied = deepcopy(selection)
limit = (
max_items_per_critical_support
if str(copied.furniture_id) in critical_furniture
else max_items_per_contextual_support
)
suggested = getattr(copied, "suggested_items", [])
if isinstance(suggested, list):
copied.suggested_items = suggested[:limit]
capped.append(copied)
return capped, {
"input_support_count": len(selections),
"selected_support_count": len(capped),
"critical_support_bindings": matched_supports,
"unresolved_critical_supports": unresolved,
"filter_fallback": fallback,
}
def task_graph_manipuland_selections(
context: dict[str, Any],
object_descriptions: dict[str, str],
context_config: dict[str, Any],
selection_class: type,
dependency_graph: dict[str, Any] | None = None,
) -> list[Any] | None:
"""Build exact task-support assignments when the task graph is complete."""
task = context.get("task", {})
entities = {
str(entity.get("entity_id")): entity
for entity in task.get("entities", [])
if entity.get("entity_id")
}
assignments = manipulation_assignments(dependency_graph or {})
if not assignments:
assignments = {}
for predicate in task.get("initial_predicates", []):
if predicate.get("name") not in {"on", "supported_by", "inside"}:
continue
subject = predicate.get("subject")
support = predicate.get("object")
if subject and support:
assignments.setdefault(str(support), []).append(str(subject))
if not assignments:
return None
support_bindings: dict[str, str] = {}
for support_id in assignments:
matches = [
furniture_id
for furniture_id, description in object_descriptions.items()
if support_id.casefold() in description.casefold()
or support_id.casefold().replace("_", " ") in description.casefold()
]
if len(matches) != 1:
return None
support_bindings[support_id] = matches[0]
asset_overrides = context_config.get("task_asset_overrides", {})
graph_nodes = {
str(node["node_id"]): node
for node in (dependency_graph or {}).get("nodes", [])
if isinstance(node, dict) and node.get("node_id")
}
selections = []
for support_id, subjects in assignments.items():
item_lines = []
for subject_id in subjects:
entity = entities.get(subject_id)
if entity is None:
return None
attributes = entity.get("attributes", {})
marker = (
f" [RHG_ASSET_ID={asset_overrides[subject_id]}]"
if subject_id in asset_overrides
else ""
)
item_lines.append(
"REQUIRED: exactly one "
f"{entity.get('category', subject_id)} named {subject_id}; "
f"attributes={json.dumps(attributes, sort_keys=True)}; "
f"depends_on={graph_nodes.get(subject_id, {}).get('depends_on', [support_id])}."
f"{marker} "
"Generate this exact asset once; do not create piles, stacks, "
"duplicates, optional variants, or substitute objects."
)
selections.append(
selection_class(
furniture_id=support_bindings[support_id],
suggested_items="\n".join(item_lines),
prompt_constraints=(
f"Build the declared manipulation subtree rooted at {support_id} in "
"parent-before-child order. Place only the required task objects; "
"preserve grasp access and the humanoid approach corridor. "
"For a single required object, call one-asset generation and one-object "
"placement tools only; never call pile or stack tools. After canonical "
"generation succeeds, its identity and dimensions are frozen: only move "
"the existing object, and never regenerate, rescale, or delete it."
),
style_notes="Sparse task-critical placement; no optional clutter.",
context_furniture_ids=[],
)
)
return selections
def should_try_task_graph(policy: ManipulandSkillPolicy, context: dict[str, Any]) -> bool:
"""Use a complete task graph before optional contextual surface analysis."""
return policy.support_selection_mode == "task_graph_first" and bool(context)
def prepare_native_gltf_supports(
baseline: dict[str, Any], scene_dir: Path, blender_server: Any
) -> dict[str, Any]:
"""Make pre-existing native GLB furniture visible to Drake shard renders."""
converted = []
reused = []
for object_id, record in sorted(baseline.get("objects", {}).items()):
if not isinstance(record, dict):
continue
metadata = record.get("metadata") or {}
geometry_value = record.get("geometry_path")
if metadata.get("asset_source") != "robothousegen" or not geometry_value:
continue
geometry_path = Path(str(geometry_value))
if geometry_path.suffix.lower() != ".glb":
continue
source = geometry_path if geometry_path.is_absolute() else scene_dir / geometry_path
output = source.with_suffix(".gltf")
if output.is_file():
reused.append(str(object_id))
else:
blender_server.convert_glb_to_gltf(
input_path=source,
output_path=output,
export_yup=True,
)
converted.append(str(object_id))
sdf_value = record.get("sdf_path")
if not sdf_value:
raise ValueError(f"native support {object_id} has no SDF path")
sdf_path = Path(str(sdf_value))
if not sdf_path.is_absolute():
sdf_path = scene_dir / sdf_path
tree = ET.parse(sdf_path)
rewritten = 0
already_gltf = 0
for uri in tree.findall(".//mesh/uri"):
if not uri.text:
continue
uri_name = Path(uri.text).name
if uri_name == source.name:
uri.text = output.name
rewritten += 1
elif uri_name == output.name:
already_gltf += 1
if rewritten == 0 and already_gltf == 0:
raise ValueError(
f"native support SDF for {object_id} does not reference {source.name}"
)
if rewritten:
tree.write(sdf_path, encoding="utf-8", xml_declaration=True)
record["geometry_path"] = (
str(output)
if geometry_path.is_absolute()
else str(output.relative_to(scene_dir))
)
return {
"converted_object_ids": converted,
"reused_object_ids": reused,
"prepared_count": len(converted) + len(reused),
}
def parse_gpu_ids(value: str | None) -> set[int] | None:
if value is None or not value.strip():
return None
ids = {int(item.strip()) for item in value.split(",") if item.strip()}
if not ids:
raise ValueError("GPU ID list must contain at least one integer")
return ids
def service_connection_kwargs(coordinator: Any) -> dict[str, Any]:
"""Resolve the service endpoints leased by the parent SceneSmith run."""
def endpoint(name: str, default_port: int) -> tuple[str, int]:
prefix = f"RHG_{name.upper()}_SERVER"
host = os.environ.get(
f"{prefix}_HOST",
str(getattr(coordinator, f"{name}_server_host", "127.0.0.1")),
)
inherited_port = getattr(coordinator, f"{name}_server_port", default_port)
port = int(os.environ.get(f"{prefix}_PORT", str(inherited_port)))
return host, port
geometry_host, geometry_port = endpoint("geometry", 7000)
hssd_host, hssd_port = endpoint("hssd", 7001)
articulated_host, articulated_port = endpoint("articulated", 7002)
materials_host, materials_port = endpoint("materials", 7008)
return {
"geometry_server_host": geometry_host,
"geometry_server_port": geometry_port,
"hssd_server_host": hssd_host,
"hssd_server_port": hssd_port,
"articulated_server_host": articulated_host,
"articulated_server_port": articulated_port,
"materials_server_host": materials_host,
"materials_server_port": materials_port,
}
def merge_scene_states(
baseline: dict[str, Any],
shards: list[tuple[str, dict[str, Any]]],
*,
reject_foreign_mutations: bool = True,
allow_unowned_shards: bool = False,
) -> tuple[dict[str, Any], dict[str, list[str]]]:
"""Merge isolated furniture deltas and reject cross-shard mutation."""
merged = deepcopy(baseline)
base_objects = baseline["objects"]
merged_objects = merged["objects"]
structural_supports = _structural_support_ids(baseline)
additions: dict[str, list[str]] = {}
for furniture_id, state in sorted(shards, key=lambda item: item[0]):
objects = state["objects"]
owner_is_object = furniture_id in base_objects
if (
not allow_unowned_shards
and not owner_is_object
and furniture_id not in structural_supports
):
raise ValueError(f"shard owner is absent from baseline: {furniture_id}")
changed_foreign = [
object_id
for object_id, base_value in base_objects.items()
if object_id != furniture_id
and object_id in objects
and objects[object_id] != base_value
]
removed = sorted(set(base_objects) - set(objects))
if (changed_foreign or removed) and reject_foreign_mutations:
raise ValueError(
f"shard {furniture_id} modified foreign objects: "
f"changed={sorted(changed_foreign)} removed={removed}"
)
if owner_is_object:
if furniture_id not in objects:
raise ValueError(f"shard removed its owner object: {furniture_id}")
merged_objects[furniture_id] = deepcopy(objects[furniture_id])
new_ids = sorted(set(objects) - set(base_objects))
for object_id in new_ids:
merged_id = object_id
if merged_id in merged_objects:
merged_id = f"{furniture_id}__{object_id}"
suffix = 1
while merged_id in merged_objects:
merged_id = f"{furniture_id}__{object_id}_{suffix}"
suffix += 1
record = deepcopy(objects[object_id])
if isinstance(record, dict) and record.get("object_id") == object_id:
record["object_id"] = merged_id
merged_objects[merged_id] = record
additions.setdefault(furniture_id, []).append(merged_id)
additions.setdefault(furniture_id, [])
return merged, additions
def consolidate_branch_assets(branch_dirs: list[Path], destination: Path) -> dict[str, int]:
"""Hard-link isolated branch assets into the merged room-local asset tree."""
destination = destination.resolve()
destination.mkdir(parents=True, exist_ok=True)
linked = 0
reused = 0
merged_registry_entries = 0
normalized_registry_entries = 0
for branch_dir in sorted(path.resolve() for path in branch_dirs):
source_root = branch_dir / "generated_assets"
if not source_root.is_dir():
continue
for source in sorted(source_root.rglob("*")):
if not source.is_file() or source.is_symlink():
continue
relative = source.relative_to(source_root)
target = destination / relative
target.parent.mkdir(parents=True, exist_ok=True)
if source.name == "asset_registry.json":
existing = (
json.loads(target.read_text(encoding="utf-8"))
if target.is_file()
else {}
)
incoming = json.loads(source.read_text(encoding="utf-8"))
if not isinstance(existing, dict) or not isinstance(incoming, dict):
raise ValueError(f"asset registry must contain an object: {relative}")
def rebase(value: Any, source_prefix: str = str(source_root)) -> Any:
if isinstance(value, str):
return value.replace(source_prefix, str(destination))
if isinstance(value, list):
return [rebase(item) for item in value]
if isinstance(value, dict):
return {key: rebase(item) for key, item in value.items()}
return value
rebased = rebase(incoming)
for asset_id, record in rebased.items():
if asset_id in existing and existing[asset_id] != record:
old = existing[asset_id]
old_metadata = old.get("metadata", {}) if isinstance(old, dict) else {}
new_metadata = (
record.get("metadata", {}) if isinstance(record, dict) else {}
)
same_identity = (
isinstance(old, dict)
and isinstance(record, dict)
and old.get("object_id") == record.get("object_id")
and old_metadata.get("robothousegen_asset_id")
== new_metadata.get("robothousegen_asset_id")
)
if not same_identity:
raise ValueError(
f"asset registry collision differs: {relative}:{asset_id}"
)
# Normalize an older projection whose absolute paths still
# point into the immutable isolated subtree. Asset identity
# and all underlying files remain unchanged.
existing[asset_id] = record
normalized_registry_entries += 1
if asset_id not in existing:
existing[asset_id] = record
merged_registry_entries += 1
target.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")
continue
if target.exists():
if target.stat().st_size != source.stat().st_size:
raise ValueError(f"branch asset collision differs: {relative}")
reused += 1
continue
os.link(source, target)
linked += 1
return {
"linked_files": linked,
"reused_files": reused,
"merged_registry_entries": merged_registry_entries,
"normalized_registry_entries": normalized_registry_entries,
}
def _structural_support_ids(state: dict[str, Any]) -> set[str]:
"""Return room-geometry supports that intentionally live outside objects."""
room_geometry = state.get("room_geometry", {})
if not isinstance(room_geometry, dict):
return set()
supports: set[str] = set()
floor = room_geometry.get("floor")
if isinstance(floor, dict) and floor.get("object_id"):
supports.add(str(floor["object_id"]))
ceiling = room_geometry.get("ceiling")
if isinstance(ceiling, dict) and ceiling.get("object_id"):
supports.add(str(ceiling["object_id"]))
return supports
def find_foreign_mutations(
baseline: dict[str, Any], shards: list[tuple[str, dict[str, Any]]]
) -> dict[str, dict[str, list[str]]]:
base_objects = baseline["objects"]
report = {}
for furniture_id, state in shards:
objects = state["objects"]
changed = sorted(
object_id
for object_id, base_value in base_objects.items()
if object_id != furniture_id
and object_id in objects
and objects[object_id] != base_value
)
removed = sorted(set(base_objects) - set(objects))
if changed or removed:
report[furniture_id] = {"changed": changed, "removed": removed}
return report
def _is_oom(error: BaseException) -> bool:
message = str(error).casefold()
return any(
marker in message
for marker in (
"out of memory",
"cuda_error_out_of_memory",
"failed to allocate",
"gpu memory",
)
)
def _shard_process_main(result_path: Path, kwargs: dict[str, Any]) -> None:
"""Execute one shard in its own process group and persist a bounded result."""
os.setsid()
envelope: dict[str, Any]
try:
furniture_id, state, timing = _run_one_shard(**kwargs)
envelope = {
"status": "complete",
"furniture_id": furniture_id,
"state": state,
"timing": timing,
}
except BaseException as error:
envelope = {
"status": "failed",
"error": repr(error),
"traceback": traceback.format_exc(),
}
temporary = result_path.with_suffix(".tmp")
temporary.write_text(json.dumps(envelope), encoding="utf-8")
temporary.replace(result_path)
def _terminate_process_group(process: multiprocessing.Process) -> None:
if process.pid is None or not process.is_alive():
return
try:
if os.getpgid(process.pid) == process.pid:
os.killpg(process.pid, signal.SIGTERM)
else:
process.terminate()
except ProcessLookupError:
return
process.join(timeout=10)
if process.is_alive():
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
process.join(timeout=10)
def _run_one_shard_isolated(
*,
baseline: dict[str, Any],
selection: Any,
output_root: Path,
shard_timeout_s: float,
fallback_on_timeout: bool,
_process_target: Any = _shard_process_main,
**kwargs: Any,
) -> tuple[str, dict[str, Any], dict[str, Any]]:
"""Enforce a real wall-clock deadline around blocking model and render calls."""
furniture_id = str(selection.furniture_id)
shard_root = output_root / furniture_id
shard_root.mkdir(parents=True, exist_ok=True)
result_path = shard_root / "shard_process_result.json"
result_path.unlink(missing_ok=True)
process_kwargs = {
**kwargs,
"baseline": baseline,
"selection": selection,
"output_root": output_root,
"shard_timeout_s": shard_timeout_s,
"fallback_on_timeout": fallback_on_timeout,
}
# Never fork a process that has imported bpy. Blender starts native worker
# threads during import, and forking that state can leave the child blocked
# before the shard target is entered. ``spawn`` costs one clean import per
# shard, but is safe when coordinator threads launch workers.
context = multiprocessing.get_context("spawn")
process = context.Process(
target=_process_target,
args=(result_path, process_kwargs),
name=f"rhg-manipuland-{furniture_id}",
)
started = time.time()
# SceneSmith is launched as a script whose main module imports Blender-only
# _bpy. multiprocessing otherwise re-runs that script in every child. Point
# the bootstrap at this side-effect-free module only while preparation data
# is captured, then immediately restore the real Hydra entry point.
import __main__
with _PROCESS_START_LOCK:
original_main_file = getattr(__main__, "__file__", None)
__main__.__file__ = str(
Path(__file__).with_name("scenesmith_process_bootstrap.py").resolve()
)
try:
process.start()
finally:
if original_main_file is None:
delattr(__main__, "__file__")
else:
__main__.__file__ = original_main_file
process.join(timeout=shard_timeout_s)
if process.is_alive():
_terminate_process_group(process)
timing = {
"furniture_id": furniture_id,
"status": "timeout_fallback" if fallback_on_timeout else "timeout",
"started_unix": started,
"duration_s": round(time.time() - started, 3),
"timeout_s": shard_timeout_s,
"selection": serialize_selection(selection),
"attempts": [],
}
if fallback_on_timeout:
(shard_root / "shard_scene_state.json").write_text(
json.dumps(baseline, indent=2), encoding="utf-8"
)
return furniture_id, deepcopy(baseline), timing
raise TimeoutError(
f"task-critical Manipuland shard {furniture_id} exceeded {shard_timeout_s}s"
)
if not result_path.is_file():
raise RuntimeError(
f"Manipuland shard {furniture_id} exited with code {process.exitcode} "
"without a result"
)
envelope = json.loads(result_path.read_text(encoding="utf-8"))
if envelope.get("status") != "complete":
raise RuntimeError(
f"Manipuland shard {furniture_id} failed: {envelope.get('error')}\n"
f"{envelope.get('traceback', '')}"
)
return envelope["furniture_id"], envelope["state"], envelope["timing"]
def apply_request_manipuland_policy(
policy: ManipulandSkillPolicy, config: dict[str, Any]
) -> ManipulandSkillPolicy:
"""Apply the small, validated per-benchmark budget surface."""
overrides = config.get("manipuland_policy", {})
if not overrides:
return policy
allowed = {
"critical_shard_timeout_s",
"contextual_shard_timeout_s",
"max_contextual_supports",
"max_items_per_critical_support",
"max_items_per_contextual_support",
}
unknown = sorted(set(overrides) - allowed)
if unknown:
raise ValueError(f"unsupported manipuland_policy fields: {unknown}")
payload = policy.model_dump()
payload.update(overrides)
return ManipulandSkillPolicy.model_validate(payload)
def _furniture_subtree_specs() -> list[dict[str, Any]]:
graph_path = Path(os.environ.get("RHG_SCENE_DEPENDENCY_GRAPH_FILE", ""))
context_path = Path(os.environ.get("RHG_SCENE_CONTEXT_FILE", ""))
if not graph_path.is_file() or not context_path.is_file():
return []
graph = json.loads(graph_path.read_text(encoding="utf-8"))
context = json.loads(context_path.read_text(encoding="utf-8"))
nodes = {str(node["node_id"]): node for node in graph.get("nodes", [])}
entities = {
str(entity["entity_id"]): entity
for entity in (context.get("task") or {}).get("entities", [])
if entity.get("entity_id")
}
planning_path = Path(os.environ.get("RHG_PLANNING_AGENT_OUTPUT_FILE", ""))
if planning_path.is_file():
planning = json.loads(planning_path.read_text(encoding="utf-8"))
partitions = [
{
"branch_id": subtree["subtree_id"],
"root_node_id": subtree["root_node_id"],
"node_ids": subtree["node_ids"],
"critical": subtree.get("critical", True),
}
for subtree in planning.get("subtrees", [])
]
else:
partitions = graph.get("branches", [])
specs = []
for branch in partitions:
furniture_nodes = [
nodes[node_id]
for node_id in branch.get("node_ids", [])
if node_id in nodes
and nodes[node_id].get("stage") == "furniture"
and nodes[node_id].get("entity_id")
]
if not furniture_nodes:
continue
entity_ids = [str(node["entity_id"]) for node in furniture_nodes]
descriptions = [
{
"entity_id": entity_id,
"category": entities.get(entity_id, {}).get("category"),
"attributes": entities.get(entity_id, {}).get("attributes", {}),
}
for entity_id in entity_ids
]
specs.append(
{
"subtree_id": str(branch["branch_id"]),
"root_node_id": str(branch["root_node_id"]),
"entity_ids": entity_ids,
"entities": descriptions,
"critical": bool(branch.get("critical", True)),
}
)
return specs
def _subtree_has_locked_furniture_pose(spec: dict[str, Any]) -> bool:
"""Return true when every owned item has a complete benchmark-locked pose.
SceneSmith's natural placement noise is useful for open-ended generation, but
it must not perturb an explicitly declared comparison layout. Besides making
exact and DAG profiles incomparable, the drift can reintroduce opening and
corridor violations after an Agent has already selected the intended pose.
"""
entities = spec.get("entities")
if not isinstance(entities, list) or not entities:
return False
for entity in entities:
attributes = entity.get("attributes", {}) if isinstance(entity, dict) else {}
center = attributes.get("placement_center_m")
if (
not attributes.get("asset_id")
or not isinstance(center, list)
or len(center) != 2
or "yaw_deg" not in attributes
):
return False
return True
def _force_locked_furniture_placement(worker: Any, perfect_mode: Any) -> None:
"""Force the agent's lazily-created furniture tools to remain noise-free."""
original_create = worker._create_designer_tools
original_set = worker._set_placement_noise_profile
def create_designer_tools(self: Any) -> list[Any]:
tools = original_create()
self.furniture_tools.set_noise_profile(perfect_mode)
return tools
def set_placement_noise_profile(_self: Any, _requested_mode: Any) -> None:
# The planner may request ``natural`` after inspecting the prose. For a
# benchmark-locked pose this would violate the declared input contract.
original_set(perfect_mode)
worker._create_designer_tools = types.MethodType(create_designer_tools, worker)
worker._set_placement_noise_profile = types.MethodType(
set_placement_noise_profile, worker
)
def _repair_furniture_entity_ids() -> set[str] | None:
"""Return the exact failed furniture entities requested by Supervisor."""
raw = os.environ.get("RHG_REPAIR_PLAN", "").strip()
if not raw:
return None
try:
plan = json.loads(raw)
except json.JSONDecodeError:
return None
entity_ids: set[str] = set()
scoped_step = False
for step in plan.get("steps", []):
if step.get("action") != "rerun_branch" or step.get("stage") != "furniture":
continue
scoped_step = True
entity_ids.update(str(item) for item in step.get("entity_ids", []) if item)
return entity_ids if scoped_step and entity_ids else None
def _score_floor(scores_path: Path) -> float | None:
try:
payload = yaml.safe_load(scores_path.read_text(encoding="utf-8")) or {}
except (OSError, yaml.YAMLError):
return None
grades = [
float(value["grade"])
for value in payload.values()
if isinstance(value, dict) and isinstance(value.get("grade"), (int, float))
]
return min(grades) if grades else None
def _cached_furniture_subtree(
resume_root: Path,
subtree_id: str,
*,
critic_min_score: float,
) -> tuple[dict[str, Any], Path, float] | None:
"""Load an accepted immutable subtree result from the parent checkpoint."""
safe_id = subtree_id.replace(":", "__").replace("/", "_")
pattern = (
"scene_*/room_*/parallel_base_branches/furniture/"
f"parallel_furniture_subtrees/{safe_id}"
)
matches = sorted(resume_root.glob(pattern))
if len(matches) != 1:
return None
branch_dir = matches[0]
snapshot = branch_dir / "subtree_result.json"
metadata = branch_dir / "subtree_result_meta.json"
if snapshot.is_file() and metadata.is_file():
try:
state = json.loads(snapshot.read_text(encoding="utf-8"))
meta = json.loads(metadata.read_text(encoding="utf-8"))
score = float(meta["critic_min_score"])
except (OSError, ValueError, KeyError, TypeError):
pass
else:
if score >= critic_min_score and isinstance(state.get("objects"), dict):
return state, branch_dir, score
render_roots = sorted(
branch_dir.glob("scene_renders/furniture/renders_*"), reverse=True
)
for render_root in render_roots:
scores = render_root / "scores.yaml"
state_path = render_root / "scene_state.json"
score = _score_floor(scores)
if score is None or score < critic_min_score or not state_path.is_file():
continue
try:
state = json.loads(state_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
continue
if isinstance(state.get("objects"), dict):
return state, branch_dir, score
return None
def run_parallel_furniture_subtrees(coordinator: Any, scene: Any) -> Any:
"""Run one real Stateful Furniture Agent per independent support/motif subtree."""
specs = _furniture_subtree_specs()
enabled = os.environ.get("RHG_AGENT_ORCHESTRATION_MODE", "legacy") == "dag_agents"
if not enabled or len(specs) <= 1:
asyncio.run(coordinator.add_furniture(scene=scene))
return scene
baseline = scene.to_state_dict()
baseline_hash = scene.content_hash()
output_root = scene.scene_dir / "parallel_furniture_subtrees"
output_root.mkdir(parents=True, exist_ok=True)
worker_limit = int(os.environ.get("RHG_FURNITURE_SUBTREE_WORKERS", "8"))
repair_entity_ids = _repair_furniture_entity_ids()
active_specs = list(specs)
cached_results: list[tuple[str, dict[str, Any]]] = []
cached_timings: list[dict[str, Any]] = []
cached_asset_dirs: list[Path] = []
if repair_entity_ids:
resume_value = os.environ.get("RHG_SCENESMITH_RESUME_FROM", "")
resume_root = Path(resume_value) if resume_value else None
if resume_root is not None and resume_root.is_dir():
active_specs = []
critic_min_score = load_scenesmith_skill_policy().furniture.early_finish_min_score
for spec in specs:
owned = {str(item) for item in spec["entity_ids"]}
if owned & repair_entity_ids:
active_specs.append(spec)
continue
cached = _cached_furniture_subtree(
resume_root,
str(spec["subtree_id"]),
critic_min_score=critic_min_score,
)
if cached is None:
active_specs.append(spec)
continue
state, branch_dir, score = cached
cached_results.append((str(spec["subtree_id"]), state))
cached_asset_dirs.append(branch_dir)
cached_timings.append(
{
"task_id": f"generation:{spec['subtree_id']}",
"role": "generation",
"status": "reused",
"subtree_id": str(spec["subtree_id"]),
"owned_entity_ids": spec["entity_ids"],
"critic_min_score": score,
"source_checkpoint": str(branch_dir),
"duration_s": 0.0,
}
)
worker_count = max(1, min(worker_limit, len(active_specs) or 1))
allowed = parse_gpu_ids(
os.environ.get("RHG_FURNITURE_GPU_IDS")
or os.environ.get("SCENESMITH_GPU_IDS")
or os.environ.get("CUDA_VISIBLE_DEVICES")
)
gpu_pool = DynamicGpuPool(
Path(os.environ.get("RHG_GPU_LOCK_ROOT", str(output_root / "gpu_locks"))),
allowed_ids=allowed,
min_free_vram_mb=int(os.environ.get("RHG_FURNITURE_MIN_FREE_VRAM_MB", "8192")),
max_used_vram_mb=int(os.environ.get("RHG_FURNITURE_MAX_USED_VRAM_MB", str(1 << 30))),
max_utilization_percent=int(
os.environ.get("RHG_FURNITURE_MAX_GPU_UTILIZATION", "100")
),
)
connections = service_connection_kwargs(coordinator)
agent_class = type(coordinator)
cfg = coordinator.cfg
logger_class = type(coordinator.logger)
scene_class = type(scene)
coordinator.cleanup()
def run_one(spec: dict[str, Any]) -> tuple[str, dict[str, Any], dict[str, Any]]:
scheduled = time.time()
lease = gpu_pool.acquire(
timeout_s=float(os.environ.get("RHG_GPU_WAIT_TIMEOUT_S", "2700"))
)
started = time.time()
worker = None
subtree_id = str(spec["subtree_id"])
safe_id = subtree_id.replace(":", "__").replace("/", "_")
try:
shard_root = output_root / safe_id
shard_root.mkdir(parents=True, exist_ok=True)
logger = logger_class(output_dir=shard_root)
shard_scene = scene_class(room_geometry=None, scene_dir=shard_root)
shard_scene.restore_from_state_dict(deepcopy(baseline))
shard_scene.text_description = (
f"{scene.text_description}\n\n"
"RoboHouseGen subtree ownership contract: generate and place exactly the "
f"following owned furniture entities and no other furniture: "
f"{json.dumps(spec['entities'], ensure_ascii=False, sort_keys=True)}. "
"Do not modify architecture or any foreign subtree. Preserve the stable entity "
"IDs in names, descriptions, and audit output. During this isolated subtree "
"critique, other furniture subtrees are intentionally absent. Do not reduce any "
"Realism, Functionality, Layout, Holistic Completeness, Prompt Following, or "
"Reachability grade because foreign furniture, the full room arrangement, or the "
"merged task scene is absent. Evaluate only the owned entities, their asset "
"quality, scale, floor contact, architecture clearance, and declared local "
"relations. Cross-subtree completeness is exclusively a Global Critic concern."
)
worker = agent_class(
cfg=deepcopy(cfg),
logger=logger,
num_workers=worker_count,
render_gpu_id=lease.gpu.index,
**connections,
)
if _subtree_has_locked_furniture_pose(spec):
# Import from the per-run SceneSmith overlay, never from or into
# the shared read-only checkout.
from scenesmith.agent_utils.placement_noise import PlacementNoiseMode
_force_locked_furniture_placement(worker, PlacementNoiseMode.PERFECT)
asyncio.run(worker.add_furniture(scene=shard_scene))
state = shard_scene.to_state_dict()
score_candidates = [
score
for path in shard_root.glob("**/scores.yaml")
if (score := _score_floor(path)) is not None
]
minimum_score = max(score_candidates) if score_candidates else 0.0
(shard_root / "subtree_result.json").write_text(
json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8"
)
(shard_root / "subtree_result_meta.json").write_text(
json.dumps(
{
"schema_version": "1.0",
"baseline_hash": baseline_hash,
"critic_min_score": minimum_score,
"owned_entity_ids": spec["entity_ids"],
},
indent=2,
sort_keys=True,
)
+ "\n",
encoding="utf-8",
)
additions = sorted(set(state.get("objects", {})) - set(baseline.get("objects", {})))
if not additions:
raise RuntimeError(f"furniture subtree {subtree_id} generated no objects")
completed = time.time()
return subtree_id, state, {
"task_id": f"generation:{subtree_id}",
"role": "generation",
"status": "complete",
"subtree_id": subtree_id,
"owned_entity_ids": spec["entity_ids"],
"added_object_ids": additions,
"gpu_id": lease.gpu.index,
"model": str(getattr(cfg.openai, "model", "unknown")),
"reasoning_effort": "medium",
"scheduled_unix": scheduled,
"lease_acquired_unix": started,
"started_unix": started,
"completed_unix": completed,
"queue_duration_s": round(started - scheduled, 3),
"duration_s": round(completed - started, 3),
"total_duration_s": round(completed - scheduled, 3),
}
finally:
if worker is not None:
worker.cleanup()
lease.close()
results: list[tuple[str, dict[str, Any]]] = list(cached_results)
timings: list[dict[str, Any]] = list(cached_timings)
parallel_started = time.time()
if active_specs:
with ThreadPoolExecutor(
max_workers=worker_count, thread_name_prefix="rhg-furniture-subtree"
) as pool:
futures = [pool.submit(run_one, spec) for spec in active_specs]
for future in as_completed(futures):
subtree_id, state, timing = future.result()
results.append((subtree_id, state))
timings.append(timing)
merged, additions = merge_scene_states(
baseline,
results,
reject_foreign_mutations=True,
allow_unowned_shards=True,
)
# Subtree RoomScene records are restored into the parent room and therefore
# resolve generated asset paths relative to the parent ``scene_dir``. Keep
# the immutable subtree copies for audit, but materialize hard links in the
# canonical room-local asset tree before manipulation workers consume them.
subtree_dirs = [
output_root
/ str(spec["subtree_id"]).replace(":", "__").replace("/", "_")
for spec in active_specs
] + cached_asset_dirs
asset_merge = consolidate_branch_assets(
subtree_dirs,
scene.scene_dir / "generated_assets",
)
scene.restore_from_state_dict(merged)
timing = {
"schema_version": "1.0",
"mode": "parallel_agent_subtrees",
"baseline_hash": baseline_hash,
"worker_count": worker_count,
"max_observed_concurrency": maximum_interval_concurrency(timings),
"repair_entity_ids": sorted(repair_entity_ids or []),
"reused_subtrees": sorted(item[0] for item in cached_results),
"subtrees": sorted(timings, key=lambda item: item["subtree_id"]),
"additions": additions,
"asset_merge": asset_merge,
"parallel_stage_duration_s": round(time.time() - parallel_started, 3),
}
(output_root / "timing.json").write_text(
json.dumps(timing, indent=2), encoding="utf-8"
)
return scene
def _run_one_shard(
*,
agent_class: type,
cfg: Any,
logger_class: type,
scene_class: type,
baseline: dict[str, Any],
scene_dir: Path,
selection: Any,
worker_count: int,
gpu_pool: DynamicGpuPool,
output_root: Path,
oom_retries: int,
service_connections: dict[str, Any],
item_limit: int,
shard_timeout_s: float,
fallback_on_timeout: bool,
) -> tuple[str, dict[str, Any], dict[str, Any]]:
furniture_id = str(selection.furniture_id)
attempted_gpus: set[int] = set()
started = time.time()
attempts: list[dict[str, Any]] = []
for attempt in range(oom_retries + 1):
lease = gpu_pool.acquire(
timeout_s=float(os.environ.get("RHG_GPU_WAIT_TIMEOUT_S", "2700")),
excluded_ids=attempted_gpus,
)
gpu_id = lease.gpu.index
attempted_gpus.add(gpu_id)
attempt_started = time.time()
worker = None
stateful_module = None
original_surface_extractor = None
try:
shard_root = output_root / furniture_id
shard_root.mkdir(parents=True, exist_ok=True)
logger = logger_class(output_dir=shard_root)
shard_scene = scene_class(room_geometry=None, scene_dir=scene_dir)
shard_scene.restore_from_state_dict(deepcopy(baseline))
shard_cfg = deepcopy(cfg)
from omegaconf import OmegaConf
OmegaConf.update(
shard_cfg, "rhg_item_limit", item_limit, force_add=True
)
worker = agent_class(
cfg=shard_cfg,
logger=logger,
num_workers=worker_count,
render_gpu_id=gpu_id,
**service_connections,
)
async def fixed_analysis(_self: Any, _scene: Any) -> list[Any]:
return [deepcopy(selection)]
worker._analyze_furniture_for_placement = types.MethodType( # noqa: SLF001
fixed_analysis, worker
)
graph_path = Path(os.environ.get("RHG_SCENE_DEPENDENCY_GRAPH_FILE", ""))
runtime_dependency_graph = (
json.loads(graph_path.read_text(encoding="utf-8"))
if graph_path.is_file()
else {}
)
protected_ids = protected_manipulation_entities(
runtime_dependency_graph, baseline, furniture_id
)
tool_guard_events: list[dict[str, Any]] = []
generated_once: set[str] = set()
tool_guard_path = shard_root / "critical_entity_tool_guard.json"
def protected_id(
object_id: str, _protected_ids: set[str] = protected_ids
) -> str | None:
return next(
(
entity_id
for entity_id in sorted(_protected_ids)
if object_id == entity_id
or object_id.startswith(f"{entity_id}_")
),
None,
)
def record_guard(
action: str,
entity_ids: list[str],
reason: str,
_events: list[dict[str, Any]] = tool_guard_events,
_path: Path = tool_guard_path,
_protected_ids: set[str] = protected_ids,
) -> str:
event = {
"timestamp_unix": time.time(),
"action": action,
"entity_ids": entity_ids,
"status": "rejected",
"reason": reason,
}
_events.append(event)
_path.write_text(
json.dumps(
{
"schema_version": "1.0",
"protected_entity_ids": sorted(_protected_ids),
"events": _events,
},
indent=2,
),
encoding="utf-8",
)
return json.dumps(
{
"success": False,
"error_type": "critical_entity_frozen",
"message": reason,
"entity_ids": entity_ids,
}
)
original_remove = worker._remove_manipuland_impl # noqa: SLF001
original_rescale = worker._rescale_manipuland_impl # noqa: SLF001
original_generate = worker._generate_assets_impl # noqa: SLF001
def guarded_remove(
_self: Any,
object_id: str,
_protected_id: Any = protected_id,
_record_guard: Any = record_guard,
_original_remove: Any = original_remove,
**kwargs: Any,
) -> str:
entity_id = _protected_id(str(object_id))
if entity_id is not None:
return _record_guard(
"remove_manipuland",
[entity_id],
f"Critical entity {entity_id} is frozen; move it instead of "
"deleting or replacing it inside the local Agent.",
)
return _original_remove(object_id=object_id, **kwargs)
def guarded_rescale(
_self: Any,
object_id: str,
scale_factor: float,
_protected_id: Any = protected_id,
_record_guard: Any = record_guard,
_original_rescale: Any = original_rescale,
**kwargs: Any,
) -> str:
entity_id = _protected_id(str(object_id))
if entity_id is not None:
return _record_guard(
"rescale_manipuland",
[entity_id],
f"Critical entity {entity_id} has canonical dimensions and "
"cannot be scaled; correct its transform or report infeasible.",
)
return _original_rescale(
object_id=object_id, scale_factor=scale_factor, **kwargs
)
def guarded_generate(
_self: Any,
request: Any,
_protected_id: Any = protected_id,
_generated_once: set[str] = generated_once,
_record_guard: Any = record_guard,
_original_generate: Any = original_generate,
) -> str:
requested = [
str(item)
for item in (getattr(request, "short_names", None) or [])
]
repeated = sorted(
entity_id
for name in requested
if (entity_id := _protected_id(name)) in _generated_once
)
if repeated:
return _record_guard(
"generate_manipuland_assets",
repeated,
"Canonical generation already succeeded for "
f"{', '.join(repeated)}; reuse the listed asset and only "
"adjust its transform.",
)
result = _original_generate(request)
try:
payload = json.loads(result)
except (TypeError, json.JSONDecodeError):
payload = {}
if payload.get("success"):
_generated_once.update(
entity_id
for name in requested
if (entity_id := _protected_id(name)) is not None
)
return result
worker._remove_manipuland_impl = types.MethodType( # noqa: SLF001
guarded_remove, worker
)
worker._rescale_manipuland_impl = types.MethodType( # noqa: SLF001
guarded_rescale, worker
)
worker._generate_assets_impl = types.MethodType( # noqa: SLF001
guarded_generate, worker
)
original_request_critique = worker._request_critique_impl # noqa: SLF001
support_projection_ledger: list[dict[str, Any]] = []
async def critique_with_declared_support_projection(
_self: Any,
*args: Any,
_graph: dict[str, Any] = runtime_dependency_graph,
_ledger: list[dict[str, Any]] = support_projection_ledger,
_shard_root: Path = shard_root,
_request_critique: Any = original_request_critique,
**kwargs: Any,
) -> Any:
corrections = project_declared_support_chain(
_self.scene, _graph
)
if corrections:
_ledger.extend(corrections)
_self.rendering_manager.clear_cache()
(_shard_root / "support_projection_ledger.json").write_text(
json.dumps(
{
"schema_version": "1.0",
"status": "applied",
"corrections": _ledger,
},
indent=2,
),
encoding="utf-8",
)
return await _request_critique(*args, **kwargs)
worker._request_critique_impl = types.MethodType( # noqa: SLF001
critique_with_declared_support_projection, worker
)
support_kind = furniture_id.casefold()
if any(
token in support_kind
for token in ("counter", "table", "desk", "workbench", "stove")
):
import scenesmith.manipuland_agents.stateful_manipuland_agent as stateful_module
original_surface_extractor = (
stateful_module.extract_and_propagate_support_surfaces
)
surface_limit = max(
1, int(os.environ.get("RHG_TASK_SUPPORT_SURFACE_LIMIT", "6"))
)
def bounded_surface_extractor(
*args: Any,
_extractor: Any = original_surface_extractor,
_limit: int = surface_limit,
**kwargs: Any,
) -> list[Any]:
surfaces = list(_extractor(*args, **kwargs))
if len(surfaces) <= _limit:
return surfaces
def rank(surface: Any) -> tuple[float, float]:
translation = surface.transform.translation()
world_top = float(translation[2] + surface.bounding_box_max[2])
return world_top, float(surface.area)
highest = max(rank(surface)[0] for surface in surfaces)
top_band = [
surface
for surface in surfaces
if rank(surface)[0] >= highest - 0.05
]
selected = sorted(top_band, key=rank, reverse=True)[:_limit]
furniture = kwargs.get("furniture_object")
if furniture is not None:
furniture.support_surfaces = selected
return selected
stateful_module.extract_and_propagate_support_surfaces = (
bounded_surface_extractor
)
try:
asyncio.run(
asyncio.wait_for(
worker.add_manipulands(scene=shard_scene),
timeout=shard_timeout_s,
)
)
except TimeoutError:
if not fallback_on_timeout:
raise
state = deepcopy(baseline)
state_path = shard_root / "shard_scene_state.json"
state_path.write_text(json.dumps(state, indent=2), encoding="utf-8")
attempts.append(
{
"attempt": attempt + 1,
"gpu_id": gpu_id,
"status": "timeout_fallback",
"duration_s": round(time.time() - attempt_started, 3),
"timeout_s": shard_timeout_s,
}
)
return furniture_id, state, {
"furniture_id": furniture_id,
"status": "timeout_fallback",
"started_unix": started,
"duration_s": round(time.time() - started, 3),
"selection": serialize_selection(selection),
"attempts": attempts,
}
state = shard_scene.to_state_dict()
state_path = shard_root / "shard_scene_state.json"
state_path.write_text(json.dumps(state, indent=2), encoding="utf-8")
attempts.append(
{
"attempt": attempt + 1,
"gpu_id": gpu_id,
"status": "complete",
"duration_s": round(time.time() - attempt_started, 3),
}
)
return furniture_id, state, {
"furniture_id": furniture_id,
"status": "complete",
"started_unix": started,
"duration_s": round(time.time() - started, 3),
"selection": serialize_selection(selection),
"attempts": attempts,
}
except BaseException as error:
attempts.append(
{
"attempt": attempt + 1,
"gpu_id": gpu_id,
"status": "oom" if _is_oom(error) else "failed",
"duration_s": round(time.time() - attempt_started, 3),
"error": repr(error),
}
)
if not _is_oom(error) or attempt >= oom_retries:
raise
finally:
if stateful_module is not None and original_surface_extractor is not None:
stateful_module.extract_and_propagate_support_surfaces = (
original_surface_extractor
)
if worker is not None:
worker.cleanup()
lease.close()
raise AssertionError("unreachable shard retry state")
def run_parallel_manipulands(coordinator: Any, scene: Any) -> Any:
"""Run independent furniture workflows concurrently and merge their deltas."""
from scenesmith.agent_utils.room import RoomScene
from scenesmith.utils.logging import ConsoleLogger
worker_limit = int(os.environ.get("RHG_MANIPULAND_PARALLEL_WORKERS", "0"))
if worker_limit < 0:
raise ValueError("RHG_MANIPULAND_PARALLEL_WORKERS must be non-negative")
baseline = scene.to_state_dict()
native_proxy_preparation = prepare_native_gltf_supports(
baseline,
scene.scene_dir,
coordinator.blender_server,
)
skill_policy = load_scenesmith_skill_policy().manipuland
request_config_path = Path(os.environ.get("RHG_CONTEXT_ASSET_CONFIG", ""))
request_config = (
json.loads(request_config_path.read_text(encoding="utf-8"))
if request_config_path.is_file()
else {}
)
skill_policy = apply_request_manipuland_policy(skill_policy, request_config)
context_path = Path(os.environ.get("RHG_SCENE_CONTEXT_FILE", ""))
context = (
json.loads(context_path.read_text(encoding="utf-8"))
if context_path.is_file()
else {}
)
dependency_graph_path = Path(os.environ.get("RHG_SCENE_DEPENDENCY_GRAPH_FILE", ""))
dependency_graph = (
json.loads(dependency_graph_path.read_text(encoding="utf-8"))
if dependency_graph_path.is_file()
else {}
)
graph_worker_limit = int(
(dependency_graph.get("scheduler") or {}).get("max_parallel_branches", 0)
)
if graph_worker_limit > 0:
worker_limit = (
min(worker_limit, graph_worker_limit) if worker_limit > 0 else graph_worker_limit
)
descriptions = {
str(object_id): " ".join(
str(record.get(key, "")) for key in ("object_id", "name", "description")
)
for object_id, record in baseline.get("objects", {}).items()
if isinstance(record, dict)
}
analysis_started = time.time()
selections = None
analysis_mode = "vlm"
if should_try_task_graph(skill_policy, context):
from scenesmith.agent_utils.scene_analyzer import FurnitureSelection
selections = task_graph_manipuland_selections(
context,
descriptions,
request_config,
FurnitureSelection,
dependency_graph,
)
if selections is not None:
analysis_mode = "task_graph"
if selections is None:
selections = asyncio.run( # noqa: SLF001
coordinator._analyze_furniture_for_placement(scene)
)
analysis_duration = time.time() - analysis_started
if not selections:
return scene
if context:
selections, selection_report = prioritize_manipuland_selections(
selections,
descriptions,
task_support_ids(context, dependency_graph),
max_contextual_supports=skill_policy.max_contextual_supports,
max_items_per_critical_support=skill_policy.max_items_per_critical_support,
max_items_per_contextual_support=skill_policy.max_items_per_contextual_support,
)
else:
selection_report = {
"input_support_count": len(selections),
"selected_support_count": len(selections),
"filter_fallback": True,
"reason": "scene context unavailable; preserving all supports",
}
baseline_hash = scene.content_hash()
worker_count = len(selections) if worker_limit == 0 else min(worker_limit, len(selections))
output_root = scene.scene_dir / "parallel_manipulands"
output_root.mkdir(parents=True, exist_ok=True)
allowed = parse_gpu_ids(
os.environ.get("RHG_MANIPULAND_GPU_IDS")
or os.environ.get("SCENESMITH_GPU_IDS")
or os.environ.get("CUDA_VISIBLE_DEVICES")
)
gpu_pool = DynamicGpuPool(
Path(os.environ.get("RHG_GPU_LOCK_ROOT", str(output_root / "gpu_locks"))),
allowed_ids=allowed,
min_free_vram_mb=int(os.environ.get("RHG_MANIPULAND_MIN_FREE_VRAM_MB", "8192")),
max_used_vram_mb=int(os.environ.get("RHG_MANIPULAND_MAX_USED_VRAM_MB", str(1 << 30))),
max_utilization_percent=int(
os.environ.get("RHG_MANIPULAND_MAX_GPU_UTILIZATION", "100")
),
)
service_connections = service_connection_kwargs(coordinator)
coordinator.cleanup()
critical_furniture_ids = set(
selection_report.get("critical_support_bindings", {}).values()
)
conservative_limits = bool(selection_report.get("filter_fallback"))
item_limits = {
str(selection.furniture_id): (
skill_policy.max_items_per_critical_support
if conservative_limits
or str(selection.furniture_id) in critical_furniture_ids
else skill_policy.max_items_per_contextual_support
)
for selection in selections
}
shard_deadlines = {
str(selection.furniture_id): (
skill_policy.critical_shard_timeout_s
if conservative_limits
or str(selection.furniture_id) in critical_furniture_ids
else skill_policy.contextual_shard_timeout_s
)
for selection in selections
}
started = time.time()
results: list[tuple[str, dict[str, Any]]] = []
timings: list[dict[str, Any]] = []
import scenesmith.agent_utils.base_stateful_agent as base_stateful_module
import scenesmith.manipuland_agents.tools.vision_tools as vision_tools_module
original_base_physics_check = base_stateful_module.check_physics_violations
original_vision_physics_check = vision_tools_module.check_physics_violations
physics_filter_events: list[dict[str, Any]] = []
physics_filter_lock = threading.Lock()
def geometry_sanity_checked_physics(*args: Any, **kwargs: Any) -> str:
report = original_base_physics_check(*args, **kwargs)
runtime_scene = kwargs.get("scene") or (args[0] if args else None)
filtered, removed = filter_disjoint_collision_report(report, runtime_scene)
if removed:
with physics_filter_lock:
physics_filter_events.append(
{
"timestamp_unix": time.time(),
"current_furniture_id": str(
kwargs.get("current_furniture_id") or ""
),
"removed_false_positive_collisions": removed,
}
)
return filtered
# Both modules import the function directly, so patch their adapter-local
# bindings for the duration of the isolated manipulation shards.
base_stateful_module.check_physics_violations = geometry_sanity_checked_physics
vision_tools_module.check_physics_violations = geometry_sanity_checked_physics
try:
with ThreadPoolExecutor(
max_workers=worker_count, thread_name_prefix="rhg-furniture"
) as pool:
futures = [
pool.submit(
_run_one_shard_isolated,
agent_class=type(coordinator),
cfg=coordinator.cfg,
logger_class=ConsoleLogger,
scene_class=RoomScene,
baseline=baseline,
scene_dir=scene.scene_dir,
selection=selection,
worker_count=worker_count,
gpu_pool=gpu_pool,
output_root=output_root,
oom_retries=int(
os.environ.get("RHG_MANIPULAND_OOM_RETRIES", "2")
),
service_connections=service_connections,
item_limit=item_limits[str(selection.furniture_id)],
shard_timeout_s=shard_deadlines[str(selection.furniture_id)],
fallback_on_timeout=(
not conservative_limits
and str(selection.furniture_id)
not in critical_furniture_ids
),
)
for selection in selections
]
for future in as_completed(futures):
furniture_id, state, timing = future.result()
results.append((furniture_id, state))
timings.append(timing)
finally:
base_stateful_module.check_physics_violations = original_base_physics_check
vision_tools_module.check_physics_violations = original_vision_physics_check
(output_root / "physics_collision_sanity.json").write_text(
json.dumps(
{
"schema_version": "1.0",
"policy": "reject_narrow_phase_collision_when_world_aabbs_disjoint",
"events": physics_filter_events,
},
indent=2,
),
encoding="utf-8",
)
merge_started = time.time()
ignored_foreign_mutations = find_foreign_mutations(baseline, results)
merged, additions = merge_scene_states(
baseline, results, reject_foreign_mutations=False
)
scene.restore_from_state_dict(merged)
planned_assignments = manipulation_assignments(dependency_graph)
expected_by_furniture = {
str(furniture_id): planned_assignments[support_id]
for support_id, furniture_id in selection_report.get(
"critical_support_bindings", {}
).items()
if support_id in planned_assignments
}
branch_completion, failed_critical_branches = evaluate_branch_completion(
additions, expected_by_furniture
)
timing = {
"schema_version": "1.0",
"mode": "parallel_furniture_shards",
"baseline_hash": baseline_hash,
"worker_count": worker_count,
"analysis_duration_s": round(analysis_duration, 3),
"analysis_mode": analysis_mode,
"effective_policy": skill_policy.model_dump(mode="json"),
"selection_policy": selection_report,
"native_proxy_preparation": native_proxy_preparation,
"service_connections": service_connections,
"item_limits": item_limits,
"shard_deadlines_s": shard_deadlines,
"shards": sorted(timings, key=lambda item: item["furniture_id"]),
"additions": additions,
"branch_completion": branch_completion,
"failed_critical_branches": failed_critical_branches,
"ignored_foreign_mutations": ignored_foreign_mutations,
"merge_duration_s": round(time.time() - merge_started, 3),
"parallel_stage_duration_s": round(time.time() - started, 3),
}
(output_root / "timing.json").write_text(
json.dumps(timing, indent=2), encoding="utf-8"
)
if failed_critical_branches:
raise RuntimeError(
"critical manipulation branches did not produce their planned entities: "
f"{failed_critical_branches}"
)
return scene
|