Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions design-docs/persistent-naming-hints.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Execution-aligned naming hints for stable references (EAPN)

Status: implemented on top of v2.3.0 (`src/simplecadapi/topology/naming_hints.py`, `ElementRef.hints` in
`src/simplecadapi/ref.py`, tests in `test/test_naming_hints.py`). Builds on `stable-refs-design.md`; nothing there is
replaced: the stable anchor and the C++ history walk stay the source of truth, the hints only decide what the anchor
alone cannot.

## 1. What the anchor alone gets wrong (measured)

Corpus: 9,207 SimpleCAD notebooks (LLM rebuilds of STEP parts). Without any edit, re-resolving `scad.ref.of(face, part)`
on the very part it was picked from returned that face for 74.0 % of 30,814 faces in 387 random cases (14.5 % `split`,
11.5 % `lost`). On 120 cases with 360 realistic edits and 240 hard edits (generated by an LLM agent, ground truth
audited against continuation tracking: 99.8 % agreement on pure parameter edits), the v2.3.0 reference was correct
for 87.0 % / 82.0 % of targets with 1.6 % / 3.9 % silent wrong picks. Every failure class is about the *dynamic
identity of operations*, not topology:

| class | example | v2.3.0 behaviour |
|---|---|---|
| copies share a birth | mirror + union of a half part; translate copies of one tool | `split` on every copied face |
| loop siblings share (feature, op, occurrence) | holes made by one line in a loop | `anchor_ambiguous`; after a count change the parameter digest finds a *neighbour* |
| positional piece names | `trace_to_birth` stops at a split, names the piece `topo=face_21` | shifts when anything upstream changes |
| ordinals over lists | `extrusion.side` ordinal 18, `fillet.patch` ordinal 3 | silently another side / patch after a profile or edge-list change |
| call-site ids | `callsite_id` is a hash that changes when *another* line of the cell is edited | sibling grouping breaks |

## 2. The mechanism

In code-based CAD an edit is a new execution of a changed program, so naming is an **alignment between two
executions** (cf. execution indexing, Xin, Sumner & Zhang, PLDI 2008). Each operation node gets an execution index

```
EI(n) = (stable key (feature, op, occurrence), call = normalised code text of the call,
rank among the call's dynamic instances, instance count, own-parameter digest, digest unique?)
```

and a face reference stores, next to its anchor (JSON, `ElementRef.hints`):

* `primary`: the anchor's EI (`sib`), the role's entity count, and the face's ranks / spacings among its siblings;
* `replay`: the EIs of the copy operations and repeated calls on its history path;
* `deep`: for a positional anchor, the role-named birth reached by following single-parent history through splits;
* `context` / `path` / `guard`: generic names of neighbouring faces, branch markers, geometric fingerprint.

Resolution (`resolve_with_hints`):

1. **Align** each EI to the new execution: a unique unchanged own-parameter digest wins (survives reordering); else the
rank when the instance count is unchanged; else *changed* (decided by spatial gating: nearest within half the old
instance spacing); no such call at all is *removed* (a modelling fact: `lost`, never repaired).
2. **Replay**: from the aligned birth, the recorded history (C++ `_resolve_by_history`) gives candidates; keep those
whose path passes through exactly the aligned replay operations (an original never stands for its mirror; a removed
instance never for its neighbour).
3. **Intra-operation naming**: an ordinal is trusted only while the role's entity count is invariant; otherwise a
guarded fingerprint match within half the old role spacing and with agreeing context; split pieces by context and
axis ranks; positional anchors verified against the faces born at the same operation.
4. Anything not narrowed to one face is `split` (candidates) or `lost` (reason, look-alikes). History that reports
`deleted` / `replaced` is final.

Hints are attached only where the anchor has one of the ambiguity classes above (`needs_hints`), so a plain reference
such as `scad.ref.face('base', 'make_box_rsolid', role='box.top', guard=...)` reads exactly as before; a reference
without hints resolves exactly as in v2.3.0.

An optional editor-level layer (not in the SDK, it needs the previous B-rep) checks the history answer against an
independent geometric channel (B-rep graph matching: exact seeds + adjacency propagation, unique only): agreement
picks, disagreement abstains with both candidates, and the geometric channel may fill only a history *gap*.

## 3. Results

Measured with an external research harness (not part of this repository) on 120 corpus cases split 60 / 60 into a
development set (used while designing the rules) and a held-out test set (evaluated once). Edit tasks and ground
truth were generated by an LLM agent and validated by script; on pure parameter edits the labels agree 99.8 % with
an independent continuation-tracking oracle. Correct / silent wrong pick, held-out test set:

| method | normal edits (1,219 targets) | hard edits (567 targets) |
|---|---|---|
| v2.3.0 `scad.ref` (anchor only) | 80.4 % / 3.3 % | 76.9 % / 7.1 % |
| CadQuery-style string selectors | 88.4 % / 10.6 % | 78.1 % / 21.2 % |
| build123d-style filter / sort / group | 87.4 % / 10.2 % | 80.1 % / 16.9 % |
| editor geometric window (`ql` recipe) | 77.1 % / 0.0 % | 58.4 % / 0.2 % |
| B-rep graph matching (deterministic, Jones et al. 2023) | 99.4 % / 0.4 % | 96.8 % / 1.4 % |
| **this change** (`scad.ref.of` with hints, JSON round trip) | **98.6 % / 0.7 %** | **97.4 % / 1.1 %** |

No-edit self-consistency (re-resolving every face of the part it was picked from; 385 cases, 30,365 faces):
73.7 % -> 97.2 % (`lost` 11.7 % -> 0 %). Ablation on the hard development set: without execution alignment
98.6 % -> 86.2 % correct; without path replay -> 96.8 %; without the intra-operation checks -> 97.8 %.
Cost: about 111 ms per face to make and resolve a reference (21 ms before), mostly Python-side history tracing.

On the 14 held-out silent wrong picks that remain, graph matching was right in all 14: an editor-level check against
the previous B-rep (agree -> pick, disagree -> ask) would remove most of them; it is not part of this change.

## 4. Limits

* Faces only (edges keep `between=` naming, which already resolves through face history).
* Spatial gating assumes instances are spaced; a layout that shifts every instance by more than half the spacing
abstains (`lost`).
* Node keys still come from the cell namespace; renaming a cell loses the anchor (as in v2.3.0).
* The hints version is independent of `scad-naming/1`: the anchor format is unchanged.
44 changes: 40 additions & 4 deletions src/simplecadapi/ref.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
import contextvars
import dataclasses
import math
from dataclasses import dataclass
from dataclasses import dataclass, field
from typing import Any, Iterable, Literal, Mapping, Optional, Sequence, Tuple, Union

from . import _cpp
Expand Down Expand Up @@ -164,6 +164,9 @@ class ElementRef:
guard: Optional[Guard] = None
digest: Optional[str] = None
naming: int = 1
# Disambiguation data recorded at pick time (simplecadapi.topology.naming_hints): copies, loop siblings,
# split pieces, moved ordinals. Plain JSON; not part of equality. ``None`` resolves exactly as before.
hints: Optional[Mapping[str, Any]] = field(default=None, compare=False)

def __post_init__(self) -> None:
if self.kind not in _KINDS:
Expand Down Expand Up @@ -214,6 +217,8 @@ def code(self, prefix: str = "scad.ref") -> str:
args.append(f"guard={_guard_code(self.guard)}")
if self.naming != 1:
args.append(f"naming={self.naming}")
if self.hints is not None:
args.append(f"hints={_hints_code(self.hints)}")
return f"{prefix}.{self.kind}({', '.join(args)})"

def __repr__(self) -> str:
Expand All @@ -228,6 +233,8 @@ def to_dict(self) -> dict[str, Any]:
value = [value[0], list(value[1]), value[2], *([list(value[3])] if len(value) == 4 else [])]
elif item.name == "between" and value is not None:
value = [face if isinstance(face, str) else face.to_dict() for face in value]
elif item.name == "hints" and value is None:
continue
out[item.name] = value
return out

Expand Down Expand Up @@ -289,6 +296,10 @@ def resolve(self, shape: Any) -> Resolution:
return self._resolve_in_pieces(list(shape))
if self.between is not None:
return self._resolve_between(shape)
if self.hints is not None and self.kind == "face" and self.follow == "identity" and self.piece is None:
from .topology import naming_hints as _nh

return _nh.resolve_with_hints(self.anchor(), dict(self.hints), shape)
resolved = _er.resolve(self.anchor(), shape, follow=self.follow, guard=self._guard_dict())
if resolved.version_changed and self.guard is not None and resolved.status in ("ok", "merged"):
# Made under other naming rules: the answer stands only if it still looks like what was picked.
Expand Down Expand Up @@ -390,6 +401,12 @@ def query(self) -> Any:
return _selector(self.kind, [self])


def _hints_code(hints: Mapping[str, Any]) -> str:
import json as _json

return repr(_json.loads(_json.dumps(hints)))


def _guard_code(guard: Guard) -> str:
def vec(v: Sequence[float]) -> str:
return "(" + ", ".join(repr(_num(c)) for c in v) + ")"
Expand Down Expand Up @@ -421,6 +438,7 @@ def face(
guard: Optional[Guard] = None,
digest: Optional[str] = None,
naming: int = 1,
hints: Optional[Mapping[str, Any]] = None,
) -> ElementRef:
"""A reference to a face born in *feature* by *op*.

Expand All @@ -437,6 +455,8 @@ def face(
guard: ``(geometry type, (x, y, z), area[, normal])`` of the face when it was picked.
digest: The operation's parameter digest, only when two operations share its name in the feature.
naming: The naming version the reference was made under (1).
hints: Disambiguation hints recorded when the face was picked (:func:`of` writes them;
:mod:`simplecadapi.topology.naming_hints`). Leave out to resolve by the anchor alone.

Returns:
ElementRef: The reference; resolve it with ``.one(shape)`` / ``.all(shape)`` / ``.resolve(shape)``.
Expand All @@ -446,7 +466,7 @@ def face(
>>> top.one(part).get_area()
"""
return _make("face", feature, op, role=role, ordinal=ordinal, topo=topo, occurrence=occurrence, slot=slot,
piece=piece, follow=follow, guard=guard, digest=digest, naming=naming)
piece=piece, follow=follow, guard=guard, digest=digest, naming=naming, hints=hints)


def edge(
Expand Down Expand Up @@ -529,7 +549,8 @@ def solid(
digest=digest, naming=naming)


def of(entity: Any, shape: Any, *, follow: Follow = "identity", guard: bool = True) -> ElementRef:
def of(entity: Any, shape: Any, *, follow: Follow = "identity", guard: bool = True,
hints: Union[bool, Literal["always"]] = True) -> ElementRef:
"""The stable reference of *entity*, a face, edge or vertex of *shape* (or of a shape *shape* descends from).

The entity is traced back through the recorded history to where it was born, so a face picked on the finished
Expand All @@ -541,6 +562,11 @@ def of(entity: Any, shape: Any, *, follow: Follow = "identity", guard: bool = Tr
shape: A recorded shape (made inside a ``GraphSession`` or a notebook cell) it belongs to.
follow: Stored in the reference (see :func:`face`).
guard: Store the entity's geometric fingerprint (the default; needed for an entity without a kernel role).
hints: Store the disambiguation hints of a face (:mod:`simplecadapi.topology.naming_hints`): copies, loop
siblings, split pieces and moved ordinals are then told apart after edits. ``True`` (default) stores them
only when the face is ambiguous where it is picked, so a plain reference reads as before; ``"always"``
also guards against ambiguity an edit introduces later (another operation of the same kind inserted in
the feature) -- what generated code such as the editor's selections should use; ``False`` never.

Returns:
ElementRef: ``repr()`` is the code that makes the same reference.
Expand All @@ -553,7 +579,17 @@ def of(entity: Any, shape: Any, *, follow: Follow = "identity", guard: bool = Tr
named = _edge_between(entity, shape, fingerprint)
if named is not None:
return named
return _born(entity, shape, follow=follow, fingerprint=fingerprint)
born = _born(entity, shape, follow=follow, fingerprint=fingerprint)
if hints and follow == "identity" and born.kind == "face":
from .topology import naming_hints as _nh

try:
data = _nh.compute_hints(entity, shape)
except Exception: # noqa: BLE001 - hints are an addition: a reference without them resolves as before
data = None
if data is not None and (hints == "always" or _nh.needs_hints(data)):
born = dataclasses.replace(born, hints=data)
return born


def _born(entity: Any, shape: Any, *, follow: str = "identity", fingerprint: Any = None) -> ElementRef:
Expand Down
Loading
Loading