Skip to content

Typed layout engine and LayoutTyped: same layouts, 13-25x faster on d2's diagrams - #6

Merged
alixander merged 4 commits into
mainfrom
perf/typed-engine
Nov 22, 2026
Merged

alixander merged 4 commits into
mainfrom
perf/typed-engine

Conversation

@alixander

@alixander alixander commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

What changes

  • Graph keeps each node's small collections in insertion-ordered slices and looks edge ids up without
    allocating (commit 1). Every enumeration keeps its order, so the existing engine's results are unchanged.
  • Layout runs a second implementation of the same algorithm (typed_*.go) whenever it accepts the graph:
    integer ids, typed labels, flat arrays reused across calls (commit 2). The existing engine (layoutAttrs)
    still lays out every graph the typed engine does not accept, and every graph on which it stops (errDecline,
    or an unexpected panic caught by runGuarded). At the original's known runtime-error sites (nil-map writes in
    assignOrder and insertSelfEdges, makeslice on an empty graph or an infinite rank) the typed engine performs
    the same failing operation, so a caller that recovers sees the same panic value. Its working buffers go back to
    the reused state on the normal return paths, not from deferred calls (TinyGo recovers panics by unwinding, and
    extra deferred closures on a panicking stack can break that recovery); runGuarded's recover is the only
    deferred call the typed engine adds.
  • New API LayoutTyped(in *LayoutInput, out *LayoutOutput): the graph and the results as Go values; defined as
    Layout(in.Graph()) followed by reading the results (commit 3). d2 switches its adapter to it. The existing API
    is unchanged.
  • Tests only (commit 4): Go leaves converting NaN to an integer to the platform (arm64 gives 0, amd64
    math.MinInt64), and the Attrs engine converts ranks and weights to ints. On graphs whose ranks or weights are
    NaN its outcome therefore depends on the platform: on amd64 addBorderSegments counts up from math.MinInt64
    and adds border nodes until memory runs out, and greedyFAS panics in makeslice. Five of the new equivalence
    tests build such graphs and exhausted the memory of amd64 CI runners; they now skip those graphs where
    int(NaN) is not 0 (nan_platform_test.go).

How exactness was checked

  • In the repository: typed_diff_test.go runs both engines on random graphs and fixtures and requires identical
    labels (float bits), process-wide counter use and panic values; regression tests on awkward inputs (fractional,
    zero and non-finite minlen and weights, greedy two-cycles, duplicate attribute spellings, unplaced nodes in every
    rank direction, the known failure sites) compare Layout/LayoutTyped with the existing engine; phase-level
    tests compare ranks and positions; LayoutTyped is compared with Layout(in.Graph()); the dagre.js differential
    tests of this repository's CI exercise the new path too (Layout uses it).
  • Before proposing (outside the repository): the typed and the modified existing engine were compared with an
    unmodified copy of the original package on tens of thousands of generated graphs (results, errors, panic values,
    counter values), on the 348 distinct requests of d2's end-to-end suite, and end to end through d2 on about 59,000
    distinct generated diagrams (no difference other than the original d2 adapter's own map-order nondeterminism;
    where the original varies, the same outputs at matching rates; 11 diagrams the original cannot lay out within
    4 GB of memory were not compared).
  • All of this ran on arm64 (and the WebAssembly build). On graphs whose ranks or weights become NaN, the original's
    own outcome differs between arm64 and amd64 (see commit 4), so on amd64 the two engines were not compared on
    such graphs. d2 never produces them: its adapter leaves every edge's minlen and weight at 1.

Please look first at

  1. typed_layout.go: lstate.build (what the typed engine declines), runGuarded and the decline path in
    layout.go (the existing engine reruns the input and replays the counter values already drawn, util.go
    drawReplay), and the known-site panics.
  2. typed_retain*.go: what survives between calls (one state of at most 4 MB in a slot that survives garbage
    collection; larger states go to a sync.Pool under gc and are dropped under TinyGo, whose sync.Pool never
    frees).
  3. The map-order cases: where the original's result depends on Go's map order (several spellings of one attribute
    key), the typed engine ranges over the same kind of map.

Measured. The engine alone: the 348 distinct requests d2's end-to-end suite makes, one pass, best of 5, on a
loaded Apple M4. d2's calls: on an idle Apple M4, alternating the original and this series (the d2 pull request
that switches to this release describes the method).

before after
Layout 393 ms, 369.7 MB, 4.32 M allocations 15.3 ms, 0.33 MB, 11.1 k allocations
LayoutTyped - 15.4 ms, 0.12 MB, 412 allocations
d2's dagre layout calls, replayed (adapter included; sum over the 386 calls of each call's fastest of 10 warm runs) 254 ms 14.5 ms (17.5x)
d2's dagre layout calls inside the end-to-end suite (sum of per-call medians of 5 runs) 298 ms 22.9 ms (13.0x)

Tests: go test ./... takes about 22 s on a loaded Apple M4 (about 65 s with -race; DAGRO_SLOW=1 opens the
few tests skipped under -race), against 1.5 s before; almost all of it is the equivalence tests.

d2 will switch its dagre adapter to LayoutTyped once this is released, in a d2 pull request that also needs the
matching elk-go release.

🤖 Generated with Claude Code

alixander and others added 4 commits November 22, 2026 04:13
…ocation

The Attrs engine spends much of its time in Graph's per-node maps and in
building edge-id strings. Graph now keeps a node's small collections
(incident edges, predecessor and successor counts, children) in
insertion-ordered slices and switches to maps only above a few entries, and
looks edge labels up with an id built in a stack buffer. Both
representations keep the same members in the same insertion order, so every
enumeration, and therefore every layout, is unchanged; network simplex and
the layer-graph builder read the collections through the same accessors.

Also:
- lodashMin2/lodashMax2 and maxJS2/minJS2: the two-argument cases of the
  variadic helpers without the slice (bit-identical for NaN, infinities and
  signed zeros; TestLodash2MatchesVariadic compares them on all pairs of
  special and ordinary values).
- Every unique-id draw of a layout graph goes through Graph.uniqueID, and a
  layout graph can replay values already drawn from the process-wide
  counter before it draws new ones. Nothing sets a replay yet; the typed
  engine of the next commit uses it when it hands an input back to this
  engine.

The 348 distinct requests d2's end-to-end suite makes, laid out with Layout
(one pass, best of 5, on a loaded Apple M4): 393 -> 279 ms,
369.7 -> 258.7 MB and 4.32 M -> 3.24 M allocations per pass.

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

Layout now runs a second implementation of the same algorithm
(typed_*.go) whenever it accepts the input graph: nodes and edges are
interned to integer ids, labels become typed structs, and the phases work
on flat arrays reused from call to call instead of string-keyed maps of
Attrs. The Attrs engine (layoutAttrs) is unchanged and still lays out
every graph the typed engine does not accept (lstate.build declines, for
example, attributes it does not model or a label holding two spellings of
one key), and every graph on which the typed engine stops (errDecline or
an unexpected panic, caught by runGuarded).

Why the results are identical: the typed engine performs the same
operations as the Attrs engine in the same order: the same iteration
orders (insertion order where the original iterates a map in insertion
order; Go's map order through the same kind of map where the original's
result depends on it), the same floating-point operations in the same
order, the same tie-breaks. Every dummy-node name is drawn from the
process-wide counter as the original draws it, so names and counter
values are the same; when the typed engine hands an input back after
drawing, the Attrs engine replays the values already drawn. Where the
original fails with a Go runtime error at a known site (a nil-map write in
assignOrder or insertSelfEdges, makeslice on an empty graph or an infinite
rank), the typed engine performs the same failing operation after bringing
the counter to the original's value, so a caller that recovers sees the
same panic value.

Faster within the engine: network simplex exchanges recompute only the
subtree that changed; initOrder sorts by rank with a counting sort when
ranks are small integers; repeated identical type-2 conflict scans are
skipped; short sorts are inlined; dummy names are made only when read.

Storage: one engine state of at most 4 MB survives garbage collection, for
callers that lay out one graph at a time; a larger state goes to a
sync.Pool under gc (the collector empties it) and is dropped under TinyGo,
whose sync.Pool never frees. A state is reused only after a call that
returned normally, and keeps no reference to the caller's attribute
values. Working buffers go back to the state on the normal return paths,
not from deferred calls: TinyGo, which d2's WebAssembly build uses,
recovers panics by unwinding, and extra deferred closures on a panicking
stack can break that recovery (in elk-go two did); here they would be on
the stack of every decline runGuarded recovers. runGuarded's deferred
recover is the only defer the typed engine adds.

Tests: typed_diff_test.go runs both engines on random graphs and fixtures
and requires identical labels (float bits included), counter use and panic
values; the regression tests built on diffspec_test.go compare Layout with
the Attrs engine on awkward inputs (fractional, zero and non-finite minlen
and weights, greedy two-cycles, duplicate attribute spellings, unplaced
nodes in every rank direction) and on single phases. Before this change was
proposed, the same comparisons were also run against the unmodified
original package, and end to end through d2 on 59,205 generated diagrams
with no difference other than the original's own map-order
nondeterminism.

The 348 distinct requests of d2's end-to-end suite through Layout (one
pass, best of 5, loaded Apple M4): 279 -> 15.3 ms, 258.7 -> 0.33 MB and
3.24 M -> 11.1 k allocations per pass (393 ms, 369.7 MB and 4.32 M
allocations before the previous commit).

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

LayoutInput describes a compound multigraph by index (nodes with sizes and
parents; edges with minlen, weight, label size and position) and
LayoutOutput receives the positions, sizes, edge points and label
positions. LayoutTyped(in, out) is defined as Layout(in.Graph()) followed
by reading the results: the typed engine builds its state from the input
directly, and any input it does not take goes through in.Graph() and the
Graph path, so results, errors and panic values are those of Layout on the
equivalent Graph. A graph of one node and no edges takes a closed form
whose arithmetic is exact (TestSingleNodeMatchesEngine compares it bit
for bit with the engine and with the Graph path; a -0 size, which the
engine turns into +0, declines it).

The existing Graph API and its results are unchanged.

Tests: LayoutTyped against Layout(in.Graph()) on random inputs and
fixtures; the process-wide counter (draws visible at once, distinct under
concurrency, replayed on a decline); the known failure sites raising the
original's runtime errors (two minimized inputs in testdata/knownsites);
bounded storage kept across calls and garbage collections.

The 348 distinct requests of d2's end-to-end suite through LayoutTyped
(one pass, best of 5, loaded Apple M4): 15.4 ms, 0.12 MB and 412
allocations per pass (Layout on the same requests: 15.3 ms, 0.33 MB and
11.1 k allocations; the original Layout: 393 ms, 369.7 MB and 4.32 M).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Go leaves converting NaN to an integer to the platform: arm64 gives 0,
amd64 gives math.MinInt64. The Attrs engine converts ranks and weights to
ints (integer() in addBorderSegments, greedyFAS's bucket count), so on
graphs whose ranks or weights are NaN its outcome depends on the platform:
on amd64, addBorderSegments counts up from math.MinInt64 and adds border
nodes until memory runs out, and greedyFAS panics in makeslice.

Five of the new equivalence tests build such graphs, and on amd64 CI
runners they exhausted memory. The three that generate graphs with
fractional, zero or unusual minlen and weights now skip where int(NaN) is
not 0; the other two leave out only their NaN cases there. The engines
are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alixander
alixander merged commit b8f901a into main Nov 22, 2026
1 check passed
@alixander
alixander deleted the perf/typed-engine branch November 23, 2026 00:36
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