Skip to content

Layout engines: dagre 13-17x and ELK 7-11x faster with identical output, TALA 3.7x faster with small layout changes - #2999

Merged
alixander merged 23 commits into
masterfrom
perf/layout-engines
Nov 22, 2026
Merged

alixander merged 23 commits into
masterfrom
perf/layout-engines

Conversation

@alixander

@alixander alixander commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

The layout engines behind d2's three layouts, made faster. dagre and ELK give byte-identical output; TALA gives
the small layout changes described below.

Depends on dagro v0.3.1 and elk-go v0.3.1 (d2lang/dagro#6 and d2lang/dagro#7, d2lang/elk-go#5 and
d2lang/elk-go#6), both released. The release-size check needed #3000: lib/pptx's use of text/template kept
about 3 MB of unused methods in every d2 binary, and #3000 removes it. #3000 is merged, and commit 23 merges master
into this branch (see "Release binary size"). The first commit bumps the engines to v0.3.0; with that bump alone,
d2's dagre and ELK layouts already run on the faster engines. From the dagre adapter commit on, the series calls
dagro.LayoutTyped and elk.Request.

What changes

Speed (one commit each):

  1. The engines: dagro v0.3.0 and elk-go v0.3.0 (go.mod, go.sum).
  2. Shared geometry (d2graph, lib/shape, internal/geomath): shapes trace to their borders through generic
    outlines instead of building SVG paths; Edge.AbsID, TraceToShape and the intersections allocate little.
  3. dagre adapter: the graph goes to dagro.LayoutTyped as Go values; the rank-spacing and cross-rank passes work on
    an index of the objects. Where the original's result depends on Go's map order, the rewrite ranges over maps of
    the same types filled the same way (map_order.go; see "TinyGo" below).
  4. ELK adapter: the graph goes to elk-go as an elk.Request; option sets and per-call storage are reused (bounded);
    the bend cleanup uses a grid index.
  5. TALA, exact: transactions, scoring sessions, routing (OVG) construction, packing and work guards. On the
    end-to-end suite every TALA layout and routing result is byte-identical to before (behaviour changes outside the
    suite: see "TALA" below).
  6. TALA placement: a faster optimizer, plus small layout changes (Swap stage over the 6 nearest siblings; annealing
    ends after 20 quiet passes; the sized phase's schedule is compressed above 48,000 terms). Three end-to-end
    goldens change (stable/us_map, stable/images, stable/circular_dependency) and are regenerated here, with TALA's
    own package goldens.
  7. A changelog entry.
  8. Three comments in TALA's placement code that still described earlier variants of commit 6.

Less code, same results and speed (commits 9-22): a pass over the code this PR adds. It takes about 350 KB off
each release binary and about 1,500 lines off d2's production code.

  • TALA (commits 9-16): structs are sorted through pointers and indices; label position preferences are uint64 bit
    sets instead of 90 maps built at package initialization; one generic step replaces the runtime-object traversal's
    eight inlined closures; the edge-length session builds its topology with out-of-line helpers; routing builds its
    OVGs with the counted loops only and placement runs one moveNodeToBest loop, while the stepped variants, which d2
    never reached, move to the tests as their references; descendantsOutside runs the descendant walk itself; two
    test-only checks move into the tests.
  • ELK adapter (17-18): every request goes through elk.Request. The cases that fell back to elk-go's JSON interface
    (invalid UTF-8, NaN and infinities, nesting deeper than 1000 levels, requests elk-go rejects) now run on the typed
    path with the original's results: strings pass through jsonText, which changes them as the JSON round trip did,
    and requests JSON cannot encode fail with json.Marshal's error as before. elk-go's JSON codec is no longer linked;
    the JSON round trip stays in the tests as the reference. Option pairs go through a small builder.
  • dagre adapter (19-21): the TinyGo-only shadow maps are compiled only under TinyGo, and the ci job runs their gc test
    with -tags dagre_shadowmaps; the arenas' methods stay out of line; every graph, including the malformed ones only
    a Go caller can build, is described as a dagro.LayoutInput, which removes the adapter's second path through
    dagro.Graph.
  • The engines (22): dagro v0.3.1, with less code in the typed engine, and elk-go v0.3.1, whose typed requests no
    longer link its JSON import.

Every pool and cache keeps bounded storage (TinyGo's sync.Pool never frees), and no expression indexes a slice
that a call in the same expression may grow (TinyGo evaluates the slice first).

How exactness was checked

  • dagre and ELK: every end-to-end golden is unchanged. The adapters' replayed layout calls (386 dagre, 369 ELK) give
    byte-identical results after every commit. Equivalence tests compare the typed requests with the graphs and JSON
    the adapters built before, the spacing passes and the bend cleanup with the previous code (kept as references in
    the tests, replaying the map orders the previous code took), and the shared geometry with the previous code (float
    bits). Before proposing, the dagre path was compared with the original end to end on about 59,000 distinct
    generated diagrams (all but 11 that the original cannot lay out within 4 GB of memory) and the ELK path on more
    than 54,000: no difference other than the original's own nondeterminism (where the original varies, the same
    outputs at matching rates). Beyond the inputs compared, the claim rests on construction: the same operations in
    the same order.
  • Commits 9-22: the dagre and ELK replays stay byte-identical to the original's (386 and 369 calls); TALA's 369
    layouts and 16 routing calls equal those of commits 1-8, at seed 1 and with d2's default seeds; every end-to-end
    golden is unchanged; the engines' corpus tests (348 dagro and 356 elk-go requests) are identical. Each commit was
    reviewed for exactness by construction against the code it replaces. The ELK commit was also compared with the
    original d2 on 48 former fallback cases (identical digests, errors and panics), and the dagre LayoutInput commit
    with the original on 320,000 random malformed graphs.
  • Malformed graphs that only a Go caller can build: commit 21 removes a difference that commits 1-8 had, where two
    edges from different objects outside g.Objects to the same node shared an id (1,771 of 45,000 random malformed
    graphs). One difference from the original remains on such graphs: a parent cycle that dagro never sees (through
    objects outside g.Objects, or g.Root in g.Objects) made the original overflow the stack in edge.AbsID, a
    fatal error that ends the process. This PR names only the edges that need a name, so it reaches dagro, which panics
    with "assignment to entry in nil map"; a caller can recover that.
  • TALA: after commit 5 all 369 TALA layouts and 16 routing calls of the end-to-end suite equal the original's;
    equivalence tests compare each fast path with the stepped or reference code. Commit 6's layout changes were
    measured against the original on 2,809 generated diagrams with TALA's penalty, bounding-box area and routed edge
    length (see "TALA" below). Side-by-side renders of the changed layouts were inspected.

TALA: what changes besides speed

  • Layouts. At seed 1, which the end-to-end suite runs, three corpus layouts change: stable/us_map, stable/images,
    stable/circular_dependency (their goldens are regenerated here). With d2's default, the best of seeds 1-3 (what
    the CLI uses), the corpus layouts that change are stable/us_map, stable/images and txtar/sql-icon. On 2,809
    generated diagrams: at seed 1, 272 of the 2,808 that both versions lay out change, TALA's penalty +0.1% on
    average, TALA's comparator 126 worse / 118 better, area and route length +0.2%; with the default, 245 change,
    penalty +0.1%, comparator 120 worse / 113 better, area and route length +0.2%. For scale, the original with seed 2
    instead of 1 changes 1,204 of these layouts (penalty +2.4%, 572 worse / 570 better).
  • One generated diagram fails at seed 1 with "found duplicate OVGNode" (a routing invariant the original also trips
    on other inputs); with the default it lays out, and with the default no diagram fails that the original lays out.
  • Topology-limit errors no longer name the kind of reference being visited: "TALA engine topology references
    exceed limit N" (and the same for CombineSubgraphs) instead of "... while visiting " / "... while reserving
    capacity", whose kind came from map order.
  • Budget accounting is deterministic. Where a work budget binds (very large graphs), units are charged in a fixed
    order (the original charged them in map order, so whether such a layout fit its budget varied from run to run)
    and BinPack's prefilter charges fewer units, so near a binding budget results can differ from the original's.
  • An isolated tree whose roots lead both ways gets its placement trees in a fixed order (Outwards, Inwards,
    Bidirectional) instead of map order: its layout, which varied from run to run in the original, is now always one
    of the original's layouts.

TALA's fuzz workflow

tala-fuzz.yml's FuzzAutolayout finds a class of layouts in which a hierarchy container overlaps another node. The
class is not new: every failing input found fails on the original as well, with an identical layout. But the faster
engine runs about 2.3 times as many executions in the pull-request job's 15 s, so the job fails more often: in about
6.3% of runs against 2.5% for the original (5 and 2 of 79 runs on an Apple M4), and the weekly 2-minute job in 9 of
15 runs against 3 of 15. Per execution the failure rate is not measurably different. GitHub's slower runners execute
fewer inputs in 15 s, so both rates are probably lower there (about 4.7% against 2.1% at half this machine's rate).
This PR leaves the workflow and the overlap class as they are.

TinyGo (the wasm build)

Under gc, dagre's map-order-dependent steps give the original's distribution of results. Under TinyGo, dagre and
ELK gave the original's layout on every input checked whose original result does not depend on Go's map order (the
end-to-end suite's diagrams in four modes and further diagrams), as they do by construction.
Where the original's dagre result does depend on map order (no diagram of the end-to-end suite does), each render
gives one of the layouts the original gives, but not necessarily with the same frequencies: TinyGo's map order also
depends on the random draws of other maps and on the objects' addresses; the rewrite repeats the draws around its
own maps (sortAncestors; crossRankShifter.originalMaps, under TinyGo only) but not those between steps; and the
original's own frequencies under TinyGo change with what the wasm instance did before (the diagrams the same page
rendered earlier), so there is no fixed distribution to match. The TinyGo statistical checks are run by hand: the
command in cross_rank.go (2 to 3 minutes), and the same command with -run 'SpacingPassDistribution|LargeGrowPassDistribution|SpacingPassFlaggedSeeds' (about 2.5 minutes); all six pass.

TALA's TinyGo results equal its gc results, also when it recovers from a panic. In test copies of this code and of
the original, panics (a string, a runtime index error, a nil dereference) were injected at 61 points of TALA's
placement, scoring, routing, packing, labeling and pipeline code, including inside every function where this change
adds a deferred call (the few that run only with several CPUs, which the WebAssembly build never has, were checked
with gc). Under TinyGo every injected panic was recovered with the same result (layout or error), through the same
recover guards and with the same recovered value as with gc, on all 1,486 injected layouts of this code and 1,368 of
the original, with d2's default seeds and with one seed; there was no trap or hang, and layouts made afterwards in
the same instance equal a fresh instance's. One instance recovered 20,000 such panics on d2's path without breaking,
in both versions. On real diagrams (the end-to-end suite, 565 generated diagrams, 12,000 fuzz-target inputs) none of
TALA's recover guards fires.

Speed of the WebAssembly build. Setup: a program that lays out the end-to-end suite's diagrams through
d2lib.Compile, built with TinyGo and d2.js's flags against the original and against this PR, run by node 24 on an
idle Apple M4, the two alternating in fresh processes over 3 rounds. Only the layout and RouteEdges calls are timed;
each diagram's fastest of 15 runs (dagre, ELK) or of 3 (TALA) is summed.

engine before after speedup
dagre (386 calls) 907 ms 70.5 ms 12.9x
ELK (388 calls) 825 ms 68.9 ms 12.0x
TALA, one seed (374 layouts and 16 RouteEdges calls) 78.0 s 20.3 s 3.8x
TALA, d2's default seeds (what d2.js runs) 220 s 58.2 s 3.8x

The first pass over the diagrams in a fresh instance is 10.5x faster with dagre and 7.1x with ELK. RouteEdges, which
the original runs very slowly under TinyGo, goes from 16.0 to 1.1 s (almost all of it one diagram); the original's
time there varies from one instance to the next (up to 18.7 s), which moves TALA's ratio between 3.8x and 4.0x. A
whole compile (parse, compile, layout and export) is 1.7x faster with dagre, 1.6x with ELK and 3.7x with TALA. The
node process's peak memory changes by about 0.1 GB at most.

Release binary size

ci/release/_build.sh fails a release whose binary exceeds MAX_RELEASE_BINARY_BYTES (45,000,000 B), and the ci
job runs the same check on linux/amd64 for every pull request. What decided that budget was something this PR does
not touch: lib/pptx executed text/template files, and text/template's method lookup by name
(reflect.Value.MethodByName) makes Go's linker keep every exported method of every type converted to an interface,
about 3 MB of every d2 binary. #3000 writes those XML parts without text/template (byte-identical output);
it is in master, and commit 23 brings it into this branch.

Built as _build.sh builds them (Go 1.27.4, -trimpath, -ldflags '-s -w ...', with -buildvcs=false):

target master before #3000 master this PR this PR adds left under 45,000,000 B
darwin/amd64 44,404,144 41,198,928 42,424,304 1,225,376 2,575,696
windows/amd64 44,274,688 41,115,648 42,317,824 1,202,176 2,682,176
linux/amd64 43,471,008 40,423,584 41,595,040 1,171,456 3,404,960
darwin/arm64 41,179,362 38,138,946 39,332,770 1,193,824 5,667,230
linux/arm64 40,042,656 37,159,072 38,273,184 1,114,112 6,726,816
windows/arm64 40,410,624 37,489,664 38,628,352 1,138,688 6,371,648

So this PR's binaries are smaller than master's were before #3000. Before commit 23, this branch's darwin/amd64
binary was 45,727,216 B (727,216 B over the budget) and windows/amd64 45,576,704 B (576,704 B over), and the Release
archives build, which checks every target, failed on this PR. The archives stay under MAX_RELEASE_ARCHIVE_BYTES
(20,000,000 B): gzip -9 of the darwin/amd64 binary alone is 17.9 MB.

Where this PR's bytes go: most of the new code is fast paths that sit beside the original code, which stays for the
inputs the fast paths do not take so that results stay identical (dagro's Attrs engine, elk-go's original
Brandes-Koepf placer, TALA's general paths), plus the runtime's function tables for that code, about 0.85 bytes per
byte of machine code, which -s -w cannot remove because stack unwinding, the garbage collector and panics use them.
Commits 9-22 took 350 KB off (TALA 176 KB, ELK 134 KB, dagre 41 KB, darwin/amd64).

Please look first at

  1. The TALA placement commit (internal/placement/tuning.go, sized_optimizer.go, swap.go) and the three
    regenerated goldens: the only intended output change.
  2. d2layouts/d2dagrelayout/map_order.go with rank_spacing.go and cross_rank.go: reproducing the original's
    map-order behaviour (and TinyGo's) is the subtlest part.
  3. d2layouts/d2elklayout/elkgo.go: how each case that went through JSON before gets the original's result on the
    typed path (jsonText, the non-finite and depth flags), checked by fallback_test.go.
  4. The pools and kept scratch (TALA typedpool, d2dagrelayout/scratch.go, d2elklayout/store.go): bounds and
    panic paths.

Measured (original -> this PR, on an idle Apple M4, load average 1-3, the two alternating):

replayed layout calls inside the end-to-end suite
dagre (386 calls) 254 -> 14.5 ms (17.5x) 298 -> 22.9 ms (13.0x)
ELK (369 calls) 149 -> 13.9 ms (10.7x) 190 -> 28.1 ms (6.7x)
TALA, one seed as in the suite (369 layouts + 16 RouteEdges calls) layouts 10.48 -> 2.85 s (3.7x); RouteEdges 622 -> 117 ms (5.3x) 11.47 -> 3.08 s (3.7x), layouts and routing
TALA with d2's default, the best of seeds 1-3 run at once 12.7 -> 3.4 s wall, 42.5 -> 11.5 s CPU (3.7x)
whole TestE2E run 14.5 -> 5.5 s (2.6x)

How: "replayed" runs the layout calls of the end-to-end suite, recorded with their inputs, in one process; per call
the fastest of 10 warm runs (TALA layouts: of 2 runs, RouteEdges: of 5), summed over the calls; the median of three
alternations (ranges: dagre 248.8-256.3 -> 14.3-14.7 ms, ELK 146.8-149.8 -> 13.7-14.2 ms). "Inside the end-to-end
suite" times every layout call where TestE2E (-parallel 1) makes it; per call the median of 5 runs, summed. The whole
TestE2E run is the time go test reports, median of 5 runs each (14.33-14.83 s -> 5.52-5.84 s). These were measured
before this series was rebased onto the current master, and before two late changes that leave its behaviour as it
was: comment edits, and dagro and elk-go handing their scratch buffers back on the normal return paths instead of
from deferred calls. The latter measured the same in alternating replays (dagre 14.7-14.9 ms with it, 14.6-14.8 ms
without; ELK 14.2-14.3 ms both; instructions retired equal within noise).

On a loaded Apple M4 (best of 3, replay) the same comparison gave: dagre 285.3 -> 16.3 ms, ELK 167.5 -> 15.9 ms,
TALA 11.9 -> 3.1 s and RouteEdges 794 -> 140 ms (one pass).

Commits 9-22 leave the speed as it was. Alternating replays of commit 8 and commit 22 (14 iterations, load average
2-6), sums of per-call minimums: dagre 14.53 -> 14.44 ms, ELK 13.91 -> 13.98 ms, TALA 2.876 -> 2.875 s, RouteEdges
116.3 -> 116.1 ms; instructions retired within 0.12% for each engine. ELK's +0.5% is code placement: a build that
keeps commit 8's ELK code byte for byte and changes only TALA and dagre is as much slower. The whole TestE2E run took
10.46 s and 10.42 s (medians of 4 alternating runs).

CI

  • Checked locally on this branch (Apple M4, arm64): go mod verify, build, vet, gofmt and the js/wasm build pass,
    and so does CI=1 go test --timeout=30m ./... (91 packages). ci.yml's TALA race step passes (78 s with 10 CPUs).
    Commits 9-22 were checked again together with pptx: write the XML parts without text/template (binaries about 3 MB smaller) #3000: the full test run (91 packages), the TALA race step (68 s),
    the new shadow-maps step and ci/test-wasm.sh pass, and each of these commits builds and vets on its own.
    Commit 23's tree is the one measured in "Release binary size"; it builds and vets, and the tests of lib/pptx,
    internal/testutil, e2etests-cli and the dagre and ELK adapters pass on it.
  • GitHub's runners are amd64, where Go converts NaN and out-of-range floats to integers differently from arm64
    (math.MinInt64 instead of 0 or a saturated value). dagro's new tests ran into that (Typed layout engine and LayoutTyped: same layouts, 13-25x faster on d2's diagrams dagro#6, fourth
    commit). So this PR's tests were also run with every int() and int64() conversion in the changed packages
    rewritten to amd64's rule: the dagre and ELK adapters, d2graph, lib/shape, internal/geomath and all TALA packages
    pass. Five conversion sites saw a NaN, all in code this PR leaves unchanged and reached by its NaN-input tests:
    the ELK adapter's inner-box padding estimate (layout.go, four int(math.Ceil(...))) and TALA's edges-per-side
    count (placement/stages.go, where max drops the converted value on both platforms). The new code converts
    at the same points as before, so on amd64 it behaves as the original does there. Commits 9-22 were checked the
    same way, with dagro v0.3.1's tests: everything passes, and no conversion in the code they change sees a NaN.
  • ci.yml's TALA race step (go test -race ./d2layouts/d2talalayout/...): six slow equivalence tests (five in
    placement, one in placementcost) skip under -race unless D2_SLOW=1; all of them run in the plain test step.
    With 4 CPUs, as on GitHub's 4-vCPU runners (GOMAXPROCS=4, -p 4), the step took 71-72 s against the original's
    73-80 s (three alternating runs each, before the rebase). The weekly race job (./ci/test.sh -race ./...) passed
    locally on an earlier state of this series with 10 CPUs under heavy load (12.9 against 14.4 minutes); it was not
    measured with 4 CPUs.
  • ci/test-wasm.sh (TinyGo) passed before the rebase. With 4 build jobs and an empty TinyGo cache it took 165 s
    against 154 s in one pair of runs and about as long in two more (172 and 181 s against 183 and 167 s); the tinygo
    process used 11-18% more CPU in these three pairs. It also needs more memory: 5.8 to over 6.0 GB at its peak
    against 4.0-5.5 GB for the original (the peak varies by about a gigabyte from run to run). The extra memory comes
    from the engines' larger code, which the d2wasm test program links (its LLVM bitcode grows by 14%), not from the
    new tests. If GitHub's runners show memory pressure, GOGC=50 for tinygo (4.6 GB in one run, no slower) or -p 2
    (3.6 GB, about 30 s slower) in ci/test-wasm.sh lowers it. This PR does not change ci/test-wasm.sh.
  • The d2js TinyGo build (make.sh's js step) took about as long as before on cold-cache runs (152 s against 166 s
    with 4 jobs, 153 s against 137 s with 10; it varies by about 15% from run to run), with about the same peak memory
    (5.5-6.0 GB with 4 jobs in both); d2.wasm grows by 6.6% (gzip 6.7%), measured before commits 9-22.
  • The ci job's time, estimated before the rebase: about 24.5 minutes against about 23.6-23.8 minutes for the
    original, under the job's 30-minute limit. This is a model calibrated on two GitHub runs of a nearby commit
    (24m43s and 24m47s); the extra minute is mostly TinyGo's CPU in make.sh's concurrent phase.

🤖 Generated with Claude Code

alixander and others added 21 commits November 22, 2026 04:40
Both releases lay out every graph as before, faster. dagro runs a typed
engine for the graphs it accepts and adds LayoutTyped; elk-go reuses its
storage across layouts and adds a typed Request API. The commits that
follow switch d2's adapters to the new APIs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…llocations

Shared code that every layout engine calls inside its layout:

- lib/shape: each shape describes its perimeter once as a generic outline
  (outline.go). The outline draws the same SVG path data as the previous
  path functions and answers TraceToShapeBorder's perimeter search
  directly, instead of building an SVG path context for every trace; a
  shape is made in one allocation.
- d2graph: Edge.AbsID without fmt.Sprintf, strings.Join and path slices;
  TraceToShape makes the endpoint shapes only when it traces;
  findOuterIntersection sorts its few points without sort.Slice's
  reflection swapper, leaving them in sort.Slice's order, ties included.
- internal/geomath: allocation-free segment and Bezier intersections for
  tracing, whose NaN results carry the sign and payload the previous code
  produced. lib/geo's own functions are unchanged.

Why results stay identical: the same floating-point operations run in the
same order. Tests compare with the previous code kept in the tests
(legacy_outline_test.go) or with the library calls replaced:
TestOutlinesMatchLegacy (path data and typed commands, float bits),
TestTraceToShapeBorderMatchesLegacy, TestTraceToShapeMatchesLegacy (random
edges into every shape, outside and inside labels and icons: indices,
points and in-place changes), TestEdgeAbsIDMatchesLegacy,
TestSegmentIntersectionMatchesIntersectionPoint (degenerate, non-finite and
signed-zero inputs), TestSortPointsMatchesSortSlice. Every end-to-end
golden is unchanged.

The layout calls of the end-to-end suite, replayed (best of 3 passes,
loaded Apple M4, with the dagro and elk-go releases this change requires):
dagre 23.9 -> 22.3 ms and 2.35 M -> 2.30 M allocations per pass; ELK
105.7 -> 102.4 ms and 3.13 M -> 3.08 M.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sses

- The adapter describes a regular graph to dagro as a LayoutInput (objects
  and edges by index) and reads the results from a LayoutOutput instead of
  building Attrs maps and a dagro.Graph; graphs the typed input does not
  express keep the Graph path. Requires the dagro release with LayoutTyped.
- adjustRankSpacing and adjustCrossRankSpacing work on an index of the
  objects (positions, ranks and ancestors in flat arrays), visit each
  ancestor once and find checkBelow's objects by binary search on a sorted
  axis; the curved route is built without vector slices; dagro edges are
  named only where names can collide; per-call working storage is kept
  across calls (bounded: at most 2 MB, and nothing that points into the
  caller's graph). The layout guard drops per-call maps small graphs do not
  need.
- Where the original's result depends on the order in which it ranges over
  a map (ties between ancestors, the grow pass over shifted containers, NaN
  rank coordinates), the rewrite ranges over maps of the same types, made
  without a size hint and filled with the same keys and writes in the same
  order (map_order.go). Under gc this gives the original's distribution of
  results. Under TinyGo it gives the same set of results, not always with
  the same frequencies: TinyGo's map order also depends on the draws of
  other maps and on the objects' addresses, and the rewrite repeats the
  draws around its own maps (sortAncestors; crossRankShifter.originalMaps
  makes the original shift's other maps, under TinyGo only) but not those
  between steps. The original's own frequencies under TinyGo change with
  what the wasm instance laid out before, so there is no fixed
  distribution to match. No diagram of the end-to-end suite depends on map
  order.

Why results stay identical: LayoutTyped(in) is defined as
Layout(in.Graph()), and in.Graph() is the graph the previous adapter built
(TestDagroInputMatchesGraphCalls). The spacing passes are compared with
the previous code (legacy_spacing_test.go: the original functions,
renamed), replaying in the rewrite the map orders the previous code took
(TestSpacingPassesMatchLegacy, ...WithNaN, TestShadowWritesMatchLegacy);
TestPointAlongNaNs pins the NaN operand order of the curve points. Under
TinyGo, statistical tests run by hand (the command is in cross_rank.go; 2
to 3 minutes) compare single spacing passes and the tie order with the
original's.

The dagre layout calls of the end-to-end suite, replayed (best of 3 passes,
loaded Apple M4): 22.3 -> 16.3 ms and 2.30 M -> 2.16 M allocations per
pass; with the original d2 and dagro: 285.3 ms and 6.74 M.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- The adapter builds an elk.Request (nodes, ports, labels, edges and
  prepared option sets) instead of marshalling JSON for elk.LayoutJSON and
  decoding the response; the few values the typed request cannot carry
  exactly still go through JSON. Requires the elk-go release with Request.
- Option sets are prepared once and reused by content; the root's set is
  found by a small key; per-call storage (object states, incidence lists,
  edge routes, bend grids) is kept across calls, bounded in bytes and free
  of the caller's data, and dropped by a layout that panics.
- The bend cleanup (deleteBends) finds collisions through a grid index
  (flat lists on small graphs) instead of scanning every object and edge;
  the descendant shifter and the ladder-corner count avoid per-call maps.

Why results stay identical: the typed request converts to exactly the
values LayoutJSON decodes from the JSON the adapter sent before, member
orders included (TestELKGoRequestMatchesJSON, TestELKGoOptionsMatchJSON,
TestRequestMatchesOriginal against the previous request builder), and
results are copied back as decoding the response did, non-finite values and
negative zero included (TestELKGoApplyMatchesJSON). The bend cleanup is
compared with the original's (legacy_bends_test.go) on random graphs
(TestDeleteBendsMatchesOriginal) and between its two index forms
(TestDeleteBendsSameWithBothIndexForms).

The ELK layout calls of the end-to-end suite, replayed (best of 3 passes,
loaded Apple M4): 102.3 -> 15.9 ms and 3.08 M -> 2.13 M allocations per
pass; with the original d2 and elk-go: 167.5 ms and 4.39 M.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…anged

- layoutgraph: transactions keep their snapshots in slot-indexed slices and
  reuse their storage, prefilter placements certain to be rejected
  (PlacementRejected), memoize container checks and index existing
  overlap pairs; validateEngineGraph takes its node and edge inventory
  through hints.
- placementcost: an EdgeLengthSession re-evaluates only the terms a trial
  move can change; symmetry works in reusable frames; the obstacle loop is
  inlined; cancellable contexts are sampled instead of polled at every
  point, and work goes to other goroutines only when it pays for them.
- routing: OVG construction charges its work in counted batches instead of
  one guard call per operation; flavor routers share grid lines; route
  search looks points and edges up in slices and keeps its search state
  between calls; the priority queue sifts a hole.
- packing: bounding boxes as values; BinPack drops candidates certain to be
  rejected and validates the rest in score order.
- limits: inlinable WorkGuard fast paths; guards set up in place or pooled.
  labeling, nodeshape, graphbounds, hierarchy, trees: cached preference
  sets, bounds computed by value.
- Every pool keeps bounded storage (TinyGo's sync.Pool never frees), and no
  expression indexes a slice that a call in the same expression may grow
  (TinyGo evaluates the slice first; TestNoEvaluationOrderHazards scans the
  sources for the pattern).

Why layouts stay identical: each fast path performs the operations of the
code it replaces in the same order; equivalence tests (...MatchesStepped,
...MatchesReference, ...MatchesLegacy, ...MatchesPlainLoop) compare them on
random graphs. The end-to-end suite's 369 TALA layouts and 16 RouteEdges
calls give byte-identical results (replayed against the recorded results),
and every golden is unchanged. The scoring session's equivalence test
(TestEdgeLengthSessionMatchesEdgeLength) runs on one CPU at a time and
takes about 92 s with the race detector, so under -race it skips unless
D2_SLOW=1; it runs in every plain test run (3 to 5 s).

Outside the corpus three things differ, each where the original's own
result varied from run to run or concerns only an error text:
- Work accounting where a budget binds (very large graphs): BinPack's
  prefilter charges fewer units, and units are charged in a fixed order
  where the original charged them in Go map order, so whether a layout
  fits a binding budget no longer varies between runs.
- Topology-limit errors no longer name the kind of reference being
  visited: the original's "TALA engine topology references exceed limit N
  while visiting <kind>" (or "while reserving <kind> capacity"; the same
  for CombineSubgraphs) named whichever kind map order put first; the
  texts now end at the limit.
- An isolated tree whose roots lead both ways gets its placement trees in
  a fixed order (Outwards, Inwards, Bidirectional) instead of map order,
  so the layout of such a tree, which varied from run to run in the
  original, is now always one of the original's layouts.

The suite's TALA layouts, replayed with one seed as the suite runs them
(loaded Apple M4): 11.9 -> 5.7 s and 31.2 M -> 14.7 M allocations per pass;
the 16 RouteEdges calls: 794 -> 142 ms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ldens

Faster, with the same layouts:
- moveNodeToBest scores candidates with a sweep scorer that keeps each
  edge's obstacles between candidates and stops adding costs once a
  candidate is discarded (ScoreUnlessAbove); scores are memoized across
  passes in a bounded table cache; the closest unoccupied point comes from
  a dense lattice memo; candidate placements are counted row by row.
- Compaction candidates that move nothing reuse their scores; gap
  normalization replays its no-op transactions; optimizer passes over
  levels with nothing to move and compactions known to change nothing are
  skipped (these change only work accounting).

Small layout changes, within the envelope agreed for this change:
- the Swap stage tries each node's 6 nearest siblings instead of all;
- the sized annealing ends after 20 quiet passes in a row;
- the sized phase's work per level is bounded by compressing its cooling
  schedule to 48,000 terms (only levels larger than that: very dense
  diagrams).
In the end-to-end suite (seed 1) three TALA layouts change
(stable/us_map, stable/images, stable/circular_dependency); their goldens
and the TALA package's own goldens are regenerated here. With d2's default,
the best of seeds 1-3, the corpus layouts that change are stable/us_map,
stable/images and txtar/sql-icon.

Measured against the original on 2,808 generated diagrams: at seed 1 (as
the end-to-end suite runs) 272 layouts change; TALA's penalty +0.1% on
average; TALA's own comparator rates 126 of them worse and 118 better;
bounding-box area and routed edge length +0.2% on average. With d2's
default (best of seeds 1-3) 245 change: penalty +0.1%, comparator 120
worse / 113 better, area and route length +0.2%. For scale, changing the
seed from 1 to 2 changes 1,204 of these layouts (penalty +2.4%, 572 worse
and 570 better). One generated diagram fails at seed 1 with "found
duplicate OVGNode", a routing invariant the original also trips on another
input; d2's default lays it out, and with the default no diagram fails
that the original lays out.

The suite's TALA layouts, replayed with one seed (loaded Apple M4): 5.7 ->
3.1 s and 14.7 M -> 8.4 M allocations per pass (11.9 s and 31.2 M with the
original); every result equals the regenerated reference.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The sized phase above maxSizedPhaseWork runs over a compressed schedule
(222 passes for us_map's level), not only its first passes, and a hub
re-search suspends the score memo and records a move instead of starting
a new epoch. The comments still described the earlier variants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Routing's same-line connector sorted []ovgLineRect and packing's candidate
ordering sorted []packTrial stably; each instantiated the generic sort for
its struct shape. The connector now sorts pointers into its rectangles and
the ordering sorts int32 indices into its trials, reusing the sorts already
instantiated for pointers and int32.

Exact: pdqsort's comparisons and swaps depend only on comparison results,
so sorting pointers gives the permutation sorting the structs gave; a stable
sort's result depends only on the keys, so the index order is the order of
the sorted trials.

Release binaries: darwin/amd64 -37,040 B, linux/amd64 -32,768 B,
windows/amd64 -33,280 B.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
LabelPositionPreferences returned shared maps that package init code built
(90 map literals). Label positions are small integers, so each tier is now a
LabelSet, a uint64 bit set returned as a constant, and callers test
membership with Has. With constant sets the per-node cache of the tier sets
(labelTierPreferences and its test) has no purpose; compareLabelPositions
reads the sets directly again, as it did before the cache.

Exact: every shape's sets hold the same positions (checked for every shape
type, tier -2..6 and position -128..127 against the maps), callers only test
membership, and the sets depend only on the shape type, so the cache and
direct reads agree.

Release binaries: darwin/amd64 -24,720 B, linux/amd64 -28,672 B,
windows/amd64 -26,112 B.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
collectRuntimeObjectsContext had eight add closures, one per kind of
runtime object, each charging a unit, skipping nil and known objects,
checking the kind's limit and enqueueing; the compiler inlined them at
about 45 call sites (46,752 B of code). They are now one generic collect
over a per-kind visited set and queue (runtimeObjects), with the limit
error built out of line; each kind's add is a one-line closure.

Exact: collect does what each closure did in the same order (one Step per
reference, the first error sticks and stops all charging, nil charged and
skipped, the same limits and messages, the node map pre-sized, the others
made on first use), and the traversal is unchanged. A differential test
(not committed) against the previous function on 3,000 random fixtures at
every work limit, and on graphs past each kind's limit, found the same
errors, units and collections.

Allocations: +5.8k per corpus pass (+0.07%): queues appended through a
pointer no longer get the stack buffer local slices get. Instructions and
time unchanged within noise.

Release binaries: darwin/amd64 -56,720 B, linux/amd64 -57,344 B,
windows/amd64 -58,368 B.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
EdgeLengthSession.buildTopology, the largest new TALA function (26,720 B),
inlined track at about 35 call sites and two add closures at about 20.
track is now variadic and out of line, the closures are one
sessionReads.add (variadic, out of line) with its marks, pairs, owner and
untracked flag, and runs of consecutive calls are single calls.

Exact: a variadic call handles its arguments in order exactly as the
separate calls did; the arguments read nothing the helpers write (slots,
marks, pairs), so evaluating them before the call changes nothing, and a
nil dereference panics before anything is recorded, as before. The
variadic arguments stay on the stack.

Release binaries: darwin/amd64 -16,384 B, linux/amd64 -16,384 B,
windows/amd64 -17,408 B.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
OVG construction kept a stepped variant of each candidate loop (one guard
call per operation) beside the counted one, chosen when the context has no
Done channel. TALA's entry points (Layout, RouteEdges, engine.Autolayout)
give the engine a context with a Done channel before routing runs, so d2
never reached them. The dispatch and the counted flags go, and the counted
loops take the plain names (addIntersectionCandidates,
addPortConnectionNodesAtBoundaries, connectNodesOnSameLine; the helpers
that return their step counts keep the Counted suffix). The stepped loops,
the map grouping of lines and the helpers only they used
(hasUnobstructedLineToPorts, passesThroughAllowingPorts, pointNear,
tooClose, hasCoordinateWithin, alignedOwners, isMisdirectedPortPair) move
to ovg_stepped_test.go, the loops as ...Stepped functions, where the
counted-vs-stepped tests keep using them as the reference.

Exact: every call from d2 ran the counted code before and runs the same
code now.

Release binaries: darwin/amd64 -24,576 B, linux/amd64 -24,576 B,
windows/amd64 -23,040 B.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
moveNodeToBest ran moveNodeToBestStepped (one guard call per operation)
when the closest-unoccupied search could not answer node's canMove checks,
and moveNodeToBestCounted otherwise; the two were the same loop. The
counted loop, now moveNodeToBestWith, takes a nil search for that case:
it then steps every loop unit as it is taken, runs indexedCanMove for
every check and treats node as a non-leaf (no score memo, no recorded
scores, the general movement capture), which is exactly what the stepped
function did. The stepped function moves verbatim to move_stepped_test.go,
where the tests keep comparing moveNodeToBest with it.

Exact: with a nil search, flush never has units to charge, the memo is off
and nothing is recorded, so every remaining statement is the stepped
function's, in its order. TestMoveNodeToBestWithoutSearchMatchesStepped
runs the nil-search mode directly against the stepped function: leaves
with fixed origins, obstacles, -0 and tight budgets, and nodes of level
graphs with containers, cluster and sequence vessels (some unplaced, some
with a nil child), with and without a Done channel. It compares outcome,
error or panic, units, moveExact, positions and the scores recorded for
the swap search, and fails if nil-search leaves are treated as leaves or
the loop's step is skipped.

Release binaries: darwin/amd64 -8,192 B, linux/amd64 -8,192 B,
windows/amd64 -9,728 B.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
descendantsOutside repeated descendantsInto's walk without the guard to
learn whether the walk succeeds and which nodes it reaches. It now runs
descendantsInto itself on a guard of its own without a limit, which fails
only where the walk fails (a nil child, a node limit), and tests the
entries against the walk's seen set.

Exact: the walks reach the same nodes and fail under the same conditions
(only their push order differs, and neither membership nor failure depends
on it), and the result is used only as a boolean. A differential test (not
committed) against the previous function on 4,000 nested graphs, some
with nil children and over-limit child lists, agreed on 53,188 calls.

Release binaries: darwin/amd64 -4,096 B, linux/amd64 -4,096 B,
windows/amd64 -4,608 B.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The edge-length session's verification (a bool tests set, and
verifySessionEdgeLength, verifySessionCrossings and the resumed-key check
it enabled) and the score memo's hit check (verifyHit, reached through a
context value only tests set) were compiled into every binary. The
session's checks are now an interface variable, sessionVerifier, that the
test sets to an implementation in edge_length_session_test.go; verifyHit
hands each hit to a function that optimizer_score_memo_test.go installs.
Production leaves both nil, so their bodies are no longer linked.

Exact: production never set the bool nor put the statistics in a context,
so the removed code never ran there; the tests run the same checks.

Release binaries: darwin/amd64 -4,096 B, linux/amd64 -8,192 B,
windows/amd64 -4,096 B.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The adapter fell back to elk-go's JSON interface (json.Marshal, LayoutJSON,
json.Unmarshal, containers looked up by ID) for requests whose strings were
not valid UTF-8, held a NaN or an infinity, nested deeper than 1000 levels,
had sections set before layout, or that elk-go rejected. That kept elk-go's
whole JSON codec in d2's binaries. Every one of these cases now runs on the
typed path with the original's result:

- Strings are passed as JSON gives them back (jsonText: each byte that is
  not part of valid UTF-8 becomes U+FFFD, through the same json.Marshal and
  json.Unmarshal round trip): IDs, label texts, edge ends, option values.
  A container whose ID JSON changed is no object's, as the original's lookup
  by ID found none (readBack records ref 0; layoutWith dereferences nil as
  the original did).
- A non-finite number, or nesting deeper than jsonSafeDepth, flags the
  request; then json.Marshal of the ELKGraph runs first, as the original's
  first step did, and its error is returned (it fails for the numbers, and
  for nesting beyond its own depth limit, which only objects outside
  g.Objects can reach past Layout's graph guard).
- A request elk-go rejects fails in typed.Layout with the error LayoutJSON
  gave (the typed Request reports Layout(graph)'s error for d2's requests),
  after the same context check.
- Sections and containers set before layout cannot occur: Layout builds
  every edge zeroed, so the JSON never carried sections either, and
  containers are never read.

The JSON round trip moves to oracle_test.go (runELKViaJSON) as the tests'
reference: TestFallbackCoverage lays out every former fallback case both
ways (invalid UTF-8 in labels, IDs, containers, layer constraints, SQL
columns, colliding IDs; NaN, infinities, -0; duplicate IDs, NaN with
duplicates, edge ends outside the walk; depths 1000, 1001 and 1023 with
D2_SLOW=1; 6000 levels through ChildrenArray, where json.Marshal fails,
except under TinyGo, whose 1 MB stack is too small) and expects the same
graph, error or panic. The byID map, laidOut, typedELKHook and
useJSONForELK go.

Checked against the original d2 (e22f4d5) with a separate program over
48 such cases (deep ones included): identical digests, errors and panics.
ELK corpus replay 369/369 identical to the original's outputs. With
elk-go's JSON codec unreachable, the release binaries shrink by about
117 KB (darwin/amd64, together with elk-go's JSONCodec split and TryGet
change).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ne switch

appendOptionPairs called four closures (str, integer, boolean, float) once
per member of the option struct; the compiler inlined each of the 35
calls, which made it 13.6 KB of code. The closures become methods of a
small builder (optionPairs) marked go:noinline, so each member costs one
call. knownString and boxedString, two identical 17-case switches, are now
thin wrappers over one switch, knownOption, which returns the boxed
constant or nil; TestBoxedValuesMatch checks both against it.

Same members in the same order, the same values, mask bits and ok; the
same known strings and the same boxes. appendOptionPairs itself takes
337 ns instead of 218 ns for a root, a container, a leaf and a port, but
option pairs are only built for an option set not seen recently, a few
times per layout: the ELK corpus replay is level with the previous code
and 369/369 identical to the original's outputs. Release binaries:
darwin/amd64 -16,560 B, linux/amd64 -12,288 B, windows/amd64 -14,336 B.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
shadowMaps was a variable set from runtime.Compiler, so gc binaries
carried the code that repeats the original's maps of a cross-rank shift
(originalMaps) and records processQueue's writes for it, although gc
never runs it. It is now a constant from two build-tagged files: true
under TinyGo (as before) or with -tags dagre_shadowmaps, false otherwise,
so gc drops all of that code.

Behavior is unchanged under both compilers (the constant has the value
the variable had). TestShadowWritesMatchLegacy, which turns the shadow
maps on under gc, needs -tags dagre_shadowmaps and skips without it, so
the ci job now also runs the adapter's tests with that tag (about 2 s).
darwin/amd64 release binary: -4,096 bytes (-4.3 KB of code and tables).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
stringArena.ptr, pointArena.take and pointRefArena.take were inlined at
18 call sites. They are now //go:noinline: the same statements run, in
the same order, once per object label, route or path (no floating-point
arithmetic in them), and the arenas stay on the stack.
darwin/amd64 release binary: -5.2 KB of code and tables.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Graphs a Go caller can make but the compiler cannot (an object repeated
in g.Objects, a parent or edge endpoint outside g.Objects, a parent
cycle, two edges with the same id) went through a second path that built
a dagro.Graph and read the result back from its labels. dagroInput now
describes those graphs too: a repeated object is one node per position
with the id of its last one (as objectMapper numbered them), and objects
outside g.Objects are one more node with id "", as they were to the
original. LayoutTyped declines such inputs and lays out in.Graph(), which
makes the original's calls (dagro guarantees LayoutTyped(in) equals
Layout(in.Graph())). dagroInput also returns the errors the original
returned besides the layout's: the SetParent error of a parent cycle,
before anything else, and, after the positions are set, the error for
the node "" or for edges that share an id.

This also restores the original's results where the Graph path differed
from them: an edge with an endpoint outside g.Objects now keeps its
AbsID as name, as every edge had in the original. With an empty name,
two such edges to the same node shared an id (every object outside
g.Objects is the node ""), the second replaced the first, and the
positions left on the objects before the "invalid node label" error
differed from the original's (1,566 of 40,000 random malformed graphs).
On 45,000 random malformed graphs the adapter now leaves exactly what the
original left (error, panic, positions, routes), except on two graphs
whose result varies from run to run in the original as well.

layoutAttrs, buildDagroGraph, boxFloat and nodeIDOf are gone. The tests
compare dagroInput with the original adapter's Graph calls on random and
randomly broken diagrams. darwin/amd64 release binary: -8,208 bytes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alixander and others added 2 commits November 22, 2026 11:40
Both releases lay out every graph as v0.3.0 did, with less code: dagro's
typed engine sums buffer sizes directly, keeps cold helpers out of line
and shares its self-loop and incidence-list builders; elk-go's typed
requests no longer link its JSON import, which moves to its own codec
type. d2's darwin/amd64 release binary: -79,872 B (dagro -20,320,
elk-go -59,536).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in #3000 (PPTX export without text/template), which keeps the
release binaries of this branch under the 45 MB limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alixander
alixander merged commit adad396 into master Nov 22, 2026
16 checks passed
@alixander
alixander deleted the perf/layout-engines branch November 22, 2026 23:14
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