diff --git a/design-docs/stable-refs-design.md b/design-docs/stable-refs-design.md index d9301155..8a50a02b 100644 --- a/design-docs/stable-refs-design.md +++ b/design-docs/stable-refs-design.md @@ -164,22 +164,79 @@ The kernel records one `TopoDelta` per node: witnesses with event `preserved`/`m | Section / split | section, split | not probed | -- | **[I]** | | Sketch | sketch solve -> wire/face | no deltas on edge/wire/face construction nodes | a profile edge's identity is its sketch geometry id (FreeCAD's `g1;SKT`) | **[I]**, stage 2 | -### 3.1 Tag propagation, production-grade [I] +### 3.1 Tags are a view over recorded history (owner decision: switch directly) -Today a tag is projected *forward* by every operation through `apply_tracking_tags` with per-channel lineage policies -(`LineagePolicy`, `lineage_policy_allows`) **[R]**, which is where the gates and gaps live. Proposal: +**Model.** A tag assignment is already a graph node: `apply_tag_rselection` and every op-kwarg tag +(`top_face_tag=`) record an `apply_tag_*` node whose `tag_binding` parameter holds the binding and its target +anchors (`explicit_refs`, or `selection_query` with `evidence.selected_refs`) **[R]**. So a tag needs no copy on +every later shape: the tags of an entity of node N's output are *computed* from N's upstream graph: -- A tag binding stores an `ElementRef` (anchor at the node where the tag was applied, `follow` and `pick` from the - tag's lineage policy: `continuation_fragment` ~ identity with `pick: all`, an edge-source tag ~ derived). -- `ql.tag("x")` on shape S = resolve the binding's refs to S's node. Split -> all pieces carry the tag (status kept - so `.exactly(n)` can explain itself); merged -> the merged face carries it; lost -> the tag is absent and - `explain_tag` says where it died and why. -- Resolution is lazy (at query time) and memoised per (binding, node): no per-op projection cost, and old tags keep - working on values restored from the cell cache because the deltas travel with the nodes (2.2, 4.3). -- Stage it behind the existing API: keep the projection for one release, compare both on the test corpus, then make - the projection a cache of the resolver. +``` +tags(N, e) = own bindings of e (the op's kernel roles; bindings set on N's own output) + + every binding B of a tag node upstream of N whose anchors reach e through the deltas, + step by step, as B's lineage policy allows +``` ---- +Per step (node M with a delta, for every witness whose parent carries B): + +| witness | carried when | +|---|---| +| `preserved` / `modified`, same kind | `lineage_policy_allows(B, derivation)`: continuation (`continuation`), continuation + fragment (`continuation_fragment`, the default: a split face tags *all* its pieces), explicit list | +| `generated` | never by continuation: a face a feature generates from a tagged source (fillet / chamfer patch from its edge, extrude / loft side from its profile edge) is *named* by that operation after its source when it runs (the projected binding, `semantic/autotag.cpp`), an op-local fact like a kernel role | +| `deleted`, not mentioned, or a node without history | not carried: the tag ends there, and `explain_tag` says where | + +Identity ops (tag assignments, selections) pass everything on under their own node. The view is computed +**incrementally per node** from its inputs' views and its own delta (O(delta entries) per node), memoised per node +object (nodes are immutable), so a query costs a lookup after the first one. It lives in the C++ kernel +(`scad::reactive` tag view, `src/cpp/src/reactive/tag_view.cpp`) and is installed as the topo layer's +history-witness provider, so `Shape::has_tag` / `list_tags` / `list_tag_bindings` / `explain_tag` and therefore +every `ql.tag(...)` call site see it without any API change **[T]** (`test_tag_view.cpp`, the audit). + +**One path per binding, chosen by where the binding lives.** A binding a *recorded* tag assignment made +(producer `user_operation` with a node id, on a value that is part of a recorded graph) is carried only by the view: +the per-operation copy (`carry_source_lineage`, `project_source_bindings` in `semantic/autotag.cpp`) skips it. What +only the shapes know keeps the copy: imported sidecar facts (`provenance.*` of a `.scadbrep`), sketch topology names, +tags assigned outside a session, values replayed without a recording session, and the projected names above. There +is no binding that both paths carry, so nothing is duplicated, and no compatibility switch. **[T]** (full suite: the +brep provenance, sketch exact-source-identity and replayed-connector tests exercise the shape path.) + +**Scopes.** `local` = bindings stored on the entity; `inherited` = from containing entities (downward +propagation); `lineage` = the history view; `effective` (the default of `ql.tag`) = local + inherited + lineage. +This is the visible change: a plain user face tag now survives booleans, blends, shells, copies and patterns +(it used to stop at the face-source gate), and an op-kwarg tag survives fillets and copies. + +**Persistence and versioning.** The tag lives in its graph node, so it travels with the cell cache (the lineage +record of a cell holds its nodes, deltas and `tag_binding` params) and with model JSON; nothing is pickled on +shapes. The binding has its schema version; the view algorithm is versioned with the naming version (section 5). + +**Bodies.** A view entry is keyed by (output slot, kind, topo id) of the node's output, so a multi-body node +(several slots, or one compound of bodies) keeps the body apart; references report which body (slot / solid) each +target lies in. + +### 3.2 Target API: queries, references, tags (production-grade) + +```python +# selection: a query is data (serialisable), resolution is explicit, cardinality is asserted +q = ql.faces().where(ql.tag("mount.face")) # tags through history (3.1) +faces = q.exactly(2).resolve(part) # error lists per-predicate counts and near misses +report = q.explain(part) # the same, as data: counts per predicate, candidates + +# references: stable anchors resolved through history (section 2, 4) +ref = scad.ref.of(face, part) # ElementRef: stable anchor + guard, JSON +ref.resolve(part) -> Resolution(status, entities, candidates, lost_at, reason, hops, bodies) +ref.one(part) / ref.all(part) # ElementRefError(status, candidates) unless exactly one / ok +ql.faces().where(ql.ref(ref)) # a reference as a predicate + +# tags: names over references +scad.apply_tag_rselection(part, faces, "mount.face") # unchanged; recorded as a tag node +scad.explain_tag(face, "mount.face") # binding, anchors, hops, where it stopped and why +ql.tag("mount.face", follow="derived") # also generated descendants (edge tag -> its patch) +ql.faces().where(ql.body("left")) # with research/multi-solid: per-body scoping +``` + +Stages: the view and the scopes (3.1) and the resolver (`simplecadapi.topology.element_ref`: `resolve`, +`require`, `stable_anchor_of`, `guard_of`) are on this branch; `scad.ref` as a public module, `ql.ref`, +`ql.body`, `Query.explain` follow (section 7). ## 4. Resolution, failure statuses, and what the editor shows @@ -242,33 +299,33 @@ way). On mismatch: resolve anyway, compare against `guard` and `last`; if they a if not, report `lost(version_changed)` with candidates. Refs never need a migration step of their own because they store anchors and policies, not resolved names. -## 6. Audit: does tag/history propagation work per family today +## 6. Audit: tag and history propagation per family (before -> now) All rows **[T]** in `test/test_element_ref_history.py` (`test_audit_tag_channels_and_history_per_family` and the -status tests) unless marked; **[R]** cells were seen in a probe run but are not asserted. -Probe: box 40x20x10 with the top face tagged by kwarg (`kw.top`) and by `apply_tag_rselection` (`user.top`). +status tests) unless marked; **[R]** = seen in a probe, not asserted. Probe: box 40x20x10 with the top face tagged +by kwarg (`kw.top`) and by `apply_tag_rselection` (`user.top`). "Before" is `dev` @ `093ef71`. -| Family | plain tag | kwarg tag | history resolver | Missing | -|---|---|---|---|---| -| cut | dies | survives | ok (trimmed top) | plain tag gate | -| cut through the face | dies **[R]** | survives on both pieces **[R]** | **split** (2 pieces) | -- (statuses are new) | -| cut removing the face | dies **[R]** | dies **[R]** | lost(deleted) | -- | -| union (disjoint top) | dies | survives | ok | plain tag gate | -| union (coplanar) | dies **[R]** | survives **[R]** | **merged** | merge not visible to tags | -| intersect | dies | survives | ok | plain tag gate | -| fillet / chamfer | dies | **dies** | ok | face-channel gap in tag projection | -| shell, face kept | dies | survives (since 7.2) | ok (was lost/replaced) | -- (fixed, 7.2) | -| shell, face removed | dies | survives (on the rim) | ok (the rim) | -- | -| translate / rotate / mirror | dies | **dies** | ok | tag projection ignores continuation witnesses | -| linear pattern (instance 3) / radial pattern (instance 2) | dies | dies | ok | same | -| transform_rsolid, scale_rsolid | dies | dies | ok (was lost/no_history) | -- (fixed: `modification_delta`) | -| offset_rsolid | dies | dies | ok (was lost/no_history) | -- (fixed) | -| draft | -- | -- | ok, the drafted face and its trimmed neighbours | -- (fixed) | -| helical sweep | -- | -- | ok through its sweep node | -- (never a gap) | -| edge -> fillet patch | (edge-source tags survive, playbook) | -- | lost(deleted) identity; the patch in derived mode | -- | -| extrude cap -> fillet | -- | **dies** | ok | face-channel gap | -| extrude / revolve / loft / sweep end cap -> union -> translate | -- | -- | ok (same area) | -- | -| loft sides | -- | -- | not probed; playbook says kernel-matched | section naming | +| Family | plain tag before -> now | kwarg tag before -> now | history resolver before -> now | +|---|---|---|---| +| cut | dies -> survives | survives -> survives | ok | +| cut through the face | dies -> both pieces **[R]** | both pieces **[R]** | split (2 pieces) | +| cut removing the face | dies | dies | lost(deleted) | +| N-ary cut (3 tools) | dies -> both pieces | -- | lost(replaced) -> split (composed steps, 7) | +| union (disjoint / coplanar) | dies -> survives | survives | ok / merged | +| intersect | dies -> survives | survives | ok | +| fillet / chamfer | dies -> survives | dies -> survives | ok | +| shell, face kept | dies -> survives | dies -> survives | lost(replaced) -> ok (7.2) | +| shell, face removed | dies -> survives (the rim) | survives | ok (the rim) | +| translate / rotate / mirror | dies -> survives | dies -> survives | ok | +| linear / radial pattern instance | dies -> survives | dies -> survives | ok | +| transform_rsolid, scale_rsolid, offset_rsolid | dies -> survives | dies -> survives | lost(no_history) -> ok | +| draft | -- | -- | lost(no_history) -> ok (drafted face and neighbours) | +| helical sweep | -- | -- | ok through its sweep node (never a gap) | +| edge -> fillet patch | the fillet names the patch after the edge (projection, unchanged) | -- | lost(deleted) identity; the patch in derived mode | +| extrude cap -> fillet | -- | dies -> survives | ok | +| creator end caps (extrude / revolve / loft / sweep) -> union -> translate | -- | -- | ok | +| tag after pickling the value | -- | -- | survives (`test_a_tag_survives_pickling_with_its_history`) | +| loft sides | -- | -- | not probed; kernel-matched (section naming, stage 2) | --- diff --git a/docs/skill/references/discipline/geometric-validation.md b/docs/skill/references/discipline/geometric-validation.md index e3e0fe77..aaf69e5b 100644 --- a/docs/skill/references/discipline/geometric-validation.md +++ b/docs/skill/references/discipline/geometric-validation.md @@ -53,8 +53,10 @@ review. picks are preserved as graph geo-select nodes. - `apply_tag(shape=..., tag=...)` attaches a tag to exactly the given shape with LOCAL scope — it never propagates downward; `list_tags(shape=...)` - reads effective tags. Downward/topology-scoped propagation is only exposed - by `apply_tag_rselection` with an explicit propagation policy. Keep numeric + reads effective tags, which include the tags the recorded history carries + to the entity (a tagged face stays tagged through later booleans, blends + and copies). Downward/topology-scoped propagation is only exposed by + `apply_tag_rselection` with an explicit propagation policy. Keep numeric facts in metadata, never in tags. - A QL-selected face or edge reused by a later feature is preserved as a stable geo-select node in replayable graphs. diff --git a/docs/skill/references/docs/api/tag.md b/docs/skill/references/docs/api/tag.md index 6effaaa3..afab3f6a 100644 --- a/docs/skill/references/docs/api/tag.md +++ b/docs/skill/references/docs/api/tag.md @@ -16,6 +16,13 @@ def tag(pattern, scope='effective') Build a tag predicate for QL filtering. +Tags are a view over the recorded history: a tag assigned in a +``GraphSession`` reaches every entity its target became through later +operations (a face cut in two keeps it on both pieces), as its lineage +policy allows. ``local`` is what the entity itself stores, ``inherited`` +what containing entities pass down, ``lineage`` what the history carries, +and ``effective`` (the default) all three. + ## Parameters ### pattern diff --git a/docs/skill/references/ql-playbook.md b/docs/skill/references/ql-playbook.md index 9b8d1015..30a388a9 100644 --- a/docs/skill/references/ql-playbook.md +++ b/docs/skill/references/ql-playbook.md @@ -37,33 +37,43 @@ around it as shown. session, and the next operation rejects it with "graph node not owned by active graph" (same surface message as the timing defect in rule 3). -3. **Tag in time — the tag lands in the step right after the operation - that produced the targets.** Projections into later outputs are - computed when each operation runs, so a tag that arrives after a - later operation has already consumed the shape can never reach - anything. Tagging there is rejected with "graph node not owned by - active graph" — the message names ownership, but the real defect is - timing. When targets only become addressable later, re-derive the - selectors from the newest result and tag immediately, before the - next operation consumes it (Pattern B tags the seam directly after - the union; the bore recipe below tags right after the cut). +3. **Tag the value you go on with.** A tag reaches the results of the + operations that consume the tagged value (the clone + `apply_tag_rselection` returns), through their recorded history. A tag + applied to a shape an operation has already consumed can never reach + that operation's result. Tagging such a stale value is rejected with + "graph node not owned by active graph" — the message names ownership, + but the real defect is timing. When targets only become addressable + later, re-derive the selectors from the newest result and tag that + (Pattern B tags the seam directly after the union; the bore recipe + below tags right after the cut). 4. **Enumerate with QL, not plural getters.** `ql.edges().resolve(shape)`, never bare `get_edges()` (raises by design; enumeration is QL-exclusive). -5. **Pick the naming channel by the reach you need:** +5. **Tags are a view over recorded history.** Every tag assignment + (`apply_tag_rselection`, an op-kwarg tag such as `top_face_tag=`) is a + graph node; `ql.tag(...)` on a later shape finds the entities the tagged + ones became, through each operation's kernel history, as the tag's + lineage policy allows (default `continuation_fragment`: a face cut in two + keeps the tag on both pieces). Verified per family in + `test/test_element_ref_history.py` (audit): - | Channel | Example | Survives boolean | Survives fillet/chamfer | + | Channel | Example | Survives boolean | Survives fillet/chamfer, shell, copies, patterns, transform/scale/offset/draft | | --- | --- | --- | --- | - | op-kwarg role naming | `extrude_rsolid(..., end_face_tag="cap.top")`, `make_box_rsolid(..., top_face_tag="base.top")` | yes (verified) | **no** (face channel gap) | - | source-edge naming | `apply_tag_rselection(profile, [edge], "profile.long.a")` → side face; `apply_tag_rselection(result, [seam], "seam.d")` → fillet patch | yes (via kernel images) | **yes** (edge→patch projection) | + | op-kwarg role naming | `extrude_rsolid(..., end_face_tag="cap.top")`, `make_box_rsolid(..., top_face_tag="base.top")` | yes | yes | + | plain user tag on a face | `apply_tag_rselection(solid, [face], "base.body")` | yes | yes | + | source-edge naming | `apply_tag_rselection(profile, [edge], "profile.long.a")` → side face; `apply_tag_rselection(result, [seam], "seam.d")` → fillet patch | yes | yes (the op names the generated face after its edge) | | `origin_role("body"/"tool")` | parent argument of a boolean | single-step only | no | | `output_role("")` | `extrusion.end`, `box.top`, `fillet.patch` | single-step only | own op only | - | plain user tag on a face | `apply_tag_rselection(solid, [face], "base.body")` | **no** (face-source gate) | **no** | "Single-step" means the metadata describes the last operation that touched - the shape; the next tracked operation overwrites it. Long-range identity = - op-kwarg names (across booleans) and edge-source names (across modifiers). + the shape; the next tracked operation overwrites it. A tag ends where the + history says the entity ends: a face a cut removes, a face a feature + replaces by a generated one (a fillet's patch is a new face, not the + edge), or an operation that records no history. `scad.explain_tag(face, + tag)` shows the binding and the lineage that carried it. The `lineage` + scope is the carried part alone; `effective` (the default) includes it. ## The selection loop (card before cardinality) @@ -236,34 +246,37 @@ ql.select(ql.faces().resolve(shape)).where(ql.prop("geom.type", "==", "PLANE")) ## Verified boundaries -Current engine gaps found by the harnesses — each has a workaround above: +What the harnesses established about the engine's reach — limits and +behaviours to design around: -1. **Plain user tags on faces do not project through any later op.** The - face-source projection gate (`autotag._project_source_bindings` with - `require_lineage_policy=True`) passes only operation-output and topology - naming; plain user bindings project from **edge** sources only. Use - op-kwarg names for cross-boolean face identity, edge names for - cross-modifier identity. -2. **Modifier face-source projection lacks `project_source_tags`** - (`tracking.py`, `tracked_fillet`/`tracked_chamfer` face query). Face names - — even op-kwarg ones that survive booleans — are dropped when the face is - trimmed by a fillet/chamfer. The edge→patch channel is complete (7/7). +1. **Tags stop where kernel history stops.** An operation that records no + topology history ends every tag through it (none of the solid modelling + operations do since the stable-refs work; check `node.topo_delta` for a + new operator). Within history a tag follows only entities that live on: + a generated face is named after its source by the operation itself + (fillet patches, extrude sides), never by continuation. +2. **Tags assigned outside a `GraphSession`, imported sidecar facts and + sketch topology names live on the shapes** and are carried by the + operations' projection, not by the recorded view: model inside a session + so the graph carries your tags (and they survive the cell cache). 3. **`origin_role` / `output_role` are single-step metadata.** After the seam fillet, every face reports the fillet's own roles; the boolean body/tool partition is gone. Query parent identity immediately after the boolean, or carry it as a name. -4. **Primitive auto role tags (`face.box.top`, ...) do not project through - booleans** — only kwarg-named slots (`top_face_tag="base.top"`) do. +4. **Primitive auto role tags (`face.box.top`, ...) are tags like any other:** + they follow their face through later operations in the effective scope, + so `face.box.top` on a finished part means "descends from the box's top". + Use `ql.output_role(...)` when you mean "the role in the last operation". 5. **The planar profile in-plane basis switches discontinuously near vertical.** The reference-axis branch (`|z_z| > 0.9`) in the plane-basis helper swaps its reference between global X and Z, so sweeping a plane normal across roughly 25° from vertical rotates the in-plane frame abruptly. When normals vary, address profile edges by length and center sign rather than by axis assumptions. -6. **N-ary cut unrolls hop-by-hop**; multi-hop modification chains can lose - projected bindings (later hops overwrite earlier witnesses for the same - output). For long-range names across a cut chain, prefer naming after the - final cut, or union-side naming. +6. **An N-ary cut is followed step by step:** its steps name the + intermediate solids, and the recorded delta composes them back to the + real inputs, so names and references cross the whole chain + (`test_an_n_ary_cut_composes_its_steps`). ## Verification harnesses diff --git a/docs/skill/references/ql-recipes.md b/docs/skill/references/ql-recipes.md index 1b595d4a..596f4b37 100644 --- a/docs/skill/references/ql-recipes.md +++ b/docs/skill/references/ql-recipes.md @@ -77,7 +77,7 @@ with GraphSession(graph_id="blend") as s: ## Recipe: tagged bore -> rim chamfer -Tag the bore wall right after the cut (Ground rule 3: tag in time), +Tag the bore wall right after the cut (Ground rule 3: tag the value you go on with), then chamfer its top rim: ```python diff --git a/examples/SDK_DEFECTS.md b/examples/SDK_DEFECTS.md index 5fe0d04a..74c5eedb 100644 --- a/examples/SDK_DEFECTS.md +++ b/examples/SDK_DEFECTS.md @@ -328,16 +328,16 @@ that surfaced it is in brackets. - **Fix direction:** done. Every `ql` factory should resolve against any scope that contains its kind; check each (kind, scope) pair when adding a factory. -## 21. Op-kwarg face tags die at translate, mirror and patterns despite full history [stable-refs research] +## 21. Face tags died at the next operation, op-kwarg ones at blends and copies [stable-refs research] -- **Symptom:** `make_box_rsolid(..., top_face_tag="kw.top")` then `translate_shape`, `mirror_shape` or - `linear_pattern_rsolidlist`: `ql.tag("kw.top")` finds 0 faces on the result. -- **Trigger:** any rigid copy after an op-kwarg tag; plain `apply_tag_rselection` face tags die at every op. -- **Root cause:** the tag projection drops the channel, not the kernel: these nodes record a `modified` / - `continuation` witness for every face (`test_element_ref_history.py` audit resolves the face through them). -- **Status:** open; documented in `design-docs/stable-refs-design.md` section 6. -- **Fix direction:** make tags a view over history-resolved references (design section 3.1) instead of per-op - projection with per-channel gates. +- **Symptom:** a plain `apply_tag_rselection` face tag was gone after any later operation; an op-kwarg face tag + (`top_face_tag=`) survived booleans but not fillet, chamfer, translate, mirror or patterns, although those nodes + record a witness for every face. +- **Root cause:** tags were copied forward per operation (`autotag.cpp`) through channel-specific gates (the + face-source gate, the face channel of blends), and the effective scope excluded lineage. +- **Status:** fixed. Tags are a view over the recorded history (`scad/reactive/tag_view.hpp`): a recorded tag + assignment reaches every entity its targets became, per lineage policy, and effective includes lineage. + Audit: `test_element_ref_history.py::test_audit_tag_channels_and_history_per_family` (every family 1/1). ## 22. `OperationGraph::from_value` header says deltas are not restored; they are [stable-refs research] diff --git a/src/cpp/bindings/python/module.cpp b/src/cpp/bindings/python/module.cpp index 38562de8..d4a012f9 100644 --- a/src/cpp/bindings/python/module.cpp +++ b/src/cpp/bindings/python/module.cpp @@ -1,11 +1,13 @@ #include "bindings.hpp" #include "occt/occt.hpp" #include "scad/core/error.hpp" +#include "scad/reactive/tag_view.hpp" PYBIND11_MODULE(_native, m, py::mod_gil_not_used()) { m.doc() = "SimpleCADAPI on OpenCASCADE, implemented in C++ (pybind11)."; scad::set_error_module_name("simplecadapi._cpp"); scad::pybind::register_exceptions(m); + scad::reactive::install_tag_view(); // tags of recorded values are read through their recorded history bind_core(m); bind_topo(m); diff --git a/src/cpp/include/scad/reactive/tag_view.hpp b/src/cpp/include/scad/reactive/tag_view.hpp new file mode 100644 index 00000000..121ff392 --- /dev/null +++ b/src/cpp/include/scad/reactive/tag_view.hpp @@ -0,0 +1,60 @@ +// Tags as a view over recorded history. +// +// A tag assignment is a graph node (apply_tag_rselection, and every op-kwarg tag such as top_face_tag=): its +// `tag_binding` parameter holds the binding and the entities it targets. The tags an entity of node N's output +// carries from upstream are therefore computed, not copied: N's view is built from the views of its inputs and +// N's own TopoDelta, witness by witness, as each binding's lineage policy allows: +// +// * preserved / modified (same kind) carried when lineage_policy_allows(binding, derivation) +// (continuation_fragment, the default: every piece of a split face); +// * generated not a continuation: an entity generated from a tagged source (an edge's +// fillet patch, a profile edge's side face) carries the operation's own +// projected binding, stored on it when the operation ran (autotag.cpp) +// and carried on with the shapes (the graph does not record it); +// * deleted / not witnessed / an op without history: not carried, the tag ends there. +// +// The view knows the bindings the graph records. What only shapes know (imported sidecar facts, sketch topology +// names, tags assigned outside a session, projected names) stays on the shapes and is carried there. +// +// Identity ops (tag assignments, selections) pass their input's view on unchanged. A view is computed once per +// node object (nodes are immutable) and memoised; building it costs O(entries of the node's delta). +// +// install_tag_view() makes the topo layer ask this view for an entity's lineage witnesses, so has_tag / +// list_tags / list_tag_bindings / explain_tag (and every ql.tag) see it. See design-docs/stable-refs-design.md 3.1. +#pragma once + +#include +#include +#include +#include + +#include "scad/reactive/graph.hpp" +#include "scad/topo/shape.hpp" +#include "scad/topo/tagging.hpp" + +namespace scad::reactive { + +// One binding carried to one entity of a node's output. +struct CarriedTag { + TagBinding binding; + LineageDerivation derivation = LineageDerivation::Continuation; + std::string source_node_id; // where the binding was assigned + std::string source_topo_id; // the entity it was assigned to there (recorded form, "face_face_5") + std::string op; // the op of the last step that carried it +}; + +// "\x1f\x1f" -> the bindings carried to that entity. +using TagView = std::unordered_map>; + +std::string tag_view_key(int output_slot, Kind kind, const std::string& recorded_topo_id); + +// The view of `node` (memoised). Never null for a non-null node. +std::shared_ptr tag_view(const NodePtr& node); + +// The lineage witnesses the history carries to `entity`, a sub-shape of a recorded output (empty otherwise). +std::vector history_witnesses(const Shape& entity); + +// Install history_witnesses as the topo layer's history-witness provider. Idempotent. +void install_tag_view() noexcept; + +} // namespace scad::reactive diff --git a/src/cpp/include/scad/semantic/autotag.hpp b/src/cpp/include/scad/semantic/autotag.hpp index d887cceb..18c34b30 100644 --- a/src/cpp/include/scad/semantic/autotag.hpp +++ b/src/cpp/include/scad/semantic/autotag.hpp @@ -5,7 +5,11 @@ // * a typed `track` metadata envelope on every face and edge, // * `.` bindings for kernel-proven output roles, // * lineage witnesses: which source tag bindings reach which result entity, -// * projected bindings for user tags the tracker proved should follow a feature. +// * projected bindings for source tags the tracker proved should follow a feature. +// Copied are the bindings only the shapes know (imported sidecar facts, sketch topology names, tags assigned +// outside a recording session) and, for any binding, the naming of a generated entity after its source (the +// projected binding of a fillet patch or an extrude side face). The continuation of a binding a recorded tag +// assignment made is carried by the tag view over the recorded history instead (scad/reactive/tag_view.hpp). // Missing evidence stays "unknown": nothing is guessed from geometry. // // Operators do not call this directly; finalize_tracked (finalize.hpp) does. diff --git a/src/cpp/include/scad/topo/shape.hpp b/src/cpp/include/scad/topo/shape.hpp index 052ecd93..11f701ef 100644 --- a/src/cpp/include/scad/topo/shape.hpp +++ b/src/cpp/include/scad/topo/shape.hpp @@ -48,6 +48,13 @@ class Face; class Shell; class Solid; class Compound; +class Shape; + +// Tags as a view over recorded history: the reactive layer installs a provider that answers, for an entity of a +// recorded output, the bindings of upstream tag assignments the operations' deltas carry to it (as lineage +// witnesses). None installed (a bare kernel): only the witnesses stored on the entity count. +using HistoryWitnessProvider = std::vector (*)(const Shape& entity); +void set_history_witness_provider(HistoryWitnessProvider provider) noexcept; class Shape { public: @@ -74,6 +81,8 @@ class Shape { bool is_same(const Shape& other) const noexcept; // Same entity: same root and same topology. bool same_entity(const Shape& other) const noexcept; + // A handle on this handle's root (the shape whose entity table this one shares). + Shape root() const; // The graph node that produced this output, as an opaque pointer (the reactive layer knows its type). void set_graph_node(std::shared_ptr node) const; std::shared_ptr graph_node() const; @@ -112,7 +121,13 @@ class Shape { // Mutators keep the tag-name caches in step. const std::vector& local_bindings() const; void add_binding(TagBinding binding); - const std::vector& lineage_witnesses() const; + // The lineage witnesses of this entity: those stored on it, then those the history-witness provider derives + // from the recorded graph (tags carried through the operations' deltas; see set_history_witness_provider). + std::vector lineage_witnesses() const; + // Only the witnesses stored on the entity (add_lineage_witness, a restored snapshot). + const std::vector& stored_lineage_witnesses() const; + // Only the witnesses the history-witness provider derives (none without a provider or a recorded graph). + std::vector history_lineage_witnesses() const; // Skipped when the same (binding, derivation, source, target) witness is already stored. void add_lineage_witness(TagLineageWitness witness); diff --git a/src/cpp/src/reactive/session.cpp b/src/cpp/src/reactive/session.cpp index cdd7a537..3a66f516 100644 --- a/src/cpp/src/reactive/session.cpp +++ b/src/cpp/src/reactive/session.cpp @@ -1,4 +1,5 @@ #include "scad/reactive/session.hpp" +#include "scad/reactive/tag_view.hpp" #include #include @@ -406,7 +407,10 @@ std::string_view to_string(NodeStatus status) noexcept { Session::Session(Options options) : graph_(options.graph_id, options.ns), options_(options), - registry_(options.registry != nullptr ? options.registry : &ExecutorRegistry::global()) {} + registry_(options.registry != nullptr ? options.registry : &ExecutorRegistry::global()) { + // Tags of recorded values are read through the recorded history. + install_tag_view(); +} Session::~Session() { // Destroyed while still installed: leave the thread as it was found. stop() is noexcept, so nothing diff --git a/src/cpp/src/reactive/tag_view.cpp b/src/cpp/src/reactive/tag_view.cpp new file mode 100644 index 00000000..cfd271e0 --- /dev/null +++ b/src/cpp/src/reactive/tag_view.cpp @@ -0,0 +1,286 @@ +#include "scad/reactive/tag_view.hpp" + +#include +#include +#include +#include + +#include "scad/reactive/lineage.hpp" +#include "scad/topo/tag_factories.hpp" + +namespace scad::reactive { + +namespace { + +const Value* member(const Value& object, const char* key) { + return object.is_object() ? object.find(key) : nullptr; +} + +std::string text(const Value* value) { + return value != nullptr && value->is_string() ? value->as_string() : std::string{}; +} + +std::optional kind_from(const std::string& name) { + std::string lowered = name; + std::transform(lowered.begin(), lowered.end(), lowered.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + for (const Kind k : {Kind::Vertex, Kind::Edge, Kind::Wire, Kind::Face, Kind::Shell, Kind::Solid, Kind::Compound}) { + if (kind_name(k) == lowered) + return k; + } + return std::nullopt; +} + +bool is_tag_op(const std::string& op) { + return op.starts_with("apply_tag"); +} + +bool is_selection_op(const std::string& op) { + return op.starts_with("make_select_"); +} + +bool has_history(const OperationNode& node) { + return node.topo_delta && !node.topo_delta->entries.empty(); +} + +// The derivation a witness proves; nullopt for one no lineage policy speaks of. +std::optional derivation_of(const TopoEntry& entry) { + if (entry.event == TopoEvent::Preserved) + return LineageDerivation::Continuation; + const std::string token = text(member(entry.metadata, "derivation")); + try { + return parse_lineage_derivation(token.empty() ? "continuation" : token); + } catch (const TagValidationError&) { + return std::nullopt; + } +} + +void carry(std::vector& into, CarriedTag tag) { + const auto same = std::find_if(into.begin(), into.end(), + [&](const CarriedTag& t) { return t.binding.binding_id == tag.binding.binding_id; }); + if (same == into.end()) + into.push_back(std::move(tag)); +} + +// The entities a tag assignment targets, as keys of its own output (slot 0). +std::vector> targets_of(const TagBinding& binding) { + std::vector refs; + if (binding.target().kind == TagTargetKind::ExplicitRefs) { + refs = binding.target().refs; + } else if (binding.target().kind == TagTargetKind::SelectionQuery) { + if (const Value* selected = member(binding.evidence->data, "selected_refs"); selected && selected->is_array()) + refs = selected->as_array(); + } + std::vector> out; + for (const Value& ref : refs) { + const auto kind = kind_from(text(member(ref, "kind"))); + const std::string topo_id = text(member(ref, "topo_id")); + if (kind && !topo_id.empty()) + out.emplace_back(tag_view_key(0, *kind, topo_id), topo_id); + } + return out; +} + +// The view of `node`, given the views of its inputs. +TagView build_view(const OperationNode& node, + const std::unordered_map>& done) { + TagView view; + const auto input_view = [&](const NodePtr& input) -> const TagView& { + static const TagView empty; + const auto found = done.find(input.get()); + return found != done.end() ? *found->second : empty; + }; + const int first_slot = node.bindings.empty() ? 0 : node.bindings.front().output_slot; + // Keys of one slot of an input, renamed to this node's single output. + const auto pass_on = [&](const TagView& from, int slot, const std::string& only_kind) { + const std::string prefix = std::to_string(slot) + '\x1f'; + for (const auto& [key, tags] : from) { + if (!key.starts_with(prefix)) + continue; + const std::string rest = key.substr(prefix.size()); + if (!only_kind.empty() && !rest.starts_with(only_kind + '\x1f')) + continue; + auto& into = view["0\x1f" + rest]; + for (const CarriedTag& tag : tags) + carry(into, tag); + } + }; + + if (!has_history(node)) { + if (node.inputs.empty()) + return view; // a creator: nothing upstream + if (is_selection_op(node.op)) { + pass_on(input_view(node.inputs.front()), first_slot, text(member(node.params, "target_kind"))); + return view; + } + if (!is_tag_op(node.op)) + return view; // no history: the tags end here + pass_on(input_view(node.inputs.front()), first_slot, {}); + const Value* payload = member(node.params, "tag_binding"); + if (payload == nullptr || !payload->is_object()) + return view; + TagBinding binding; + try { + binding = tag_binding_from_value(*payload); + } catch (const std::exception&) { + return view; // a malformed payload names nothing + } + for (const auto& [key, topo_id] : targets_of(binding)) + carry(view[key], CarriedTag{binding, LineageDerivation::Continuation, node.node_id, topo_id, node.op}); + return view; + } + + // An entity of an input is named by the node that made it, which may sit behind identity ops (a tag node keeps + // its producer as the topology owner): map every such owner to the views that hold its entities. + struct Holder { + const TagView* view; + bool alias; // the view is an identity op's: keyed by slot 0 + }; + std::unordered_map> holders; + for (const NodePtr& input : node.inputs) { + const TagView& held = input_view(input); + holders[input->node_id].push_back({&held, false}); + NodePtr owner = input; + while (owner && !has_history(*owner) && (is_tag_op(owner->op) || is_selection_op(owner->op)) && + !owner->inputs.empty()) { + owner = owner->inputs.front(); + holders[owner->node_id].push_back({&held, true}); + } + } + const auto carried_by = [&](const TopoRef& parent) { + std::vector out; + const auto found = holders.find(parent.node_id); + if (found == holders.end()) + return out; + for (const Holder& holder : found->second) { + const auto hit = + holder.view->find(tag_view_key(holder.alias ? 0 : parent.output_slot, parent.kind, parent.topo_id)); + if (hit == holder.view->end()) + continue; + for (const CarriedTag& tag : hit->second) + out.push_back(&tag); + } + return out; + }; + + for (const TopoEntry& entry : node.topo_delta->entries) { + if (entry.event == TopoEvent::Deleted) + continue; + const std::optional derivation = derivation_of(entry); + if (!derivation) + continue; + // Continuation only: a generated entity named after its source is the operation's own projected binding + // (semantic/autotag.cpp), stored on it when the operation ran. + if (entry.event == TopoEvent::Generated) + continue; + const std::string key = tag_view_key(entry.ref.output_slot, entry.ref.kind, entry.ref.topo_id); + for (const TopoRef& parent : entry.parent_refs) { + for (const CarriedTag* tag : carried_by(parent)) { + if (parent.kind != entry.ref.kind || !lineage_policy_allows(tag->binding.propagation(), *derivation)) + continue; + CarriedTag next = *tag; + next.derivation = *derivation; + next.op = node.op; + carry(view[key], std::move(next)); + } + } + } + return view; +} + +struct Cache { + std::mutex mutex; + std::unordered_map, std::shared_ptr>> + views; +}; + +Cache& cache() { + static Cache instance; + return instance; +} + +std::vector provider(const Shape& entity) { + return history_witnesses(entity); +} + +} // namespace + +std::string tag_view_key(int output_slot, Kind kind, const std::string& recorded_topo_id) { + return std::to_string(output_slot) + '\x1f' + std::string(kind_name(kind)) + '\x1f' + recorded_topo_id; +} + +std::shared_ptr tag_view(const NodePtr& node) { + if (!node) + return std::make_shared(); + Cache& c = cache(); + { + const std::lock_guard lock(c.mutex); + if (const auto found = c.views.find(node.get()); + found != c.views.end() && !found->second.first.expired() && found->second.first.lock() == node) + return found->second.second; + } + // Inputs first, each once: the views of the whole upstream closure, reusing what is cached. + std::unordered_map> done; + for (const NodePtr& item : upstream_closure({node})) { + std::shared_ptr view; + { + const std::lock_guard lock(c.mutex); + if (const auto found = c.views.find(item.get()); found != c.views.end() && found->second.first.lock() == item) + view = found->second.second; + } + if (!view) { + view = std::make_shared(build_view(*item, done)); + const std::lock_guard lock(c.mutex); + if (c.views.size() > 16384) { + for (auto it = c.views.begin(); it != c.views.end();) + it = it->second.first.expired() ? c.views.erase(it) : std::next(it); + } + c.views[item.get()] = {item, view}; + } + done.emplace(item.get(), std::move(view)); + } + return done.at(node.get()); +} + +std::vector history_witnesses(const Shape& entity) { + const Shape root = entity.root(); + const auto opaque = root.graph_node(); + if (!opaque) + return {}; + const auto node = std::static_pointer_cast(opaque); + const std::optional lineage = lineage_of(root); + const int slot = lineage ? lineage->output_slot : 0; + const std::shared_ptr view = tag_view(node); + const auto found = + view->find(tag_view_key(slot, entity.kind(), std::string(kind_name(entity.kind())) + "_" + entity.topo_id())); + if (found == view->end()) + return {}; + std::vector out; + out.reserve(found->second.size()); + for (const CarriedTag& tag : found->second) { + TagLineageWitness witness; + witness.binding = tag.binding; + witness.derivation = tag.derivation; + witness.source_topo_id = tag.source_topo_id; + witness.target_topo_id = entity.topo_id(); + TagEvidence evidence; + evidence.kind = TagEvidenceKind::TopologyChange; + evidence.data = Value::object(); + evidence.data.set("op", tag.op); + evidence.data.set("derivation", std::string(to_string(tag.derivation))); + evidence.data.set("coverage", "complete"); + evidence.data.set("assigned_at", tag.source_node_id); + evidence.data.set("via", "recorded_history"); + witness.evidence = Cow(std::move(evidence)); + witness.coverage = "complete"; + out.push_back(std::move(witness)); + } + return out; +} + +void install_tag_view() noexcept { + set_history_witness_provider(&provider); +} + +} // namespace scad::reactive diff --git a/src/cpp/src/semantic/autotag.cpp b/src/cpp/src/semantic/autotag.cpp index d14ea185..3e6c7bd7 100644 --- a/src/cpp/src/semantic/autotag.cpp +++ b/src/cpp/src/semantic/autotag.cpp @@ -262,6 +262,17 @@ std::optional lineage_derivation_or_none(const std::string& t } } +// A binding a recorded tag assignment made (apply_tag_rselection, an op-kwarg tag): it is part of the graph, and +// the tag view (scad/reactive/tag_view.hpp) carries it through the recorded history, so its continuation is never +// copied onto a result here. What is copied is what only the shapes know (imported sidecar facts, sketch topology +// names, tags assigned outside a recording session) and an operation's own naming of what it generates. +// That holds while the source is part of a recorded graph; a value replayed or built outside a session has no +// graph to read, so there the shape carries the binding as before. +bool graph_borne(const TagBinding& binding, const Shape& source) { + return binding.producer().kind == TagProducerKind::UserOperation && binding.producer().node_id.has_value() && + source.root().graph_node() != nullptr; +} + const Shape* source_of(const Value& witness, const TopologyIndex& sources) { const Value* id = member(witness, "input_topo_id"); return present(id) ? sources.find(py_str(*id)) : nullptr; @@ -289,7 +300,7 @@ void carry_source_lineage(Shape& target, const Value& entry, const TopologyIndex {"derivation", derivation_token}}); std::vector bindings = source->local_tag_bindings(); - for (const TagLineageWitness& carried : source->lineage_witnesses()) + for (const TagLineageWitness& carried : source->stored_lineage_witnesses()) if (carried.coverage == "complete" && lineage_policy_allows(carried.binding.propagation(), carried.derivation)) bindings.push_back(carried.binding); // One binding per id; the later record of an id replaces the earlier, keeping its place. @@ -303,7 +314,7 @@ void carry_source_lineage(Shape& target, const Value& entry, const TopologyIndex unique.push_back(std::move(binding)); } for (const TagBinding& binding : unique) { - if (!lineage_policy_allows(binding.propagation(), *derivation)) + if (graph_borne(binding, *source) || !lineage_policy_allows(binding.propagation(), *derivation)) continue; target.add_tag_lineage(binding, *derivation, source->topo_id(), evidence, coverage); } @@ -363,6 +374,10 @@ void project_source_bindings(Shape& target, const Value& entry, const TopologyIn } for (const TagBinding& binding : source->local_tag_bindings()) { + // A generated entity named after its source (an edge's fillet patch, a profile edge's side face) is this + // operation's own naming fact, for any binding. The continuation of a recorded assignment is the view's. + if (graph_borne(binding, *source) && event != "generated") + continue; const Value& evidence = binding.evidence->data; const bool is_user = binding.producer().kind == TagProducerKind::UserOperation; const bool is_prior_projection = binding.producer().kind == TagProducerKind::AutoRule && diff --git a/src/cpp/src/semantic/finalize.cpp b/src/cpp/src/semantic/finalize.cpp index 0124f9b7..bc38e5f5 100644 --- a/src/cpp/src/semantic/finalize.cpp +++ b/src/cpp/src/semantic/finalize.cpp @@ -3,6 +3,7 @@ #include "scad/semantic/finalize.hpp" #include +#include #include #include #include @@ -393,7 +394,7 @@ void attach_lineage_from_source(const Shape& source, Shape& target, LineageDeriv for (TagBinding& binding : source.local_tag_bindings()) if (lineage_policy_allows(binding.propagation(), derivation)) carried.push_back({std::move(binding), effective}); - for (const TagLineageWitness& witness : source.lineage_witnesses()) { + for (const TagLineageWitness& witness : source.stored_lineage_witnesses()) { if (!lineage_policy_allows(witness.binding.propagation(), witness.derivation) || !lineage_policy_allows(witness.binding.propagation(), derivation)) continue; @@ -435,13 +436,56 @@ std::optional merge_topo_deltas(const std::vector& deltas) const auto append = [](std::vector& to, const std::vector& from) { to.insert(to.end(), from.begin(), from.end()); }; + // A later step names what it consumed by the kernel ids of an earlier step's outputs (the intermediate solid, + // which no recorded node owns). Compose: such a parent stands for the earlier step's own parents, so every + // entry descends from the operation's real inputs and the chain is not cut at the intermediate. + std::unordered_map> sources_of; // kind|kernel id of an output -> its inputs + const auto key = [](const TopoRef& ref) { return std::string(kind_name(ref.kind)) + '|' + ref.topo_id; }; + const auto compose = [&](const std::vector& parents) { + std::vector out; + for (const TopoRef& parent : parents) { + const auto found = sources_of.find(key(parent)); + if (found == sources_of.end()) { + out.push_back(parent); + continue; + } + for (const TopoRef& source : found->second) { + if (std::none_of(out.begin(), out.end(), [&](const TopoRef& r) { return key(r) == key(source); })) + out.push_back(source); + } + } + return out; + }; for (const TopoDelta& delta : deltas) { append(merged.preserved, delta.preserved); append(merged.modified, delta.modified); append(merged.generated, delta.generated); append(merged.deleted, delta.deleted); append(merged.section_edges, delta.section_edges); - merged.entries.insert(merged.entries.end(), delta.entries.begin(), delta.entries.end()); + std::unordered_map> produced; + for (const TopoEntry& entry : delta.entries) { + if (entry.event == TopoEvent::Deleted) { + // The deletion of an intermediate entity is the deletion of what it came from. + const std::vector originals = compose({entry.ref}); + for (const TopoRef& original : originals) { + TopoEntry item = entry; + item.ref = original; + item.parent_refs = compose(entry.parent_refs); + merged.entries.push_back(std::move(item)); + } + continue; + } + TopoEntry item = entry; + item.parent_refs = compose(entry.parent_refs); + auto& sources = produced[key(item.ref)]; + for (const TopoRef& source : item.parent_refs) { + if (std::none_of(sources.begin(), sources.end(), [&](const TopoRef& r) { return key(r) == key(source); })) + sources.push_back(source); + } + merged.entries.push_back(std::move(item)); + } + for (auto& [id, sources] : produced) + sources_of[id] = std::move(sources); steps.push_back(object({{"index", index++}, {"preserved", static_cast(delta.preserved.size())}, {"modified", static_cast(delta.modified.size())}, diff --git a/src/cpp/src/surface/finalize.cpp b/src/cpp/src/surface/finalize.cpp index 8ef450a7..1d82aa18 100644 --- a/src/cpp/src/surface/finalize.cpp +++ b/src/cpp/src/surface/finalize.cpp @@ -112,7 +112,7 @@ void carry_face_provenance(const std::vector& result_faces, const std::vec } bool has_semantic_state(const Shape& shape) { - return !shape.local_bindings().empty() || !shape.lineage_witnesses().empty() || shape.metadata().size() != 0 || + return !shape.local_bindings().empty() || !shape.stored_lineage_witnesses().empty() || shape.metadata().size() != 0 || shape.runtime().size() != 0; } diff --git a/src/cpp/src/topo/shape_tags.cpp b/src/cpp/src/topo/shape_tags.cpp index 20b3aa45..180fe417 100644 --- a/src/cpp/src/topo/shape_tags.cpp +++ b/src/cpp/src/topo/shape_tags.cpp @@ -284,12 +284,37 @@ const std::vector& Shape::local_bindings() const { return state != nullptr ? state->bindings : empty; } -const std::vector& Shape::lineage_witnesses() const { +namespace { +std::atomic history_provider{nullptr}; +} // namespace + +void set_history_witness_provider(HistoryWitnessProvider provider) noexcept { + history_provider.store(provider, std::memory_order_release); +} + +const std::vector& Shape::stored_lineage_witnesses() const { static const std::vector empty; const SemanticState* state = entity_->state_if(); return state != nullptr ? state->lineage : empty; } +std::vector Shape::history_lineage_witnesses() const { + const HistoryWitnessProvider provider = history_provider.load(std::memory_order_acquire); + return provider != nullptr ? provider(*this) : std::vector{}; +} + +std::vector Shape::lineage_witnesses() const { + std::vector out = stored_lineage_witnesses(); + for (TagLineageWitness& witness : history_lineage_witnesses()) + out.push_back(std::move(witness)); + return out; +} + +Shape Shape::root() const { + const TopoDS_Shape& top = registry_->root(); + return Shape(top, registry_->acquire(kind_of(top), top), registry_); +} + // --------------------------------------------------------------------------- // Reading bindings // --------------------------------------------------------------------------- @@ -332,6 +357,27 @@ std::vector Shape::inherited_tag_bindings() const { return out; } +namespace { + +// The bindings the witnesses carry, once each, as their own lineage policy allows. strict: an incomplete witness +// refuses the query (the lineage scope promises complete history); otherwise it is skipped. +std::vector policy_allowed(const std::vector& witnesses, bool strict) { + std::vector out; + std::set seen; + for (const auto& w : witnesses) { + if (w.coverage != "complete") { + if (strict) + throw UnsupportedQueryCapabilityError("lineage tag scope has incomplete lineage witnesses"); + continue; + } + if (lineage_policy_allows(w.binding.propagation(), w.derivation) && seen.insert(w.binding.binding_id).second) + out.push_back(w.binding); + } + return out; +} + +} // namespace + std::vector Shape::lineage_tag_bindings() const { const SemanticState* state = entity_->state_if(); Value coverage_scratch; @@ -342,17 +388,7 @@ std::vector Shape::lineage_tag_bindings() const { throw UnsupportedQueryCapabilityError("lineage tag scope requires complete topology history; coverage=" + available); } - std::vector out; - if (state == nullptr) - return out; - for (const auto& w : state->lineage) - if (w.coverage != "complete") - throw UnsupportedQueryCapabilityError("lineage tag scope has incomplete lineage witnesses"); - std::set seen; - for (const auto& w : state->lineage) - if (lineage_policy_allows(w.binding.propagation(), w.derivation) && seen.insert(w.binding.binding_id).second) - out.push_back(w.binding); - return out; + return policy_allowed(lineage_witnesses(), /*strict=*/true); } std::vector Shape::list_tag_bindings(TagScope scope) const { @@ -374,6 +410,9 @@ std::vector Shape::list_tag_bindings(TagScope scope) const { all.push_back(std::move(b)); for (auto& b : legacy_effective_bindings()) all.push_back(std::move(b)); + // Effective includes what the history carries to this entity (tags as a view over the recorded graph). + for (auto& b : policy_allowed(lineage_witnesses(), /*strict=*/false)) + all.push_back(std::move(b)); std::vector unique; std::set seen; for (auto& b : all) @@ -408,6 +447,8 @@ std::vector Shape::list_tags(TagScope scope) const { names.insert(b.tag.str()); for (const auto& b : inherited_tag_bindings()) names.insert(b.tag.str()); + for (const auto& b : policy_allowed(lineage_witnesses(), /*strict=*/false)) + names.insert(b.tag.str()); break; } return {names.begin(), names.end()}; @@ -458,8 +499,12 @@ bool Shape::has_tag(std::string_view tag, TagScope scope) const { return stored(); case TagScope::Inherited: return inherited(); - case TagScope::Effective: - return stored() || holds(true) || inherited(); + case TagScope::Effective: { + if (stored() || holds(true) || inherited()) + return true; + const auto carried = policy_allowed(lineage_witnesses(), /*strict=*/false); + return std::any_of(carried.begin(), carried.end(), [&](const TagBinding& b) { return b.tag == *symbol; }); + } case TagScope::Lineage: { const auto bindings = lineage_tag_bindings(); return std::any_of(bindings.begin(), bindings.end(), [&](const TagBinding& b) { return b.tag == *symbol; }); @@ -496,8 +541,8 @@ std::vector Shape::explain_tag(std::string_view tag, TagScope scope) cons } Value witnesses = Value::array(); - if (state != nullptr) { - for (const auto& w : state->lineage) { + { + for (const auto& w : lineage_witnesses()) { if (w.binding.binding_id != binding.binding_id || !lineage_policy_allows(binding.propagation(), w.derivation)) continue; Value entry = Value::object(); diff --git a/src/cpp/tests/cpp/reactive/test_tag_view.cpp b/src/cpp/tests/cpp/reactive/test_tag_view.cpp new file mode 100644 index 00000000..02bc8527 --- /dev/null +++ b/src/cpp/tests/cpp/reactive/test_tag_view.cpp @@ -0,0 +1,149 @@ +// The tag view over hand-built graphs: which bindings each witness carries, by lineage policy. +#include "doctest.h" + +#include + +#include "scad/reactive/graph.hpp" +#include "scad/reactive/tag_view.hpp" +#include "scad/topo/tag_factories.hpp" + +using namespace scad; +using namespace scad::reactive; + +namespace { + +TopoRef face_ref(const std::string& node, const std::string& id, Kind kind = Kind::Face) { + return TopoRef{"g", node, 0, kind, std::string(kind_name(kind)) + "_" + id}; +} + +TopoEntry witness(TopoRef out, TopoEvent event, std::vector parents, const char* derivation, + bool project = false) { + TopoEntry e; + e.ref = std::move(out); + e.event = event; + e.parent_refs = std::move(parents); + e.metadata = Value::object(); + e.metadata.set("derivation", derivation); + if (project) + e.metadata.set("project_source_tags", true); + return e; +} + +Value tag_payload(const std::string& tag, const TopoRef& target, LineagePolicy lineage) { + UserTagOptions options; + TagTarget explicit_target; + explicit_target.kind = TagTargetKind::ExplicitRefs; + explicit_target.refs.push_back(scad::to_value(target)); + options.target = explicit_target; + options.lineage = lineage; + Value params = Value::object(); + params.set("tag_binding", user_tag_binding(tag, options).to_value()); + return params; +} + +struct G { + OperationGraph graph{"g"}; + NodePtr add(const std::string& id, const std::string& op, std::vector inputs, + std::optional> entries = std::nullopt, Value params = Value::object()) { + NodeSpec spec; + spec.node_id = id; + spec.op = op; + spec.params = std::move(params); + for (const NodePtr& input : inputs) + spec.bindings.push_back(InputBinding{input->node_id, 0, {}}); + spec.inputs = std::move(inputs); + if (entries) { + TopoDelta delta; + delta.entries = std::move(*entries); + spec.topo_delta = std::move(delta); + } + return graph.add_node(std::move(spec)); + } +}; + +std::vector tags_at(const NodePtr& node, const TopoRef& entity) { + const auto view = tag_view(node); + const auto found = view->find(tag_view_key(entity.output_slot, entity.kind, entity.topo_id)); + std::vector out; + if (found != view->end()) + for (const CarriedTag& tag : found->second) + out.push_back(tag.binding.tag.str()); + std::sort(out.begin(), out.end()); + return out; +} + +const std::vector kTop{"user.top"}; + +} // namespace + +TEST_CASE("a tag rides the witnesses of every later operation") { + G g; + const NodePtr box = g.add("a", "make_box_rsolid", {}); + const NodePtr tagged = g.add("t", "apply_tag_rselection", {box}, std::nullopt, + tag_payload("user.top", face_ref("a", "face_5"), LineagePolicy::ContinuationFragment)); + CHECK(tags_at(tagged, face_ref("t", "face_5")) == kTop); + // The cut names its input face by the node that made it (the box), behind the tag node. + const NodePtr cut = g.add( + "c", "make_cut_rsolid", {tagged}, + std::vector{witness(face_ref("c", "face_2"), TopoEvent::Modified, {face_ref("a", "face_5")}, "fragment"), + witness(face_ref("c", "face_7"), TopoEvent::Modified, {face_ref("a", "face_5")}, "fragment"), + witness(face_ref("c", "face_0"), TopoEvent::Preserved, {face_ref("a", "face_0")}, "continuation")}); + CHECK(tags_at(cut, face_ref("c", "face_2")) == kTop); // both pieces of the split face + CHECK(tags_at(cut, face_ref("c", "face_7")) == kTop); + CHECK(tags_at(cut, face_ref("c", "face_0")).empty()); + const NodePtr moved = g.add( + "m", "make_translate_rshape", {cut}, + std::vector{witness(face_ref("m", "face_2"), TopoEvent::Modified, {face_ref("c", "face_2")}, "continuation")}); + CHECK(tags_at(moved, face_ref("m", "face_2")) == kTop); + // An operation without history ends it. + const NodePtr offset = g.add("o", "make_offset_rsolid", {moved}); + CHECK(tags_at(offset, face_ref("o", "face_2")).empty()); +} + +TEST_CASE("the lineage policy decides which derivations a tag follows") { + G g; + const NodePtr box = g.add("a", "make_box_rsolid", {}); + const NodePtr tagged = g.add("t", "apply_tag_rselection", {box}, std::nullopt, + tag_payload("user.top", face_ref("a", "face_5"), LineagePolicy::Continuation)); + const NodePtr cut = + g.add("c", "make_cut_rsolid", {tagged}, + std::vector{witness(face_ref("c", "face_2"), TopoEvent::Modified, {face_ref("a", "face_5")}, "fragment")}); + CHECK(tags_at(cut, face_ref("c", "face_2")).empty()); // a fragment is no continuation + const NodePtr moved = g.add( + "m", "make_translate_rshape", {tagged}, + std::vector{witness(face_ref("m", "face_5"), TopoEvent::Modified, {face_ref("a", "face_5")}, "continuation")}); + CHECK(tags_at(moved, face_ref("m", "face_5")) == kTop); + + const NodePtr local = g.add("l", "apply_tag_rselection", {box}, std::nullopt, + tag_payload("user.top", face_ref("a", "face_5"), LineagePolicy::None)); + const NodePtr kept = g.add( + "k", "make_translate_rshape", {local}, + std::vector{witness(face_ref("k", "face_5"), TopoEvent::Preserved, {face_ref("a", "face_5")}, "continuation")}); + CHECK(tags_at(kept, face_ref("k", "face_5")).empty()); // `none` stays on the tagged output +} + +TEST_CASE("a generated entity is no continuation of its source") { + // The fillet patch an edge generates is named after the edge by the fillet itself (a projected binding stored + // on the patch when the fillet runs); the view only follows entities that live on. + G g; + const NodePtr box = g.add("a", "make_box_rsolid", {}); + const TopoRef edge = face_ref("a", "edge_1", Kind::Edge); + const NodePtr tagged = g.add("t", "apply_tag_rselection", {box}, std::nullopt, + tag_payload("seam.d", edge, LineagePolicy::ContinuationFragment)); + Value edge_kind = Value::object(); + edge_kind.set("target_kind", "edge"); + const NodePtr pick = g.add("s", "make_select_redge", {tagged}, std::nullopt, edge_kind); + CHECK(tags_at(pick, face_ref("s", "edge_1", Kind::Edge)) == std::vector{"seam.d"}); + const NodePtr fillet = g.add("f", "make_fillet_rsolid", {tagged, pick}, + std::vector{witness(face_ref("f", "face_9"), TopoEvent::Generated, + {face_ref("s", "edge_1", Kind::Edge)}, "boundary", true), + witness(face_ref("f", "edge_3", Kind::Edge), TopoEvent::Modified, + {face_ref("a", "edge_1", Kind::Edge)}, "fragment")}); + CHECK(tags_at(fillet, face_ref("f", "face_9")).empty()); + // A face selection passes no edge on. + Value face_kind = Value::object(); + face_kind.set("target_kind", "face"); + const NodePtr faces = g.add("p", "make_select_rface", {tagged}, std::nullopt, face_kind); + CHECK(tags_at(faces, face_ref("p", "edge_1", Kind::Edge)).empty()); + CHECK(tags_at(fillet, face_ref("f", "edge_3", Kind::Edge)) == std::vector{"seam.d"}); +} diff --git a/src/cpp/tests/cpp/semantic/test_finalize.cpp b/src/cpp/tests/cpp/semantic/test_finalize.cpp index 1f8be4fa..cddc7d3e 100644 --- a/src/cpp/tests/cpp/semantic/test_finalize.cpp +++ b/src/cpp/tests/cpp/semantic/test_finalize.cpp @@ -306,10 +306,13 @@ TEST_CASE("user tags follow a cut only through proven lineage") { std::any_of(track.find("origin_roles")->as_array().begin(), track.find("origin_roles")->as_array().end(), [](const Value& v) { return v.as_string() == "body"; }); if (from_body && track.find("status")->as_string() == "proven") { - CHECK_FALSE(face.has_tag("role.source_face", TagScope::Effective)); const std::string coverage = face.get_runtime("semantic.lineage.coverage").as_string(); - if (coverage == "complete" && face.has_tag("role.source_face", TagScope::Lineage)) + if (coverage == "complete" && face.has_tag("role.source_face", TagScope::Lineage)) { lineage_seen = true; + // Effective includes what the lineage carries (tags as a view over history), never a local copy. + CHECK(face.has_tag("role.source_face", TagScope::Effective)); + CHECK_FALSE(face.has_tag("role.source_face", TagScope::Local)); + } } } CHECK(lineage_seen); diff --git a/src/cpp/tests/cpp/semantic/test_tagging.cpp b/src/cpp/tests/cpp/semantic/test_tagging.cpp index a36cfcd0..e6a40013 100644 --- a/src/cpp/tests/cpp/semantic/test_tagging.cpp +++ b/src/cpp/tests/cpp/semantic/test_tagging.cpp @@ -196,7 +196,7 @@ TEST_CASE("explain_tag names the inherited path from the ancestor down") { CHECK(own[0].find("attachment")->as_string() == "local"); } -TEST_CASE("effective tags exclude lineage; lineage needs complete history") { +TEST_CASE("effective tags include lineage; the lineage scope needs complete history") { Solid source = box_solid(1, 1, 1); Solid result = box_solid(2, 2, 2); const TagBinding binding = user_tag_binding("role.datum"); @@ -208,7 +208,9 @@ TEST_CASE("effective tags exclude lineage; lineage needs complete history") { result.add_tag_lineage(binding, LineageDerivation::Continuation, source.topo_id(), topology_change()); result.set_runtime("semantic.lineage.coverage", "complete"); - CHECK_FALSE(contains(result.list_tags(TagScope::Effective), "role.datum")); + // Tags are a view over history: what the lineage carries is part of the entity's effective tags. + CHECK(contains(result.list_tags(TagScope::Effective), "role.datum")); + CHECK(result.has_tag("role.datum", TagScope::Effective)); CHECK(result.list_tags(TagScope::Lineage) == std::vector{"role.datum"}); CHECK(result.has_tag("role.datum", TagScope::Lineage)); // The same witness twice is one witness. diff --git a/src/cpp/tests/golden/ops_features_chamfer.json b/src/cpp/tests/golden/ops_features_chamfer.json index bfaab388..6204a24c 100644 --- a/src/cpp/tests/golden/ops_features_chamfer.json +++ b/src/cpp/tests/golden/ops_features_chamfer.json @@ -300,7 +300,9 @@ -5.0, 4.5 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -309,7 +311,9 @@ 0.5, 10.0 ], - [] + [ + "face.box.top" + ] ], [ [ @@ -318,7 +322,9 @@ 0.023, 4.977 ], - [] + [ + "face.box.back" + ] ], [ [ @@ -327,7 +333,9 @@ 0.023, 4.977 ], - [] + [ + "face.box.front" + ] ], [ [ @@ -336,7 +344,9 @@ 0.0, 0.0 ], - [] + [ + "face.box.bottom" + ] ], [ [ @@ -345,7 +355,9 @@ 5.0, 5.0 ], - [] + [ + "face.box.right" + ] ] ], "faces": 7, diff --git a/src/cpp/tests/golden/ops_features_cut_intersect.json b/src/cpp/tests/golden/ops_features_cut_intersect.json index d6b8d54f..f0b52402 100644 --- a/src/cpp/tests/golden/ops_features_cut_intersect.json +++ b/src/cpp/tests/golden/ops_features_cut_intersect.json @@ -185,7 +185,9 @@ 0.0, 0.0 ], - [] + [ + "face.box.bottom" + ] ], [ [ @@ -194,7 +196,9 @@ 0.0, 30.0 ], - [] + [ + "face.box.top" + ] ], [ [ @@ -203,7 +207,9 @@ -10.0, 15.0 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -212,7 +218,9 @@ 10.0, 15.0 ], - [] + [ + "face.box.right" + ] ], [ [ @@ -221,7 +229,9 @@ -0.0, 15.0 ], - [] + [ + "face.box.back" + ] ], [ [ @@ -230,7 +240,9 @@ -0.0, 15.0 ], - [] + [ + "face.box.front" + ] ], [ [ @@ -239,7 +251,9 @@ -0.0, 15.0 ], - [] + [ + "face.cylinder.side" + ] ] ], "faces": 7, @@ -354,7 +368,10 @@ 0.0, 0.0 ], - [] + [ + "face.box.bottom", + "face.cylinder.start" + ] ], [ [ @@ -363,7 +380,9 @@ 0.0, 30.0 ], - [] + [ + "face.box.top" + ] ], [ [ @@ -372,7 +391,9 @@ -0.0, 15.0 ], - [] + [ + "face.cylinder.side" + ] ] ], "faces": 3, diff --git a/src/cpp/tests/golden/ops_features_extrude_profile_tags.json b/src/cpp/tests/golden/ops_features_extrude_profile_tags.json index d1a578a8..d5820770 100644 --- a/src/cpp/tests/golden/ops_features_extrude_profile_tags.json +++ b/src/cpp/tests/golden/ops_features_extrude_profile_tags.json @@ -61,7 +61,8 @@ 0.0 ], [ - "edge.boundary" + "edge.boundary", + "pad.edge.line1" ] ], [ @@ -83,7 +84,8 @@ 0.0 ], [ - "edge.boundary" + "edge.boundary", + "pad.edge.line3" ] ], [ @@ -105,7 +107,8 @@ 0.0 ], [ - "edge.boundary" + "edge.boundary", + "pad.edge.line4" ] ], [ @@ -127,7 +130,8 @@ 0.0 ], [ - "edge.boundary" + "edge.boundary", + "pad.edge.line2" ] ], [ diff --git a/src/cpp/tests/golden/ops_features_fillet_tags.json b/src/cpp/tests/golden/ops_features_fillet_tags.json index b0d13c9b..56cbee84 100644 --- a/src/cpp/tests/golden/ops_features_fillet_tags.json +++ b/src/cpp/tests/golden/ops_features_fillet_tags.json @@ -287,7 +287,9 @@ 0.0, 10.0 ], - [] + [ + "face.box.top" + ] ], [ [ @@ -296,7 +298,9 @@ -0.0, 4.5 ], - [] + [ + "face.box.back" + ] ], [ [ @@ -305,7 +309,9 @@ -5.0, 4.5 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -314,7 +320,9 @@ 5.0, 4.5 ], - [] + [ + "face.box.right" + ] ], [ [ @@ -323,7 +331,9 @@ -0.0, 4.5 ], - [] + [ + "face.box.front" + ] ], [ [ @@ -332,7 +342,9 @@ 0.0, 0.0 ], - [] + [ + "face.box.bottom" + ] ] ], "faces": 10, diff --git a/src/cpp/tests/golden/ops_features_rigid_solid.json b/src/cpp/tests/golden/ops_features_rigid_solid.json index 81965b4e..5f044ffd 100644 --- a/src/cpp/tests/golden/ops_features_rigid_solid.json +++ b/src/cpp/tests/golden/ops_features_rigid_solid.json @@ -152,7 +152,9 @@ 0.0, 0.0 ], - [] + [ + "face.box.bottom" + ] ], [ [ @@ -161,7 +163,9 @@ 0.0, 4.0 ], - [] + [ + "face.box.top" + ] ], [ [ @@ -170,7 +174,9 @@ -1.5, 2.0 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -179,7 +185,9 @@ 1.5, 2.0 ], - [] + [ + "face.box.right" + ] ], [ [ @@ -188,7 +196,9 @@ 0.0, 2.0 ], - [] + [ + "face.box.front" + ] ], [ [ @@ -197,7 +207,9 @@ 0.0, 2.0 ], - [] + [ + "face.box.back" + ] ] ], "faces": 6, @@ -359,7 +371,9 @@ -0.5, 0.0 ], - [] + [ + "face.box.bottom" + ] ], [ [ @@ -368,7 +382,9 @@ -0.5, 4.0 ], - [] + [ + "face.box.top" + ] ], [ [ @@ -377,7 +393,9 @@ 0.799, 2.0 ], - [] + [ + "face.box.right" + ] ], [ [ @@ -386,7 +404,9 @@ -1.799, 2.0 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -395,7 +415,9 @@ -1.0, 2.0 ], - [] + [ + "face.box.back" + ] ], [ [ @@ -404,7 +426,9 @@ 0.0, 2.0 ], - [] + [ + "face.box.front" + ] ] ], "faces": 6, @@ -565,7 +589,9 @@ 2.0, 3.0 ], - [] + [ + "face.box.bottom" + ] ], [ [ @@ -574,7 +600,9 @@ 2.0, 7.0 ], - [] + [ + "face.box.top" + ] ], [ [ @@ -583,7 +611,9 @@ 0.5, 5.0 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -592,7 +622,9 @@ 3.5, 5.0 ], - [] + [ + "face.box.right" + ] ], [ [ @@ -601,7 +633,9 @@ 2.0, 5.0 ], - [] + [ + "face.box.back" + ] ], [ [ @@ -610,7 +644,9 @@ 2.0, 5.0 ], - [] + [ + "face.box.front" + ] ] ], "faces": 6, diff --git a/src/cpp/tests/golden/ops_features_shell.json b/src/cpp/tests/golden/ops_features_shell.json index 557a8b05..43da0a67 100644 --- a/src/cpp/tests/golden/ops_features_shell.json +++ b/src/cpp/tests/golden/ops_features_shell.json @@ -292,6 +292,7 @@ 10.0 ], [ + "face.box.top", "face.shell.closing_descendant", "role.rim" ] @@ -364,6 +365,7 @@ 5.0 ], [ + "face.box.back", "face.shell.body_face" ] ], @@ -375,6 +377,7 @@ 5.0 ], [ + "face.box.left", "face.shell.body_face" ] ], @@ -386,6 +389,7 @@ 0.0 ], [ + "face.box.bottom", "face.shell.body_face" ] ], @@ -397,6 +401,7 @@ 5.0 ], [ + "face.box.right", "face.shell.body_face" ] ], @@ -408,6 +413,7 @@ 5.0 ], [ + "face.box.front", "face.shell.body_face" ] ] diff --git a/src/cpp/tests/golden/ops_features_tag_projection.json b/src/cpp/tests/golden/ops_features_tag_projection.json index c3b3cead..eb450dff 100644 --- a/src/cpp/tests/golden/ops_features_tag_projection.json +++ b/src/cpp/tests/golden/ops_features_tag_projection.json @@ -284,7 +284,10 @@ 0.0, 10.0 ], - [] + [ + "face.box.top", + "role.top" + ] ], [ [ @@ -293,7 +296,9 @@ -0.0, 4.5 ], - [] + [ + "face.box.back" + ] ], [ [ @@ -302,7 +307,9 @@ -5.0, 4.5 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -311,7 +318,9 @@ 5.0, 4.5 ], - [] + [ + "face.box.right" + ] ], [ [ @@ -320,7 +329,9 @@ -0.0, 4.5 ], - [] + [ + "face.box.front" + ] ], [ [ @@ -329,7 +340,9 @@ 0.0, 0.0 ], - [] + [ + "face.box.bottom" + ] ] ], "faces": 10, @@ -522,7 +535,9 @@ -0.0, 0.0 ], - [] + [ + "face.box.bottom" + ] ], [ [ @@ -531,7 +546,10 @@ -0.0, 10.0 ], - [] + [ + "face.box.top", + "role.top" + ] ], [ [ @@ -540,7 +558,9 @@ -0.0, 5.0 ], - [] + [ + "face.box.back" + ] ], [ [ @@ -549,7 +569,9 @@ -5.0, 5.0 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -558,7 +580,9 @@ 5.0, 5.0 ], - [] + [ + "face.box.right" + ] ], [ [ @@ -567,7 +591,9 @@ -0.0, 5.0 ], - [] + [ + "face.box.front" + ] ], [ [ @@ -576,7 +602,9 @@ -0.0, 5.0 ], - [] + [ + "face.cylinder.side" + ] ] ], "faces": 7, @@ -870,7 +898,10 @@ 0.0, 10.0 ], - [] + [ + "face.box.top", + "role.top" + ] ], [ [ @@ -879,7 +910,9 @@ -0.0, 4.5 ], - [] + [ + "face.box.back" + ] ], [ [ @@ -888,7 +921,9 @@ -5.0, 4.5 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -897,7 +932,9 @@ 5.0, 4.5 ], - [] + [ + "face.box.right" + ] ], [ [ @@ -906,7 +943,9 @@ -0.0, 4.5 ], - [] + [ + "face.box.front" + ] ], [ [ @@ -915,7 +954,9 @@ 0.0, 0.0 ], - [] + [ + "face.box.bottom" + ] ] ], "faces": 10, @@ -1075,7 +1116,9 @@ -0.0, 5.0 ], - [] + [ + "face.box.front" + ] ], [ [ @@ -1084,7 +1127,9 @@ -5.0, 5.0 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -1093,7 +1138,9 @@ 0.0, 0.0 ], - [] + [ + "face.box.bottom" + ] ], [ [ @@ -1102,7 +1149,10 @@ 0.0, 10.0 ], - [] + [ + "face.box.top", + "role.top" + ] ], [ [ @@ -1111,7 +1161,9 @@ 5.0, 5.0 ], - [] + [ + "face.box.right" + ] ], [ [ @@ -1120,7 +1172,9 @@ -0.0, 5.0 ], - [] + [ + "face.box.back" + ] ] ], "faces": 6, @@ -1282,7 +1336,9 @@ -2.5, 5.0 ], - [] + [ + "face.box.back" + ] ], [ [ @@ -1291,7 +1347,9 @@ 4.33, 5.0 ], - [] + [ + "face.box.right" + ] ], [ [ @@ -1300,7 +1358,9 @@ -0.0, 0.0 ], - [] + [ + "face.box.bottom" + ] ], [ [ @@ -1309,7 +1369,10 @@ -0.0, 10.0 ], - [] + [ + "face.box.top", + "role.top" + ] ], [ [ @@ -1318,7 +1381,9 @@ -4.33, 5.0 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -1327,7 +1392,9 @@ 2.5, 5.0 ], - [] + [ + "face.box.front" + ] ] ], "faces": 6, @@ -1624,6 +1691,7 @@ 5.0 ], [ + "face.box.back", "face.shell.closing_descendant" ] ], @@ -1690,6 +1758,7 @@ 5.0 ], [ + "face.box.left", "face.shell.body_face" ] ], @@ -1701,6 +1770,7 @@ 0.0 ], [ + "face.box.bottom", "face.shell.body_face" ] ], @@ -1712,7 +1782,9 @@ 10.0 ], [ - "face.shell.body_face" + "face.box.top", + "face.shell.body_face", + "role.top" ] ], [ @@ -1723,6 +1795,7 @@ 5.0 ], [ + "face.box.right", "face.shell.body_face" ] ], @@ -1734,6 +1807,7 @@ 5.0 ], [ + "face.box.front", "face.shell.body_face" ] ] @@ -1895,7 +1969,9 @@ 2.0, 8.0 ], - [] + [ + "face.box.back" + ] ], [ [ @@ -1904,7 +1980,9 @@ -3.0, 8.0 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -1913,7 +1991,9 @@ 2.0, 3.0 ], - [] + [ + "face.box.bottom" + ] ], [ [ @@ -1922,7 +2002,10 @@ 2.0, 13.0 ], - [] + [ + "face.box.top", + "role.top" + ] ], [ [ @@ -1931,7 +2014,9 @@ 7.0, 8.0 ], - [] + [ + "face.box.right" + ] ], [ [ @@ -1940,7 +2025,9 @@ 2.0, 8.0 ], - [] + [ + "face.box.front" + ] ] ], "faces": 6, @@ -2232,7 +2319,9 @@ 0.0, 11.0 ], - [] + [ + "face.box.back" + ] ], [ [ @@ -2241,7 +2330,9 @@ -1.0, 11.0 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -2250,7 +2341,9 @@ 0.0, 12.0 ], - [] + [ + "face.box.top" + ] ], [ [ @@ -2259,7 +2352,9 @@ 1.0, 11.0 ], - [] + [ + "face.box.right" + ] ], [ [ @@ -2268,7 +2363,9 @@ 0.0, 11.0 ], - [] + [ + "face.box.front" + ] ], [ [ @@ -2277,7 +2374,10 @@ 0.0, 10.0 ], - [] + [ + "face.box.top", + "role.top" + ] ], [ [ @@ -2286,7 +2386,9 @@ -0.0, 5.0 ], - [] + [ + "face.box.back" + ] ], [ [ @@ -2295,7 +2397,9 @@ -5.0, 5.0 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -2304,7 +2408,9 @@ 0.0, 0.0 ], - [] + [ + "face.box.bottom" + ] ], [ [ @@ -2313,7 +2419,9 @@ 5.0, 5.0 ], - [] + [ + "face.box.right" + ] ], [ [ @@ -2322,7 +2430,9 @@ -0.0, 5.0 ], - [] + [ + "face.box.front" + ] ] ], "faces": 11, diff --git a/src/cpp/tests/golden/ops_features_union_contact.json b/src/cpp/tests/golden/ops_features_union_contact.json index 313fc84b..0f42738f 100644 --- a/src/cpp/tests/golden/ops_features_union_contact.json +++ b/src/cpp/tests/golden/ops_features_union_contact.json @@ -370,7 +370,9 @@ 0.0, 0.5 ], - [] + [ + "face.box.back" + ] ], [ [ @@ -379,7 +381,9 @@ 0.0, 0.5 ], - [] + [ + "face.box.front" + ] ], [ [ @@ -388,7 +392,9 @@ -0.5, 0.5 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -397,7 +403,9 @@ 0.0, 0.0 ], - [] + [ + "face.box.bottom" + ] ], [ [ @@ -406,7 +414,9 @@ 0.0, 1.0 ], - [] + [ + "face.box.top" + ] ], [ [ @@ -415,7 +425,9 @@ 0.5, 0.5 ], - [] + [ + "face.box.right" + ] ] ], "faces": 6, diff --git a/src/cpp/tests/golden/ops_features_union_overlap.json b/src/cpp/tests/golden/ops_features_union_overlap.json index a6b6ca9a..a46f194b 100644 --- a/src/cpp/tests/golden/ops_features_union_overlap.json +++ b/src/cpp/tests/golden/ops_features_union_overlap.json @@ -266,7 +266,9 @@ 0.5, 2.5 ], - [] + [ + "face.box.back" + ] ], [ [ @@ -275,7 +277,9 @@ 0.0, 2.5 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -284,7 +288,9 @@ 0.5, 3.0 ], - [] + [ + "face.box.top" + ] ], [ [ @@ -293,7 +299,9 @@ -0.167, 2.0 ], - [] + [ + "face.box.top" + ] ], [ [ @@ -302,7 +310,9 @@ 0.0, 1.0 ], - [] + [ + "face.box.back" + ] ], [ [ @@ -311,7 +321,9 @@ -1.0, 1.0 ], - [] + [ + "face.box.left" + ] ], [ [ @@ -320,7 +332,9 @@ 0.0, 0.0 ], - [] + [ + "face.box.bottom" + ] ], [ [ @@ -329,7 +343,9 @@ 1.0, 1.3 ], - [] + [ + "face.box.right" + ] ], [ [ @@ -338,7 +354,9 @@ 0.1, 1.3 ], - [] + [ + "face.box.front" + ] ] ], "faces": 9, diff --git a/src/cpp/tests/python/test_semantic_tagging.py b/src/cpp/tests/python/test_semantic_tagging.py index 42af9ddf..76908d3d 100644 --- a/src/cpp/tests/python/test_semantic_tagging.py +++ b/src/cpp/tests/python/test_semantic_tagging.py @@ -182,7 +182,7 @@ def test_lineage_scope_needs_complete_history(): result._add_tag_lineage(binding, derivation="continuation", source_topo_id=source.topo_id, evidence=tagging.TagEvidence("topology_change", {"change_ids": ["c1"]})) result._set_runtime("semantic.lineage.coverage", "complete") - assert "role.datum" not in result._list_tags("effective") + assert "role.datum" in result._list_tags("effective") # effective includes lineage (tags as a view) assert result._list_tags("lineage") == ["role.datum"] explained = scad.explain_tag(result, "role.datum", "lineage") assert explained[0]["lineage"][0]["derivation"] == "continuation" diff --git a/src/simplecadapi/_glue/docstrings.json b/src/simplecadapi/_glue/docstrings.json index 3b8d2a77..ec35ba9d 100644 --- a/src/simplecadapi/_glue/docstrings.json +++ b/src/simplecadapi/_glue/docstrings.json @@ -300,7 +300,7 @@ "suspend_graph_recording": "Temporarily suspend automatic graph recording for internal API composition.", "sweep_multisection_rsolid": "Sweep through explicit ordered sections along a continuous path.\n\nAt least two ordered sections are needed. Face sections supply their outer\nwire, matching build123d's multi-section sweep contract. ``binormal`` is an\noptional direction vector or an auxiliary spine. The kernel must produce\none valid solid. Every section and the path are recorded as inputs of\n``make_sweep_multisection_rsolid``, so model JSON preserves the\nconstruction.\n\nArgs:\n profiles: Ordered section faces or wires (at least two).\n path: The continuous path wire.\n is_frenet: Use the Frenet frame along the path.\n binormal: A direction, or an auxiliary spine wire, that fixes the\n section orientation.\n\nReturns:\n The swept solid.\n\nRaises:\n TypeError: A section is neither a Face nor a Wire.\n ValueError: Fewer than two sections, a zero ``binormal`` direction, or\n the kernel could not make a solid.", "sweep_rsolid": "Create a swept solid, with optional kernel-role-based tags.", - "tag": "Build a tag predicate for QL filtering.\n\nArgs:\n pattern: Exact tag string or a trailing `*` prefix match.\n scope: One of ``local``, ``inherited``, ``effective``, or ``lineage``.\n\nReturns:\n Serializable predicate that can be used in `Query.where(...)`.", + "tag": "Build a tag predicate for QL filtering.\n\nTags are a view over the recorded history: a tag assigned in a\n``GraphSession`` reaches every entity its target became through later\noperations (a face cut in two keeps it on both pieces), as its lineage\npolicy allows. ``local`` is what the entity itself stores, ``inherited``\nwhat containing entities pass down, ``lineage`` what the history carries,\nand ``effective`` (the default) all three.\n\nArgs:\n pattern: Exact tag string or a trailing `*` prefix match.\n scope: One of ``local``, ``inherited``, ``effective``, or ``lineage``.\n\nReturns:\n Serializable predicate that can be used in `Query.where(...)`.", "topo_ref_from_dict": "Reconstruct a TopoRef from serialized data.", "topo_ref_to_dict": "Serialize a TopoRef into a JSON-compatible dictionary.", "track_union_history": "Build one face-level union delta from retained N-ary OCC history.", diff --git a/test/test_element_ref_history.py b/test/test_element_ref_history.py index d78b2291..7ab4418c 100644 --- a/test/test_element_ref_history.py +++ b/test/test_element_ref_history.py @@ -51,7 +51,7 @@ def test_plain_face_tag_after_a_boolean(): box, anchor = _box_with_top_anchor() cut = scad.cut_rsolid(box, scad.make_cylinder_rsolid(3, 30)) - assert _tagged(cut, "user.top") == 0 # today: the face-source gate drops the tag + assert _tagged(cut, "user.top") == 1 # the tag is a view over the same history (it used to die here) r = er.resolve(anchor, cut) assert r.status == "ok" @@ -66,7 +66,7 @@ def test_plain_face_tag_after_a_fillet(): box, anchor = _box_with_top_anchor() filleted = scad.fillet_rsolid(box, _edges_at(box, 10), 2.0) - assert _tagged(filleted, "user.top") == 0 + assert _tagged(filleted, "user.top") == 1 r = er.resolve(anchor, filleted) assert r.status == "ok" @@ -81,7 +81,7 @@ def test_extrude_cap_after_a_fillet_of_its_edges(): (anchor,) = er.anchors_for_role(solid, "extrusion.end") filleted = scad.fillet_rsolid(solid, _edges_at(solid, 10), 2.0) - assert _tagged(filleted, "cap.top") == 0 # today: the op-kwarg face channel stops at blends + assert _tagged(filleted, "cap.top") == 1 # the op-kwarg face channel used to stop at blends r = er.resolve(anchor, filleted) assert r.status == "ok" @@ -226,28 +226,29 @@ def test_a_creator_end_cap_anchor_survives_a_boolean_and_a_copy(kind): # --------------------------------------------------------------------------- _AUDIT = { - # family: (op on the tagged box, plain tag survives, op-kwarg tag survives, history status) - "cut": (lambda b: scad.cut_rsolid(b, scad.make_cylinder_rsolid(3, 30)), 0, 1, "ok"), - "union": (lambda b: scad.union_rsolid(b, scad.make_box_rsolid(4, 4, 4, (0, 0, 10))), 0, 1, "ok"), - "intersect": (lambda b: scad.intersect_rsolid(b, scad.make_box_rsolid(30, 30, 30, (10, 0, -5))), 0, 1, "ok"), - "fillet": (lambda b: scad.fillet_rsolid(b, _edges_at(b, 10), 2.0), 0, 0, "ok"), - "chamfer": (lambda b: scad.chamfer_rsolid(b, _edges_at(b, 10), 2.0), 0, 0, "ok"), - "shell_kept_face": (lambda b: scad.shell_rsolid(b, _faces_at(b, 0), 1.0), 0, 1, "ok"), - "shell_opened_face": (lambda b: scad.shell_rsolid(b, _faces_at(b, 10), 1.0), 0, 1, "ok"), - "translate": (lambda b: scad.translate_shape(b, (5, 0, 0)), 0, 0, "ok"), - "mirror": (lambda b: scad.mirror_shape(b, (0, 0, 0), (1, 0, 0)), 0, 0, "ok"), - "linear_pattern": (lambda b: scad.linear_pattern_rsolidlist(b, (1, 0, 0), 3, 50)[2], 0, 0, "ok"), - "rotate": (lambda b: scad.rotate_shape(b, 30, (0, 0, 1)), 0, 0, "ok"), - "radial_pattern": (lambda b: scad.radial_pattern_rsolidlist(b, (0, 0, 0), (0, 0, 1), 4, 360)[1], 0, 0, "ok"), + # family: (op on the tagged box, plain tag survives, op-kwarg tag survives, history status). Before tags + # became a view over history the plain tag survived nothing and the kwarg tag only booleans and the shell. + "cut": (lambda b: scad.cut_rsolid(b, scad.make_cylinder_rsolid(3, 30)), 1, 1, "ok"), + "union": (lambda b: scad.union_rsolid(b, scad.make_box_rsolid(4, 4, 4, (0, 0, 10))), 1, 1, "ok"), + "intersect": (lambda b: scad.intersect_rsolid(b, scad.make_box_rsolid(30, 30, 30, (10, 0, -5))), 1, 1, "ok"), + "fillet": (lambda b: scad.fillet_rsolid(b, _edges_at(b, 10), 2.0), 1, 1, "ok"), + "chamfer": (lambda b: scad.chamfer_rsolid(b, _edges_at(b, 10), 2.0), 1, 1, "ok"), + "shell_kept_face": (lambda b: scad.shell_rsolid(b, _faces_at(b, 0), 1.0), 1, 1, "ok"), + "shell_opened_face": (lambda b: scad.shell_rsolid(b, _faces_at(b, 10), 1.0), 1, 1, "ok"), + "translate": (lambda b: scad.translate_shape(b, (5, 0, 0)), 1, 1, "ok"), + "mirror": (lambda b: scad.mirror_shape(b, (0, 0, 0), (1, 0, 0)), 1, 1, "ok"), + "linear_pattern": (lambda b: scad.linear_pattern_rsolidlist(b, (1, 0, 0), 3, 50)[2], 1, 1, "ok"), + "rotate": (lambda b: scad.rotate_shape(b, 30, (0, 0, 1)), 1, 1, "ok"), + "radial_pattern": (lambda b: scad.radial_pattern_rsolidlist(b, (0, 0, 0), (0, 0, 1), 4, 360)[1], 1, 1, "ok"), # These five recorded no history before this branch (lost / no_history); they now carry builder history. - "scale": (lambda b: scad.scale_rsolid(b, (1.0, 1.0, 1.0)), 0, 0, "ok"), + "scale": (lambda b: scad.scale_rsolid(b, (1.0, 1.0, 1.0)), 1, 1, "ok"), "transform_rsolid": ( lambda b: scad.transform_rsolid(b, [[1, 0, 0, 5], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]), - 0, - 0, + 1, + 1, "ok", ), - "offset": (lambda b: scad.offset_rsolid(b, -1.0), 0, 0, "ok"), + "offset": (lambda b: scad.offset_rsolid(b, -1.0), 1, 1, "ok"), } @@ -443,3 +444,43 @@ def test_two_look_alike_boxes_make_the_anchor_ambiguous_never_a_guess(): r = er.resolve(stable, edited) assert r.status == "lost" assert r.reason == "anchor_ambiguous" + + +# --------------------------------------------------------------------------- +# Tags as a view over history: chains, persistence +# --------------------------------------------------------------------------- + + +def test_an_n_ary_cut_composes_its_steps(): + # One node cuts three tools in turn; its steps name the intermediate solids, which the delta now composes + # back to the real inputs, so the top face is followed through all three (here: split by the groove). + with scad.GraphSession(): + box, anchor = _box_with_top_anchor() + cut = scad.cut_rsolid( + box, + scad.make_cylinder_rsolid(3, 30), + scad.translate_shape(scad.make_cylinder_rsolid(2, 30), (10, 0, 0)), + scad.translate_shape(scad.make_box_rsolid(4, 30, 4, (0, 0, 8)), (-14, 0, 0)), + ) + r = er.resolve(anchor, cut) + assert r.status == "split" + assert sorted(round(f.get_area(), 2) for f in r.entities) == [80.0, round(640 - 13 * math.pi, 2)] + assert sorted(round(f.get_area(), 2) for f in ql.faces().where(ql.tag("user.top")).resolve(cut)) == [ + 80.0, + round(640 - 13 * math.pi, 2), + ] + + +def test_a_tag_survives_pickling_with_its_history(): + import pickle + + with scad.GraphSession(): + box, _ = _box_with_top_anchor() + holed = scad.cut_rsolid(box, scad.make_cylinder_rsolid(3, 30)) + cut = scad.fillet_rsolid(holed, _edges_at(holed, 0), 1.0) + data = pickle.dumps(cut) + restored = pickle.loads(data) + (face,) = ql.faces().where(ql.tag("user.top")).resolve(restored) + assert face.get_area() == pytest.approx(800 - 9 * math.pi) + explained = scad.explain_tag(face, "user.top") + assert explained and explained[0]["lineage"][0]["evidence"]["via"] == "recorded_history" diff --git a/test/test_tagging_refactor.py b/test/test_tagging_refactor.py index 1e7ca5d9..31545a40 100644 --- a/test/test_tagging_refactor.py +++ b/test/test_tagging_refactor.py @@ -41,7 +41,8 @@ class TestTaggingRefactor(unittest.TestCase): self.assertNotIn(binding, face._tag_bindings) self.assertIn("role.mounting_surface", face._tags) - def test_effective_excludes_lineage(self): + def test_effective_includes_lineage(self): + # Tags are a view over history: what the lineage carries is part of the effective tags. source = scad.make_point_rvertex(0.0, 0.0, 0.0) result = scad.make_point_rvertex(1.0, 0.0, 0.0) binding = source._apply_user_tag("role.datum") @@ -55,7 +56,7 @@ class TestTaggingRefactor(unittest.TestCase): ) result._set_runtime("semantic.lineage.coverage", "complete") - self.assertNotIn("role.datum", result._list_tags("effective")) + self.assertIn("role.datum", result._list_tags("effective")) self.assertEqual(result._list_tags("lineage"), ["role.datum"]) def test_lineage_requires_complete_history(self): @@ -89,7 +90,7 @@ class TestTaggingRefactor(unittest.TestCase): first = scad.translate_shape(source, (1.0, 0.0, 0.0)) second = scad.translate_shape(first, (1.0, 0.0, 0.0)) - self.assertNotIn("role.datum", scad.list_tags(second, "effective")) + self.assertIn("role.datum", scad.list_tags(second, "effective")) self.assertEqual(scad.list_tags(second, "lineage"), ["role.datum"]) def test_disallowed_lineage_does_not_seed_later_continuation(self):