From bb52031e306d362eca09f7ebda0b272e25ba3f60 Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Mon, 5 Oct 2026 23:05:15 +0000 Subject: [PATCH 1/8] perf: probe GD&T corridor retries before CAD construction --- src/draftwright/annotations/_common.py | 45 +++++++- src/draftwright/annotations/_gdt.py | 108 +++++++++++++----- .../annotations/_placement_occupancy.py | 5 +- tests/test_gdt_ink_shared.py | 26 +++++ tests/test_gdt_placement.py | 87 ++++++++++++++ 5 files changed, 238 insertions(+), 33 deletions(-) diff --git a/src/draftwright/annotations/_common.py b/src/draftwright/annotations/_common.py index 74ea7a5c..9080185f 100644 --- a/src/draftwright/annotations/_common.py +++ b/src/draftwright/annotations/_common.py @@ -2235,6 +2235,18 @@ def _adjust_strip_candidate_labels(run) -> None: run.solved = solved +@dataclass(frozen=True) +class DeferredCompactCandidate: + """Exact leader ink metadata before constructing a costly retry annotation.""" + + label_bbox: tuple[float, float, float, float] + materialize: Any + tip: tuple[float, float] | None = None + elbow: tuple[float, float] | None = None + segments: tuple = () + analytical_straight_leader: bool = False + + def _compact_strip_candidate_ink(run) -> None: """Try bounded contraction against settled and same-batch ink.""" dwg, view, cands = run.dwg, run.view, run.cands @@ -2253,7 +2265,38 @@ def _compact_strip_candidate_ink(run) -> None: index = next((i for i, (key, _dim) in enumerate(solved) if key == name), None) original = solved[index][1] if index is not None else None others = [item for key, item in solved if key != name] - for candidate in alternatives(original): + # Label clashes are decisive for exact-ink clearance. Filter them, page + # bounds, furniture, and projected view edges before constructing the + # heavyweight CAD leader. The full check below still validates survivors. + foreign_labels = [] + for item in (*others, *(annotation for _, annotation in dwg.iter_annotations())): + try: + label = getattr(item, "label_bbox", None) + except Exception: # noqa: BLE001 — the exact check fails closed below + continue + if label is not None and len(label) == 4: + foreign_labels.append(label) + page = _drawing_bounds(dwg) + for proposal in alternatives(original): + if isinstance(proposal, DeferredCompactCandidate): + label = proposal.label_bbox + if ( + label[0] < page[0] + or label[1] < page[1] + or label[2] > page[2] + or label[3] > page[3] + or ((forbid or {}).get(name) is not None and _box_hits(label, (forbid[name],))) + or (label_clear is not None and not label_clear(label)) + or any(_boxes_overlap(label, foreign) for foreign in foreign_labels) + ): + continue + if proposal.analytical_straight_leader and not annotation_ink_clear( + dwg, proposal, additional=others + ): + continue + candidate = proposal.materialize() + else: + candidate = proposal if ( original is not None and hasattr(candidate, "arc_radius") diff --git a/src/draftwright/annotations/_gdt.py b/src/draftwright/annotations/_gdt.py index 5c98740b..5971a043 100644 --- a/src/draftwright/annotations/_gdt.py +++ b/src/draftwright/annotations/_gdt.py @@ -22,6 +22,7 @@ from draftwright.annotations._common import ( PRIORITY, CorridorCandidate, + DeferredCompactCandidate, _anno_box, _box_hits, annotation_ink_clear, @@ -80,8 +81,7 @@ class _GdtDropState: def _gdt_glyph(item, draft): """Build the ISO 1101/5459/1302 glyph sketch for one GD&T IR item at the origin - (the :class:`Leader` repositions it). A fresh sketch per call — the leader translate - must not alias a shared object across the strip solve's repeated probe builds.""" + (the :class:`Leader` repositions a moved copy of it).""" if item.kind == "control_frame": tolerance = item.display_tolerance or item.tolerance if item.spherical_diameter: @@ -324,17 +324,30 @@ def _gdt_visual_finish(glyph, draft, value: str) -> str: return "" -def _attach_gdt_text_evidence(leader, glyph, item, draft) -> None: - """Keep the placed glyph's value beside PDF text for independent PMI lint.""" - leader.pdf_text_relative_specs = _gdt_pdf_text_specs(glyph, item, draft) +def _gdt_text_evidence(glyph, item, draft) -> dict[str, object]: + """Validate one immutable glyph once, independently of its leader position.""" + evidence: dict[str, object] = { + "pdf_text_relative_specs": _gdt_pdf_text_specs(glyph, item, draft) + } if item.kind == "finish": - leader.gdt_visual_finish = _gdt_visual_finish(glyph, draft, item.ra) + evidence["gdt_visual_finish"] = _gdt_visual_finish(glyph, draft, item.ra) if item.kind == "control_frame": zone = _gdt_visual_zone(glyph, draft) - leader.gdt_visual_tolerance = _gdt_visual_tolerance( - glyph, draft, zone, modifier=bool(item.modifier) - ) - leader.gdt_visual_zone = zone if leader.gdt_visual_tolerance else "" + tolerance = _gdt_visual_tolerance(glyph, draft, zone, modifier=bool(item.modifier)) + evidence["gdt_visual_tolerance"] = tolerance + evidence["gdt_visual_zone"] = zone if tolerance else "" + return evidence + + +def _apply_gdt_text_evidence(leader, evidence: dict[str, object]) -> None: + """Keep the validated glyph's value beside PDF text for independent PMI lint.""" + for name, value in evidence.items(): + setattr(leader, name, value) + + +def _attach_gdt_text_evidence(leader, glyph, item, draft) -> None: + """Attach independently checked glyph evidence to a placed leader.""" + _apply_gdt_text_evidence(leader, _gdt_text_evidence(glyph, item, draft)) def _gdt_retry_sides(side: str, *, normal_side_only: bool) -> tuple[str, ...]: @@ -538,7 +551,7 @@ def _retry(): def _gdt_compact_candidates( - original, build, strip, size, horizontal, item, site, tier, material_field + original, build, ink_at, strip, size, horizontal, item, site, tier, material_field ): """Nearest-first same-strip landings checked later against exact ink. @@ -564,14 +577,12 @@ def _gdt_compact_candidates( if travel >= distance - 1e-6: break pos = site + strip.direction * travel - candidate = build(pos) + proposal = ink_at(pos) # A symbol inside the whole-view box must sit in projected # whitespace, not on a blank face with no visible edge. The # shared postsolve also checks visible edges and exact ink. - if _datum_label_has_whitespace( - candidate.label_bbox, strip, horizontal, material_field - ): - yield candidate + if _datum_label_has_whitespace(proposal.label_bbox, strip, horizontal, material_field): + yield proposal near = strip.anchor + strip.direction * (strip.gap + extent / 2.0) distance = (original_pos - near) * strip.direction if distance <= 1e-6: @@ -583,36 +594,70 @@ def _gdt_compact_candidates( pos = near + strip.direction * travel if abs(pos - original_pos) <= 1e-6: return - yield build(pos) + yield ink_at(pos) def _gdt_candidate_builders( item, draft, leader_ctor, fallback_glyph, px, py, horizontal, strip, size, tier, material_field ): """Build one glyph's primary and fallback leaders plus bounded strip retries.""" + # Every retry moves the same validated glyph. Its value/zone checks are expensive + # OCC operations, but do not depend on the eventual leader elbow. + evidence = _gdt_text_evidence(fallback_glyph, item, draft) if item.kind != "note" else {} + glyph_box = fallback_glyph.bounding_box() + + def _elbow(pos): + # Keep the analytical preflight and actual helper's zero-shaft guard identical. + if horizontal: + delta = pos - py + return px, pos if abs(delta) >= _MIN_LEADER else py + math.copysign( + _MIN_LEADER, delta or 1.0 + ) + delta = pos - px + return pos if abs(delta) >= _MIN_LEADER else px + math.copysign( + _MIN_LEADER, delta or 1.0 + ), py + + def _label_bbox_at(pos): + elbow_x, elbow_y = _elbow(pos) + shelf_dir = 1.0 if elbow_x >= px else -1.0 + anchor_x = glyph_box.min.X if shelf_dir > 0 else glyph_box.max.X + dx = elbow_x + shelf_dir * draft.pad_around_text - anchor_x + dy = elbow_y - (glyph_box.min.Y + glyph_box.max.Y) / 2.0 + return ( + glyph_box.min.X + dx, + glyph_box.min.Y + dy, + glyph_box.max.X + dx, + glyph_box.max.Y + dy, + ) + + def _ink_at(pos): + elbow = _elbow(pos) + shelf_dir = 1.0 if elbow[0] >= px else -1.0 + shelf_end = (elbow[0] + shelf_dir * draft.pad_around_text, elbow[1]) + return DeferredCompactCandidate( + label_bbox=_label_bbox_at(pos), + materialize=lambda _pos=pos: _build(_pos), + tip=(px, py), + elbow=elbow, + segments=(((px, py), elbow), (elbow, shelf_end)), + analytical_straight_leader=True, + ) - def _build(pos, _px=px, _py=py, _hz=horizontal, _it=item): - g = _gdt_glyph(_it, draft) + def _build(pos, _px=px, _py=py, _hz=horizontal, _it=item, _g=fallback_glyph): tip = (_px, _py) # A zero-length leader shaft (the projected site coincides with the solved tier — # `pos == py` above/below, `pos == px` left/right) makes OCC's edge builder raise, # which would crash the whole build on a public-IR declaration. Guarantee a # minimum shaft along the stacking axis (nudge outward; 0.05 mm is invisible) so # `_build` is total — the drop-don't-crash invariant holds for every build call. - if _hz: - dy = pos - _py - pos = pos if abs(dy) >= _MIN_LEADER else _py + math.copysign(_MIN_LEADER, dy or 1.0) - elbow = (_px, pos) - else: - dx = pos - _px - pos = pos if abs(dx) >= _MIN_LEADER else _px + math.copysign(_MIN_LEADER, dx or 1.0) - elbow = (pos, _py) + elbow = _elbow(pos) leader = leader_ctor( tip=tip, elbow=elbow, label="", draft=draft, - callout=g, + callout=_g, all_around=getattr(_it, "all_around", False), all_over=getattr(_it, "all_over", False), ) @@ -628,7 +673,7 @@ def _build(pos, _px=px, _py=py, _hz=horizontal, _it=item): getattr(draft, "font", "Arial"), ) else: - _attach_gdt_text_evidence(leader, g, _it, draft) + _apply_gdt_text_evidence(leader, evidence) return leader def _build_at(elbow, _px=px, _py=py, _it=item, _g=fallback_glyph): @@ -650,7 +695,7 @@ def _build_at(elbow, _px=px, _py=py, _it=item, _g=fallback_glyph): getattr(draft, "font", "Arial"), ) else: - _attach_gdt_text_evidence(leader, _g, _it, draft) + _apply_gdt_text_evidence(leader, evidence) return leader def _build_routed(bends, elbow, _px=px, _py=py, _it=item, _g=fallback_glyph): @@ -673,13 +718,14 @@ def _build_routed(bends, elbow, _px=px, _py=py, _it=item, _g=fallback_glyph): getattr(draft, "font", "Arial"), ) else: - _attach_gdt_text_evidence(leader, _g, _it, draft) + _apply_gdt_text_evidence(leader, evidence) return leader def _compact_candidates(original): return _gdt_compact_candidates( original, _build, + _ink_at, strip, size, horizontal, diff --git a/src/draftwright/annotations/_placement_occupancy.py b/src/draftwright/annotations/_placement_occupancy.py index 51da529b..70a05a62 100644 --- a/src/draftwright/annotations/_placement_occupancy.py +++ b/src/draftwright/annotations/_placement_occupancy.py @@ -613,7 +613,10 @@ def annotation_ink_clear(dwg, candidate, *, view=None, additional=(), against=No candidate_elbow = getattr(candidate, "elbow", None) annotation_elbow = getattr(annotation, "elbow", None) shares_leader_trunk = ( - type(candidate) is Leader + ( + type(candidate) is Leader + or getattr(candidate, "analytical_straight_leader", False) + ) and type(annotation) is Leader and candidate_tip is not None and annotation_tip is not None diff --git a/tests/test_gdt_ink_shared.py b/tests/test_gdt_ink_shared.py index 4bee997d..9028754e 100644 --- a/tests/test_gdt_ink_shared.py +++ b/tests/test_gdt_ink_shared.py @@ -2,6 +2,7 @@ from types import SimpleNamespace +import pytest from build123d_drafting import FeatureControlFrame, Leader from build123d_drafting.helpers import Draft @@ -141,6 +142,31 @@ def _assert_capacity_fixture_fits_each_alone(monkeypatch, outer_limit): assert remaining == [] +def test_deferred_compaction_rejects_out_of_page_label_before_build(monkeypatch): + monkeypatch.setattr(_common, "strip_obstacles", lambda *_args, **_kwargs: []) + monkeypatch.setattr(_common, "pending_title_block_box", lambda _drawing: None) + drawing = _Drawing() + strip = Strip(anchor=0.0, outer_limit=50.0, direction=1.0, gap=8.0, spacing=3.0) + deferred = _common.DeferredCompactCandidate( + (101.0, 20.0, 110.0, 25.0), + lambda: pytest.fail("a provably off-page retry built CAD ink"), + ) + remaining = _common.place_strip_candidates( + drawing, + strip, + "plan", + "y", + [("frame", _frame)], + tier=5.0, + ctx=drawing, + force=True, + sizes={"frame": (10.0, 5.0)}, + compact_candidates={"frame": lambda _original: (deferred,)}, + ) + assert remaining == [] + assert [name for name, _item in drawing.added] == ["frame"] + + def test_frame_moves_as_whole_when_same_batch_dimension_crosses_its_glyph(monkeypatch): unchecked, unchecked_remaining = _solve(monkeypatch, repair=False, required=False) assert unchecked_remaining == [], [(name, item.pos) for name, item in unchecked.added] diff --git a/tests/test_gdt_placement.py b/tests/test_gdt_placement.py index 46a91b57..0c320af1 100644 --- a/tests/test_gdt_placement.py +++ b/tests/test_gdt_placement.py @@ -52,6 +52,93 @@ def _leader_path_length(leader): ) +def test_gdt_retry_reuses_validated_glyph_without_changing_placed_ink(monkeypatch): + from draftwright._core import Strip + from draftwright.annotations import _gdt + + draft = Draft(font_size=3.0) + frame = ControlFrame( + frame=Frame((0.0, 0.0, 0.0), "z"), + characteristic="position", + tolerance="0.1", + view="plan", + side="above", + datums=("A",), + diameter=True, + ) + glyph = _gdt._gdt_glyph(frame, draft) + origin_box = glyph.bounding_box() + strip = Strip(anchor=20.0, outer_limit=90.0, direction=1.0, gap=8.0, spacing=3.0) + real_visual_tolerance = _gdt._gdt_visual_tolerance + validated = [] + + def counted_visual_tolerance(*args, **kwargs): + validated.append(True) + return real_visual_tolerance(*args, **kwargs) + + monkeypatch.setattr(_gdt, "_gdt_visual_tolerance", counted_visual_tolerance) + build, _, _, compact, _ = _gdt._gdt_candidate_builders( + frame, + draft, + Leader, + glyph, + 30.0, + 20.0, + True, + strip, + (origin_box.size.X, origin_box.size.Y), + 5.0, + None, + ) + monkeypatch.setattr( + _gdt, "_gdt_glyph", lambda *_args: pytest.fail("placement rebuilt a validated glyph") + ) + assert len(validated) == 1 + for tier in (35.0, 45.0, 35.0): + placed = build(tier) + fresh = Leader( + tip=(30.0, 20.0), + elbow=(30.0, tier), + label="", + draft=draft, + callout=glyph, + ) + _gdt._attach_gdt_text_evidence(fresh, glyph, frame, draft) + assert placed.label_bbox == pytest.approx(fresh.label_bbox) + assert placed.segments == fresh.segments + assert placed.pdf_text_relative_specs + assert placed.pdf_text_relative_specs == fresh.pdf_text_relative_specs + # Only the direct reference attachment above adds validations; the three + # placement retries must reuse the builder's single checked result. + assert len(validated) == 4 + proposals = list(compact(build(55.0)))[:3] + assert proposals + other = build(55.0) + + class EmptyDrawing: + @staticmethod + def iter_annotations(): + return () + + @staticmethod + def view_of(_name): + return "plan" + + for proposal in proposals: + actual = proposal.materialize() + assert proposal.label_bbox == pytest.approx(actual.label_bbox) + assert proposal.segments == tuple(actual.segments) + assert proposal.tip == actual.tip + assert proposal.elbow == actual.elbow + assert _gdt.annotation_ink_clear( + EmptyDrawing(), proposal, additional=(other,) + ) == _gdt.annotation_ink_clear(EmptyDrawing(), actual, additional=(other,)) + unchanged = glyph.bounding_box() + assert (unchanged.min.X, unchanged.min.Y, unchanged.max.X, unchanged.max.Y) == pytest.approx( + (origin_box.min.X, origin_box.min.Y, origin_box.max.X, origin_box.max.Y) + ) + + def test_control_frame_places_first_class(): frame = ControlFrame( frame=Frame((0.0, 0.0, 0.0), "z"), From 7b49b4c8d57610c9d1dbd4b2462e304771678f4c Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Tue, 6 Oct 2026 01:48:46 +0000 Subject: [PATCH 2/8] perf: skip impossible joint principal-view scales --- src/draftwright/build_policy.py | 23 +++++++++++++++------ tests/test_issue_1146_scale_completeness.py | 4 +++- tests/test_pmi_gtol_lowering.py | 10 +++++++-- 3 files changed, 28 insertions(+), 9 deletions(-) diff --git a/src/draftwright/build_policy.py b/src/draftwright/build_policy.py index 2197ab3d..6caf9e49 100644 --- a/src/draftwright/build_policy.py +++ b/src/draftwright/build_policy.py @@ -533,11 +533,13 @@ def _scale_attempt( def _principal_view_exceeds_page(scale, page, bounds, views) -> bool: - """Rule out a fixed-scale build whose unannotated principal cannot fit. + """Rule out a fixed-scale build whose bare principal projections cannot fit. - This uses only the part's world-space bounding box and the full page, leaving - margins and annotation footprints out of the bound. A rejected candidate - therefore cannot be rescued by a different arrangement or ink placement. + The third-/first-angle principal origins keep front and plan in one vertical + column and side next to that column in every supported arrangement. Use only + the part's world-space box and the *full* page: omitting even the mandatory + gutters, margins and annotation footprints makes this a necessary bound, + never a speculative fit verdict. No ink solve can rescue a rejected scale. """ extents = { "x": bounds.max.X - bounds.min.X, @@ -546,12 +548,21 @@ def _principal_view_exceeds_page(scale, page, bounds, views) -> bool: } axes = {"front": ("x", "z"), "plan": ("x", "y"), "side": ("y", "z")} page_w, page_h = page - return any( + if any( extents[horizontal] * scale > page_w + 1e-9 or extents[vertical] * scale > page_h + 1e-9 for view in views if (pair := axes.get(view)) is not None for horizontal, vertical in (pair,) - ) + ): + return True + selected = set(views) + if "side" in selected and ({"front", "plan"} & selected): + if (extents["x"] + extents["y"]) * scale > page_w + 1e-9: + return True + if {"front", "plan"} <= selected: + if (extents["z"] + extents["y"]) * scale > page_h + 1e-9: + return True + return False def _has_detail_view(views) -> bool: diff --git a/tests/test_issue_1146_scale_completeness.py b/tests/test_issue_1146_scale_completeness.py index 565b5bd1..c75feeaf 100644 --- a/tests/test_issue_1146_scale_completeness.py +++ b/tests/test_issue_1146_scale_completeness.py @@ -567,7 +567,9 @@ def test_principal_projection_must_fit_inside_the_physical_page(): page = (1189.0, 841.0) assert not builder._principal_view_exceeds_page(0.5, page, bounds, ("front", "plan", "side")) assert builder._principal_view_exceeds_page(1.0, page, bounds, ("front", "plan", "side")) - assert not builder._principal_view_exceeds_page(1.0, page, bounds, ("front", "side")) + # The two bare projections fit individually, but cannot share the horizontal row. + assert builder._principal_view_exceeds_page(1.0, page, bounds, ("front", "side")) + assert not builder._principal_view_exceeds_page(1.0, page, bounds, ("front",)) @pytest.mark.slow diff --git a/tests/test_pmi_gtol_lowering.py b/tests/test_pmi_gtol_lowering.py index 1fc043dc..40cd2f01 100644 --- a/tests/test_pmi_gtol_lowering.py +++ b/tests/test_pmi_gtol_lowering.py @@ -20,7 +20,7 @@ from draftwright.builder import build_drawing, detect_part_model from draftwright.linting.pmi_coverage import lint_pmi_rendering from draftwright.model import build_pmi_features -from draftwright.model.ir import ControlFrame, Frame, PmiFeature +from draftwright.model.ir import ControlFrame, CylindricalReference, Frame, PmiFeature from draftwright.pmi import PmiExtractionReport, PmiRecord from draftwright.sheet_emit import _feature_block, _feature_line @@ -789,7 +789,13 @@ def _execute_feature_line(feature): sheet = SimpleNamespace(add=captured.append) exec( _feature_line(feature), - {"sheet": sheet, "ControlFrame": ControlFrame, "Frame": Frame, "PmiFeature": PmiFeature}, + { + "sheet": sheet, + "ControlFrame": ControlFrame, + "CylindricalReference": CylindricalReference, + "Frame": Frame, + "PmiFeature": PmiFeature, + }, ) (restored,) = captured return restored From 430acc4fb8e3727c8641aa2790c3586c5343eace Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Tue, 6 Oct 2026 01:51:56 +0000 Subject: [PATCH 3/8] perf: avoid inadmissible no-ISO page proposal --- src/draftwright/builder.py | 136 +++++++++-------------- tests/test_issue_1299_page_escalation.py | 2 +- 2 files changed, 51 insertions(+), 87 deletions(-) diff --git a/src/draftwright/builder.py b/src/draftwright/builder.py index 7973c809..5367703c 100644 --- a/src/draftwright/builder.py +++ b/src/draftwright/builder.py @@ -2445,11 +2445,17 @@ def recover_optional_iso(self): def try_without_iso(self): try: - without_iso_proposal = self.context.build( + # The comparison is admitted only on the already selected sheet. An + # unconstrained no-ISO proposal may choose a different page, but that + # drawing can never win this gate; the old path then compiled the same + # fixed-page candidate anyway. Start with the only admissible page and + # leave larger sheets to the bounded page tail below. + without_iso = self.context.build( None, arrangements=(self.settled_arrangement,), views=self.settled_principal_views, include_iso=False, + page_override=self.original_page, retry_reason="remove_optional_iso", ) except (ValueError, Standard_Failure) as exc: @@ -2465,98 +2471,56 @@ def try_without_iso(self): error=str(exc), ) else: - proposal_page = ( - without_iso_proposal.page_w, - without_iso_proposal.page_h, + without_iso = self.retain_arrangement(without_iso) + assert (without_iso.page_w, without_iso.page_h) == self.original_page + issues, blockers, rejection = self.qualify_candidate( + without_iso, + require_axial_coverage=True, + allow_recovery_detail=True, ) - if proposal_page != self.original_page: + if rejection is None: self.record_attempt( - without_iso_proposal.scale, - "scale_proposal", + without_iso.scale, + "complete", reason="remove_optional_iso", - candidate=without_iso_proposal, + candidate=without_iso, ) - try: - without_iso = self.context.build( - None, - arrangements=(self.settled_arrangement,), - views=self.settled_principal_views, - include_iso=False, - retry_reason="remove_optional_iso", - page_override=self.original_page, - ) - except (ValueError, Standard_Failure) as exc: - if not _is_expected_candidate_build_failure(exc): - raise - _log.info( - "fixed-page optional-ISO replan rejected (build failed: %s)", - exc, - ) - self.record_attempt( - None, - "error", - reason="remove_optional_iso", - views=without_iso_proposal.views, - page=self.original_page, - error=str(exc), - ) - without_iso = None + self.drawing = without_iso + self.settled_issues = issues + self.replanned = True else: - without_iso = without_iso_proposal - - if without_iso is not None: - without_iso = self.retain_arrangement(without_iso) - assert (without_iso.page_w, without_iso.page_h) == self.original_page - issues, blockers, rejection = self.qualify_candidate( - without_iso, - require_axial_coverage=True, - allow_recovery_detail=True, + self.record_attempt( + without_iso.scale, + "rejected", + blockers, + reason="remove_optional_iso", + rejection=rejection, + violations=_layout_issue_records(_hard_layout_issues(issues)), + candidate=without_iso, ) - if rejection is None: - self.record_attempt( - without_iso.scale, - "complete", - reason="remove_optional_iso", - candidate=without_iso, - ) - self.drawing = without_iso - self.settled_issues = issues - self.replanned = True - else: - self.record_attempt( - without_iso.scale, - "rejected", - blockers, - reason="remove_optional_iso", - rejection=rejection, - violations=_layout_issue_records(_hard_layout_issues(issues)), - candidate=without_iso, + # Page preference is subordinate to manufacturing + # completeness. Once the settled no-ISO arrangement has failed + # on the automatically selected sheet, try only the bounded + # sequence of larger standard pages. Each page chooses its scale + # through the established fixed-page policy and must pass the + # same axial, structural, and required-outcome gates above. A + # A detail may be introduced or retained here: it is itself a + # semantic recovery view, and this correction must not reject a + # complete candidate merely because removing the optional ISO + # made room for that required detail. + if self.context.options.page is None: + larger, issues = self.trials.try_larger_standard_pages( + self.original_page, + include_iso=False, + reason="page_escalation_after_optional_iso", + fallback_views=tuple(name for name in self.drawing.views if name != "iso"), + require_axial_coverage=True, + allow_recovery_detail=True, ) - # Page preference is subordinate to manufacturing - # completeness. Once the settled no-ISO arrangement has failed - # on the automatically selected sheet, try only the bounded - # sequence of larger standard pages. Each page chooses its scale - # through the established fixed-page policy and must pass the - # same axial, structural, and required-outcome gates above. A - # A detail may be introduced or retained here: it is itself a - # semantic recovery view, and this correction must not reject a - # complete candidate merely because removing the optional ISO - # made room for that required detail. - if self.context.options.page is None: - larger, issues = self.trials.try_larger_standard_pages( - self.original_page, - include_iso=False, - reason="page_escalation_after_optional_iso", - fallback_views=tuple( - name for name in self.drawing.views if name != "iso" - ), - require_axial_coverage=True, - allow_recovery_detail=True, - ) - if larger is not None: - self.drawing = larger - self.settled_issues = issues - self.replanned = True + if larger is not None: + self.drawing = larger + self.settled_issues = issues + self.replanned = True def replay_scale(self): if ( diff --git a/tests/test_issue_1299_page_escalation.py b/tests/test_issue_1299_page_escalation.py index 79e33e34..5a57169a 100644 --- a/tests/test_issue_1299_page_escalation.py +++ b/tests/test_issue_1299_page_escalation.py @@ -125,6 +125,7 @@ def fake_one_pass( call for call in calls if not call["include_iso"] and call["page"] == (297.0, 210.0) ] assert fixed_page_calls == [{"scale": None, "page": (297.0, 210.0), "include_iso": False}] + assert all(call["page"] is not None for call in calls if not call["include_iso"]) assert (drawing.page_w, drawing.page_h, drawing.scale) == (297.0, 210.0, 2.0) assert [ (attempt["status"], attempt["reason"], attempt.get("rejection")) @@ -133,7 +134,6 @@ def fake_one_pass( ("axial_coverage_incomplete", "remove_optional_iso", None), ("rejected", "scale_escalation_on_selected_page", "axial_coverage_incomplete"), ("rejected", "scale_escalation_on_selected_page", "axial_coverage_incomplete"), - ("scale_proposal", "remove_optional_iso", None), ("complete", "remove_optional_iso", None), ] From e6137e549445cde5b8066cca969e290b3b8ad085 Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Tue, 6 Oct 2026 01:57:52 +0000 Subject: [PATCH 4/8] refactor: keep PMI probe within source-shape guards --- src/draftwright/annotations/_common.py | 41 ++-------------- src/draftwright/annotations/_gdt.py | 48 +++++++++---------- .../annotations/_placement_occupancy.py | 41 +++++++++++++++- 3 files changed, 68 insertions(+), 62 deletions(-) diff --git a/src/draftwright/annotations/_common.py b/src/draftwright/annotations/_common.py index 9080185f..8f7d8317 100644 --- a/src/draftwright/annotations/_common.py +++ b/src/draftwright/annotations/_common.py @@ -82,6 +82,7 @@ from draftwright.annotations._placement_occupancy import ( # noqa: F401 — stable _common imports _PAGE_SPANNING_RIDERS, CROSSABLE_TYPES, + DeferredCompactCandidate, annotation_ink_clear, annotation_ink_obstacles, annotation_obstacle_boxes, @@ -89,6 +90,7 @@ balloon_annotation_label_boxes, balloon_geometry_hits_annotation_labels, box_within_page_and_clear, + compact_probe_clear, corridor_blockers, full_strip_message, is_page_spanning_rider, @@ -2235,18 +2237,6 @@ def _adjust_strip_candidate_labels(run) -> None: run.solved = solved -@dataclass(frozen=True) -class DeferredCompactCandidate: - """Exact leader ink metadata before constructing a costly retry annotation.""" - - label_bbox: tuple[float, float, float, float] - materialize: Any - tip: tuple[float, float] | None = None - elbow: tuple[float, float] | None = None - segments: tuple = () - analytical_straight_leader: bool = False - - def _compact_strip_candidate_ink(run) -> None: """Try bounded contraction against settled and same-batch ink.""" dwg, view, cands = run.dwg, run.view, run.cands @@ -2265,33 +2255,10 @@ def _compact_strip_candidate_ink(run) -> None: index = next((i for i, (key, _dim) in enumerate(solved) if key == name), None) original = solved[index][1] if index is not None else None others = [item for key, item in solved if key != name] - # Label clashes are decisive for exact-ink clearance. Filter them, page - # bounds, furniture, and projected view edges before constructing the - # heavyweight CAD leader. The full check below still validates survivors. - foreign_labels = [] - for item in (*others, *(annotation for _, annotation in dwg.iter_annotations())): - try: - label = getattr(item, "label_bbox", None) - except Exception: # noqa: BLE001 — the exact check fails closed below - continue - if label is not None and len(label) == 4: - foreign_labels.append(label) - page = _drawing_bounds(dwg) for proposal in alternatives(original): if isinstance(proposal, DeferredCompactCandidate): - label = proposal.label_bbox - if ( - label[0] < page[0] - or label[1] < page[1] - or label[2] > page[2] - or label[3] > page[3] - or ((forbid or {}).get(name) is not None and _box_hits(label, (forbid[name],))) - or (label_clear is not None and not label_clear(label)) - or any(_boxes_overlap(label, foreign) for foreign in foreign_labels) - ): - continue - if proposal.analytical_straight_leader and not annotation_ink_clear( - dwg, proposal, additional=others + if not compact_probe_clear( + dwg, proposal, others, (forbid or {}).get(name), label_clear ): continue candidate = proposal.materialize() diff --git a/src/draftwright/annotations/_gdt.py b/src/draftwright/annotations/_gdt.py index 5971a043..440d03f8 100644 --- a/src/draftwright/annotations/_gdt.py +++ b/src/draftwright/annotations/_gdt.py @@ -606,9 +606,9 @@ def _gdt_candidate_builders( evidence = _gdt_text_evidence(fallback_glyph, item, draft) if item.kind != "note" else {} glyph_box = fallback_glyph.bounding_box() - def _elbow(pos): + def _elbow(pos, _hz=horizontal): # Keep the analytical preflight and actual helper's zero-shaft guard identical. - if horizontal: + if _hz: delta = pos - py return px, pos if abs(delta) >= _MIN_LEADER else py + math.copysign( _MIN_LEADER, delta or 1.0 @@ -644,28 +644,28 @@ def _ink_at(pos): analytical_straight_leader=True, ) - def _build(pos, _px=px, _py=py, _hz=horizontal, _it=item, _g=fallback_glyph): - tip = (_px, _py) + def _build(pos, _hz=horizontal): + tip = (px, py) # A zero-length leader shaft (the projected site coincides with the solved tier — # `pos == py` above/below, `pos == px` left/right) makes OCC's edge builder raise, # which would crash the whole build on a public-IR declaration. Guarantee a # minimum shaft along the stacking axis (nudge outward; 0.05 mm is invisible) so # `_build` is total — the drop-don't-crash invariant holds for every build call. - elbow = _elbow(pos) + elbow = _elbow(pos, _hz) leader = leader_ctor( tip=tip, elbow=elbow, label="", draft=draft, - callout=_g, - all_around=getattr(_it, "all_around", False), - all_over=getattr(_it, "all_over", False), + callout=fallback_glyph, + all_around=getattr(item, "all_around", False), + all_over=getattr(item, "all_over", False), ) - if _it.kind == "note": + if item.kind == "note": # The outer leader intentionally has label="" because the visible # payload is a TextBlock callout. Preserve the authored note and measure # the embedded Text renderer's face-dependent newline pitch for PDF. - leader.pdf_text = _font_safe_text(_it.text) + leader.pdf_text = _font_safe_text(item.text) leader.pdf_text_font_style = "REGULAR" leader.pdf_text_line_spacing = _text_line_spacing_em( draft.font_size, @@ -676,18 +676,18 @@ def _build(pos, _px=px, _py=py, _hz=horizontal, _it=item, _g=fallback_glyph): _apply_gdt_text_evidence(leader, evidence) return leader - def _build_at(elbow, _px=px, _py=py, _it=item, _g=fallback_glyph): + def _build_at(elbow): leader = leader_ctor( - tip=(_px, _py), + tip=(px, py), elbow=(*elbow, 0), label="", draft=draft, - callout=_g, - all_around=getattr(_it, "all_around", False), - all_over=getattr(_it, "all_over", False), + callout=fallback_glyph, + all_around=getattr(item, "all_around", False), + all_over=getattr(item, "all_over", False), ) - if _it.kind == "note": - leader.pdf_text = _font_safe_text(_it.text) + if item.kind == "note": + leader.pdf_text = _font_safe_text(item.text) leader.pdf_text_font_style = "REGULAR" leader.pdf_text_line_spacing = _text_line_spacing_em( draft.font_size, @@ -698,19 +698,19 @@ def _build_at(elbow, _px=px, _py=py, _it=item, _g=fallback_glyph): _apply_gdt_text_evidence(leader, evidence) return leader - def _build_routed(bends, elbow, _px=px, _py=py, _it=item, _g=fallback_glyph): + def _build_routed(bends, elbow): leader = RoutedLeader( - (_px, _py), + (px, py), bends, elbow, "", draft, - callout=_g, - all_around=getattr(_it, "all_around", False), - all_over=getattr(_it, "all_over", False), + callout=fallback_glyph, + all_around=getattr(item, "all_around", False), + all_over=getattr(item, "all_over", False), ) - if _it.kind == "note": - leader.pdf_text = _font_safe_text(_it.text) + if item.kind == "note": + leader.pdf_text = _font_safe_text(item.text) leader.pdf_text_font_style = "REGULAR" leader.pdf_text_line_spacing = _text_line_spacing_em( draft.font_size, diff --git a/src/draftwright/annotations/_placement_occupancy.py b/src/draftwright/annotations/_placement_occupancy.py index 70a05a62..cab4a174 100644 --- a/src/draftwright/annotations/_placement_occupancy.py +++ b/src/draftwright/annotations/_placement_occupancy.py @@ -7,11 +7,13 @@ import math from collections.abc import Iterable +from dataclasses import dataclass from itertools import chain +from typing import Any from build123d_drafting.helpers import Dimension, Leader, Note, SafeDimension -from draftwright._core import Analysis, _analysis_margins, place_annotation +from draftwright._core import Analysis, _analysis_margins, _drawing_bounds, place_annotation from draftwright._geometry import _boxes_overlap, _segment_clips_box, _segments_cross_or_overlap from draftwright.annotations._dimension_ink import DimensionInkCandidate from draftwright.annotations._placement_geometry import ( @@ -44,6 +46,43 @@ _PAGE_SPANNING_RIDERS = ("is_sheet_frame", "is_zone_grid") +@dataclass(frozen=True) +class DeferredCompactCandidate: + """Exact leader ink metadata before constructing a costly retry annotation.""" + + label_bbox: tuple[float, float, float, float] + materialize: Any + tip: tuple[float, float] | None = None + elbow: tuple[float, float] | None = None + segments: tuple = () + analytical_straight_leader: bool = False + + +def compact_probe_clear(dwg, proposal, others, forbid_box, label_clear) -> bool: + """Reject decisive label, page, furniture and straight-shaft collisions cheaply.""" + label = proposal.label_bbox + page = _drawing_bounds(dwg) + if ( + label[0] < page[0] + or label[1] < page[1] + or label[2] > page[2] + or label[3] > page[3] + or (forbid_box is not None and _box_hits(label, (forbid_box,))) + or (label_clear is not None and not label_clear(label)) + ): + return False + for item in (*others, *(annotation for _, annotation in dwg.iter_annotations())): + try: + foreign = getattr(item, "label_bbox", None) + except Exception: # noqa: BLE001 — the exact check fails closed below + continue + if foreign is not None and len(foreign) == 4 and _boxes_overlap(label, foreign): + return False + return not proposal.analytical_straight_leader or annotation_ink_clear( + dwg, proposal, additional=others + ) + + def is_page_spanning_rider(annotation) -> bool: """Is *annotation* one of the page-spanning riders (see :data:`_PAGE_SPANNING_RIDERS`)? From 97f277d321366c3a6a2cc34d7f75c6d9386e7979 Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Tue, 6 Oct 2026 02:05:19 +0000 Subject: [PATCH 5/8] fix: retain AP242 plan witness stations for Y dimensions --- .../annotations/_pmi_dimensions.py | 12 +++++--- tests/test_pmi.py | 28 +++++++++++++++++++ 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/src/draftwright/annotations/_pmi_dimensions.py b/src/draftwright/annotations/_pmi_dimensions.py index af097bca..3d36ec64 100644 --- a/src/draftwright/annotations/_pmi_dimensions.py +++ b/src/draftwright/annotations/_pmi_dimensions.py @@ -433,11 +433,15 @@ def _pmi_witness_from_bbox(rec, view: str, a: Analysis): p2 = (SX(hi), SZ((zmin + zmax) / 2), 0) avg_t = SZ((zmin + zmax) / 2) elif view == "plan" and ax == "Y": - avg_x = (xmin + xmax) / 2 + # AP242 may attach broad plate faces to a local Y measurement. Their + # combined bbox can cover the whole part, so its midpoint collapses + # distinct witness pairs onto one X station. The proved reference points + # are the dimension's actual stations (as for plan/X above). + witness_x = sum(point[0] for point in pts) / len(pts) lo, hi = min(point[1] for point in pts), max(point[1] for point in pts) - p1 = (PX(avg_x), PY(lo), 0) - p2 = (PX(avg_x), PY(hi), 0) - avg_t = PX(avg_x) + p1 = (PX(witness_x), PY(lo), 0) + p2 = (PX(witness_x), PY(hi), 0) + avg_t = PX(witness_x) else: return None diff --git a/tests/test_pmi.py b/tests/test_pmi.py index 442577bc..e501d55a 100644 --- a/tests/test_pmi.py +++ b/tests/test_pmi.py @@ -242,6 +242,34 @@ def capture(_drawing, _ctx, options, _axis, _label, _record): ) assert queued and all(option["view"] == "plan" for option in queued) + def test_plan_y_witness_uses_source_station_not_broad_face_bbox_issue_2192(self): + from draftwright.annotations._pmi_dimensions import _pmi_witness_from_bbox + + def identity(value): + return value + analysis = SimpleNamespace( + proj=SimpleNamespace( + front_x=identity, + front_z=identity, + side_x=identity, + side_z=identity, + plan_x=identity, + plan_y=identity, + ) + ) + stations = (-25.0, 0.0, 25.0) + witnesses = [] + for station in stations: + record = SimpleNamespace( + dominant_axis="Y", + ref_pts=((station, -40.0, 6.0), (station, 0.0, 6.0)), + ref_bbox=(-60.0, -40.0, 0.0, 60.0, 40.0, 12.0), + ) + witnesses.append(_pmi_witness_from_bbox(record, "plan", analysis)) + + assert [witness[0][0] for witness in witnesses] == list(stations) + assert all(witness[0][1] == -40.0 and witness[1][1] == 0.0 for witness in witnesses) + def test_nist_ctc01_returns_records(self, ctc01_extraction_report): recs = ctc01_extraction_report.records assert len(recs) > 0 From 9818b872461adabaad97a775240f7d028e489ec2 Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Tue, 6 Oct 2026 02:12:17 +0000 Subject: [PATCH 6/8] fix: reserve routes for unhinted AP242 linear PMI --- src/draftwright/compose.py | 15 +++++++++++++++ tests/test_issue_563_placement_intent.py | 21 +++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/draftwright/compose.py b/src/draftwright/compose.py index d8c1c94a..3859375e 100644 --- a/src/draftwright/compose.py +++ b/src/draftwright/compose.py @@ -821,6 +821,21 @@ def _reserve_authored_dimensions( if view_hint is None and side_hint is None and angular_reference is None: if kind == "linear" and axis == "?" and target_view is not None: pass + elif kind == "linear" and axis == "X": + # The renderer tries front/above, then front/below. Imported + # AP242 X dimensions commonly have no route hint; omitting both + # bands leaves even a required overall tolerance with a zero- + # capacity strip despite ample space on the sheet (#2192). + _reserve_corridor(corridors, "front", "above") + _reserve_corridor(corridors, "front", "below") + continue + elif kind == "linear" and axis == "Y": + # The no-hint route tries the side's two horizontal strips and + # then the plan's below strip. Reserve those same alternatives. + _reserve_corridor(corridors, "side", "above") + _reserve_corridor(corridors, "side", "below") + _reserve_corridor(corridors, "plan", "below") + continue elif kind not in ("diameter", "radius", "angular") and axis == "Z": _reserve_corridor(corridors, "front", "left") _reserve_corridor(corridors, "front", "right") diff --git a/tests/test_issue_563_placement_intent.py b/tests/test_issue_563_placement_intent.py index b4640949..87da5c8e 100644 --- a/tests/test_issue_563_placement_intent.py +++ b/tests/test_issue_563_placement_intent.py @@ -419,6 +419,27 @@ def test_compose_reserves_every_supported_measured_corridor_family(): assert footprint.sv_top > 0 and footprint.sv_bottom > 0 +def test_unhinted_source_linear_dimensions_reserve_their_render_routes_issue_2192(): + sheet = Sheet(Box(120, 80, 12)).authored_dimensions() + for axis, points in ( + ("X", ((-60, 0, 6), (60, 0, 6))), + ("Y", ((0, -40, 6), (0, 0, 6))), + ): + sheet.measured_dimension( + kind="linear", + value=120 if axis == "X" else 40, + label="120 ±0.05" if axis == "X" else "40", + dominant_axis=axis, + ref_bbox=(-60, -40, 0, 60, 40, 12), + ref_pts=points, + ) + + footprint = _footprint_from_boxes(_compose_anno_boxes(sheet.model(), n_steps=0)) + assert footprint.fv_top > 0 and footprint.fv_bottom > 0 + assert footprint.sv_top > 0 and footprint.sv_bottom > 0 + assert footprint.pv_bottom > 0 + + def test_compose_ignores_an_unresolved_defensive_target(monkeypatch): import draftwright.compose as compose From 134df87f9918f47cd47a9e3e04a60aa362b37f65 Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Tue, 6 Oct 2026 02:21:13 +0000 Subject: [PATCH 7/8] refactor: keep PMI reservation within review guards --- src/draftwright/compose.py | 36 +++++++++++++++++------------------- tests/test_pmi.py | 1 + 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/src/draftwright/compose.py b/src/draftwright/compose.py index 3859375e..3964858d 100644 --- a/src/draftwright/compose.py +++ b/src/draftwright/compose.py @@ -788,6 +788,22 @@ def _reserve_planned_angles( ) +def _reserve_unhinted_linear_corridors(corridors, kind, axis) -> None: + """Reserve the same default/fallback strips the linear PMI renderer tries.""" + if kind == "linear" and axis == "X": + # Imported AP242 X dimensions commonly have no route hint. Without these + # bands even a required overall tolerance has a zero-capacity strip (#2192). + _reserve_corridor(corridors, "front", "above") + _reserve_corridor(corridors, "front", "below") + elif kind == "linear" and axis == "Y": + _reserve_corridor(corridors, "side", "above") + _reserve_corridor(corridors, "side", "below") + _reserve_corridor(corridors, "plan", "below") + elif kind not in ("diameter", "radius", "angular") and axis == "Z": + _reserve_corridor(corridors, "front", "left") + _reserve_corridor(corridors, "front", "right") + + def _reserve_authored_dimensions( model, boxes: list[AnnoBox], @@ -821,26 +837,8 @@ def _reserve_authored_dimensions( if view_hint is None and side_hint is None and angular_reference is None: if kind == "linear" and axis == "?" and target_view is not None: pass - elif kind == "linear" and axis == "X": - # The renderer tries front/above, then front/below. Imported - # AP242 X dimensions commonly have no route hint; omitting both - # bands leaves even a required overall tolerance with a zero- - # capacity strip despite ample space on the sheet (#2192). - _reserve_corridor(corridors, "front", "above") - _reserve_corridor(corridors, "front", "below") - continue - elif kind == "linear" and axis == "Y": - # The no-hint route tries the side's two horizontal strips and - # then the plan's below strip. Reserve those same alternatives. - _reserve_corridor(corridors, "side", "above") - _reserve_corridor(corridors, "side", "below") - _reserve_corridor(corridors, "plan", "below") - continue - elif kind not in ("diameter", "radius", "angular") and axis == "Z": - _reserve_corridor(corridors, "front", "left") - _reserve_corridor(corridors, "front", "right") - continue else: + _reserve_unhinted_linear_corridors(corridors, kind, axis) continue if target_view is None: continue diff --git a/tests/test_pmi.py b/tests/test_pmi.py index e501d55a..bd6f8860 100644 --- a/tests/test_pmi.py +++ b/tests/test_pmi.py @@ -247,6 +247,7 @@ def test_plan_y_witness_uses_source_station_not_broad_face_bbox_issue_2192(self) def identity(value): return value + analysis = SimpleNamespace( proj=SimpleNamespace( front_x=identity, From a17d0c4ea423bae0db2e71824916f24561ca173b Mon Sep 17 00:00:00 2001 From: Paul Fremantle Date: Tue, 6 Oct 2026 05:35:19 +0000 Subject: [PATCH 8/8] fix: preserve page choice and authored PMI intent in probe stack --- .../annotations/_pmi_dimensions.py | 6 +- src/draftwright/build_policy.py | 22 +-- src/draftwright/builder.py | 131 +++++++++++------- src/draftwright/compose.py | 4 + tests/test_issue_1146_scale_completeness.py | 4 +- tests/test_issue_1299_page_escalation.py | 2 +- 6 files changed, 98 insertions(+), 71 deletions(-) diff --git a/src/draftwright/annotations/_pmi_dimensions.py b/src/draftwright/annotations/_pmi_dimensions.py index 3d36ec64..0024a533 100644 --- a/src/draftwright/annotations/_pmi_dimensions.py +++ b/src/draftwright/annotations/_pmi_dimensions.py @@ -437,7 +437,11 @@ def _pmi_witness_from_bbox(rec, view: str, a: Analysis): # combined bbox can cover the whole part, so its midpoint collapses # distinct witness pairs onto one X station. The proved reference points # are the dimension's actual stations (as for plan/X above). - witness_x = sum(point[0] for point in pts) / len(pts) + point_x = sum(point[0] for point in pts) / len(pts) + # Some authored records supply reference points on an abstract datum + # line outside their support box. Keep the support box as the fallback + # in that case; use the actual stations when they lie on the geometry. + witness_x = point_x if xmin - 1e-6 <= point_x <= xmax + 1e-6 else (xmin + xmax) / 2 lo, hi = min(point[1] for point in pts), max(point[1] for point in pts) p1 = (PX(witness_x), PY(lo), 0) p2 = (PX(witness_x), PY(hi), 0) diff --git a/src/draftwright/build_policy.py b/src/draftwright/build_policy.py index 6caf9e49..c299d02a 100644 --- a/src/draftwright/build_policy.py +++ b/src/draftwright/build_policy.py @@ -535,11 +535,10 @@ def _scale_attempt( def _principal_view_exceeds_page(scale, page, bounds, views) -> bool: """Rule out a fixed-scale build whose bare principal projections cannot fit. - The third-/first-angle principal origins keep front and plan in one vertical - column and side next to that column in every supported arrangement. Use only - the part's world-space box and the *full* page: omitting even the mandatory - gutters, margins and annotation footprints makes this a necessary bound, - never a speculative fit verdict. No ink solve can rescue a rejected scale. + Use only the part's world-space box and the *full* page: omitting even the + mandatory gutters, margins and annotation footprints makes this a necessary + bound, never a speculative fit verdict. No ink solve can rescue a rejected + scale. """ extents = { "x": bounds.max.X - bounds.min.X, @@ -548,21 +547,12 @@ def _principal_view_exceeds_page(scale, page, bounds, views) -> bool: } axes = {"front": ("x", "z"), "plan": ("x", "y"), "side": ("y", "z")} page_w, page_h = page - if any( + return any( extents[horizontal] * scale > page_w + 1e-9 or extents[vertical] * scale > page_h + 1e-9 for view in views if (pair := axes.get(view)) is not None for horizontal, vertical in (pair,) - ): - return True - selected = set(views) - if "side" in selected and ({"front", "plan"} & selected): - if (extents["x"] + extents["y"]) * scale > page_w + 1e-9: - return True - if {"front", "plan"} <= selected: - if (extents["z"] + extents["y"]) * scale > page_h + 1e-9: - return True - return False + ) def _has_detail_view(views) -> bool: diff --git a/src/draftwright/builder.py b/src/draftwright/builder.py index 5367703c..b971f7e0 100644 --- a/src/draftwright/builder.py +++ b/src/draftwright/builder.py @@ -2445,17 +2445,11 @@ def recover_optional_iso(self): def try_without_iso(self): try: - # The comparison is admitted only on the already selected sheet. An - # unconstrained no-ISO proposal may choose a different page, but that - # drawing can never win this gate; the old path then compiled the same - # fixed-page candidate anyway. Start with the only admissible page and - # leave larger sheets to the bounded page tail below. - without_iso = self.context.build( + without_iso_proposal = self.context.build( None, arrangements=(self.settled_arrangement,), views=self.settled_principal_views, include_iso=False, - page_override=self.original_page, retry_reason="remove_optional_iso", ) except (ValueError, Standard_Failure) as exc: @@ -2471,56 +2465,93 @@ def try_without_iso(self): error=str(exc), ) else: - without_iso = self.retain_arrangement(without_iso) - assert (without_iso.page_w, without_iso.page_h) == self.original_page - issues, blockers, rejection = self.qualify_candidate( - without_iso, - require_axial_coverage=True, - allow_recovery_detail=True, + proposal_page = ( + without_iso_proposal.page_w, + without_iso_proposal.page_h, ) - if rejection is None: + if proposal_page != self.original_page: self.record_attempt( - without_iso.scale, - "complete", + without_iso_proposal.scale, + "scale_proposal", reason="remove_optional_iso", - candidate=without_iso, + candidate=without_iso_proposal, ) - self.drawing = without_iso - self.settled_issues = issues - self.replanned = True + try: + without_iso = self.context.build( + None, + arrangements=(self.settled_arrangement,), + views=self.settled_principal_views, + include_iso=False, + retry_reason="remove_optional_iso", + page_override=self.original_page, + ) + except (ValueError, Standard_Failure) as exc: + if not _is_expected_candidate_build_failure(exc): + raise + _log.info("fixed-page optional-ISO replan rejected (build failed: %s)", exc) + self.record_attempt( + None, + "error", + reason="remove_optional_iso", + views=without_iso_proposal.views, + page=self.original_page, + error=str(exc), + ) + without_iso = None else: - self.record_attempt( - without_iso.scale, - "rejected", - blockers, - reason="remove_optional_iso", - rejection=rejection, - violations=_layout_issue_records(_hard_layout_issues(issues)), - candidate=without_iso, + without_iso = without_iso_proposal + + if without_iso is not None: + without_iso = self.retain_arrangement(without_iso) + assert (without_iso.page_w, without_iso.page_h) == self.original_page + issues, blockers, rejection = self.qualify_candidate( + without_iso, + require_axial_coverage=True, + allow_recovery_detail=True, ) - # Page preference is subordinate to manufacturing - # completeness. Once the settled no-ISO arrangement has failed - # on the automatically selected sheet, try only the bounded - # sequence of larger standard pages. Each page chooses its scale - # through the established fixed-page policy and must pass the - # same axial, structural, and required-outcome gates above. A - # A detail may be introduced or retained here: it is itself a - # semantic recovery view, and this correction must not reject a - # complete candidate merely because removing the optional ISO - # made room for that required detail. - if self.context.options.page is None: - larger, issues = self.trials.try_larger_standard_pages( - self.original_page, - include_iso=False, - reason="page_escalation_after_optional_iso", - fallback_views=tuple(name for name in self.drawing.views if name != "iso"), - require_axial_coverage=True, - allow_recovery_detail=True, + if rejection is None: + self.record_attempt( + without_iso.scale, + "complete", + reason="remove_optional_iso", + candidate=without_iso, ) - if larger is not None: - self.drawing = larger - self.settled_issues = issues - self.replanned = True + self.drawing = without_iso + self.settled_issues = issues + self.replanned = True + else: + self.record_attempt( + without_iso.scale, + "rejected", + blockers, + reason="remove_optional_iso", + rejection=rejection, + violations=_layout_issue_records(_hard_layout_issues(issues)), + candidate=without_iso, + ) + # Page preference is subordinate to manufacturing + # completeness. Once the settled no-ISO arrangement has failed + # on the automatically selected sheet, try only the bounded + # sequence of larger standard pages. Each page chooses its scale + # through the established fixed-page policy and must pass the + # same axial, structural, and required-outcome gates above. A + # detail may be introduced or retained here: it is itself a + # semantic recovery view, and this correction must not reject a + # complete candidate merely because removing the optional ISO + # made room for that required detail. + if self.context.options.page is None: + larger, issues = self.trials.try_larger_standard_pages( + self.original_page, + include_iso=False, + reason="page_escalation_after_optional_iso", + fallback_views=tuple(name for name in self.drawing.views if name != "iso"), + require_axial_coverage=True, + allow_recovery_detail=True, + ) + if larger is not None: + self.drawing = larger + self.settled_issues = issues + self.replanned = True def replay_scale(self): if ( diff --git a/src/draftwright/compose.py b/src/draftwright/compose.py index 3964858d..c80bc812 100644 --- a/src/draftwright/compose.py +++ b/src/draftwright/compose.py @@ -814,6 +814,10 @@ def _reserve_authored_dimensions( text_position: str, text_orientation: str, ) -> None: + # Report/off modes retain imported records for diagnostics but do not draw + # them. Their corridors must not enlarge the sheet for invisible ink. + if not model.pmi_annotations_enabled: + return # Measured placement hints are semantic corridor requirements and therefore part of # compose-before-pack, not merely renderer filters. Resolve every valid explicit route; # a view-only hint conservatively reserves both supported sides, while the legacy diff --git a/tests/test_issue_1146_scale_completeness.py b/tests/test_issue_1146_scale_completeness.py index c75feeaf..565b5bd1 100644 --- a/tests/test_issue_1146_scale_completeness.py +++ b/tests/test_issue_1146_scale_completeness.py @@ -567,9 +567,7 @@ def test_principal_projection_must_fit_inside_the_physical_page(): page = (1189.0, 841.0) assert not builder._principal_view_exceeds_page(0.5, page, bounds, ("front", "plan", "side")) assert builder._principal_view_exceeds_page(1.0, page, bounds, ("front", "plan", "side")) - # The two bare projections fit individually, but cannot share the horizontal row. - assert builder._principal_view_exceeds_page(1.0, page, bounds, ("front", "side")) - assert not builder._principal_view_exceeds_page(1.0, page, bounds, ("front",)) + assert not builder._principal_view_exceeds_page(1.0, page, bounds, ("front", "side")) @pytest.mark.slow diff --git a/tests/test_issue_1299_page_escalation.py b/tests/test_issue_1299_page_escalation.py index 5a57169a..79e33e34 100644 --- a/tests/test_issue_1299_page_escalation.py +++ b/tests/test_issue_1299_page_escalation.py @@ -125,7 +125,6 @@ def fake_one_pass( call for call in calls if not call["include_iso"] and call["page"] == (297.0, 210.0) ] assert fixed_page_calls == [{"scale": None, "page": (297.0, 210.0), "include_iso": False}] - assert all(call["page"] is not None for call in calls if not call["include_iso"]) assert (drawing.page_w, drawing.page_h, drawing.scale) == (297.0, 210.0, 2.0) assert [ (attempt["status"], attempt["reason"], attempt.get("rejection")) @@ -134,6 +133,7 @@ def fake_one_pass( ("axial_coverage_incomplete", "remove_optional_iso", None), ("rejected", "scale_escalation_on_selected_page", "axial_coverage_incomplete"), ("rejected", "scale_escalation_on_selected_page", "axial_coverage_incomplete"), + ("scale_proposal", "remove_optional_iso", None), ("complete", "remove_optional_iso", None), ]