Skip to content

performance: speed up isometric SVG export, repeated renders and the e2e suite - #2992

Merged
alixander merged 13 commits into
masterfrom
perf/10x-e2e
Nov 20, 2026
Merged

alixander merged 13 commits into
masterfrom
perf/10x-e2e

Conversation

@alixander

@alixander alixander commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

This makes the e2e suite about 6x faster, makes slow isometric SVG exports about 4x faster, and removes text and font work that the renderer repeated for every diagram. No output changes: every e2e golden (SVG, board JSON and isometric SVG) is byte-identical.

go test ./e2etests (Apple M4, 10 cores) master this branch
wall time 76.1 s 12.3 s
wall time with SKIP_ISOMETRIC_CHECK=1 11.2 s 3.6 s
CPU time (user + sys) 212 s 75 s
peak RSS 477 MiB 620 MiB

Wall times are the fastest of four runs of each test binary (six without isometric checks), taken in rotation; CPU time and peak RSS are medians of the same runs. Other work on the machine overlapped some runs: the whole-suite runs of this branch took between 12.3 s and 16.6 s, and master's between 76.1 s and 78.1 s.

Where the suite's time goes, adding the changes one group at a time:

whole suite SKIP_ISOMETRIC_CHECK=1
master 76.1 s 11.2 s
+ goldens compared in memory 60.9 s 5.8 s
+ test groups started together 54.7 s 3.6 s
+ four isometric renders at a time 32.5 s
+ the rendering changes (this branch) 12.3 s 3.6 s

The last two rows of the whole-suite column depend on their order. In the commits the rendering changes come first: they take the suite from 54.7 s to about 18.2 s, and four slots take it from there to about 12.2 s (the slot measurements under Notes for review).

Isometric SVG, one render of each of the suite's 870 isometric boards from its stored layout, one at a time, each compared with its golden: 104.1 s in total on master, 30.2 s on this branch. The 165 boards that took 100 ms or more on master are 3.8x faster at the median. The slowest board of each of the five slowest cases:

board master this branch
real_world/tpmjs_architecture (dagre) 4,633 ms 800 ms
stable/us_map (dagre) 3,642 ms 810 ms
regression/grid_oom (tala) 3,351 ms 843 ms
stable/nesting_power (dagre) 2,978 ms 610 ms
stable/arrowhead_scaling (tala) 1,632 ms 321 ms

Ordinary (non-isometric) rendering of a single diagram changes little. See the last section.

Test harness

  • Compare goldens in memory. diff.Testdata writes a .got file and starts git diff for every golden: 2,801 processes per run. The harness now compares bytes first and calls diff.Testdata only on a mismatch, so failures print the same diff and TESTDATA_ACCEPT works as before. Three git processes are left per run, on purpose: TestIsometricSVGSnapshot writes a golden into an empty directory, and a missing golden still goes through diff.Testdata. TestTestdataComparesGoldens hands the new comparison a mismatch twice.
  • Start the twelve test groups together. Each group's cases were already parallel, but the groups ran one after another. Side effect: -failfast stops less. Every group has started before a case can fail, so it skips only the cases a group has not created yet, where it used to skip every later group.
  • Run four isometric renders at a time instead of two. This is a trade of memory for time: see the note on memory below. The solver changes do not pay for it. With four slots the suite's peak RSS is the same on master's isometric code and on this branch's (622 and 620 MiB, medians of four runs).

Rendering

  • textmeasure: share glyph metrics of the bundled fonts between rulers. Every Ruler measured all 352 runes of each (font, size) it met, and the renderer creates more rulers than the one a compile is given: for a legend, for each positioned tooltip, for the appendix, and for a render that contains Markdown. The suite built 2,429 atlases per run; it now builds 78. The shared map is never written after it is built. Only the ten text fonts compiled into D2 are shared (the new internal/bundledfont recognises them by backing array); a font registered at run time is measured as before and is never retained. The table stops at 256 atlases, about 10 MB.
  • d2fonts: remember encoded subsets of the bundled fonts. Cutting, compressing and base64-encoding a subset is most of the cost of embedding fonts, and 1,323 of the suite's 1,845 subset requests repeat an earlier one. Bounded at 8 MiB of keys and values; fonts registered at run time are not cached.
  • d2layouts: list a graph's objects only when the log is written. LayoutNested called g.PrintString() twice for every graph it laid out, whether or not debug logging was on.
  • d2svg: scan for Markdown text only in documents that contain it. 785 of the suite's 956 renders skip the regular expression.

The first two help a process that renders more than once (watch mode, d2.js, the Go API, the tests) and a CLI run that needs a second Ruler. The first render of a font and size costs what it did before. The last two save microseconds per render.

Isometric SVG

  • Visibility solver. The same fragments, bit for bit, and the same work accounting, from the same subtraction of nearer faces:

    • a subtraction clips the fragment once instead of twice, and charges the budget for the pass it no longer runs;
    • polygon storage comes from a per-solve pool with free lists, and the scratch is reused across renders unless it has grown past 8 MiB;
    • occluders are ranked once per scene instead of sorted per face;
    • the fragment index uses slices and stamps instead of maps, and reclaims the slots of removed fragments once they far outnumber live ones;
    • charging the work budget is one inlined comparison, and the context is consulted every 4,096 units (1.9 billion checks per suite run become 836 thousand).

    On a generated 3,000-face scene: 98 ms and 41 MB allocated become 43 ms and 1 MB.

  • Path output numbers vertices so its edge tables hash one word, and reuses loop buffers.

  • Surface textures are premultiplied without draw.Draw: transparent pixels are skipped and opaque ones copied, which is 97.6% of the pixels in the suite.

The previous solver is kept as a test oracle in svg_visibility_reference_test.go (804 lines, identifiers renamed, otherwise verbatim). TestSVGVisibilityMatchesReferenceSolver and TestSVGVisibilityLimitsMatchReferenceSolver require bit-identical fragments, and identical errors wherever a work, fragment, vertex or index limit stops the solve, on generated scenes including one large enough for the bounding-box tree. If you would rather not carry the oracle, it can go together with those two tests and the reference run of BenchmarkSVGVisibility. The 870 isometric goldens still cover the output.

Verification

  • ./ci/test.sh passes (90 packages), and each of the first nine commits builds and passes the tests of the packages it touches. The four after them are review follow-ups, a changelog entry and tests.
  • At the head of the branch, go test -race passes for ./e2etests, with and without isometric checks, and for the seven other packages the branch changes.
  • GOOS=js GOARCH=wasm go build ./d2js/..., GOOS=windows go build ./..., and go build ./... and go vet ./... with GOOS=linux GOARCH=386 are clean.
  • Before this was opened, the diff was reviewed in four parts by Claude agents, and a second agent then tried to refute each finding. They compared the rewritten functions with the code they replace on generated input (218,625 solver comparisons over 2,584 scenes, 900,000 path merges, 8,000,000 polygon pairs through the paint-order comparison, every channel value at every alpha of the texture conversion). No difference in rendered output was found. What was found is fixed here: a cache budget that ignored its keys, a worker retention cap that counted less than half the scratch, fragment slots that were not reclaimed until the next face, a budget fast path that was not actually inlined, and several tests that could not fail. The new tests were checked against seventeen seeded mistakes, again at the head of the branch, and each one fails a test.

Notes for review

  • Memory. Four isometric slots and concurrent groups raise the suite's peak RSS from about 477 MiB to about 620 MiB on 10 cores. With the slot count varied on this branch (mean time and highest RSS of two runs each): 18.2 s and 463 MiB at two slots, 12.2 s and 594 MiB at four, 10.5 s and 893 MiB at eight. On a 4-core runner go test runs at most four cases at once by default, so the slot limit no longer binds there.
  • Retained memory. For the life of a process the new caches hold at most about 10 MB of glyph metrics and 8 MiB of font subsets. Each idle solver worker keeps up to 8 MiB of scratch in a sync.Pool, which Go empties at garbage collection. As far as I can tell from its source, TinyGo's sync.Pool never drops entries, so d2.js would keep that scratch for the life of the instance.
  • Behaviour changes. Besides -failfast above: a cancelled isometric render is noticed within 4,096 units of solver work (a few nanoseconds each) instead of at the next charge. LayoutNested logs a value that reads the graph when a handler formats it, so a handler has to format attributes inside Handle, as slog's handlers and log.PrettyHandler do. A caller that edits textmeasure.Runes in place, instead of assigning a new slice, is served the bundled fonts' metrics as measured before the edit. The comment on Runes says so.
  • Not run locally: the TinyGo WASM test (ci/test-wasm.sh). CI ran it at the head of the branch and it passed.
  • Commit messages. Where a commit message and this description differ, the description is the one to go by. aba88aa gives smaller allocations as the reason for four slots, and the measurements above do not bear that out. 7abdf41 says that with -failfast the later groups' cases already exist when the first failure is reported. Some may not have been created yet, and those are still skipped. 47f6c5a quotes an earlier run of the 3,000-face benchmark (110 ms and 44 ms, where the figures here are 98 ms and 43 ms). 03db2bb says that LayoutNested logs every nested graph, and it logs the root graph too. 203ebf2 and 47f6c5a write 8 MB for the two limits, which are 8 MiB.
  • Not included: an earlier version also stopped TALA's EdgeLength from starting a goroutine per processor for small graphs. It saved CPU but made a single layout slower on an idle machine (up to 2x for that call on graphs with a few connections per node), so I took it out. A threshold based on work rather than node count might be worth a separate look.
  • What this does not do. A single CLI render of an ordinary diagram is not meaningfully faster. Compiling and rendering every suite diagram in one process takes 1,657 ms on master and 1,135 ms here with dagre and ELK together, and 12,274 ms and 11,934 ms with TALA. On this branch the TALA runs are 91% of the total, and 10,920 of their 11,934 ms are spent inside the layout engine (10,933 of 12,274 ms on master), which is untouched. The dagre and ELK cores live in dagro and elk-go. With those two engines, 666 of the remaining 1,135 ms are spent outside the layout engines, in D2's own compiling and rendering. One CLI run gained under 1 ms on each of five test diagrams that take 15.0 to 47.3 ms. For a tiny diagram nearly all of the run is start-up: d2 --version takes 12.8 ms against 14.3 ms for the render in the same session, and about 7.0 ms of a run is package initialisation, 5.0 ms of it chroma's lexer and style registries.

🤖 Generated with Claude Code

alixander and others added 13 commits November 19, 2026 19:55
diff.Testdata writes a .got file and runs git diff for every golden,
which is 2,801 processes in one run of the suite. Nearly every golden
matches, so compare the bytes first and call diff.Testdata only when
they differ. A mismatch is reported, and accepted with TESTDATA_ACCEPT,
exactly as before.

The cases of a group already ran in parallel, but the twelve groups ran
one after another, each waiting for its slowest case. Start the groups
together so the run is bounded by its total work. With -failfast, the
groups after a failing one are no longer skipped, because their cases
already exist when the first failure is reported.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
LayoutNested logs every nested graph before and after its layout. The
attribute was g.PrintString(), which builds the absolute ID of every
object, and Go evaluated it whether or not debug logging was on.

Pass a value that prints the graph when a handler formats it. It has
both String, for log.PrettyHandler, and LogValue, for slog's handlers,
so the logged text is unchanged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
A Ruler measured all 352 runes of every font and size it met, and each
compile, legend, tooltip and Markdown block creates its own Ruler. One
run of the e2e suite built 2,429 such atlases for 78 distinct ones.

Keep the glyph map and line metrics of a bundled font in a process-wide
table keyed by font file, size and rune set. The map is never written
after it is built, and every Ruler keeps its own face. The table stops
growing at 256 atlases, about 10 MB.

Only the font files compiled into D2 are shared. internal/bundledfont
recognises them by backing array, so a font registered at run time is
measured as before and is never kept alive by the table.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Cutting a font down to the characters of a diagram, compressing it to
WOFF and encoding it is most of the cost of embedding fonts in an SVG,
and it was repeated for every render. The result depends only on the
font file and the characters, so remember it for the bundled fonts.

The cache is guarded by FontFamiliesMu and emptied when its keys and
values pass 8 MB. Fonts registered at run time are not cached.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
embedFonts ran a regular expression over the whole SVG to collect the
text of natively rendered Markdown. A match needs the literal md-text
class, which most diagrams never contain, so look for that first.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The solver subtracts every nearer face from every fragment of a face.
It allocated three slices per clipped edge, clipped each overlapping
pair twice, kept its fragment index in maps, sorted each face's
occluders with a comparator, and asked the context whether it was
canceled on every unit of work: 1.9 billion times in one run of the
e2e suite.

Keep the algorithm, its output and its work accounting, and change how
it is carried out:

- Clip a fragment against a cut once. The second pass repeated the
  first to collect the outside pieces; collect them in the first and
  charge the budget for the pass that is no longer run.
- Take polygon storage from a per-solve pool with free lists, and copy
  what survives into slabs. The scratch is reused between renders
  unless it has grown past 8 MB.
- Rank occluders once per scene; a face sorts the ranks of its
  candidates.
- Index fragments with slices and stamps instead of maps.
- Charge the budget with one inlined comparison, and consult the
  context every 4,096 units of work.

On a generated scene of 3,000 faces this takes 44 ms instead of 110 ms
and allocates 1 MB instead of 41 MB.

svg_visibility_reference_test.go freezes the previous solver as an
oracle. The new tests require bit-identical fragments, and identical
errors wherever a limit stops the solve, on generated scenes.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Paint ordering clips pairs of polygons the way the visibility solver
does. Use the solver's in-place helpers and two reused buffers instead
of three slices and a closure per edge.

svgFillPath numbers each vertex, so an edge is one word in its tables
instead of two points, and keeps adjacency in flat arrays. Loops are
walked in the same order, so the path text is unchanged. Canonical
loops are rotated in place in a buffer shared across polygons.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Rasterized label and icon surfaces are converted to premultiplied
textures. draw.Draw multiplies and divides every channel of every
pixel, but 97.6% of the pixels in the e2e suite are fully transparent or
fully opaque. Skip the former, copy the latter, and do the arithmetic
for antialiased edges only. A test compares the result with draw.Draw
for every channel value at every alpha.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The isometric renders of the suite are bounded separately from go
test's parallelism because of their memory use. A render now allocates
far less, so allow four at once instead of two.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
A removed fragment kept its slot and its cell entries until the next
face, so a face whose fragments are replaced again and again needed
memory for every fragment it ever had: tens of megabytes where the
previous solver, with maps of live fragments, needed a few. Renumber
the survivors once removed fragments far outnumber them. The budget
charges for live fragments only, so the accounting does not change.

Return a worker that has outgrown the retention limit to the pool
empty instead of dropping it. A pool that keeps its entries in a
slice, as TinyGo's does, could go on referring to a dropped worker.

The equivalence test's scene for the bounding-box tree ran out of work
in both solvers, so only two error strings were compared. Use a scene
that fits, and fail when a scene that is meant to complete does not.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Take one copy of Runes for the key and for the measurement, and say on
Runes that a different set must be a new slice. Note in the two tests
that modify a bundled font's bytes in place that nothing may measure
or subset the font meanwhile, since those results are now shared.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Nothing failed if the e2e golden comparison stopped comparing, because
the suite only hands it output that matches. Test both outcomes and
the acceptance path directly.

The order tree's tie-break test passed with the tie-break removed,
because its input was already sorted, and nothing checked that
nativePremultiply goes on consulting the context after its first row.

svgAppendCanonicalLoop now clears its buffer itself instead of
requiring an empty one.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alixander
alixander merged commit e22f4d5 into master Nov 20, 2026
13 checks passed
@alixander
alixander deleted the perf/10x-e2e branch November 20, 2026 15:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant