feat(errors): assembly solve diagnosis + zero-hit render guard lists available tags

P1 family 7 (assembly solve): the solver's five strict raise sites emitted
one-line ValueErrors that discarded the residual and connectivity data
already in hand. Residual failures (forwarded + final pass) now carry
measured translation/angular errors against both tolerances, a
per-constraint inventory (exceeded/ok with numeric deltas), and a
worst-first repair that targets connector frame definitions instead of
component placements, plus the closed-loop overconstraint escape (break
the loop or solve it inside a subassembly). Structural failures
(unresolvable loop / no grounded path / unsolved components) carry the
connectivity verdict as inventory (grounded/reachable/unsolved with
constraint-reference counts). The public wrapper surfaces them unchanged
via the SimpleCADError passthrough.

P1 family 8 (render export): the zero-hit highlight_tags guard now lists
the tags actually available on the shapes (solid + face level, capped at
24 + count row), so the typo question is answerable from the error
itself; _RenderTagMismatch promotes the payload to what_happened
(mechanism-A surgical promotion).

Tests: 3 assembly cases (15 mm residual asserted, connectivity verdict,
wrapper passthrough) + 1 render guard case (missing + available tags in
the headline). Full suite 1852 passed, 5 skipped; ty unchanged.
This commit is contained in:
NiJingzhe
2026-09-12 17:03:42 +08:00
parent 4eb01c2076
commit e06109f3d6
4 changed files with 440 additions and 13 deletions
+38 -3
View File
@@ -358,6 +358,16 @@ def __getattr__(name: str):
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
class _RenderTagMismatch(ValueError):
"""Zero-hit ``highlight_tags`` guard.
The message already carries the actionable payload (missing tags plus
the tags that ARE available on these shapes); the render error handler
promotes it to ``what_happened`` instead of demoting it into technical
details.
"""
def render_screenshot_rpath(
shapes: Union[Solid, Sequence[Solid], Any],
output_path: str,
@@ -436,10 +446,30 @@ def render_screenshot_rpath(
)
)
if missing:
raise ValueError(
# Name what IS available: the typo guess ("was it boss_root or
# boss-root?") is answerable only from the shapes themselves.
available = sorted(
{
tag
for shape in solids
if isinstance(shape, Solid)
for tag in (
*shape._list_tags(),
*(face_tag for face in shape._iter_faces()
for face_tag in face._list_tags()),
)
}
)
shown = ", ".join(available[:24]) or "none"
more = (
f" (+{len(available) - 24} more)"
if len(available) > 24 else ""
)
raise _RenderTagMismatch(
"highlight_tags matched no geometry: "
+ ", ".join(missing)
+ " — check tag names and the build stage that produced them"
+ f" — available tags on these shapes: {shown}{more}; "
"check tag names and the build stage that produced them"
)
return str(
_render_sdk_screenshot_rpath(
@@ -467,7 +497,12 @@ def render_screenshot_rpath(
except Exception as e:
_wrap_public_api_error(
operation="render_screenshot_rpath",
what_happened="Failed to render the screenshot.",
# Mechanism-A promotion: the zero-hit guard's payload (missing
# + available tags) is the headline fact, not a footnote.
what_happened=(
str(e) if isinstance(e, _RenderTagMismatch)
else "Failed to render the screenshot."
),
possible_causes=[
"The input does not contain any valid Solid objects.",
"The rendering view or zoom configuration is invalid.",
+227 -10
View File
@@ -36,6 +36,223 @@ _PLACEMENT_TOLERANCE = 1e-7
_ANGLE_TOLERANCE_DEGREES = 1e-6
# --- Structured solve-failure channel -------------------------------------
#
# The solver's five strict-mode raise sites previously emitted one-line
# ValueErrors that discarded the residual data already in hand. These
# helpers raise the same conditions as SimpleCADError (a ValueError
# subclass, so legacy handlers keep working) carrying measurements,
# inventory, and parameterized repair per the error-guidance contract.
# ``raise_harness_error`` passes SimpleCADError through, so the public
# ``solve_assembly_constraints_rassembly`` wrapper surfaces them unchanged.
_INVENTORY_CAP = 16
def _constraint_description(constraint: Constraint) -> str:
"""One-line constraint summary shared by inventory rows and repair text."""
try:
return (
f"{constraint.constraint_kind} "
f"{constraint.connector_a.component_id}"
f"\u2194{constraint.connector_b.component_id}"
)
except Exception:
return str(constraint.constraint_kind)
def _raise_residual_failure(
assembly: Assembly,
residuals: List[ConstraintResidual],
*,
stage: str,
) -> None:
"""Structured failure: constraint residual(s) exceed tolerance.
``stage`` distinguishes mid-solve propagation ("forwarded") from the
final report pass ("final"), which the repair advice differs on.
"""
from ..errors import ErrorMeasurement, InventoryEntry, raise_harness_error
failed = sorted(residuals, key=lambda r: not r.within_tolerance)
measurements = [
ErrorMeasurement("placement tolerance", _PLACEMENT_TOLERANCE, "mm"),
ErrorMeasurement("angular tolerance", _ANGLE_TOLERANCE_DEGREES, "deg"),
]
for residual in failed:
if not residual.within_tolerance:
measurements.extend((
ErrorMeasurement(
f"{residual.constraint_id} translation error",
residual.translation_error, "mm"),
ErrorMeasurement(
f"{residual.constraint_id} angular error",
residual.angular_error_degrees, "deg"),
))
inventory = []
exceeded = 0
for index, residual in enumerate(residuals):
if index >= _INVENTORY_CAP:
break
constraint = assembly.get_constraint(residual.constraint_id)
inventory.append(InventoryEntry(
symbol=residual.constraint_id,
status="ok" if residual.within_tolerance else "exceeded",
description=(
f"{_constraint_description(constraint)}: "
f"\u0394t={residual.translation_error:.3g} mm, "
f"\u0394\u03b8={residual.angular_error_degrees:.3g} deg"
),
))
if not residual.within_tolerance:
exceeded += 1
worst = max(
(r for r in residuals if not r.within_tolerance),
key=lambda r: max(
r.translation_error / max(_PLACEMENT_TOLERANCE, 1e-30),
r.angular_error_degrees / max(_ANGLE_TOLERANCE_DEGREES, 1e-30),
),
default=None,
)
repair = []
if worst is not None:
repair.append(
f"残差最大的约束是 {worst.constraint_id}"
f"(\u0394t={worst.translation_error:.3g} mm, "
f"\u0394\u03b8={worst.angular_error_degrees:.3g} deg):"
"先核对该约束两端 connector 的局部坐标系定义(datum 与接口方向),"
"而不是移动组件位置"
)
repair.extend((
"闭环约束各自满足但合并不满足 = 过约束:解开环路(删一条冗余约束),"
"或让嵌套子装配在内部解算、父级只消费其公共接口",
"重跑 inspect_assembly_constraints_rassembly(assembly) 查看全量残差后再改约束集",
))
failed_ids = ", ".join(
residual.constraint_id for residual in residuals if not residual.within_tolerance
)
raise_harness_error(
operation="solve_assembly_constraints",
what_happened=(
f"{len([r for r in residuals if not r.within_tolerance])} of "
f"{len(residuals)} constraint(s) exceed tolerance at the {stage} "
f"pass: {failed_ids}"
),
possible_causes=[
"A connector's local frame (datum or axis orientation) does not match the intended mating geometry.",
"A closed kinematic loop is overconstrained: each constraint alone fits, the combination cannot.",
"A nested subassembly still owns internal degrees of freedom that the parent cannot close.",
],
how_to_fix=[
"Fix the connector frame definitions named in the repair lines, not the placements.",
"For closed loops, remove one redundant constraint or solve the loop internally in a subassembly.",
],
measurements=measurements,
repair=repair,
inventory=tuple(inventory),
technical_details=(
f"assembly_id={assembly.assembly_id}, "
f"grounded={list(assembly.grounded_component_ids)}"
),
)
def _raise_structural_failure(
assembly: Assembly,
kind: str,
constraint: Optional[Constraint] = None,
unsolved_ids: Optional[List[str]] = None,
) -> None:
"""Structured failure for graph-level solve blockages.
``kind`` is one of ``"unresolvable_loop"``, ``"no_grounded_path"``, or
``"unsolved_components"`` — connectivity failures where residual
numbers do not apply and the repair targets the constraint graph.
"""
from ..errors import ErrorMeasurement, InventoryEntry, raise_harness_error
measurements = [
ErrorMeasurement("component count", len(assembly.components)),
ErrorMeasurement("constraint count", len(assembly.constraints)),
ErrorMeasurement("grounded components", len(assembly.grounded_component_ids)),
]
inventory = []
for component in assembly.components[:_INVENTORY_CAP]:
if component.component_id in assembly.grounded_component_ids:
status = "grounded"
elif unsolved_ids and component.component_id in unsolved_ids:
status = "unsolved"
else:
status = "reachable"
constraint_refs = sum(
1
for existing in assembly.constraints
if component.component_id in (
existing.connector_a.component_id,
existing.connector_b.component_id,
)
)
inventory.append(InventoryEntry(
symbol=component.component_id,
status=status,
description=f"{constraint_refs} connecting constraint(s)",
))
if constraint is not None and kind == "unresolvable_loop":
what = (
f"constraint '{constraint.constraint_id}' "
f"({_constraint_description(constraint)}) forms a closed loop with "
"no feasible scalar inside its limits"
)
repair = [
"给该约束加/放宽 ScalarLimit(angle_limit / distance_limit),"
"或删掉环上一条约束解开环路",
"嵌套子装配先在内部解算闭环,父级消费其公共接口",
]
elif constraint is not None and kind == "no_grounded_path":
what = (
f"constraint '{constraint.constraint_id}' "
f"({_constraint_description(constraint)}) connects two components "
"that are both unreachable from any grounded component"
)
repair = [
"用 ground_component_rassembly 给链路一端加 ground,"
"或补一条连接约束使该组件从 grounded 组件可达",
]
else:
what = (
"components unreachable from any grounded component through the "
"constraint graph: " + ", ".join(unsolved_ids or ())
)
repair = [
"为列出的 [unsolved] 组件补 ground 或连接约束,使其从 grounded 组件可达",
]
raise_harness_error(
operation="solve_assembly_constraints",
what_happened=what,
possible_causes=[
"No grounding path reaches a constrained component.",
"The constraint graph splits into disconnected islands.",
"A closed loop cannot be satisfied within its scalar limits.",
],
how_to_fix=repair[:1] + [
"Inspect the component inventory: [grounded]/[reachable]/[unsolved] "
"is the connectivity verdict.",
],
measurements=measurements,
repair=repair,
inventory=tuple(inventory),
technical_details=f"assembly_id={assembly.assembly_id}, kind={kind}",
)
def constraint_reports_match(
actual: Mapping[str, Any],
expected: Mapping[str, Any],
@@ -223,8 +440,8 @@ def solve_assembly_constraints(assembly: Assembly, strict: bool = True) -> Assem
if adjusted is not None:
assembly = adjusted
elif strict:
raise ValueError(
f"constraint '{constraint.constraint_id}' residual exceeds tolerance"
_raise_residual_failure(
assembly, [residual], stage="forwarded"
)
else:
remaining.append(constraint)
@@ -236,8 +453,8 @@ def solve_assembly_constraints(assembly: Assembly, strict: bool = True) -> Assem
bounds = _constraint_scalar_bounds(constraint)
if bounds is None:
if strict:
raise ValueError(
f"constraint '{constraint.constraint_id}' forms an unresolvable loop"
_raise_structural_failure(
assembly, "unresolvable_loop", constraint=constraint
)
continue
if a_id in solved and b_id in solved:
@@ -248,8 +465,8 @@ def solve_assembly_constraints(assembly: Assembly, strict: bool = True) -> Assem
known_placement = solved[b_id]
else:
if strict:
raise ValueError(
f"constraint '{constraint.constraint_id}' has no grounded path"
_raise_structural_failure(
assembly, "no_grounded_path", constraint=constraint
)
continue
@@ -281,8 +498,8 @@ def solve_assembly_constraints(assembly: Assembly, strict: bool = True) -> Assem
if component.component_id not in solved
)
if strict and unsolved:
raise ValueError(
"unsolved components in constrained assembly: " + ", ".join(unsolved)
_raise_structural_failure(
assembly, "unsolved_components", unsolved_ids=list(unsolved)
)
result = assembly
for component_id, placement in solved.items():
@@ -296,8 +513,8 @@ def solve_assembly_constraints(assembly: Assembly, strict: bool = True) -> Assem
if not residual.within_tolerance
]
if failed:
raise ValueError(
"constraint residual exceeds tolerance: " + ", ".join(failed)
_raise_residual_failure(
result, list(report.residuals), stage="final"
)
result._set_runtime("constraint_report", report.to_dict())
result._set_runtime(
+154
View File
@@ -0,0 +1,154 @@
"""Assembly solve-failure diagnosis (P1 family 7).
The solver's strict-mode raise sites previously discarded the residual and
connectivity data already in hand. These tests pin the structured channel:
residual failures carry measured translation/angular errors with a
worst-first repair; structural failures carry the connectivity verdict
(grounded / reachable / unsolved) as inventory.
"""
from __future__ import annotations
import pytest
import simplecadapi as scad
from simplecadapi.errors import SimpleCADError
def _part_with_origin(part_id: str) -> scad.Part:
body = scad.make_box_rsolid(20.0, 10.0, 2.0)
part = scad.make_part_rpart(part_id=part_id, body=body)
origin = scad.make_placement_connector_rconnector(
connector_id="origin",
placement=scad.make_placement_rplacement(origin=(0.0, 0.0, 0.0)),
)
return scad.add_connector_rpart(part=part, connector=origin)
def _part_with_shifted_mark(part_id: str, shift: float) -> scad.Part:
body = scad.make_box_rsolid(4.0, 4.0, 4.0)
part = scad.make_part_rpart(part_id=part_id, body=body)
mark = scad.make_placement_connector_rconnector(
connector_id="mark",
placement=scad.make_placement_rplacement(origin=(shift, 0.0, 0.0)),
)
return scad.add_connector_rpart(part=part, connector=mark)
def test_residual_failure_measures_translation_error():
# base.origin == moving.mark AND base.far == moving.mark cannot both
# hold: the second fixed constraint lands 15 mm off after the first
# solves — the structured error must carry that number.
base = _part_with_origin("base_part")
base = scad.add_connector_rpart(
part=base,
connector=scad.make_placement_connector_rconnector(
connector_id="far",
placement=scad.make_placement_rplacement(origin=(15.0, 0.0, 0.0)),
),
)
moving = _part_with_shifted_mark("moving_part", shift=5.0)
assembly = scad.make_assembly_rassembly(assembly_id="residual_fixture")
assembly = scad.add_component_rassembly(
assembly=assembly, item=base, component_id="base",
placement=scad.identity_placement_rplacement(),
)
assembly = scad.add_component_rassembly(
assembly=assembly, item=moving, component_id="moving",
placement=scad.identity_placement_rplacement(),
)
assembly = scad.ground_component_rassembly(
assembly=assembly, component_id="base")
assembly = scad.add_fixed_constraint_rassembly(
assembly=assembly, constraint_id="hold",
connector_a=scad.make_connector_ref_rconnectorref("base", "origin"),
connector_b=scad.make_connector_ref_rconnectorref("moving", "mark"),
)
assembly = scad.add_fixed_constraint_rassembly(
assembly=assembly, constraint_id="hold2",
connector_a=scad.make_connector_ref_rconnectorref("base", "far"),
connector_b=scad.make_connector_ref_rconnectorref("moving", "mark"),
)
with pytest.raises(SimpleCADError) as ctx:
scad.solve_assembly_constraints_rassembly(assembly=assembly)
payload = ctx.value.to_dict()
measurements = {m["name"]: m["value"] for m in payload["measurements"]}
assert measurements["hold2 translation error"] == pytest.approx(15.0)
assert measurements["placement tolerance"] == pytest.approx(1e-7)
inventory = {(entry.symbol, entry.status) for entry in ctx.value.guidance.inventory}
assert ("hold2", "exceeded") in inventory
# The repair targets the connector frames, not the placements — moving
# a component cannot fix an inconsistent constraint pair.
assert any("connector" in line for line in ctx.value.guidance.repair)
assert any("hold2" in line for line in ctx.value.guidance.repair)
# Text axiom: the measured error appears in the error text itself.
assert "hold2 translation error: 15" in str(ctx.value)
def test_structural_failure_lists_connectivity_verdict():
# 'island' has no constraint path from the grounded component: the
# inventory is the connectivity verdict, not a bare component list.
part = _part_with_origin("p")
assembly = scad.make_assembly_rassembly(assembly_id="structural_fixture")
assembly = scad.add_component_rassembly(
assembly=assembly, item=part, component_id="base",
placement=scad.identity_placement_rplacement(),
)
assembly = scad.add_component_rassembly(
assembly=assembly, item=part, component_id="floating",
placement=scad.identity_placement_rplacement(),
)
assembly = scad.add_component_rassembly(
assembly=assembly, item=part, component_id="island",
placement=scad.identity_placement_rplacement(),
)
assembly = scad.ground_component_rassembly(
assembly=assembly, component_id="base")
assembly = scad.add_revolute_constraint_rassembly(
assembly=assembly, constraint_id="link",
connector_a=scad.make_connector_ref_rconnectorref("base", "origin"),
connector_b=scad.make_connector_ref_rconnectorref("floating", "origin"),
)
with pytest.raises(SimpleCADError) as ctx:
scad.solve_assembly_constraints_rassembly(assembly=assembly)
guidance = ctx.value.guidance
assert "island" in guidance.what_happened
statuses = {entry.symbol: entry.status for entry in guidance.inventory}
assert statuses["base"] == "grounded"
assert statuses["floating"] == "reachable"
assert statuses["island"] == "unsolved"
assert any("ground" in line for line in guidance.repair)
def test_solve_error_passes_through_public_wrapper():
# The public wrapper must surface the solver's structured payload
# unchanged (raise_harness_error SimpleCADError passthrough) — the
# operation stays the solver's, not the generic wrapper's.
part = _part_with_origin("p")
assembly = scad.make_assembly_rassembly(assembly_id="passthrough_fixture")
assembly = scad.add_component_rassembly(
assembly=assembly, item=part, component_id="base",
placement=scad.identity_placement_rplacement(),
)
assembly = scad.add_component_rassembly(
assembly=assembly, item=part, component_id="floating",
placement=scad.identity_placement_rplacement(),
)
assembly = scad.add_component_rassembly(
assembly=assembly, item=part, component_id="island",
placement=scad.identity_placement_rplacement(),
)
assembly = scad.ground_component_rassembly(
assembly=assembly, component_id="base")
# The constraint gives the solver work to do; the island stays
# disconnected from it, which is the failure being surfaced.
assembly = scad.add_revolute_constraint_rassembly(
assembly=assembly, constraint_id="link",
connector_a=scad.make_connector_ref_rconnectorref("base", "origin"),
connector_b=scad.make_connector_ref_rconnectorref("floating", "origin"),
)
with pytest.raises(SimpleCADError) as ctx:
scad.solve_assembly_constraints_rassembly(assembly=assembly)
assert ctx.value.operation == "solve_assembly_constraints"
+21
View File
@@ -276,5 +276,26 @@ class TestRenderScreenshotMultiView(unittest.TestCase):
self.assertNotEqual(standard.read_bytes(), studio.read_bytes())
class TestZeroHitHighlightGuard(unittest.TestCase):
def test_zero_hit_names_missing_and_available_tags(self):
# The guard must answer the typo question from the shapes
# themselves: the missing tags AND the tags that are actually
# available lead what_happened (mechanism-A promotion), so a
# text-only agent can repair without re-querying.
box = scad.make_box_rsolid(4.0, 3.0, 2.0)
box = scad.apply_tag(box, "role.body")
with tempfile.TemporaryDirectory() as tmp, self.assertRaises(scad.SimpleCADError) as ctx:
scad.render_screenshot_rpath(
box,
str(Path(tmp) / "guard.png"),
highlight_tags=["role.bodyy", "total_fabrication"],
)
text = ctx.exception.guidance.what_happened
self.assertIn("role.bodyy", text)
self.assertIn("total_fabrication", text)
self.assertIn("role.body", text) # the available set contains the typo's neighbor
self.assertIn("available tags", text)
if __name__ == "__main__":
unittest.main()