Skip to content

Faster layered layout and a typed Request API; identical results - #5

Merged
alixander merged 6 commits into
mainfrom
perf/typed-request
Nov 22, 2026
Merged

alixander merged 6 commits into
mainfrom
perf/typed-request

Conversation

@alixander

Copy link
Copy Markdown
Contributor

What changes (six commits, each with its own measurements)

  1. Foundations: graph.PropertyMap with interned keys and one insertion-ordered entry slice;
    javacompat.GoStableSort, a reflection-free replica of sort.SliceStable (same comparisons, same permutation);
    reuse.Pool, a pool with one slot that survives garbage collection for bounded values.
  2. Request path: elk.Request, a graph given as Go values and imported by Import's own steps (d2 switches to
    it); option registries built once; suffix lookup through an index; the codec and model arenas reused across
    calls; pure option parses and resolved member orders remembered; graphjson lets Go callers set the member
    order of option maps.
  3. Layered: the LGraph arena and its property storage reused across layouts; processors read options once and walk
    lists in place; the orthogonal router pools its generators; no pooled storage is returned by a call that is
    unwinding a panic, and scratch buffers go back on the normal return paths, not from deferred calls (see
    "TinyGo" below); recursion no deeper per level than before (TinyGo's 1 MiB stack).
  4. Layering: network simplex without node maps; iterative walks that recurse past a bound as the original did
    (cyclic inputs still end in the original's stack overflow). Its reused buffers panic as make does for a
    negative length: with node or port sizes near MaxFloat64 under NETWORK_SIMPLEX node placement, the layer span
    network simplex normalizes overflows an int, and the original's make([]int, n) panicked with
    "makeslice: len out of range"; a caller of LayoutJSON or Layout that recovers sees that value here too
    (TestHugePortPanicsLikeOriginal, TestZeroedNegativeLengthPanicsLikeMake).
  5. Crossing minimisation: a pooled dense workspace for the layer sweep.
  6. Node placement: Brandes-Koepf over dense arrays; the original implementation still places graphs whose layer
    lists and nodes' Layer fields disagree.

How exactness was checked

  • In the repository: equivalence tests for every replaced structure (property maps against an ordered list, the
    stable sort against sort.SliceStable, iterative walks against the recursive originals kept in the tests, dense
    Brandes-Koepf against the original implementation, a Request's model against Import's on random requests,
    a reused codec against a new one), pool tests (bounded, nothing of the caller's retained, nothing returned while
    a panic unwinds) and child-process stack tests. The official elk.js oracle job of the CI runs unchanged.
  • Before proposing (outside the repository): every step reproduced the recorded responses of the 356 distinct
    requests d2's end-to-end suite sends; the final state was compared with the original on 124,000 generated graphs
    through every public entry point: LayoutJSON (123,849 compared) and SetLayoutOptionKeys gave no difference;
    Layout on Go-built graphs differed only where the original itself is nondeterministic (graphs without a member
    order, the random and spore algorithms: the same outcomes at matching rates) and on the panic value above, which
    commit 4 fixes; the new Request documents where it differs (it reports a duplicate node id before an option it
    cannot construct, where Layout reports the option first). Also 5,000 engine-level JSON requests, and end to end
    through d2 on more than 54,000 diagrams with no difference.

TinyGo (WebAssembly builds)

TinyGo 0.44, which d2's WebAssembly build uses, recovers panics by unwinding the stack (Asyncify). During this work,
two deferred closures that handed scratch buffers back, in the network simplex layerer and in the layer-sweep type
decider, broke that recovery on requests that panic in the original too: the WebAssembly instance trapped
("unreachable") or the caller recovered a different panic value (10 of 4,952 generated engine-level requests). In
this series every such store happens on the normal return paths; the only deferred call it adds is the unlock of the
property-key registry's mutex, which must run if its critical section ever panicked and is never on the stack of a
layout panic. Built with TinyGo, the 10 requests now give the original's outcome, and so do 4,950 of the 4,952, the
356 requests d2's suite sends and 1,796 more captured from d2; the other two broke only late in a long-lived
instance, which is the limit below.

What remains is TinyGo's own: each recovered panic leaks stack space, so a long-lived instance that recovers many
panics eventually breaks (a trap, wrong results or a hang). The original has the same limit; this series reaches it
sooner with some callers. Measured on requests that panic, one instance each:

  • a caller that recovers each LayoutJSON panic in a closure inside its loop: the original breaks after 42 and 81
    recovered panics on two requests, this series after 33 and 53;
  • a caller that recovers in a named function around LayoutJSON: neither breaks (6,000 recovered panics);
  • the same caller also calling the typed Request on each request: this series breaks after 34 and 58 requests
    (the original has no typed Request);
  • d2's own path (whose adapter uses the typed Request) recovered 1,800 panics in one instance, identically in
    both.
    An embedder that recovers layout panics under TinyGo should create a new WebAssembly instance after one.

Please look first at

  1. internal/reuse and every caller's release path (internal/core/codec.go release and its byte bounds, the
    p3order/p4nodes/orthogonal workspaces): bounded storage, no caller data kept, nothing pooled while a panic
    unwinds, scratch handed back on normal return paths only, and the gc/TinyGo split (oversized_gc.go,
    oversized_tinygo.go).
  2. request.go and internal/core/typed.go: the claim that a Request imports exactly as Import does.
  3. internal/graph/properties.go: everything builds on it.
  4. internal/layered/p4nodes/bk_node_placer.go: when the dense path declines to the original.

Measured. The engine alone: the 356 distinct requests d2's end-to-end suite sends, one pass, best of 3, 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
LayoutJSON 207 ms, 151.6 MB, 2.22 M allocations 99 ms, 64.0 MB, 0.94 M allocations
Request (Go values, as d2 calls it) - 22.6 ms, 5.7 MB, 112 k allocations
d2's ELK layout calls, replayed (adapter included; sum over the 369 calls of each call's fastest of 10 warm runs) 149 ms 13.9 ms (10.7x)
d2's ELK layout calls inside the end-to-end suite (sum of per-call medians of 5 runs) 190 ms 28.1 ms (6.7x)

Tests: go test ./... takes about 15 s of package time on a loaded Apple M4 (about 2 minutes with -race),
against 4 s before.

d2 will switch its ELK adapter to elk.Request once this is released, in a d2 pull request that also needs the
matching dagro release.

🤖 Generated with Claude Code

alixander and others added 6 commits November 22, 2026 04:13
…ed storage

Foundations the later commits build on; the layered engine is unchanged.

- graph.PropertyMap: keys are interned once per option ID (PropertyKey) and
  a map keeps its entries in one insertion-ordered slice with a small
  position hint per key class instead of a hash index per map. Lookups,
  updates, deletes and copies keep the insertion order the map had before,
  so every enumeration is unchanged (TestPropertyMapMatchesOrderedList
  checks them against an insertion-ordered list, from a few entries to more
  than 255). Small ints are boxed from a shared table and []string values
  are shared when a map is copied, never written in place.
- Model.Descendants walks pending nodes on an explicit stack in the same
  pre-order (TestDescendantsPreOrder).
- javacompat.GoStableSort: a replica of sort.SliceStable without
  reflection that performs the same comparisons in the same sequence and
  leaves the same permutation, also for inconsistent comparators
  (TestGoStableSortMatchesSliceStable).
- reuse.Pool: a pool with one slot that survives garbage collection for
  storage of bounded size; larger values go to a sync.Pool under gc and are
  dropped under TinyGo, whose sync.Pool never frees. Storage goes back on
  normal return paths, never from a deferred call (the package comment
  says why: TinyGo recovers panics by unwinding, and deferred closures on
  a panicking stack can break that recovery).

The 356 distinct requests d2's end-to-end suite sends, through LayoutJSON
(one pass, best of 3, loaded Apple M4): 207 -> 189 ms, 151.6 -> 138.3 MB and
2.22 M -> 2.10 M allocations per pass; every response unchanged.

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

- Request: a graph given element by element as Go values (nodes, ports,
  labels, edges, option sets prepared once and shared), imported by
  Import's own steps in Import's order, so its model equals the one Import
  builds from the equivalent JSON, member orders and errors included.
  graphjson lets Go callers set the member order of option maps
  (SetLayoutOptionKeys), which decides the order options are applied in.
- The default option registries are built once; option suffixes resolve
  through an index over their last segment (BySuffix answers what the
  linear scan answered, for every registered ID, legacy ID and suffix);
  each option key costs one map lookup on import.
- The codec and the model arenas are reused across Layout calls: one
  released codec of bounded size survives garbage collection, keeps
  nothing that refers to the caller's data, and is never offered for reuse
  by a call that is unwinding a panic. Parses of pure option texts
  (padding, points, enum sets) and resolved member orders are remembered
  per text; a registration that changes what a key resolves to is seen.
- An empty recorded member order reads as no order, as the original
  importer read it through LayoutOptionKeys.

Why results stay identical: every remembered value is a pure function of
its key and is invalidated by registrations; a reused codec imports as a new
one (TestReleasedCodecImportsAsNew); a Request's model is compared with
Import's on random requests (TestRequestMatchesImport) and on the error
cases (TestRequestErrorsMatchLayout).

The 356 requests of d2's suite through LayoutJSON (best of 3, loaded Apple
M4): 189 -> 128 ms, 138.3 -> 99.8 MB and 2.10 M -> 1.83 M allocations per
pass; every response unchanged. The same requests as Go values through
Request (the way d2 calls elk-go after this series): 22.6 ms, 5.7 MB and
112 k allocations per pass at the end of the series.

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

- The LGraph arena, its element property storage and the import and
  transfer bookkeeping are reused across layouts (bounded in bytes; a
  released arena keeps no property values, label texts or boxes of the
  caller's) and dense indexes replace per-graph maps on import and on
  layout transfer. Processor configuration slots are bit sets; graph runs
  share one block; phase lists are arrays.
- Intermediate processors read graph options and per-element properties
  once by precomputed key and walk node and port lists in place where
  nothing changes them; the four hottest stable sorts use the
  reflection-free replica; preserveorder keeps its transitive order as bit
  rows; the orthogonal router pools its generators and recycles segments
  and dependencies per call.
- Storage goes back to a pool only from calls that returned, never while a
  panic unwinds, so a recovered panic cannot change later layouts. Scratch
  buffers go back to the arena's scratch slot or to the routing generator
  on the normal return paths, not from deferred calls, which under TinyGo
  can break the recovery of a panic that unwinds through them.
- Recursions are no deeper per level than the original's (TinyGo's stack
  is 1 MiB): the compound traversal key loops with an explicit stack up to
  a bound and then recurses as the original did, so a cyclic input still
  ends in the original's stack overflow; radial routeEdges is iterative.

Why results stay identical: the same elements are visited in the same
order and pooled storage is reset completely before reuse; the loops that
replace recursions are compared with the recursive originals on random
inputs (TestTraversalKeyLoopMatchesRecursion,
TestIterativeRouteEdgesMatchesRecursion,
TestIterativePortWalkMatchesRecursion).

The 356 requests of d2's suite through LayoutJSON (loaded Apple M4): 99.8 ->
79.7 MB and 1.83 M -> 1.60 M allocations per pass; every response
unchanged (times too noisy at this load to separate this step).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Network simplex layering works on index-addressed nodes in storage kept
  in the arena and reused across calls; topological layering, cut values
  and normalization reuse their buffers. They go back on the normal return
  paths, not from deferred calls: under TinyGo a deferred store in the
  layerer killed the WebAssembly instance ("unreachable") on requests on
  which the original panics and the caller recovers.
- The component search, tight-tree search and post-order traversal of
  network simplex, and the longest-path and interactive layerers, walk
  with explicit stacks up to a bound and recurse beyond it as the original
  did: long chains fit a 1 MiB stack (TestLongChainFitsOneMiBStack lays out
  chains in child processes with a 1 MiB stack limit), and a cyclic graph
  still ends in the original's stack overflow instead of growing without
  bound (checked in child processes).
- A reused buffer of negative length panics as make does. Normalization
  asks for highest-lowest+1 entries, which overflows to a negative int for
  the layers that huge node or port sizes produce (a port of height
  MaxFloat64 under NETWORK_SIMPLEX node placement); the original's
  make([]int, n) panicked with "makeslice: len out of range", and the
  buffer helpers now call make for n < 0, so a caller that recovers sees
  the original's panic value (TestZeroedNegativeLengthPanicsLikeMake;
  TestHugePortPanicsLikeOriginal through LayoutJSON and Layout).

Why results stay identical: each loop visits nodes and edges in the
recursion's order and writes the same flags, lists and numbers, which the
tests compare with the recursive originals on random graphs from every
start node (tree-edge order included); a reused buffer of length n >= 0 is
zeroed to the values make would give.

The 356 requests of d2's suite through LayoutJSON (loaded Apple M4): 79.7 ->
77.7 MB and 1.60 M -> 1.55 M allocations per pass; every response
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The layer sweep, barycenter heuristic, Forster constraint resolver, port
distributor and crossing counters work on a workspace of dense per-node and
per-port tables (node slot index, port and edge table, side blocks of each
node's ports) that is reused across sweeps and calls instead of per-node
maps and freshly built lists. Try flags, barycenter associates, successor
constraints and port constraints are read once per sweep; a Forster stage
that cannot add a constraint and port distribution for nodes whose port
order is fixed are skipped; a root holding one node is minimised without
the workspace (TestSingleNodeMatchesGeneral compares graph, layer and node
numbers, properties and the Random state with the general path).

Pooling: a workspace above its bound is not kept (it goes to the sync.Pool
under gc and is dropped under TinyGo); a call that panics never gives its
workspace back; a barycenter state caches only its own node's reads.
Buffers go back to the workspace on the normal return paths, not from
deferred calls: under TinyGo a deferred store in the layer-sweep type
decider made requests on which the original panics recover a different
panic value.
TestRecoveredPanicLeavesNoState and TestPanicDoesNotPoisonLaterLayouts lay
out inputs on which crossing minimisation panics (the original panics on
them too) and check that later layouts in the process are unchanged.

Why results stay identical: the tables hold the values the original read
from properties and maps, consumed in the original's order, with the same
floating-point operations and tie-breaks; skipped work is work whose result
is known not to change anything.

The 356 requests of d2's suite through LayoutJSON (best of 3, loaded Apple
M4): 77.7 -> 69.3 MB and 1.55 M -> 1.26 M allocations per pass, 135 ms;
every response unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brandes-Koepf runs over dense per-node arrays (alignment, roots, sinks,
shifts, inner shifts, per-type vertical spacing) kept in a workspace reused
within and across placements, instead of per-node maps and boxed values; a
single node in a single layer is placed without the workspace. The original
implementation stays and still places every graph whose layer lists and
nodes' Layer fields disagree (a node listed twice, a listed layer of another
graph), where the dense path's indexing would not apply.

Why results stay identical: the dense path performs the original's
operations in the original's order, with inlinable equivalents of math.Max
and math.Min (TestFloatMinMaxMatchMath); TestBKDenseMatchesOriginal and
TestInconsistentLayersMatchOriginal place random layered graphs with both
implementations and require bit-identical positions (and the same panics).

The 356 requests of d2's suite through LayoutJSON (best of 3, loaded Apple
M4): 69.3 -> 64.0 MB and 1.26 M -> 0.94 M allocations per pass, 99 ms
(207 ms, 151.6 MB and 2.22 M allocations before this series); every
response unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alixander
alixander merged commit 71acb1d into main Nov 22, 2026
3 checks passed
@alixander
alixander deleted the perf/typed-request 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