Skip to content

Perf: cut optimal bounding-box and deepcopy cost in annotation/text geometry (~25-33% of samples) #1943

Open

Description

@pzfreo

Originally tracked in code-health epic #1939; now an open performance follow-up. Profiled on main @ 71b8c94 with py-spy and call-count wrappers on a 4-core box (timings ±20%). The parts were a build123d box with five holes, evaluation/blind-hole.step, grm03_thumbwheel_drive_screw_ap242_pmi.step and nist_ctc_02_asme1_ap203.stp, all built through build_drawing(src) with defaults. On simple parts about 90% of build time is build123d/OCC work on annotation, text and title-block geometry. HLR is 1–3% and recognition 0.3–5%.

Problem

  • Almost every bbox is the slow optimal kind. There are 91 .bounding_box() calls in draftwright and 29 in helpers, and all but 2 use the default optimal=True (BRepBndLib.AddOptimal).
  • This is the biggest single cost. On the box part it is the largest self-time entry (1.59 s over 1,026 calls), and 24–28% of samples overall. On CTC-02 it is 33%.
  • The shape is copied on every move. Shape.moved → copy.deepcopy adds another 22–23%.
  • Some boxes are recomputed without need:
    • projection._projected_shape_bounds (projection.py:76) recomputes the part's optimal bbox on every call.
    • leaders._fixed_component_bounds (leaders.py:1145) recomputes boxes for components that have none, 5,460 calls on the box part.
    • _possible_fixed_components is a linear scan with no spatial index.

Proposal

  • For planar annotation and text ink, use optimal=False where a slightly loose box is safe, or compute the box once and cache it on the object. Lint's own geometry checks must keep exact boxes. Check each site before changing it.
  • Cache the part's projected bounds for each build.
  • Avoid .moved() deepcopies in hot loops by transforming boxes instead of shapes.
  • If helpers is the right owner for any of this, file it upstream in build123d-drafting-helpers.

Progress

  • Reuse exact assembly bounds across projections (#1943) #1988 reused the exact source Solid bounding box across principal and initial iso projections. On CTC-02, exact projection bbox calls fell 23→13 and quiet paired build time 97.779→94.822 s; 18 corpus inputs preserved nine-decimal placement boxes and full lint. Shape.moved calls remained 14,777, so the deepcopy cost and full measured acceptance remain open. Independent review, changed-line coverage, and CI passed.

  • A 2026-09-28 exact Drawing.view_bounds cache experiment on main 9aa24587 was rejected under the epic no-regression gate: CTC-02 bbox calls fell 672→46 and nine-decimal signatures/lint matched, but three interleaved build pairs were slower by 2.806, 4.348, and 1.586 s. GRM03 paired median was unchanged at 2.842 s. The cache was not committed. Profiling located the remaining Shape.moved/deepcopy cost mainly in build123d and drafting-helper geometry construction; Perf: cut optimal bounding-box and deepcopy cost in annotation/text geometry (~25-33% of samples) #1943 remains open for a measured, parity-preserving approach.

  • Fresh read-only profile on main 63cb9fe5 (2026-09-29) through default build_drawing(src): five-hole Box 670 optimal bbox calls/181 deepcopies, blind-hole STEP 554/152, GRM03 2,166/610, CTC-02 AP203 76,557/15,379. An instrumented CTC run spent 25.07 s in wrapped optimal bbox and 1.91 s in wrapped deepcopy out of 121 s; concurrent load changed wall time enough that this is a cost location, not a speed comparison. scripts/profile-builds on tests/test_lint_summary.py collected today's 15 tests and passed 15/15 (summary in /private/tmp/profile1943-next-20260929/summary.json). The remaining promising seam is dependency-owned build123d text alignment (prior profile: 2,856 CTC bbox calls/2.43 s); it needs an isolated upstream microbenchmark, exact parity, and quiet paired four-workload timing before a patch. No code was changed in this profile.

Acceptance

  • The share of samples spent in AddOptimal and deepcopy falls measurably on the four profiled parts.
  • Lint findings and the golden corpus are unchanged.

2026-09-30 follow-up hotspot audit

On unpublished 0f9534c9, a read-only call-count audit found no remaining high-frequency draftwright-owned bbox/deepcopy site with both clear exactness and a material expected payoff. The closest small idea is a guarded LINE-endpoint fast path in projection._bounded_projected_edges: GRM03 had 792 projected-edge bbox checks, 228 LINE edges and 172 safely interior by >1e-3; observed LINE bbox extents matched endpoints within 1e-7. Historic profiling priced all 792 GRM edge bbox calls at ~0.012 s, so skipping 172 suggests only ~0.003 s. On CTC the old profile counted 41,784 calls but only 0.764 s of ~172 s. OCC tolerance and bbox side effects remain unproved for that shortcut, and the earlier candidate-memo/view-bounds experiments were rejected for regression/staleness. No patch was made. The local build123d text-alignment cache optimization (acfec8d) is retired by maintainer decision: its measured savings do not justify an upstream patch. It is not a general deepcopy fix and will not be pursued for this epic. #1943 measured acceptance stays open for a worthwhile, parity-preserving change.

2026-09-30 maintainer disposition

The maintainer chose to close #1939 promptly and keep this issue open as a separate measured performance follow-up. The original four-workload AddOptimal/deepcopy acceptance is not met. Exact source-bbox reuse in #1988 remains merged, but fresh profiling and independent review found no further Draftwright-owned change with a credible material gain and exact output parity; earlier cache experiments regressed and the upstream text-cache patch was retired as insufficiently valuable. No new optimization or ADR change is claimed by this disposition. Resume this issue only with a new structural candidate and paired four-workload timing plus drawing/lint parity evidence.

Activity

  1. added
    tech-debtInternal maintainability or refactoring work
    area:layoutLayout, placement, scale/page, strips, repack
    on Sep 28, 2026
  2. pzfreo commented on Sep 28, 2026

    @pzfreo
    OwnerAuthor

    Fresh four-part call-count profiling on main 688aa344 (same build_drawing(src) entry path) found AddOptimal / Shape deepcopy counts of: five-hole box 742 / 206; blind-hole 557 / 152; GRM03 3,102 / 1,420; CTC-02 78,295 / 16,881. Wall times under concurrent local load were noisy, so no speed claim is made.

    Two narrow ideas were tested and rejected without a PR. Reusing lint's annotation-bbox memo in Drawing.layout_utilization() saved exactly 19 AddOptimal calls on each of the first three parts, no deepcopies, with identical SVG hashes and lint; the gain is too small for this issue's acceptance, especially versus CTC-02's 78,295 calls. A pre-_exactify_silhouettes BSpline gate targeted a path taking only 1–6 ms/build on the first three parts. Both trials were reverted; static checks and 22 focused tests passed. The dominant first-three-part bbox cost is in helper/build123d text construction, while lint's exact geometry checks must remain exact. Continue with a measured hot-loop candidate or upstream helper investigation; #1943 stays open.

  3. pzfreo commented on Sep 28, 2026

    @pzfreo
    OwnerAuthor

    Follow-up profile on main cc4781a3: no safe, material #1943 candidate found; issue remains open. Instrumented build_drawing(src) showed Shape.bounding_box calls / wrapped time of 620 / 0.127 s (five-hole box), 565 / 0.122 s (blind-hole STEP), 2,166 / 0.574 s (GRM03), and 77,801 / 20.007 s (CTC-02). The CTC count is a proxy for AddOptimal, not an exact AddOptimal count. CTC had 15,379 shape deepcopies / 1.388 s, mostly through Shape.moved (14,777 calls).

    Largest CTC bbox sites included annotation _geom_box (3,707 / 2.443 s), text alignment (2,856 / 2.414 s), projection bounds (13 / 2.397 s), and Drawing.view_bounds (672 / 2.678 s). An isolated installed-helper experiment combined per-face Dimension boxes into one compound box: GRM03 site calls fell 178→27, but site time rose 0.022→0.040 s. Box/GRM03 nine-decimal signatures and lint matched. The overall instrumented timing was contaminated by concurrent workers, so it is not a paired speed claim; the helper was restored byte-exact. No code was committed or PR opened. A future attempt needs a narrower positive microbenchmark, then quiet paired four-workload timings and exact corpus/lint parity.

  4. pzfreo commented on Sep 29, 2026

    @pzfreo
    OwnerAuthor

    Bounded follow-up experiment on the current epic branch: threading the existing Drawing.box_cache from registered strip obstacles into the non-segmented occupancy fallback. The candidate stayed isolated and has been discarded under #1939's measured no-regression gate.

    Four workload snapshots (views, nine-decimal annotation boxes and labels, model kinds, and ordered lint) were byte-identical in all 12 quiet paired comparisons. A focused guard confirmed one bounding-box call for repeated cache identity and was mutation-checked by removing the cache threading. Static checks passed.

    Fresh-process, interleaved three-pair median candidate changes versus the same baseline:

    Workload Median build-time change
    Five-hole 0.27% slower
    Blind-hole 0.53% faster
    GRM03 1.72% slower
    CTC-02 3.90% faster

    GRM03 was slower in all three quiet pairs (+0.053, +0.032, +0.121 s), and the five-hole case showed no gain. The CTC-02 improvement does not meet the agreed no-benchmark-regression acceptance. No code from this experiment was retained; #1943 remains open for another measured approach.

  5. pzfreo commented on Sep 29, 2026

    @pzfreo
    OwnerAuthor

    Additional #1943 profiling on the current execution machine (main 174cf97d) found 76,558 optimal bounding-box calls taking 20.217 s and 14,777 shape moves taking 1.438 s in an instrumented 93 s CTC-02 build. The largest draftwright-owned call sites were Drawing.view_bounds (672 calls, 2.706 s), transient placement geometry (2,437 calls, 2.167 s), and face-exactly-covered checks (1,891 calls, 0.528 s). Most of the remaining text alignment cost is in build123d/drafting helpers.

    The earlier exact view-bounds cache and build-local strip-box memo preserved output but failed the agreed paired no-regression timing gate; both were discarded. A conservative leader-validation bbox check would address only about 0.5 s of this CTC-02 run and would leave deepcopy untouched, so it does not meet this issue's measured acceptance. No new #1943 code was committed. The issue remains open for a parity-preserving change that measurably lowers both costs across the four profiled parts without a benchmark regression.

  6. pzfreo commented on Sep 29, 2026

    @pzfreo
    OwnerAuthor

    Read-only follow-up on merged main e801f6f9 (2026-09-29). Profiled default build_drawing(src) for a build123d box with five Ø6 through holes, tests/fixtures/evaluation/blind-hole.step, tests/fixtures/grm03_thumbwheel_drive_screw_ap242_pmi.step, and tests/fixtures/nist_ctc_02_asme1_ap203.stp. These are application-entry builds, not direct build123d.import_step calls.

    On CTC-02, instrumented bbox costs included Drawing.view_bounds 672 calls / 2.74 s, _geom_box 3,707 / 2.44 s, build123d text 2,856 / 2.43 s, and _projected_shape_bounds 13 / 2.39 s. Moved-shape calls were mainly in build123d translate (2,872 / 0.67 s) and drafting-helper dimension/constructor geometry, with direct RoutedLeader moves only 12 / 0.009 s. The CTC cProfile/wrapper run included a deliberate ~30 s process pause during a separate quiet benchmark, so its 226 s elapsed time is not a build-time comparison.

    The exact source-bbox reuse from #1988 already handles the obvious projection seam. A global loose bbox could change placement or lint, and a prior exact view-bounds memo regressed paired builds. I found no additional app-owned candidate with proved no-regression timing and exact parity, so made no code change. The issue's AddOptimal/deepcopy acceptance remains open; the next useful candidate may be in build123d-drafting-helpers or build123d itself, or a newly measured app seam.

  7. pzfreo commented on Sep 29, 2026

    @pzfreo
    OwnerAuthor

    Measured follow-up on the current #1939 stack (d7d3184b), using default build_drawing(path) for the STEP workloads and an isolated clean worktree. I tested reusing the existing annotation-box memo in layout_utilization. It removed 19 direct bounding-box calls on tests/fixtures/evaluation/blind-hole.step and 172 on tests/fixtures/nist_ctc_02_asme1_ap203.stp; the 14-input direct drawing-signature corpus was byte-identical, and the standard golden suite passed 23/23.

    Two quiet alternating CTC-02 pairs were mixed: base/candidate 90.109/90.513 s (+0.404 s candidate) and 91.083/89.751 s (-1.332 s candidate). Earlier short-workload pairs overlapped other local test activity and were excluded from the decision. Deepcopy cost was unchanged. This does not establish a stable no-regression gain or meet the issue's AddOptimal and deepcopy acceptance, so the experiment was reverted and no PR was made. The opt-in DRAFTWRIGHT_GOLDEN_EXACT gate fails on the untouched base too, so direct same-base signatures were used for parity.

    A targeted scripts/profile-builds run collected 15/15 at /private/tmp/profile1943-targeted-20260929. CTC-02 call-site samples still point chiefly to placement geometry, helper text geometry, projected source bounds, and hidden view bounds. #1943 remains open.

  8. pzfreo commented on Sep 29, 2026

    @pzfreo
    OwnerAuthor

    2026-09-29 local follow-up on merged main 6e645c2f, using build_drawing(src) for a centered five-hole Box, evaluation/blind-hole.step, grm03_thumbwheel_drive_screw_ap242_pmi.step, and nist_ctc_02_asme1_ap203.stp (STEP paths use the application's path reader). Instrumented Shape.bounding_box calls were 620 / 565 / 2,166 / 77,801; wrapped time was 0.121 / 0.120 / 0.560 / 19.706 s. Shape.__deepcopy__ calls were 138 / 152 / 610 / 15,379; CTC-02 had 14,777 Shape.moved calls and 1.330 s wrapped deepcopy time in a 90.369 s build. Bounding-box calls are a proxy, not an exact AddOptimal census.

    The largest CTC-02 bbox sites were _placement_geometry._geom_box (2.377 s), projection._projected_shape_bounds (2.373 s, 13 source-Solid boxes after #1988), build123d text alignment (2.366 s), Drawing.view_bounds (2.661 s combined), helper Dimension face boxes (1.351 s), helper _dim_line_ink (1.303 s), and independent lint _ann_box (1.274 s). Earlier exact view_bounds caching cut calls but was slower in all three quiet CTC-02 pairs; helper face-box batching was also slower at its site. No application-level change cleared the epic's measured no-regression gate in this follow-up, so no patch was committed. Raw local profile data is in /private/tmp/dw1943-agent2-hotspots-*.json and /private/tmp/dw1943-agent2-deepcopy-*.json.

  9. pzfreo commented on Sep 29, 2026

    @pzfreo
    OwnerAuthor

    Measured on main at 63cb9fe5 through build_drawing: optimal-bbox/deepcopy calls were Box 670/181, blind-hole STEP 554/152, GRM-03 2,166/610, and CTC-02 AP203 76,557/15,379. The draftwright-side strip-box memo was discarded after a 1.72% GRM-03 median regression in three quiet pairs.

    A local build123d dev patch (acfec8d, unpushed) caches the text-alignment extent and moves each newly created text compound in place. Independent review found and resolved a same-path font replacement case and a concurrent cache race. Direct drawing/lint signatures stayed identical for the four workloads. Reversed-order fresh-process timings were faster in all pairs: Box 8/8 (median −0.0249 s), blind-hole STEP 6/6 (−0.015 s), GRM-03 6/6 (−0.0948 s), CTC-02 3/3 (−3.966 s). The upstream suite passed 2,765 tests with 2 skipped and 324 subtests. No draftwright dependency or source change has been published; the issue's full acceptance remains open.

  10. pzfreo commented on Sep 30, 2026

    @pzfreo
    OwnerAuthor

    2026-09-30 follow-up after the maintainer chose to continue the performance search: two independent read-only audits found no larger, parity-safe draftwright-owned bbox/deepcopy shortcut. On merged main f4aa3214, fresh call-count wrappers around default build_drawing(src) measured Box 620 bounding_box / 128 moved calls, evaluation/blind-hole.step 565 / 137, and grm03_thumbwheel_drive_screw_ap242_pmi.step 2,166 / 491 (/private/tmp/dw1943-current-main-{box,blind,grm}.json). These are call counts, not AddOptimal samples or speed comparisons.

    The earlier CTC-02 AP203 default-build_drawing(path) trace (before current main) attributed only 16 of 14,777 direct moved calls to draftwright (~0.008 s of ~90 s); most shape copies arise while build123d and drafting-helpers construct selected annotation/text geometry. Current source has seven direct .moved() call sites. Draftwright's leader and strip candidates already use analytical geometry before constructing survivors. The largest remaining draftwright bbox sites either serve exact placement/lint checks or have already failed paired timing gates (Drawing.view_bounds cache and strip-box memo). The helper-face batching experiment also regressed. These older CTC numbers are a lead, not a new current-head benchmark.

    No patch was made. The retired build123d text-cache patch stays excluded. #1943 remains open for a structural/dependency-owned candidate with measured four-workload improvement, exact drawing/lint corpus parity, and no benchmark regression; neither audit found one in the current seams.

  11. pzfreo commented on Sep 30, 2026

    @pzfreo
    OwnerAuthor

    2026-09-30 fresh current-main (b5ba5564) four-part follow-up after the maintainer asked to continue the search. The call-count wrapper used default draftwright.build_drawing(src) on a Box, evaluation/blind-hole.step, grm03_thumbwheel_drive_screw_ap242_pmi.step, and /Users/paul/repos/draftwright/tests/fixtures/nist_ctc_02_asme1_ap203.stp (CTC AP203, not build123d.import_step). Results are in /private/tmp/dw1943-current-main-{box,blind,grm,ctc}.json.

    Input Build elapsed bbox calls moved calls
    Box 0.501 s 620 128
    blind-hole STEP 0.524 s 565 137
    GRM03 STEP 2.799 s 2,166 491
    CTC-02 AP203 87.518 s 77,801 14,777

    On CTC, 76,557 bbox calls used optimal=True (19.142 wrapped seconds); 1,244 used false (0.009 s). Direct moved ownership was build123d 3,355/0.610 s, drafting-helpers 11,406/0.690 s, draftwright only 16/0.008 s. Deepcopy was 15,379 calls/1.294 wrapped seconds, almost entirely inside build123d; move and deepcopy timings overlap and must not be added. The most plausible drafting-helper fresh-shape in-place move sites together account for at most 0.474 s on this 87.5 s CTC build (~0.54%), with <=0.008 s on GRM and <=0.002 s on the simple parts. That is an optimistic ceiling, not a measured patch speedup. The earlier retired upstream text-cache candidate saved much more CTC time, yet the maintainer judged it insufficient for upstream work.

    Two independent reviews of the hot paths found no simple application-owned or drafting-helper change with a credible material four-workload gain and exact parity. The highest remaining application bbox sites serve exact placement/lint, source projection is already memoized, and the exact view-bounds cache and strip-box memo had measured regressions. No new patch was made. The issue's original AddOptimal/deepcopy-share acceptance is not met; further work should require a new structural candidate rather than another small cache or in-place move experiment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:layoutLayout, placement, scale/page, strips, repacktech-debtInternal maintainability or refactoring work

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions