Datasets:
Download code/robohome/src/engine/source/packages/runtime/scenesmith_parallel.py from RoboParty/RoboHome: direct link, hf CLI and curl.
- Browser
- Download file 80 kB
-
https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/source/packages/runtime/scenesmith_parallel.py
- Command line
-
hf download hf://datasets/RoboParty/RoboHome/code/robohome/src/engine/source/packages/runtime/scenesmith_parallel.py
-
curl -L -o scenesmith_parallel.py https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/source/packages/runtime/scenesmith_parallel.py
80 kB
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
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
)
]