From 9533e8bfee0952a8504fcd6c84482a4e8f171f33 Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Tue, 6 Oct 2026 23:14:24 +0000 Subject: [PATCH 1/4] Reuse exact fixed-ink face meshes across Sheet replays --- docs/reference/sheet.md | 21 ++++ src/draftwright/__init__.py | 3 + .../annotations/_leader_fixed_ink.py | 19 +++- src/draftwright/fixed_ink_cache.py | 96 +++++++++++++++++++ src/draftwright/sheet.py | 43 +++++---- tests/test_issue_367_leader_ink.py | 84 +++++++++++++++- 6 files changed, 245 insertions(+), 21 deletions(-) create mode 100644 src/draftwright/fixed_ink_cache.py diff --git a/docs/reference/sheet.md b/docs/reference/sheet.md index 58b03b8ad..44533eff7 100644 --- a/docs/reference/sheet.md +++ b/docs/reference/sheet.md @@ -281,6 +281,27 @@ The token associates features; it does not specify an annotation position or add Generated scripts preserve this association using Draftwright-owned tokens instead of provider keys. A groove can still be declared when the authored set omits all of that body's steps. +### Repeated editor builds + +An editor that rebuilds a declared sheet after annotation-only edits may reuse a +caller-owned fixed-ink mesh cache: + +```python +from draftwright import FixedInkMeshCache + +mesh_cache = FixedInkMeshCache(max_entries=2048) +drawing = sheet.build(mesh_cache=mesh_cache) +# After a bounded layout edit, rebuild with the same cache. +sheet.layout_override("declaration:datum", side="left") +drawing = sheet.build(mesh_cache=mesh_cache) +``` + +This is optional; ordinary `build()` behavior is unchanged. Cache entries use the exact +located geometry of rendered annotation faces and the tessellation tolerance, so moving +an annotation or changing the part, scale or views cannot reuse stale ink. The cache is +bounded by entry count, can be cleared with `mesh_cache.clear()`, and only avoids face +tessellation; it does not skip the drawing's placement or validation solve. + ## Build-scoped declaration selectors An editable script can give a feature a declaration identity and later address that intent diff --git a/src/draftwright/__init__.py b/src/draftwright/__init__.py index 8b2e9b8a3..498eab3f8 100644 --- a/src/draftwright/__init__.py +++ b/src/draftwright/__init__.py @@ -31,6 +31,7 @@ "BuildCancelled": "draftwright.progress", "observe_build": "draftwright.progress", "FeatureInfo": "draftwright.drawing", + "FixedInkMeshCache": "draftwright.fixed_ink_cache", "ReportUnavailableError": "draftwright.reporting", "INSPECTION_SCHEMA": "draftwright.inspection", "INSPECTION_SCHEMA_VERSION": "draftwright.inspection", @@ -103,6 +104,7 @@ def __getattribute__(self, name): from draftwright.compose import choose_scale from draftwright.document import Document, DocumentBuildError, DocumentResult from draftwright.drawing import Drawing, FeatureInfo + from draftwright.fixed_ink_cache import FixedInkMeshCache from draftwright.inspection import ( INSPECTION_SCHEMA, INSPECTION_SCHEMA_VERSION, @@ -143,6 +145,7 @@ def __dir__(): "DocumentBuildError", "SoftDeprecationWarning", "FeatureInfo", + "FixedInkMeshCache", "InspectionUnavailableError", "LeaderRegionPolicy", "PmiExtractionReport", diff --git a/src/draftwright/annotations/_leader_fixed_ink.py b/src/draftwright/annotations/_leader_fixed_ink.py index b294897bb..4bd6378a1 100644 --- a/src/draftwright/annotations/_leader_fixed_ink.py +++ b/src/draftwright/annotations/_leader_fixed_ink.py @@ -15,6 +15,7 @@ from draftwright._geometry import _leader_ink_polygons, _stroke_polygon from draftwright.annotations._common import DerivedViewReservation, _geom_box +from draftwright.fixed_ink_cache import _active_fixed_ink_mesh_cache from draftwright.progress import checkpoint _FIXED_INVENTORY_EXHAUSTED = object() @@ -121,6 +122,16 @@ def _validated_face_mesh(face, tolerance): """Return one complete finite triangular mesh, or ``None`` when malformed.""" checkpoint() + cache = _active_fixed_ink_mesh_cache() + key = None + if cache is not None: + try: + key = cache._key(face, tolerance) + cached = cache.get(key) + if cached is not None: + return cached + except Exception: # noqa: BLE001 — optional cache must fail open to validation + key = None try: vertices, raw_triangles = face.tessellate(tolerance) points = tuple((float(vertex.X), float(vertex.Y)) for vertex in vertices) @@ -146,7 +157,13 @@ def _validated_face_mesh(face, tolerance): ) except Exception: # noqa: BLE001 — optional placement must fail closed return None - return points, tuple(triangles), edge_kinds + mesh = points, tuple(triangles), edge_kinds + if cache is not None and key is not None: + try: + cache.put(key, mesh) + except Exception: # noqa: BLE001 — cache failure must not fail ink validation + pass + return mesh def _convex_hull(points): diff --git a/src/draftwright/fixed_ink_cache.py b/src/draftwright/fixed_ink_cache.py new file mode 100644 index 000000000..3a7f2c4fd --- /dev/null +++ b/src/draftwright/fixed_ink_cache.py @@ -0,0 +1,96 @@ +"""Caller-owned exact-face cache for repeated fixed-ink validation (#2207). + +The cached faces are rendered annotation ink, not merely projected part faces. +Part/scale/view identity therefore cannot prove reuse after a layout edit: the key +must contain the complete located face geometry as well as tessellation tolerance. +""" + +from __future__ import annotations + +from collections import OrderedDict +from contextlib import contextmanager +from contextvars import ContextVar +from io import BytesIO +from threading import Lock + +from OCP.BRepTools import BRepTools +from OCP.TopTools import TopTools_FormatVersion + +FaceMesh = tuple[ + tuple[tuple[float, float], ...], + tuple[tuple[int, int, int], ...], + tuple[str, ...], +] + + +class FixedInkMeshCache: + """Bounded, reusable cache for exact rendered face meshes. + + Pass one instance to successive ``Sheet.build(mesh_cache=...)`` calls. The + cache is optional, never global, and safe to reuse across part/scale/view + changes because its key includes each *located* face's exact B-rep. A + failed key or malformed mesh is never cached; normal validation still runs. + """ + + def __init__(self, *, max_entries: int = 2048) -> None: + if isinstance(max_entries, bool) or not isinstance(max_entries, int) or max_entries < 1: + raise ValueError("max_entries must be a positive integer") + self.max_entries = max_entries + self._entries: OrderedDict[tuple[float, bytes], FaceMesh] = OrderedDict() + self._lock = Lock() + self.hits = 0 + self.misses = 0 + + @staticmethod + def _key(face, tolerance: float) -> tuple[float, bytes]: + stream = BytesIO() + BRepTools.Write_s( + face.wrapped, + stream, + False, + False, + TopTools_FormatVersion.TopTools_FormatVersion_VERSION_3, + ) + return float(tolerance), stream.getvalue() + + def get(self, key: tuple[float, bytes]) -> FaceMesh | None: + with self._lock: + mesh = self._entries.get(key) + if mesh is None: + self.misses += 1 + else: + self.hits += 1 + self._entries.move_to_end(key) + return mesh + + def put(self, key: tuple[float, bytes], mesh: FaceMesh) -> None: + with self._lock: + self._entries[key] = mesh + self._entries.move_to_end(key) + if len(self._entries) > self.max_entries: + self._entries.popitem(last=False) + + def clear(self) -> None: + """Release retained face geometry and reset counters.""" + + with self._lock: + self._entries.clear() + self.hits = self.misses = 0 + + +_ACTIVE_MESH_CACHE: ContextVar[FixedInkMeshCache | None] = ContextVar( + "draftwright_fixed_ink_mesh_cache", default=None +) + + +@contextmanager +def _using_fixed_ink_mesh_cache(cache: FixedInkMeshCache | None): + token = _ACTIVE_MESH_CACHE.set(cache) + try: + yield + finally: + _ACTIVE_MESH_CACHE.reset(token) + + +def _active_fixed_ink_mesh_cache() -> FixedInkMeshCache | None: + return _ACTIVE_MESH_CACHE.get() diff --git a/src/draftwright/sheet.py b/src/draftwright/sheet.py index 5c696cd21..cb027e0ba 100644 --- a/src/draftwright/sheet.py +++ b/src/draftwright/sheet.py @@ -63,6 +63,7 @@ from draftwright.compose import _est_table_size from draftwright.document_input import DocumentInput, physical_features from draftwright.fits import fit_class +from draftwright.fixed_ink_cache import FixedInkMeshCache, _using_fixed_ink_mesh_cache from draftwright.model import ( DefaultSurfaceFinish, DimensionParameterId, @@ -2826,10 +2827,13 @@ def model(self): self._authored_set(), ) - def build(self): + def build(self, *, mesh_cache: FixedInkMeshCache | None = None): """Build the :class:`~draftwright.drawing.Drawing` — detection skipped; only the declared features are drawn. Declared corner-block tables (:meth:`table`/:meth:`notes`) - are placed last, clear of everything already on the sheet.""" + are placed last, clear of everything already on the sheet. A caller-held + ``mesh_cache`` can reuse exact rendered-face tessellations across replays.""" + if mesh_cache is not None and not isinstance(mesh_cache, FixedInkMeshCache): + raise TypeError("mesh_cache must be a FixedInkMeshCache or None") self._prepare() # `add_dimension` augments the planner's set, so the sheet must have asked for # one (ADR 4 (was 0016)). Checked HERE rather than in the verb so intent stays @@ -2885,23 +2889,24 @@ def place_declared_tables(dwg): if not automatic_details: opts["detail_view"] = False try: - return build_drawing( - self._part, - model=self._build_model_input(), - _document_input=self._document_input, - decorations=self._decorations( - section_request, - suppress_auto_sections=self._derived_view_source == "authored", - ), - requested=self._requested_dimensions(), - authored=self._authored_set(), - _post_build=place_declared_tables if self._tables else None, - _required_tables=required_tables, - _views=principal_views, - _include_iso=include_iso, - _view_constraints=constraints, - **opts, - ) + with _using_fixed_ink_mesh_cache(mesh_cache): + return build_drawing( + self._part, + model=self._build_model_input(), + _document_input=self._document_input, + decorations=self._decorations( + section_request, + suppress_auto_sections=self._derived_view_source == "authored", + ), + requested=self._requested_dimensions(), + authored=self._authored_set(), + _post_build=place_declared_tables if self._tables else None, + _required_tables=required_tables, + _views=principal_views, + _include_iso=include_iso, + _view_constraints=constraints, + **opts, + ) except ViewPlanIncomplete as exc: if self._principal_view_source != "authored": raise diff --git a/tests/test_issue_367_leader_ink.py b/tests/test_issue_367_leader_ink.py index a33ce1394..f8c8736d0 100644 --- a/tests/test_issue_367_leader_ink.py +++ b/tests/test_issue_367_leader_ink.py @@ -3,15 +3,18 @@ import math import pytest -from build123d import HeadType, Vector +from build123d import Box, Cylinder, Face, HeadType, Vector from build123d_drafting.helpers import ArrowHead, Draft, Leader +from draftwright import Sheet from draftwright._geometry import ( _convex_polygon_overlaps_box, _leader_ink_crosses_box, _segment_crosses_box, ) +from draftwright.annotations._leader_fixed_ink import _validated_face_mesh from draftwright.annotations.holes import _leader_hits +from draftwright.fixed_ink_cache import FixedInkMeshCache, _using_fixed_ink_mesh_cache def _leader(draft, elbow=(20.0, 0.0)): @@ -21,6 +24,85 @@ def _leader(draft, elbow=(20.0, 0.0)): return leader, tip, elbow, side +def test_exact_face_cache_reuses_identical_ink_but_not_moved_ink(monkeypatch): + draft = Draft() + first = tuple(_leader(draft)[0].faces())[0] + identical = tuple(_leader(draft)[0].faces())[0] + moved = tuple(_leader(draft, elbow=(21.0, 0.0))[0].faces())[0] + calls = 0 + tessellate = Face.tessellate + + def counted(face, tolerance): + nonlocal calls + calls += 1 + return tessellate(face, tolerance) + + monkeypatch.setattr(Face, "tessellate", counted) + cache = FixedInkMeshCache(max_entries=2) + with _using_fixed_ink_mesh_cache(cache): + original = _validated_face_mesh(first, 0.01) + assert original is not None + assert _validated_face_mesh(identical, 0.01) == original + assert _validated_face_mesh(moved, 0.01) is not None + assert _validated_face_mesh(identical, 0.02) is not None + assert calls == 3 + assert cache.hits == 1 + assert cache.misses == 3 + cache.clear() + assert cache.hits == cache.misses == 0 + + +def test_face_cache_key_failure_falls_back_to_uncached_validation(): + class UnserializableFace: + def tessellate(self, _tolerance): + return ( + [Vector(0, 0), Vector(1, 0), Vector(0, 1)], + [(0, 1, 2)], + ) + + def edges(self): + return () + + cache = FixedInkMeshCache() + with _using_fixed_ink_mesh_cache(cache): + assert _validated_face_mesh(UnserializableFace(), 0.01) is not None + assert cache.hits == cache.misses == 0 + + +def test_face_cache_write_failure_keeps_validated_mesh(monkeypatch): + face = tuple(_leader(Draft())[0].faces())[0] + cache = FixedInkMeshCache() + + def unavailable(_key, _mesh): + raise RuntimeError("cache unavailable") + + monkeypatch.setattr(cache, "put", unavailable) + with _using_fixed_ink_mesh_cache(cache): + assert _validated_face_mesh(face, 0.01) is not None + + +def test_sheet_replay_reuses_exact_ink_without_changing_drawing() -> None: + part = Box(20, 40, 50) - Cylinder(2, 20, rotation=(0, 90, 0)) + sheet = Sheet(part, scale=2).authored_dimensions() + bore = sheet.hole(diameter=4, depth=20, at=(0, 0, 0), axis="x") + sheet.dimension(bore, "bore.diameter") + with pytest.raises(TypeError, match="FixedInkMeshCache"): + sheet.build(mesh_cache=object()) # type: ignore[arg-type] + with pytest.raises(ValueError, match="positive integer"): + FixedInkMeshCache(max_entries=0) + cache = FixedInkMeshCache() + + first = sheet.build(mesh_cache=cache) + first_hits, first_misses = cache.hits, cache.misses + second = sheet.build(mesh_cache=cache) + + assert first_misses > 0 + assert cache.hits > first_hits + assert cache.misses == first_misses + assert first.annotations().keys() == second.annotations().keys() + assert first.lint_summary() == second.lint_summary() + + @pytest.mark.parametrize("head_type", tuple(HeadType)) @pytest.mark.parametrize("angle", (0.0, 35.0, -35.0, 145.0)) def test_arrowhead_flare_is_collision_evidence_beyond_the_idealised_segment(angle, head_type): From f9aec4bb58179f77c0180580fd33e54a4a483db7 Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Tue, 6 Oct 2026 23:20:54 +0000 Subject: [PATCH 2/4] Route fixed-ink cache changes to focused contract tests --- tests/_tier_manifest.py | 6 +++++- tests/test_tier_manifest.py | 6 ++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/tests/_tier_manifest.py b/tests/_tier_manifest.py index 09a5fb3b2..90ad43782 100644 --- a/tests/_tier_manifest.py +++ b/tests/_tier_manifest.py @@ -263,10 +263,14 @@ class ContractGroup: ), ), "leader_fixed_ink": ContractGroup( - ("src/draftwright/annotations/_leader_fixed_ink.py",), + ( + "src/draftwright/annotations/_leader_fixed_ink.py", + "src/draftwright/fixed_ink_cache.py", + ), ( "test_issue_1166_cross_pass_feature_leaders.py", "test_issue_1534_build_progress.py", + "test_issue_367_leader_ink.py", "test_issue_798_silhouette_lint.py", ), ), diff --git a/tests/test_tier_manifest.py b/tests/test_tier_manifest.py index 7766a607e..2e3e0a0ea 100644 --- a/tests/test_tier_manifest.py +++ b/tests/test_tier_manifest.py @@ -133,6 +133,12 @@ def test_every_fast_module_has_a_pr_route(): assert available - routed == set(NONFAST_ONLY_MODULES) +def test_fixed_ink_cache_uses_the_leader_ink_contract_group(): + source = "src/draftwright/fixed_ink_cache.py" + assert selected_groups([source]) == frozenset({"leader_fixed_ink"}) + assert "test_issue_367_leader_ink.py" in pr_modules(_TESTS, [source]) + + def test_post_merge_only_modules_have_no_fast_test_functions(): for module in NONFAST_ONLY_MODULES: path = _TESTS / module From a10c68755cdd4330c2553833091da6e7ab00d368 Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Tue, 6 Oct 2026 23:59:53 +0000 Subject: [PATCH 3/4] Rank fixed-ink cache in the architecture DAG --- docs/architecture.md | 5 ++++- tests/test_import_boundaries.py | 3 +++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/architecture.md b/docs/architecture.md index 53c94b83c..ee3eb4236 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -10,7 +10,7 @@ document in step. The *why* behind every shape here lives in `docs/adr/`. The dependency graph is a DAG (the #138 / ADR 1 (was 0005) split is complete). Bottom to top: strict rank-0 package leaves: `progress.py`, `layout.py` (including semantic survival order), `registry.py`, `fonts/`, -`_geometry.py`, +`_geometry.py`, `fixed_ink_cache.py`, `fits.py`, `contract_values.py`, `measurement_support.py`, `sheet_metadata.py`, `angular_geometry.py`, `family_table.py`, `recogniser_policy.py`, @@ -55,6 +55,9 @@ contract, such as `reporting.py`, states and guards that contract at its own sea corridor demand from approved model groups, and compose consumes that topology. `recognition_cache.py` sits beside `analysis.py` at rank 3: both consume bottom-layer recognition contracts, while `drawing_state.py` and `builder.py` consume the cache. +`fixed_ink_cache.py` is a rank-0 package leaf: its caller-owned, bounded face-mesh cache +uses exact located B-rep bytes and tessellation tolerance as the key. Annotation fixed-ink +validation and `Sheet.build()` consume it; it never owns placement or model state. `test_rank_zero_modules_are_package_leaves` enforces that every rank-0 file has no package import across runtime, type-only and lazy paths. `model/` shares a numerical rank with `_core` but its separate fail-closed import allowlist still prohibits any diff --git a/tests/test_import_boundaries.py b/tests/test_import_boundaries.py index bc3868320..b516909e5 100644 --- a/tests/test_import_boundaries.py +++ b/tests/test_import_boundaries.py @@ -87,6 +87,9 @@ def _tree(path: Path) -> ast.Module: _LAYERS: dict[str, int] = { # Bottom/shared declarations: every rank-0 entry is a strict package leaf. "_geometry": 0, + # Caller-owned exact rendered-face meshes; imports no engine modules and is + # consumed by annotation validation and the Sheet facade. + "fixed_ink_cache": 0, # Structured ISO 10303-21 facts only; XCAF correspondence remains in rank-2 pmi.py. "_pmi_part21": 0, # Warning categories only. Imports nothing at all — deliberately, because a category From df6bee2aab23f974f1eac5f7167071cdbececb3d Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Wed, 7 Oct 2026 01:53:49 +0000 Subject: [PATCH 4/4] Verify fixed-ink mesh cache evicts oldest entry --- tests/test_issue_367_leader_ink.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/test_issue_367_leader_ink.py b/tests/test_issue_367_leader_ink.py index f8c8736d0..b35a535e5 100644 --- a/tests/test_issue_367_leader_ink.py +++ b/tests/test_issue_367_leader_ink.py @@ -45,9 +45,11 @@ def counted(face, tolerance): assert _validated_face_mesh(identical, 0.01) == original assert _validated_face_mesh(moved, 0.01) is not None assert _validated_face_mesh(identical, 0.02) is not None - assert calls == 3 + assert len(cache._entries) == 2 + assert _validated_face_mesh(first, 0.01) == original # oldest entry was evicted + assert calls == 4 assert cache.hits == 1 - assert cache.misses == 3 + assert cache.misses == 4 cache.clear() assert cache.hits == cache.misses == 0