Skip to content

Official Codebase of 3DCodeVerse

Python

planner: a degenerate plan is re-sampled from the original prompt, not edited in context

ziyao8f302d29672a
diff --git a/harness/codeverse/tracks/plan_features.py b/harness/codeverse/tracks/plan_features.py
index 28395a4f..a04f2cf5 100644
--- a/harness/codeverse/tracks/plan_features.py
+++ b/harness/codeverse/tracks/plan_features.py
@@ -64,6 +64,8 @@ LIVE_SWITCHES: dict[str, str] = {
# plan-time geometry re-ask for articulated plans (tracks/plan_checks.py); plan-side,
# so an A/B over it can never --pin-plan. Off by default (A/B 2026-08-28: no gain).
"CV3D_PLAN_GEOMETRY": "codeverse/tracks/planner.py",
+ # re-sample a degenerate plan from the original prompt instead of editing it in context
+ "CV3D_PLAN_RESTART": "codeverse/tracks/planner.py",
"CV3D_SCOPED_PARTS": "codeverse/tracks/depth.py",
"CV3D_DETAIL_ROUNDS": "codeverse/tracks/lifecycle.py",
"CV3D_REFERENCE_DIFF": "codeverse/judges/vlm_judge.py", # reference.py merged in, 2026-08-28
diff --git a/harness/codeverse/tracks/planner.py b/harness/codeverse/tracks/planner.py
index 7c94abad..e3b3b1ce 100644
--- a/harness/codeverse/tracks/planner.py
+++ b/harness/codeverse/tracks/planner.py
@@ -566,6 +566,13 @@ MAX_QUALITY_REASKS = 1
#: a plan whose boxes / pivots / ranges contradict each other (tracks/plan_checks.py) is
#: re-asked with the numbers; after this many it ships anyway and the joint sweep decides
MAX_GEOMETRY_REASKS = 2
+#: a validation failure whose plan is DEGENERATE (joints naming links the plan never lists)
+#: is answered by re-sampling from the original prompt instead of editing the broken answer
+#: in context; at most this many times per plan. Measured 2026-09-02: 3-4 % of plan calls
+#: end this way, and both in-context re-asks reproduce the same broken plan verbatim.
+MAX_PLAN_RESTARTS = 1
+#: kill-switch for that restart (default ON, mirrors CV3D_AXIS_REPAIR)
+PLAN_RESTART_ENV = "CV3D_PLAN_RESTART"
#: ``CV3D_PLAN_GEOMETRY=1`` turns the geometry re-ask ON (registered in
#: tracks/plan_features.LIVE_SWITCHES). OFF by default since the 2026-08-28 A/B
#: (compare_art_v4 pf vs pf0, n = 14): score Δ +0.064 [−0.188, +0.315], wins 6/6/2,
@@ -655,6 +662,50 @@ def _schema_echo(raw: dict[str, Any]) -> str:
return ", ".join(bad[:6])
+def missing_link_names(raw: Any) -> list[str]:
+ """Link names the joints reference that ``parts`` does not define (snake-compared).
+
+ The one failure class measured on 200 plan calls (2026-09-02, both trees, 3-4 %): the
+ planner writes ONE top-level part and hangs every joint off links it never lists, then
+ reproduces that answer through both in-context re-asks."""
+ if not isinstance(raw, dict):
+ return []
+ parts = raw.get("parts")
+ joints = raw.get("joints")
+ if not isinstance(parts, list) or not isinstance(joints, list):
+ return []
+ known = {to_snake(str(p.get("name", ""))) for p in parts if isinstance(p, dict)}
+ known |= {to_snake(str(c.get("name", ""))) for p in parts if isinstance(p, dict)
+ for c in (p.get("children") or []) if isinstance(c, dict)}
+ missing: list[str] = []
+ for j in joints:
+ if not isinstance(j, dict):
+ continue
+ for side in ("parent", "child"):
+ name = str(j.get(side, "")).strip()
+ if name and to_snake(name) not in known and name not in missing:
+ missing.append(name)
+ return missing
+
+
+def restart_note(raw: Any, missing: list[str], budget: PlanBudget) -> str:
+ """The user turn that replaces the whole conversation when a plan comes back degenerate."""
+ n_parts = len(raw.get("parts") or []) if isinstance(raw, dict) else 0
+ return (
+ "\n\nYour previous attempt listed only "
+ f"{n_parts} top-level part(s) and then referenced links it never defined: "
+ f"{', '.join(missing[:10])}. Start again from this request. Rules that answer is missing:\n"
+ f"- `parts` must contain EVERY link a joint names, each with its own name, bbox and material "
+ f"(about {budget.target_parts} parts for this request).\n"
+ "- `joints[].parent` and `joints[].child` must be spelled exactly like those part names.\n"
+ "- Nothing that a joint moves may live in `children`; sub-parts are rigid detail only."
+ )
+
+
+def restart_enabled() -> bool:
+ return os.environ.get(PLAN_RESTART_ENV, "1").strip().lower() not in ("0", "false", "off", "no")
+
+
def _thin_plan_note(raw: Any, budget: PlanBudget) -> str:
"""A second line for the validation re-ask when the invalid plan is also far too small.
@@ -770,9 +821,10 @@ def plan_with_usage[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P]
user = build_user_prompt(spec, brief=brief, budget=budget, unit=unit)
images = [ImagePart(path=r.path, label=f"{r.role}: {r.note}".strip(": ")) for r in spec.references]
messages = [ChatMessage.user(user, images=images or None)]
+ base_messages = list(messages)
schema = plan_model.model_json_schema()
last_error = ""
- invalid = requeried = grown = 0
+ invalid = requeried = grown = restarts = 0
tokens = plan_tokens(budget, max_output_tokens)
thinking = "medium"
wait_scale = 1.0
@@ -818,6 +870,20 @@ def plan_with_usage[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P]
events.emit("plan.invalid", attempt=attempt, error=last_error[:500])
if invalid > MAX_VALIDATION_REASKS:
break
+ missing = missing_link_names(raw)
+ if missing and restarts < MAX_PLAN_RESTARTS and restart_enabled():
+ # Editing a degenerate answer in context reproduces it: the model reads its
+ # own one-part plan and returns it again (measured, both re-asks, 2026-09-02).
+ # Re-sample from the original request instead, with the rule it broke.
+ restarts += 1
+ if events is not None:
+ events.emit("plan.restart", attempt=attempt, n_parts=len(raw.get("parts") or []),
+ missing=missing[:10])
+ messages = base_messages[:-1] + [
+ ChatMessage.user(base_messages[-1].text + restart_note(raw, missing, budget),
+ images=images or None),
+ ]
+ continue
messages = messages + [
_echo(raw, resp.text),
ChatMessage.user("Your plan failed validation. Fix EXACTLY these problems and return the full corrected "
@@ -858,7 +924,7 @@ def plan_with_usage[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P]
stats = (event_stats or default_event_stats)(result)
events.emit("plan.done", model=model_id, **stats,
cost_usd=round(usage.cost_usd, 4), prompt_hash=prompt_hash(system), attempt=attempt,
- brief=brief is not None, quality_reasks=requeried, **budget.as_dict())
+ brief=brief is not None, quality_reasks=requeried, restarts=restarts, **budget.as_dict())
return result, usage
raise PlanningError(f"plan did not validate after re-ask: {last_error}", usage)
@@ -1010,6 +1076,8 @@ def normalise_names[P: BaseModel](plan_obj: P) -> P:
return plan_obj
-__all__ = ["MAX_GEOMETRY_REASKS", "articulation_acceptance", "PLAN_GEOMETRY_ENV", "geometry_check_enabled", "MAX_QUALITY_REASKS", "MAX_VALIDATION_REASKS", "PLAN_TOKENS_MAX", "PlanningError", "plan",
- "plan_tokens", "plan_with_usage", "plan_example", "ensure_acceptance", "add_acceptance_item",
- "default_event_stats", "normalise_names", "build_system_prompt", "build_user_prompt"]
+__all__ = ["MAX_GEOMETRY_REASKS", "MAX_PLAN_RESTARTS", "MAX_QUALITY_REASKS", "MAX_VALIDATION_REASKS",
+ "PLAN_GEOMETRY_ENV", "PLAN_RESTART_ENV", "PLAN_TOKENS_MAX", "PlanningError", "add_acceptance_item",
+ "articulation_acceptance", "build_system_prompt", "build_user_prompt", "default_event_stats",
+ "ensure_acceptance", "geometry_check_enabled", "missing_link_names", "normalise_names", "plan",
+ "plan_example", "plan_tokens", "plan_with_usage", "restart_enabled", "restart_note"]
diff --git a/harness/tests/orchestrator_tracks/test_planner_geometry_reask.py b/harness/tests/orchestrator_tracks/test_planner_geometry_reask.py
index 632f3e6a..672f8966 100644
--- a/harness/tests/orchestrator_tracks/test_planner_geometry_reask.py
+++ b/harness/tests/orchestrator_tracks/test_planner_geometry_reask.py
@@ -120,8 +120,13 @@ def test_a_crashing_geometry_check_never_costs_the_plan(tmp_ws, monkeypatch):
def test_validation_reask_names_the_missing_parts_when_the_plan_is_thin(tmp_ws):
+ """A thin plan whose joints stay INSIDE the part list: the in-context re-ask still owns
+ it (a plan that also references links it never lists is a restart — see
+ test_planner_restart.py, which measured that editing that one in context reproduces it)."""
thin = _good()
- thin["parts"] = thin["parts"][:1] # only the cabinet; the joint still references the drawer
+ thin["parts"] = thin["parts"][:1] # only the cabinet ...
+ thin["joints"] = [] # ... and no joint references the dropped link
+ thin["root_link"] = "NoSuchLink" # a plain validation failure to trigger the re-ask
answers = [thin, _good()]
model = FakeChatModel(lambda req: answers.pop(0))
p = plan(_spec(), "fake:planner", ArticulatedPlan, tmp_ws, model=model, runtime=FakeRuntime(Language.URDF_BLENDER))
diff --git a/harness/tests/orchestrator_tracks/test_planner_restart.py b/harness/tests/orchestrator_tracks/test_planner_restart.py
new file mode 100644
index 00000000..fdb0b0df
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_planner_restart.py
@@ -0,0 +1,100 @@
+"""A degenerate plan is re-sampled from the original prompt, not edited in context.
+
+Measured 2026-09-02 over 200 plan calls on two trees: 3-4 % of articulated plan calls end
+in `PlanningError`, always the same way — one top-level part, joints naming links the plan
+never lists — and both in-context re-asks come back with that same answer."""
+
+from __future__ import annotations
+
+import copy
+
+import pytest
+
+from codeverse.contracts.common import Language, Track
+from codeverse.contracts.plan import ArticulatedPlan
+from codeverse.proc import EventLog
+from codeverse.tracks.planner import (
+ MAX_PLAN_RESTARTS,
+ PLAN_RESTART_ENV,
+ PlanningError,
+ missing_link_names,
+ plan,
+ plan_example,
+)
+from tests.orchestrator_tracks.conftest import make_spec
+from tests.orchestrator_tracks.fakes import FakeChatModel, FakeRuntime
+
+
+def _good() -> dict:
+ return copy.deepcopy(plan_example(Track.ARTICULATED_OBJECT))
+
+
+def _degenerate() -> dict:
+ """One part; the joint still moves a link the plan never lists (the measured shape)."""
+ d = _good()
+ d["parts"] = [p for p in d["parts"] if p["name"] == "Cabinet"]
+ return d
+
+
+def _spec():
+ return make_spec(track=Track.ARTICULATED_OBJECT, language=Language.URDF_BLENDER, prompt="a desk drawer unit")
+
+
+def _run(tmp_ws, answers, events=None):
+ model = FakeChatModel(lambda req: answers.pop(0))
+ p = plan(_spec(), "fake:planner", ArticulatedPlan, tmp_ws, model=model, events=events,
+ runtime=FakeRuntime(Language.URDF_BLENDER))
+ return p, model
+
+
+def test_missing_link_names_reports_what_the_joints_reference_and_parts_lack():
+ assert missing_link_names(_degenerate()) == ["Drawer"]
+ assert missing_link_names(_good()) == []
+ assert missing_link_names({"parts": [], "joints": []}) == []
+ assert missing_link_names("not a dict") == []
+ nested = _good()
+ nested["parts"] = [nested["parts"][0]]
+ nested["parts"][0]["children"] = [{"name": "Drawer"}]
+ assert missing_link_names(nested) == [] # a sub-part IS a name the plan defines
+
+
+def test_a_degenerate_plan_is_resampled_without_its_own_answer_in_context(tmp_ws):
+ events = EventLog(tmp_ws.events_path)
+ p, model = _run(tmp_ws, [_degenerate(), _good()], events=events)
+ assert isinstance(p, ArticulatedPlan) and len(model.requests) == 2
+ first, second = model.requests
+ assert len(second.messages) == len(first.messages) == 1 # no echo, no accumulated turns
+ text = second.messages[-1].text
+ assert text.startswith(first.messages[-1].text) # the original request is kept verbatim
+ assert "listed only 1 top-level part(s)" in text and "Drawer" in text
+ assert "must contain EVERY link a joint names" in text
+ ev = [e for e in events.read() if e["event"] == "plan.restart"]
+ assert len(ev) == 1 and ev[0]["n_parts"] == 1 and ev[0]["missing"] == ["Drawer"]
+ assert [e for e in events.read() if e["event"] == "plan.done"][0]["restarts"] == 1
+
+
+def test_an_ordinary_validation_error_still_edits_in_context(tmp_ws):
+ """Nothing changes for the failures a re-ask does fix: the model sees its own answer."""
+ bad = _good()
+ bad["joints"][0]["axis"] = [0, 0, 0] # a real slip, not a degenerate plan
+ p, model = _run(tmp_ws, [bad, _good()])
+ assert isinstance(p, ArticulatedPlan) and len(model.requests) == 2
+ assert len(model.requests[1].messages) == 3 # user + echoed answer + complaint
+ assert "failed validation" in model.requests[1].messages[-1].text
+
+
+def test_the_kill_switch_restores_the_in_context_reask(tmp_ws, monkeypatch):
+ monkeypatch.setenv(PLAN_RESTART_ENV, "0")
+ p, model = _run(tmp_ws, [_degenerate(), _good()])
+ assert isinstance(p, ArticulatedPlan) and len(model.requests[1].messages) == 3
+
+
+def test_one_restart_per_plan_then_the_normal_reask_budget(tmp_ws):
+ """Two degenerate answers: restart once, then edit in context, then give up as before."""
+ model = FakeChatModel(lambda req: _degenerate())
+ with pytest.raises(PlanningError):
+ plan(_spec(), "fake:planner", ArticulatedPlan, tmp_ws, model=model,
+ runtime=FakeRuntime(Language.URDF_BLENDER))
+ assert len(model.requests) == 3 # first + one restart + one in-context re-ask
+ assert MAX_PLAN_RESTARTS == 1
+ assert len(model.requests[1].messages) == 1 and len(model.requests[2].messages) == 3