Repository navigation
Typed layout engine and LayoutTyped: same layouts, 13-25x faster on d2's diagrams - #6
Merged
Merged
Conversation
…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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changes
Graphkeeps each node's small collections in insertion-ordered slices and looks edge ids up withoutallocating (commit 1). Every enumeration keeps its order, so the existing engine's results are unchanged.
Layoutruns 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 inassignOrderandinsertSelfEdges,makesliceon an empty graph or an infinite rank) the typed engine performsthe 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 onlydeferred call the typed engine adds.
LayoutTyped(in *LayoutInput, out *LayoutOutput): the graph and the results as Go values; defined asLayout(in.Graph())followed by reading the results (commit 3). d2 switches its adapter to it. The existing APIis unchanged.
math.MinInt64), and the Attrs engine converts ranks and weights to ints. On graphs whose ranks or weights areNaN its outcome therefore depends on the platform: on amd64
addBorderSegmentscounts up frommath.MinInt64and adds border nodes until memory runs out, and
greedyFASpanics inmakeslice. Five of the new equivalencetests 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
typed_diff_test.goruns both engines on random graphs and fixtures and requires identicallabels (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/LayoutTypedwith the existing engine; phase-leveltests compare ranks and positions;
LayoutTypedis compared withLayout(in.Graph()); the dagre.js differentialtests of this repository's CI exercise the new path too (Layout uses it).
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).
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
typed_layout.go:lstate.build(what the typed engine declines),runGuardedand the decline path inlayout.go(the existing engine reruns the input and replays the counter values already drawn,util.godrawReplay), and the known-site panics.typed_retain*.go: what survives between calls (one state of at most 4 MB in a slot that survives garbagecollection; larger states go to a
sync.Poolunder gc and are dropped under TinyGo, whosesync.Poolneverfrees).
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).
LayoutLayoutTypedTests:
go test ./...takes about 22 s on a loaded Apple M4 (about 65 s with-race;DAGRO_SLOW=1opens thefew tests skipped under
-race), against 1.5 s before; almost all of it is the equivalence tests.d2 will switch its dagre adapter to
LayoutTypedonce this is released, in a d2 pull request that also needs thematching elk-go release.
🤖 Generated with Claude Code