Datasets:
Download code/robohome/src/engine/source/packages/supervisor/runner.py from RoboParty/RoboHome: direct link, hf CLI and curl.
- Browser
- Download file 43.8 kB
-
https://huggingface.co/datasets/RoboParty/RoboHome/resolve/86ffa4ecc1047bb404fdc283987bd22cbc259a96/code/robohome/src/engine/source/packages/supervisor/runner.py
- Command line
-
hf download hf://datasets/RoboParty/RoboHome@86ffa4ecc1047bb404fdc283987bd22cbc259a96/code/robohome/src/engine/source/packages/supervisor/runner.py
-
curl -L -o runner.py https://huggingface.co/datasets/RoboParty/RoboHome/resolve/86ffa4ecc1047bb404fdc283987bd22cbc259a96/code/robohome/src/engine/source/packages/supervisor/runner.py
43.8 kB
from __future__ import annotations
import json
import os
import re
import shutil
import time
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
import yaml # type: ignore[import-untyped]
from pydantic import BaseModel, ConfigDict
from packages.core.files import atomic_write_text
from packages.scene_generation.design_contract import (
validate_repair_plan_against_contract,
)
from packages.supervisor.case import VERSION_PATTERN, CaseManager
from packages.supervisor.models import (
GateResult,
IterationPolicy,
QualityReport,
RepairAction,
RepairPlan,
RepairStep,
)
from packages.supervisor.planner import RepairPlanner
from packages.supervisor.quality import QualityEvaluator
from packages.supervisor.snapshot import ensure_version_media
BuildAttempt = Callable[[Path, RepairPlan | None], dict[str, Any]]
def is_packaging_only_recheck(plan: RepairPlan | None) -> bool:
"""Return whether a repair only revalidates an already accepted scene payload."""
return bool(plan is not None and plan.strategy == "portable_packaging_recheck")
def materialize_packaging_recheck(
case_root: Path,
output: Path,
plan: RepairPlan,
) -> dict[str, Any]:
"""Clone an immutable parent payload without re-entering SceneSmith.
Portable-package defects are downstream of generation. Re-running SceneSmith can
change geometry and, more importantly, turns a packaging repair into another model
generation. The clone deliberately excludes prior Supervisor decisions, checksums,
and portable validation so the new version receives fresh evidence.
"""
if not is_packaging_only_recheck(plan):
raise ValueError("repair plan is not a portable packaging recheck")
root = case_root.resolve()
source = (root / plan.parent_version).resolve()
destination = output.resolve()
if not source.is_relative_to(root) or not destination.is_relative_to(root):
raise ValueError("packaging recheck paths must remain inside the case directory")
if source == destination or not source.is_dir():
raise ValueError(f"invalid packaging recheck parent: {source}")
required = ("root.usda", "manifests/task.json", "manifests/scene.json")
missing = [name for name in required if not (source / name).is_file()]
if missing:
raise ValueError(f"packaging recheck parent is incomplete: missing={missing}")
def ignore(directory: str, names: list[str]) -> set[str]:
current = Path(directory).resolve()
ignored: set[str] = set()
if current == source:
ignored.update({"supervisor", "checksums.sha256"} & set(names))
if current == source / "manifests":
ignored.update({"portable_validation.json"} & set(names))
return ignored
shutil.copytree(source, destination, dirs_exist_ok=True, symlinks=True, ignore=ignore)
provenance = {
"schema_version": "1.0",
"mode": "packaging_only_recheck",
"source_version": source.name,
"scene_generation_invoked": False,
"excluded_evidence": [
"supervisor/",
"checksums.sha256",
"manifests/portable_validation.json",
],
}
atomic_write_text(
destination / "supervisor" / "packaging_recheck_provenance.json",
json.dumps(provenance, ensure_ascii=False, indent=2) + "\n",
)
return provenance
def generation_failure_entities(exc: BaseException) -> list[str]:
"""Extract stable entity IDs from evidence-bound subtree failures."""
message = str(exc)
deterministic_match = re.search(
r"deterministic_placement_failed:affected_entities=([^:;\s]+)", message
)
if deterministic_match:
return sorted(
{entity_id for entity_id in deterministic_match.group(1).split(",") if entity_id}
)
scored_failures = {
match.group(1)
for match in re.finditer(
r"['\"]local-critic:branch-([A-Za-z0-9_.-]+)['\"]\s*:\s*"
r"['\"][^'\"]*critic_below_threshold[^'\"]*['\"]",
message,
)
}
if scored_failures:
return sorted(scored_failures)
incomplete_branches = re.search(
r"critical manipulation branches did not produce their planned entities:\s*\[([^]]+)\]",
message,
flags=re.IGNORECASE,
)
if incomplete_branches:
branch_ids = re.findall(r"['\"]([A-Za-z0-9_.-]+)['\"]", incomplete_branches.group(1))
# A furniture repair may expand one stable support into implementation
# modules. Report the stable owner so checkpoint repair can replace the
# invalid expansion without leaking generated instance IDs into the task.
return sorted({re.sub(r"_module_[0-9]+$", "", item) for item in branch_ids})
return sorted(
{match.group(1) for match in re.finditer(r"local-critic:branch-([A-Za-z0-9_.-]+)", message)}
)
def generation_failure_signature(exc: BaseException) -> str:
"""Classify infrastructure failures so unrelated defects do not stagnate."""
message = str(exc).casefold()
if (
"deterministic_placement_failed:" in message
or "infeasible_asset:semantic_constraint:" in message
):
# Asset generation has completed. The failed hard gate belongs to the
# deterministic placement/composition stage and must never trigger a
# furniture or manipulation regeneration by default.
return "deterministic_placement_failure"
if "final_usd_geometry_failed:" in message:
# The expensive generative stages succeeded. This is a deterministic
# composition/export defect and must only re-run post-processing.
return "final_usd_geometry_failure"
if (
"agent execution dag failed" in message
and ("merge:world" in message or "global-critic:scene" in message)
and "local-critic:branch-" not in message
):
# Generation, local placement, and local critics have already completed.
# Merge/global audit failures are downstream post-processing defects; a
# manipulation resume would throw away accepted subtree work.
return "agent_postprocess_failure"
if (
"agent execution dag failed" in message
and "local-critic:branch-" in message
):
# Preserve the semantic failure across the SceneSmith subprocess boundary.
# This is an owned furniture-subtree rejection, not the final composed
# visual gate. Route it to furniture checkpoint repair so the rejected
# subtree is regenerated while accepted siblings remain frozen.
return "agent_local_critic_failure"
if (
"critical manipulation branches did not produce their planned entities" in message
and re.search(r"_module_[0-9]+", message)
):
# Manipulation is only the first consumer to notice the defect. A stable
# furniture entity was replaced by ad-hoc modules, so replaying the same
# manipulation checkpoint cannot repair it.
return "upstream_entity_identity_failure"
if "no object binding for" in message:
# Non-fatal tracing timeouts can precede the terminal traceback. The
# deterministic binding error is the actionable cause and takes priority.
return "entity_binding_failure"
if isinstance(exc, TimeoutError) or "timed out" in message or "timeout" in message:
return "generation_timeout"
if "manipuland shard" in message:
return "manipuland_worker_failure"
if "scenesmith failed" in message:
return "scenesmith_generation_failure"
return "generation_failure"
def generation_failure_fingerprint(exc: BaseException) -> str:
"""Scope semantic failures to the owned subtree for stagnation accounting."""
signature = generation_failure_signature(exc)
entities = generation_failure_entities(exc)
if (
signature
in {
"supervisor_visual_critic",
"agent_local_critic_failure",
"deterministic_placement_failure",
"upstream_entity_identity_failure",
}
and entities
):
return f"{signature}:{','.join(entities)}"
return signature
def refine_historical_failure(report: QualityReport, output: Path | None = None) -> QualityReport:
"""Recover a semantic gate from an older generic subprocess failure report."""
original_signature = (report.failure_signature or "").split(":", 1)[0]
if original_signature not in {
"scenesmith_generation_failure",
"supervisor_visual_critic",
}:
return report
message = "\n".join(gate.message for gate in report.gates if gate.message)
classified = generation_failure_signature(RuntimeError(message))
if (
original_signature == "supervisor_visual_critic"
and classified != "agent_local_critic_failure"
):
return report
refined = (
report.failure_signature
if classified in {"generation_failure", "scenesmith_generation_failure"}
else classified
)
if refined == report.failure_signature and output is not None:
minimum_visual_score: float | None = None
for score_path in output.glob("scenesmith/upstream/**/scores.yaml"):
try:
payload = yaml.safe_load(score_path.read_text(encoding="utf-8")) or {}
except (OSError, yaml.YAMLError):
continue
grades = [
float(value["grade"])
for value in payload.values()
if isinstance(value, dict) and isinstance(value.get("grade"), (int, float))
]
if grades:
score = min(grades)
minimum_visual_score = (
score if minimum_visual_score is None else min(minimum_visual_score, score)
)
if minimum_visual_score is not None and minimum_visual_score < 7.0:
refined = "supervisor_visual_critic"
if refined == report.failure_signature:
return report
gates = [
gate.model_copy(
update={
"gate_id": refined,
"affected_entities": gate.affected_entities
or generation_failure_entities(RuntimeError(gate.message)),
}
)
if gate.gate_id
in {"scenesmith_generation_failure", "supervisor_visual_critic"}
else gate
for gate in report.gates
]
return report.model_copy(update={"failure_signature": refined, "gates": gates})
class IterationResult(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
case_dir: Path
output_dir: Path | None
released_version: str | None
release: Path | None
blocked: Path | None
attempts: list[str]
payload: dict[str, Any] | None = None
class SupervisorRunner:
def __init__(
self,
manager: CaseManager,
policy: IterationPolicy,
build_attempt: BuildAttempt,
*,
evaluator: QualityEvaluator | None = None,
resume_blocked: bool = False,
) -> None:
self.manager = manager
self.policy = policy
self.build_attempt = build_attempt
self.evaluator = evaluator or QualityEvaluator(policy)
self.planner = RepairPlanner(policy.repair_policy, policy.stagnation_repeat_limit)
self.resume_blocked = resume_blocked
def run(self) -> IterationResult:
with self.manager.campaign_locked():
return self._run_locked()
def _run_locked(self) -> IterationResult:
started = time.monotonic()
atomic_write_text(
self.manager.root / "supervisor_policy.json",
self.policy.model_dump_json(indent=2) + "\n",
)
self._reconcile_interrupted_attempts()
existing_release = self.manager.root / "release.json"
if existing_release.is_file():
release_data = json.loads(existing_release.read_text(encoding="utf-8"))
output = self.manager.root / str(release_data["run_dir"])
return IterationResult(
case_dir=self.manager.root,
output_dir=output,
released_version=output.name,
release=existing_release,
blocked=None,
attempts=[],
)
history = self._attempt_history()
attempts: list[str] = []
parent: str | None = history[-1][1].version if history else None
repair_plan: RepairPlan | None = None
last_signature, consecutive_failures = self._consecutive_failure_state(history)
blocked_path = self.manager.root / "blocked.json"
resumed_campaign = False
if self.resume_blocked:
if not blocked_path.is_file():
raise RuntimeError("--resume-blocked requires an existing blocked.json")
blocked_payload = json.loads(blocked_path.read_text(encoding="utf-8"))
if not blocked_payload.get("resumable"):
raise RuntimeError("the blocked campaign is not resumable")
audit_path = self.manager.root / "resume_audit.jsonl"
with audit_path.open("a", encoding="utf-8") as handle:
handle.write(
json.dumps(
{
"schema_version": "1.0",
"resumed_at": datetime.now(UTC).isoformat(),
"prior_block": blocked_payload,
"history_attempt_count": len(history),
},
ensure_ascii=False,
)
+ "\n"
)
blocked_path.unlink()
resumed_campaign = True
# A requested resume starts a fresh repeated-failure audit while
# preserving all attempts and their original quality reports.
consecutive_failures = 0
last_payload: dict[str, Any] | None = None
if consecutive_failures >= self.policy.same_failure_signature_limit:
repeat_phrase = (
"twice"
if self.policy.same_failure_signature_limit == 2
else f"{self.policy.same_failure_signature_limit} times"
)
return self._blocked_result(
f"failure signature {last_signature!r} repeated consecutively {repeat_phrase}",
started,
parent,
attempts,
)
if history:
last_report = self._quality_report(history[-1][0])
if last_report is None:
return self._blocked_result(
"latest attempt has no valid quality report",
started,
parent,
attempts,
)
if last_report.accepted:
release = self.manager.release(history[-1][0], last_report)
return IterationResult(
case_dir=self.manager.root,
output_dir=history[-1][0],
released_version=history[-1][1].version,
release=release,
blocked=None,
attempts=attempts,
)
last_report = refine_historical_failure(last_report, history[-1][0])
if (
self.policy.max_total_attempts is not None
and len(history) >= self.policy.max_total_attempts
):
return self._blocked_result(
f"maximum of {self.policy.max_total_attempts} outer attempts already reached",
started,
parent,
attempts,
)
repair_plan = self.planner.plan(
last_report,
parent_version=parent or history[-1][1].version,
signature_occurrences=max(consecutive_failures, 1),
)
repair_plan = self._checkpoint_repair_plan(repair_plan)
if repair_plan is None and not self._can_retry_failed_stage_without_checkpoint(
last_report,
parent or history[-1][1].version,
) and not resumed_campaign:
return self._blocked_result(
"no validated checkpoint-local repair is available",
started,
parent,
attempts,
)
while time.monotonic() - started < self.policy.wall_clock_budget_s:
if (
self.policy.max_total_attempts is not None
and len(history) + len(attempts) >= self.policy.max_total_attempts
):
break
output, manifest = self.manager.allocate_attempt(parent_version=parent)
attempts.append(output.name)
attempt_started = time.monotonic()
attempt_number = len(history) + len(attempts)
budget_multiplier = (
self.policy.first_attempt_budget_multiplier if attempt_number == 1 else 1.0
)
effective = {
"schema_version": "1.0",
"attempt_number": attempt_number,
"attempt_budget_multiplier": budget_multiplier,
"max_total_attempts": self.policy.max_total_attempts,
"critic_min_score": self.policy.critic_min_score,
"checkpoint_repairs_only_after_first": (
self.policy.checkpoint_repairs_only_after_first
),
}
if repair_plan is not None:
repair_path = output / "supervisor" / "repair_plan.json"
atomic_write_text(repair_path, repair_plan.model_dump_json(indent=2) + "\n")
effective.update(
{
"parent_version": repair_plan.parent_version,
"strategy": repair_plan.strategy,
"steps": [step.model_dump(mode="json") for step in repair_plan.steps],
}
)
manifest.repair_plan = "supervisor/repair_plan.json"
self.manager.write_attempt(output, manifest)
atomic_write_text(
output / "supervisor" / "effective_overrides.json",
json.dumps(effective, ensure_ascii=False, indent=2) + "\n",
)
report: QualityReport
error: str | None = None
try:
if is_packaging_only_recheck(repair_plan):
assert repair_plan is not None
last_payload = materialize_packaging_recheck(
self.manager.root, output, repair_plan
)
else:
with repair_environment(
repair_plan,
self.manager.root,
attempt_budget_multiplier=budget_multiplier,
):
last_payload = self.build_attempt(output, repair_plan)
ensure_version_media(
output,
force_snapshot=True,
allow_final_preview_fallback=False,
)
report = self.evaluator.evaluate(output)
if report.accepted:
ensure_version_media(output, force_snapshot=True)
else:
ensure_version_media(
output,
force_snapshot=True,
allow_final_preview_fallback=False,
)
except Exception as exc:
error = f"{type(exc).__name__}: {exc}"
gate_id = generation_failure_signature(exc)
failure_signature = generation_failure_fingerprint(exc)
try:
# Persist the failure first so a pre-render diagnostic frame
# contains the actual failed stage instead of a generic card.
manifest.error = error
self.manager.write_attempt(output, manifest)
ensure_version_media(
output,
force_snapshot=True,
allow_final_preview_fallback=False,
)
except Exception as media_exc:
error += f"; media_contract={type(media_exc).__name__}: {media_exc}"
report = QualityReport(
accepted=False,
hard_gates_passed=False,
critic_passed=not self.policy.critic_required,
gates=[
GateResult(
gate_id=gate_id,
passed=False,
message=error,
affected_entities=generation_failure_entities(exc),
)
],
failure_signature=failure_signature,
)
quality_path = output / "supervisor" / "quality_report.json"
atomic_write_text(quality_path, report.model_dump_json(indent=2) + "\n")
manifest.status = "passed" if report.accepted else "failed"
manifest.completed_at = datetime.now(UTC).isoformat()
manifest.duration_s = round(time.monotonic() - attempt_started, 3)
manifest.quality_report = "supervisor/quality_report.json"
manifest.failure_signature = report.failure_signature
manifest.error = error
self.manager.write_attempt(output, manifest)
self.manager.append_attempt(manifest)
self.manager.update_campaign()
if report.accepted and (output / "snapshot.jpg").is_file():
self.manager.consider_for_major(output, report)
if report.accepted:
release = self.manager.release(output, report)
return IterationResult(
case_dir=self.manager.root,
output_dir=output,
released_version=output.name,
release=release,
blocked=None,
attempts=attempts,
payload=last_payload,
)
signature = report.failure_signature or "unknown"
if signature == last_signature:
consecutive_failures += 1
else:
last_signature = signature
consecutive_failures = 1
if consecutive_failures >= self.policy.same_failure_signature_limit:
repeat_phrase = (
"twice"
if self.policy.same_failure_signature_limit == 2
else f"{self.policy.same_failure_signature_limit} times"
)
return self._blocked_result(
f"failure signature {signature!r} repeated consecutively {repeat_phrase}",
started,
output.name,
attempts,
output=output,
payload=last_payload,
)
repair_plan = self.planner.plan(
report,
parent_version=output.name,
signature_occurrences=consecutive_failures,
)
repair_plan = self._checkpoint_repair_plan(repair_plan)
parent = output.name
if repair_plan is None and not self._can_retry_failed_stage_without_checkpoint(
report,
parent,
):
return self._blocked_result(
"allowlisted checkpoint-local repair strategies exhausted",
started,
parent,
attempts,
output=output,
payload=last_payload,
)
attempt_limit_reached = (
self.policy.max_total_attempts is not None
and len(history) + len(attempts) >= self.policy.max_total_attempts
)
blocked = self.manager.block(
reason=(
f"maximum of {self.policy.max_total_attempts} outer attempts reached"
if attempt_limit_reached
else "wall-clock budget exhausted"
),
elapsed_s=time.monotonic() - started,
last_version=parent,
)
return IterationResult(
case_dir=self.manager.root,
output_dir=self.manager.root / parent if parent else None,
released_version=None,
release=None,
blocked=blocked,
attempts=attempts,
payload=last_payload,
)
def _attempt_history(self) -> list[tuple[Path, Any]]:
history = []
for output in self.manager.root.iterdir():
if not output.is_dir() or VERSION_PATTERN.fullmatch(output.name) is None:
continue
manifest_path = output / "supervisor" / "attempt_manifest.json"
if manifest_path.is_file():
history.append((output, self.manager.read_attempt(output)))
return sorted(
history,
key=lambda item: int(VERSION_PATTERN.fullmatch(item[0].name).group("number")),
)
@staticmethod
def _consecutive_failure_state(history: list[tuple[Path, Any]]) -> tuple[str | None, int]:
signature: str | None = None
count = 0
for _, manifest in reversed(history):
if manifest.status != "failed":
break
current = manifest.failure_signature or "unknown"
if signature is None:
signature = current
if current != signature:
break
count += 1
return signature, count
@staticmethod
def _quality_report(output: Path) -> QualityReport | None:
path = output / "supervisor" / "quality_report.json"
if not path.is_file():
return None
try:
return QualityReport.model_validate_json(path.read_text(encoding="utf-8"))
except ValueError:
return None
def _checkpoint_repair_plan(self, plan: RepairPlan | None) -> RepairPlan | None:
if plan is None or not self.policy.checkpoint_repairs_only_after_first:
return plan
checkpoint = self._nearest_ancestor_checkpoint(plan.parent_version)
if checkpoint is None:
return None
steps = list(plan.steps)
resume_index = next(
(
index
for index, step in enumerate(steps)
if step.action == RepairAction.RERUN_STAGE_FROM_CHECKPOINT
),
None,
)
failure_kind = (plan.failure_signature or "").split(":", 1)[0]
requested_resume_stage = steps[resume_index].stage if resume_index is not None else None
# A process can be interrupted while carrying out a postprocess-only
# repair after its reusable upstream checkpoint has already been copied.
# The generic interrupted-attempt strategy asks for ``manipuland``, but
# that would unnecessarily reopen accepted Agent geometry. Preserve the
# interrupted parent's explicitly persisted postprocess scope instead.
if failure_kind == "interrupted_attempt":
parent_plan_path = (
self.manager.root
/ plan.parent_version
/ "supervisor"
/ "repair_plan.json"
)
if parent_plan_path.is_file():
try:
parent_plan = RepairPlan.model_validate_json(
parent_plan_path.read_text(encoding="utf-8")
)
except (OSError, ValueError):
parent_plan = None
parent_resume = (
next(
(
step
for step in parent_plan.steps
if step.action == RepairAction.RERUN_STAGE_FROM_CHECKPOINT
),
None,
)
if parent_plan is not None
else None
)
if parent_resume is not None and parent_resume.stage == "postprocess":
requested_resume_stage = "postprocess"
resume_stage = (
"postprocess"
if requested_resume_stage == "postprocess"
or failure_kind
in {
"final_usd_geometry_failure",
"agent_postprocess_failure",
"deterministic_placement_failure",
}
else self._checkpoint_resume_stage(checkpoint)
)
if resume_stage is None:
return None
# The checkpoint detector identifies how far a prior attempt completed;
# it must not silently narrow an explicit repair plan past the stage that
# actually failed. For example, a completed manipulation checkpoint can
# still contain furniture rejected by the final visual critic, in which
# case the planner's requested furniture repair must be honored.
if resume_index is not None and plan.strategy in {
"global_dag_furniture_repair",
"visual_support_and_layout_repair",
"upstream_entity_identity_repair",
}:
requested_stage = steps[resume_index].stage
stage_order = ("floor_plan", "furniture", "wall", "ceiling", "manipuland")
if (
requested_stage in stage_order
and resume_stage in stage_order
and stage_order.index(requested_stage) < stage_order.index(resume_stage)
):
resume_stage = requested_stage
resume = RepairStep(
action=RepairAction.RERUN_STAGE_FROM_CHECKPOINT,
stage=resume_stage,
checkpoint=checkpoint.as_posix(),
reason="Resume the failed branch from the parent SceneSmith checkpoint.",
)
if resume_index is None:
steps.insert(0, resume)
else:
original = steps[resume_index]
steps[resume_index] = original.model_copy(
update={"stage": resume_stage, "checkpoint": checkpoint.as_posix()}
)
return plan.model_copy(update={"steps": steps})
def _can_retry_failed_stage_without_checkpoint(
self,
report: QualityReport,
parent_version: str,
) -> bool:
"""Permit one deterministic stage retry when no checkpoint can exist yet.
A worker/runtime failure before the first materialized checkpoint cannot
be expressed honestly as a checkpoint-local scene repair. The outer
repeated-signature guard still stops the campaign if the retry produces
the same failure again. Once any usable checkpoint exists, the normal
checkpoint-only repair policy remains authoritative.
"""
if report.failure_signature not in {
"generation_failure",
"generation_timeout",
"interrupted_attempt",
"scenesmith_generation_failure",
}:
return False
return self._nearest_ancestor_checkpoint(parent_version) is None
def _checkpoint_resume_stage(self, checkpoint: Path) -> str | None:
"""Select the earliest unfinished SceneSmith stage in a checkpoint."""
root = self.manager.root / checkpoint
for timing_path in root.glob("scene_*/room_*/parallel_manipulands/timing.json"):
try:
timing = json.loads(timing_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
continue
completions = timing.get("branch_completion") or {}
failed = timing.get("failed_critical_branches") or []
if (
isinstance(completions, dict)
and completions
and not failed
and all(
isinstance(value, dict) and value.get("passed") is True
for value in completions.values()
)
):
# Re-enter manipulation to reproduce the final merged blend;
# the accepted furniture/architecture checkpoint remains frozen.
return "manipuland"
for ledger_path in root.glob("scene_*/room_*/parallel_base_branches/execution_ledger.json"):
try:
ledger = json.loads(ledger_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
continue
if ledger.get("status") == "complete":
return "manipuland"
floor_render_patterns = (
"scene_*/floor_plans/floor_plan_renders/renders_*",
"scene_*/floor_plans/*/floor_plan_renders/renders_*",
)
if any(any(root.glob(pattern)) for pattern in floor_render_patterns):
return "furniture"
return None
def _nearest_ancestor_checkpoint(self, version: str) -> Path | None:
"""Return the newest usable checkpoint in an attempt's ancestry.
Infrastructure failures may create a version directory before SceneSmith
writes any checkpoint. Follow parent_version links so a later invocation
can resume from the last materialized attempt instead of treating the
resource-only failure as a request for full regeneration.
"""
candidate = version
visited: set[str] = set()
while candidate and candidate not in visited:
visited.add(candidate)
checkpoint = Path(candidate) / "scenesmith" / "upstream"
resolved = self.manager.root / checkpoint
# Logs, Hydra configs and half-written scene directories are not a
# resumable checkpoint. SceneSmith writes this marker only after
# the reusable base state has been materialized.
if (
(resolved / "checkpoint.json").is_file()
or self._legacy_upstream_complete(resolved)
or self._checkpoint_resume_stage(checkpoint) is not None
):
return checkpoint
manifest_path = resolved.parents[1] / "supervisor" / "attempt_manifest.json"
if not manifest_path.is_file():
return None
try:
manifest = self.manager.read_attempt(resolved.parents[1])
except ValueError:
return None
candidate = manifest.parent_version or ""
return None
@staticmethod
def _legacy_upstream_complete(upstream: Path) -> bool:
"""Recognize runs completed before the checkpoint marker was introduced."""
log_path = upstream.parent / "upstream.log"
if not log_path.is_file():
return False
try:
if "Experiment execution completed in" not in log_path.read_text(
encoding="utf-8", errors="replace"
):
return False
except OSError:
return False
return any(upstream.glob("scene_*/room_*/scene_states/final_scene/scene.blend")) or any(
upstream.glob("**/house.blend")
)
def _blocked_result(
self,
reason: str,
started: float,
parent: str | None,
attempts: list[str],
*,
output: Path | None = None,
payload: dict[str, Any] | None = None,
) -> IterationResult:
blocked = self.manager.block(
reason=reason,
elapsed_s=time.monotonic() - started,
last_version=parent,
)
return IterationResult(
case_dir=self.manager.root,
output_dir=output or (self.manager.root / parent if parent else None),
released_version=None,
release=None,
blocked=blocked,
attempts=attempts,
payload=payload,
)
def _reconcile_interrupted_attempts(self) -> None:
"""Finalize attempts left running by a prior process interruption.
A process cannot execute cleanup after SIGKILL or host loss. The next
Supervisor invocation therefore repairs the visual contract before it
allocates another version, without requiring an external backfill job.
"""
reconciled = False
for output in sorted(self.manager.root.iterdir()):
if not output.is_dir() or VERSION_PATTERN.fullmatch(output.name) is None:
continue
manifest_path = output / "supervisor" / "attempt_manifest.json"
if not manifest_path.is_file():
continue
manifest = self.manager.read_attempt(output)
if manifest.status != "running":
continue
error = "Supervisor process ended before attempt finalization; auto-reconciled"
failure_signature = "interrupted_attempt"
# If a bad retry was interrupted before it produced a checkpoint,
# retain a deterministic parent failure that can be repaired from
# the parent's completed upstream scene. Otherwise the generic
# interruption would unnecessarily rerun an expensive Agent stage.
current_upstream = output / "scenesmith" / "upstream"
if manifest.parent_version and not (current_upstream / "checkpoint.json").is_file():
parent_output = self.manager.root / manifest.parent_version
parent_report = self._quality_report(parent_output)
if parent_report is not None:
parent_report = refine_historical_failure(parent_report, parent_output)
parent_failure_kind = (parent_report.failure_signature or "").split(":", 1)[0]
if parent_failure_kind in {
"final_usd_geometry_failure",
"agent_postprocess_failure",
"deterministic_placement_failure",
}:
failure_signature = parent_report.failure_signature
error += "; retained deterministic failure from parent checkpoint"
manifest.error = error
try:
ensure_version_media(
output,
force_snapshot=True,
allow_final_preview_fallback=False,
)
except Exception as media_exc:
manifest.error += f"; media_contract={type(media_exc).__name__}: {media_exc}"
report = QualityReport(
accepted=False,
hard_gates_passed=False,
critic_passed=not self.policy.critic_required,
gates=[
GateResult(
gate_id=failure_signature,
passed=False,
message=manifest.error,
)
],
failure_signature=failure_signature,
)
quality_path = output / "supervisor" / "quality_report.json"
atomic_write_text(quality_path, report.model_dump_json(indent=2) + "\n")
manifest.status = "failed"
manifest.completed_at = datetime.now(UTC).isoformat()
manifest.quality_report = "supervisor/quality_report.json"
manifest.failure_signature = failure_signature
self.manager.write_attempt(output, manifest)
self.manager.append_attempt(manifest)
reconciled = True
if reconciled:
self.manager.update_campaign()
@contextmanager
def repair_environment(
plan: RepairPlan | None,
case_root: Path,
*,
attempt_budget_multiplier: float = 1.0,
) -> Iterator[None]:
updates = {
"RHG_CASE_ROOT": str(case_root),
"RHG_ATTEMPT_BUDGET_MULTIPLIER": str(attempt_budget_multiplier),
}
design_contract = case_root / "case_design" / "contract.json"
if design_contract.is_file():
if plan is not None:
validate_repair_plan_against_contract(design_contract, plan)
updates["RHG_CASE_DESIGN_CONTRACT"] = str(design_contract.resolve())
fresh_scene = os.environ.get("RHG_FRESH_SCENE", "0").casefold() in {
"1",
"true",
"yes",
}
external_reuse = (
"" if fresh_scene else os.environ.get("RHG_SCENESMITH_REUSE_FROM", "").strip()
)
if external_reuse:
resolved_external_reuse = Path(external_reuse).resolve()
if not resolved_external_reuse.is_dir():
raise NotADirectoryError(resolved_external_reuse)
# A product suite may reuse a separately accepted immutable room. The
# adapter still makes a private copy before deterministic postprocessing.
updates["RHG_SCENESMITH_REUSE_FROM"] = str(resolved_external_reuse)
if plan is not None:
updates["RHG_REPAIR_PLAN"] = json.dumps(plan.model_dump(mode="json"))
resume = (
next(
(
step
for step in plan.steps
if step.action == RepairAction.RERUN_STAGE_FROM_CHECKPOINT
),
None,
)
if plan is not None
else None
)
if resume is not None and not fresh_scene:
if resume.stage == "postprocess":
if not resume.checkpoint:
raise ValueError("postprocess repair requires a SceneSmith checkpoint")
checkpoint = Path(resume.checkpoint)
if not checkpoint.is_absolute():
checkpoint = case_root / checkpoint
resolved = checkpoint.resolve()
if not resolved.is_relative_to(case_root.resolve()):
raise ValueError("repair checkpoint must remain within the case directory")
# The checkpoint points at ``scenesmith/upstream``. The adapter
# stages that completed SceneSmith directory into the new version
# and asks the worker to re-run deterministic export/validation only.
updates["RHG_SCENESMITH_REUSE_FROM"] = str(resolved.parent)
else:
if resume.stage:
updates["RHG_SCENESMITH_START_STAGE"] = resume.stage
if resume.checkpoint:
checkpoint = Path(resume.checkpoint)
if not checkpoint.is_absolute():
checkpoint = case_root / checkpoint
resolved = checkpoint.resolve()
if not resolved.is_relative_to(case_root.resolve()):
raise ValueError("repair checkpoint must remain within the case directory")
updates["RHG_SCENESMITH_RESUME_FROM"] = str(resolved)
managed_keys = {
*updates,
"RHG_REPAIR_PLAN",
"RHG_SCENESMITH_START_STAGE",
"RHG_SCENESMITH_RESUME_FROM",
"RHG_SCENESMITH_REUSE_FROM",
}
previous = {key: os.environ.get(key) for key in managed_keys}
for key in managed_keys - updates.keys():
os.environ.pop(key, None)
os.environ.update(updates)
try:
yield
finally:
for key, value in previous.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
from __future__ import annotations
import json
import os
import re
import shutil
import time
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
import yaml # type: ignore[import-untyped]
from pydantic import BaseModel, ConfigDict
from packages.core.files import atomic_write_text
from packages.scene_generation.design_contract import (
validate_repair_plan_against_contract,
)
from packages.supervisor.case import VERSION_PATTERN, CaseManager
from packages.supervisor.models import (
GateResult,
IterationPolicy,
QualityReport,
RepairAction,
RepairPlan,
RepairStep,
)
from packages.supervisor.planner import RepairPlanner
from packages.supervisor.quality import QualityEvaluator
from packages.supervisor.snapshot import ensure_version_media
BuildAttempt = Callable[[Path, RepairPlan | None], dict[str, Any]]
def is_packaging_only_recheck(plan: RepairPlan | None) -> bool:
"""Return whether a repair only revalidates an already accepted scene payload."""
return bool(plan is not None and plan.strategy == "portable_packaging_recheck")
def materialize_packaging_recheck(
case_root: Path,
output: Path,
plan: RepairPlan,
) -> dict[str, Any]:
"""Clone an immutable parent payload without re-entering SceneSmith.
Portable-package defects are downstream of generation. Re-running SceneSmith can
change geometry and, more importantly, turns a packaging repair into another model
generation. The clone deliberately excludes prior Supervisor decisions, checksums,
and portable validation so the new version receives fresh evidence.
"""
if not is_packaging_only_recheck(plan):
raise ValueError("repair plan is not a portable packaging recheck")
root = case_root.resolve()
source = (root / plan.parent_version).resolve()
destination = output.resolve()
if not source.is_relative_to(root) or not destination.is_relative_to(root):
raise ValueError("packaging recheck paths must remain inside the case directory")
if source == destination or not source.is_dir():
raise ValueError(f"invalid packaging recheck parent: {source}")
required = ("root.usda", "manifests/task.json", "manifests/scene.json")
missing = [name for name in required if not (source / name).is_file()]
if missing:
raise ValueError(f"packaging recheck parent is incomplete: missing={missing}")
def ignore(directory: str, names: list[str]) -> set[str]:
current = Path(directory).resolve()
ignored: set[str] = set()
if current == source:
ignored.update({"supervisor", "checksums.sha256"} & set(names))
if current == source / "manifests":
ignored.update({"portable_validation.json"} & set(names))
return ignored
shutil.copytree(source, destination, dirs_exist_ok=True, symlinks=True, ignore=ignore)
provenance = {
"schema_version": "1.0",
"mode": "packaging_only_recheck",
"source_version": source.name,
"scene_generation_invoked": False,
"excluded_evidence": [
"supervisor/",
"checksums.sha256",
"manifests/portable_validation.json",
],
}
atomic_write_text(
destination / "supervisor" / "packaging_recheck_provenance.json",
json.dumps(provenance, ensure_ascii=False, indent=2) + "\n",
)
return provenance
def generation_failure_entities(exc: BaseException) -> list[str]:
"""Extract stable entity IDs from evidence-bound subtree failures."""