diff --git a/CHANGELOG.md b/CHANGELOG.md index b1139b56..8f8391fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,32 @@ platform API version. ### Added +- **An estimate of a layered layout, before it runs** + (`@dialogram/diagram-server/server/layout-cost`). A layout is costed pass + by pass: a pass is what one container lays out, its nodes and the edges + among them, with no positions and no sizes. `layerSpan` layers the nodes by + their longest path, as ELK does, and sums the layers each edge spans (every + layer an edge skips is a dummy node to ELK, which is where its time goes). + The edges of a cycle are turned round as ELK turns them, by its greedy + order, and a port of a container that an edge of the inside ends on is a + node of the pass, as it is to ELK. Nodes another algorithm lays out (a + force, a tree) are in no estimate, and are counted (`unpriced`). + `estimatePassMs` turns a pass into milliseconds with the rates of an engine, + and `estimateElkLayout` does both for the ELK graph about to be laid out, + with the rates of the preset the graph asks for (`LAYOUT_RATES`: elkjs and + the ELK server on the default, middle and fast presets, and on the default + one with the options of Untangled and Free Ports). A product costs + what it has not laid out yet the same way (what opening a collapsed + container would take): it builds the passes from its own model, says which + edges only order the layers (`counted: false`) or run against the flow + (`orders: false`), and gives the rates it measured on its own layout + options. The rates of the platform are measured by + `test/layout-rates.measure.test.ts` and fitted by + `scripts/fit-layout-rates.mjs`, on 84 generated networks of 30 to 10,000 + nodes and 24 of them again as Untangled lays them out, and checked on + seven graphs of a real design. The estimate is good to about a factor of + two. + - **A `ram` flow symbol.** The flow symbols (`FlowSymbols`, the dataflow pictograms a product draws a node as) have a 29th kind, `ram`, in the memory family: a memory itself, with no operand and one result. `memory` @@ -109,6 +135,40 @@ platform API version. ### Changed +- **`auto` chooses the layout engine by what a layout is estimated to take**, + not by 150 nodes or 400 edges. A graph goes to the Java ELK server when + elkjs is estimated to need more than a second for it (`AUTO_ELKJS_BUDGET_MS`), + and stays on elkjs otherwise. Size said little: of two graphs of 150 nodes + on the default preset, elkjs laid one out in 0.7 s and the other in 21 s, + with the host waiting, and both stayed on elkjs (the server takes 0.2 s + and 2.5 s). The engines lay a graph out alike, so the diagram does not + show which one took it. A diagram elkjs lays out within the second stays + on it as before, and a graph another algorithm than the layered one lays + out, which the estimate does not cost, still goes to the server past 150 + nodes. Every layout logs its estimate beside the time it took + (`[dialogram layout] elkjs: 40 nodes, 110 edges in 229 ms (estimated + 228 ms)`). +- **A layout the ELK server did not answer is refused when elkjs would not + finish it in the same time.** The server's timeout + (`.layout.serverTimeoutMs`, 120 s) or failure used to + hand any graph to elkjs, which runs on the extension host's thread: a + graph the server could not finish in two minutes held every diagram, and + the host, for many times that. Such a layout now fails with a + `LayoutRefusedError`, and the diagram says on its status line that it was + not laid out, with the estimate. A graph elkjs is estimated to finish + within the timeout still falls back to it, or within a minute when the + timeout is shorter (`elkjsTakeoverMs`), and so does every graph when there + is no server to ask (no Java, no jar): elkjs is all there is then. A Free + Ports layout is refused at its probe, so the server is asked once. +- **A layout that fails leaves the diagram as it was.** The layout commands + clear every edge route before ELK is asked, and Untangled and Free Ports + move the ports first. A layout that then failed, for any reason, left the + edges as straight lines and the ports in their new order, and the next + save kept them. The routes (`layoutFromClearedRoutes`) and the ports are + now put back, and the options a layout command sets for its own run are + taken off the nodes again in every command (the boundary-flow and + serpentine ones left them on). + - **The palette's loupe opens find**, not GLSP's field. That field filtered the tools and the lines of the view options, and said "No results found." when it matched neither. The text of find filters the diff --git a/packages/diagram-server/src/operations/boundary-flow-layout.ts b/packages/diagram-server/src/operations/boundary-flow-layout.ts index 11feb3e8..dd108cd9 100644 --- a/packages/diagram-server/src/operations/boundary-flow-layout.ts +++ b/packages/diagram-server/src/operations/boundary-flow-layout.ts @@ -1,6 +1,6 @@ import { GPort, LayoutEngine } from '@eclipse-glsp/server'; import { isBoundaryNodeType, WorkflowDiagramMetadata, WorkflowDiagramTypes } from '@dialogram/shared'; -import { clearAllEdgeRoutingPoints } from '../routing/clear-edge-routes'; +import { layoutFromClearedRoutes } from '../routing/clear-edge-routes'; /** * Shared boundary-flow layout routine. @@ -205,7 +205,11 @@ export function restoreNodeLayoutOptions( */ export async function runBoundaryFlowLayout(root: any, layoutEngine: LayoutEngine): Promise { const previousLayoutOptionsByNodeId = applyBoundaryFlowLayerConstraints(root, new Set(), false); - clearAllEdgeRoutingPoints(root); - await layoutEngine.layout(); - restoreNodeLayoutOptions(root, previousLayoutOptionsByNodeId); + try { + await layoutFromClearedRoutes(root, async () => layoutEngine.layout()); + } finally { + // Also when the layout was refused or failed: the constraints are this + // run's, and left on the nodes they would pin the next layout too. + restoreNodeLayoutOptions(root, previousLayoutOptionsByNodeId); + } } diff --git a/packages/diagram-server/src/operations/layout-boundary-flow-handler.ts b/packages/diagram-server/src/operations/layout-boundary-flow-handler.ts index a527d48a..d5de5083 100644 --- a/packages/diagram-server/src/operations/layout-boundary-flow-handler.ts +++ b/packages/diagram-server/src/operations/layout-boundary-flow-handler.ts @@ -11,7 +11,7 @@ import { } from '@eclipse-glsp/server'; import { inject, injectable, optional } from 'inversify'; import { LayoutPersistenceService } from '../services/layout-persistence-service'; -import { clearAllEdgeRoutingPoints } from '../routing/clear-edge-routes'; +import { layoutFromClearedRoutes } from '../routing/clear-edge-routes'; import { applyBoundaryFlowLayerConstraints, restoreNodeLayoutOptions } from './boundary-flow-layout'; import { WORKFLOW_REROUTE_EDGES_AVOID_OVERLAPS_OPERATION_KIND, @@ -80,10 +80,13 @@ export class WorkflowLayoutBoundaryFlowOperationHandler extends OperationHandler const previousLayoutOptionsByNodeId = applyBoundaryFlowLayerConstraints(this.modelState.root, selectedMovableNodeIds, hasSelection); - clearAllEdgeRoutingPoints(this.modelState.root); - await this.layoutEngine?.layout(LayoutOperation.create(operation.elementIds)); - - restoreNodeLayoutOptions(this.modelState.root, previousLayoutOptionsByNodeId); + try { + await layoutFromClearedRoutes(this.modelState.root, async () => this.layoutEngine?.layout(LayoutOperation.create(operation.elementIds))); + } finally { + // Also when the layout was refused or failed: the constraints are + // this run's, and left on the nodes they would pin the next layout. + restoreNodeLayoutOptions(this.modelState.root, previousLayoutOptionsByNodeId); + } if (hasSelection && preNodePositionsById && preEdgeRoutesById) { restoreUnselectedLayout(this.modelState.index, this.modelState.root, selectedMovableNodeIds, preNodePositionsById, preEdgeRoutesById); diff --git a/packages/diagram-server/src/operations/layout-serpentine-mesh-handler.ts b/packages/diagram-server/src/operations/layout-serpentine-mesh-handler.ts index 81dcbffc..dee49aaa 100644 --- a/packages/diagram-server/src/operations/layout-serpentine-mesh-handler.ts +++ b/packages/diagram-server/src/operations/layout-serpentine-mesh-handler.ts @@ -75,9 +75,13 @@ export class WorkflowLayoutSerpentineMeshOperationHandler extends OperationHandl const previousGraphLayoutOptions = this.applySerpentineMeshPlacement(this.modelState.root, selectedMovableNodeIds, hasSelection); - await this.layoutEngine?.layout(LayoutOperation.create(operation.elementIds)); - - (this.modelState.root as any).layoutOptions = previousGraphLayoutOptions ? { ...previousGraphLayoutOptions } : undefined; + try { + await this.layoutEngine?.layout(LayoutOperation.create(operation.elementIds)); + } finally { + // Also when the layout was refused or failed: the placement is this + // run's, not the graph's. + (this.modelState.root as any).layoutOptions = previousGraphLayoutOptions ? { ...previousGraphLayoutOptions } : undefined; + } if (hasSelection && preNodePositionsById && preEdgeRoutesById) { restoreUnselectedLayout(this.modelState.index, this.modelState.root, selectedMovableNodeIds, preNodePositionsById, preEdgeRoutesById); diff --git a/packages/diagram-server/src/routing/clear-edge-routes.ts b/packages/diagram-server/src/routing/clear-edge-routes.ts index f98c0779..28f3a27d 100644 --- a/packages/diagram-server/src/routing/clear-edge-routes.ts +++ b/packages/diagram-server/src/routing/clear-edge-routes.ts @@ -21,3 +21,49 @@ export function clearAllEdgeRoutingPoints(root: any): void { }; visit(root); } + +/** + * Runs a layout that starts from cleared edge routes, and puts the routes back + * when the layout fails: refused, or an error of the engine. + * + * The routes are cleared so that ELK routes every edge anew. A layout that + * does not run puts nothing in their place, and the model would go on with + * every edge a straight line between nodes that never moved. So the diagram + * stays as it was. + */ +export async function layoutFromClearedRoutes(root: any, layout: () => Promise): Promise { + const routes: Array<{ edge: any; routingPoints: unknown; manual: unknown; hadManual: boolean }> = []; + const visit = (element: any): void => { + if (!element) { + return; + } + if (element instanceof GEdge) { + const args = (element as any).args as Record | undefined; + const hadManual = !!args && typeof args === 'object' && 'cal:manualRoute' in args; + routes.push({ edge: element, routingPoints: (element as any).routingPoints, manual: hadManual ? args!['cal:manualRoute'] : undefined, hadManual }); + } + const children = element.children as any[] | undefined; + if (Array.isArray(children)) { + for (const child of children) { + visit(child); + } + } + }; + visit(root); + clearAllEdgeRoutingPoints(root); + try { + return await layout(); + } catch (error) { + for (const { edge, routingPoints, manual, hadManual } of routes) { + if (routingPoints === undefined) { + delete edge.routingPoints; + } else { + edge.routingPoints = routingPoints; + } + if (hadManual && edge.args && typeof edge.args === 'object') { + edge.args['cal:manualRoute'] = manual; + } + } + throw error; + } +} diff --git a/packages/diagram-server/src/server/diagram-action-handlers.ts b/packages/diagram-server/src/server/diagram-action-handlers.ts index 37222e90..26fff949 100644 --- a/packages/diagram-server/src/server/diagram-action-handlers.ts +++ b/packages/diagram-server/src/server/diagram-action-handlers.ts @@ -60,7 +60,7 @@ import { WorkflowRerouteEdgesAvoidOverlapsOperationHandler, WORKFLOW_REROUTE_EDGES_AVOID_OVERLAPS_OPERATION_KIND } from '../operations/reroute-edges-avoid-overlaps-handler'; -import { clearAllEdgeRoutingPoints } from '../routing/clear-edge-routes'; +import { layoutFromClearedRoutes } from '../routing/clear-edge-routes'; import { releaseBoundaryNodeConstraints, restoreNodeLayoutOptions, runBoundaryFlowLayout } from '../operations/boundary-flow-layout'; import { perfNow } from './graph-load-perf'; import { type FreshNode, type NodeLink, type PlacedNode, placeBesideNeighbours, routeCrosses } from './incremental-placement'; @@ -1631,8 +1631,8 @@ export class WorkflowLayoutOperationHandler extends OperationHandler { // When a user triggers a manual auto-layout, we want ELK to fully recompute edge routing. // Existing routing points (from previous ELK runs or manual routing) can otherwise - // constrain routing and lead to stale/unstable layouts. - clearAllEdgeRoutingPoints(this.modelState.root); + // constrain routing and lead to stale/unstable layouts. They are cleared for the + // layout below, and put back when it does not run (layoutFromClearedRoutes). // What makes this the COMPACT layout rather than a second boundary-flow // one: the network's input and output pills are released from their @@ -1645,7 +1645,7 @@ export class WorkflowLayoutOperationHandler extends OperationHandler { // not to one layout run, so the boundary-flow layout still gets them. const previousBoundaryOptions = releaseBoundaryNodeConstraints(this.modelState.root); try { - await this.layoutEngine?.layout(operation); + await layoutFromClearedRoutes(this.modelState.root, async () => this.layoutEngine?.layout(operation)); } finally { restoreNodeLayoutOptions(this.modelState.root, previousBoundaryOptions); } diff --git a/packages/diagram-server/src/server/elk-layout-engine.ts b/packages/diagram-server/src/server/elk-layout-engine.ts index fd7143f1..42d6d677 100644 --- a/packages/diagram-server/src/server/elk-layout-engine.ts +++ b/packages/diagram-server/src/server/elk-layout-engine.ts @@ -28,6 +28,7 @@ import { drawInSourceOrder, givenPortOrders, gportSide, onePortOrderPerDefinitio import { FAST_LAYOUT_OPTIONS, countLayoutElements, layoutTierFor, type LayoutGraphSize, type LayoutTier } from './layout-configurator'; import { isRowsLayout } from '../model/group-edges'; import { joinPinToPinEdges, splitPinToPinEdges } from './pin-to-pin-edges'; +import { LayoutRefusedError } from './elk-server/switching-elk'; import * as os from 'node:os'; import * as path from 'node:path'; import { mkdir, writeFile } from 'node:fs/promises'; @@ -219,6 +220,12 @@ export class WorkflowElkLayoutEngine extends GlspElkLayoutEngine { try { await this.orderPortsAgainstCrossings(root, tier); } catch (e) { + // A probe the engines refused is the layout refused: the + // layout after it would ask the server for the same graph + // and wait its timeout a second time. + if (e instanceof LayoutRefusedError) { + throw e; + } console.warn('[cal-elk] port ordering skipped:', e); } } else if (this.portsInSourceOrder(root)) { @@ -265,7 +272,37 @@ export class WorkflowElkLayoutEngine extends GlspElkLayoutEngine { } return root; }; - return run(); + // A layout that fails leaves the diagram as it was. Before ELK is + // asked, the ports may have been put in another order (Free Ports, or + // back in the source's): they go back where they were. A layout the + // engines refused is told where the reader looks, once for the probe, + // the layout and the band of pinned groups alike. The log is not it. + const ports = this.portPlaces(root); + return run().catch(error => { + for (const [port, position] of ports) { + port.position = position; + } + if (error instanceof LayoutRefusedError && this.actionDispatcher) { + void Promise.resolve(this.actionDispatcher.dispatch(StatusAction.create(error.message, { severity: 'ERROR' }))) + .catch(e => console.warn('[cal-elk] layout status not shown:', e)); + } + throw error; + }); + } + + /** Where every port of the diagram is drawn on its node. */ + private portPlaces(root: GGraph): Array<[GPort, GPort['position']]> { + const places: Array<[GPort, GPort['position']]> = []; + const visit = (element: GModelElement): void => { + if (element instanceof GPort) { + places.push([element, element.position ? { ...element.position } : element.position]); + } + for (const child of element.children ?? []) { + visit(child); + } + }; + visit(root); + return places; } /** diff --git a/packages/diagram-server/src/server/elk-server/elk-server-options.ts b/packages/diagram-server/src/server/elk-server/elk-server-options.ts index 4a818911..d7e73445 100644 --- a/packages/diagram-server/src/server/elk-server/elk-server-options.ts +++ b/packages/diagram-server/src/server/elk-server/elk-server-options.ts @@ -16,11 +16,11 @@ /** Which engine lays a graph out. */ export type LayoutEngineChoice = - /** The server above the size where the platform's cheaper presets start, elkjs below and whenever the server is unavailable. */ + /** The server for a graph elkjs is estimated to be slow on (`layout-cost.ts`), elkjs for the rest and whenever the server is not there. */ | 'auto' /** elkjs only; the server is never started. */ | 'elkjs' - /** The server for every graph, elkjs only when the server is unavailable. */ + /** The server for every graph, elkjs only when the server is not there. */ | 'elk-server'; export interface ElkServerOptions { @@ -31,7 +31,12 @@ export interface ElkServerOptions { javaPath?: string; /** JVM options, split on whitespace (e.g. `-Xmx2g`). */ javaOpts?: string; - /** How long one layout may take on the server before elkjs takes it over. Default 120 s. */ + /** + * How long one layout may take on the server. Past it elkjs takes the + * layout over when it is estimated to finish within the same time, or + * within a minute when the timeout is shorter, and the layout is refused + * otherwise. Default 120 s. + */ timeoutMs?: number; } diff --git a/packages/diagram-server/src/server/elk-server/index.ts b/packages/diagram-server/src/server/elk-server/index.ts index 47b95e81..6f0eeffd 100644 --- a/packages/diagram-server/src/server/elk-server/index.ts +++ b/packages/diagram-server/src/server/elk-server/index.ts @@ -12,7 +12,16 @@ import { SwitchingElk } from './switching-elk'; export * from './elk-server-options'; export { ElkServerProcess } from './elk-server-process'; -export { SwitchingElk, elkGraphSize, goesToServer, serverCanLayOut } from './switching-elk'; +export { + AUTO_ELKJS_BUDGET_MS, + ELKJS_TAKEOVER_BUDGET_MS, + LayoutRefusedError, + SwitchingElk, + elkGraphSize, + elkjsTakeoverMs, + goesToServer, + serverCanLayOut +} from './switching-elk'; export { layoutOnServer } from './elk-server-client'; const processes = new Map(); diff --git a/packages/diagram-server/src/server/elk-server/switching-elk.ts b/packages/diagram-server/src/server/elk-server/switching-elk.ts index f7b9fa7c..5dca9fca 100644 --- a/packages/diagram-server/src/server/elk-server/switching-elk.ts +++ b/packages/diagram-server/src/server/elk-server/switching-elk.ts @@ -1,19 +1,29 @@ /** - * The ELK the layout engine calls: elkjs, or the ELK server for a large graph. + * The ELK the layout engine calls: elkjs, or the ELK server for a graph elkjs + * would be slow on. * * It stands where the elkjs instance stood (`ElkFactory`), so the engine, its * Free Ports probe and every layout command go through it unchanged. A graph - * goes to the server when the choice is `elk-server`, or `auto` and the graph - * is past the size at which the platform starts trading quality for speed - * (`LAYOUT_TIER_MIDDLE_NODES`, `LAYOUT_TIER_MIDDLE_EDGES`): below it elkjs is - * done before a request would be, and a small diagram lays out exactly as it - * always has. A graph that asks for an algorithm the server does not have + * goes to the server when the choice is `elk-server`, or `auto` and elkjs is + * estimated to take longer for it than the host's thread should be held + * (`AUTO_ELKJS_BUDGET_MS`, `layout-cost.ts`): below that elkjs is done before + * a request would be. The two engines lay a graph out alike + * (`test/elk-server-parity.test.ts`), so which one took a graph is not seen + * in its diagram. A graph that asks for an algorithm the server does not have * (`SERVER_ALGORITHMS`: an automaton placed by stress) stays on elkjs, which - * has them all. Anything the server cannot do — not started, timed out, - * failed — falls back to elkjs for that layout. + * has them all. + * + * A server that is not there (no Java, no jar) leaves every graph to elkjs. + * One that was asked and did not answer, in time or at all, leaves the graph + * to elkjs only when elkjs is estimated to finish in the time a layout may + * take ({@link elkjsTakeoverMs}). elkjs runs on the extension host's thread: a + * graph the server could not lay out in two minutes would hold every diagram, + * and the host, for many times that. Such a layout is refused + * ({@link LayoutRefusedError}) and the diagram stays as it was. */ import type { ELK, ElkLayoutArguments, ElkNode } from 'elkjs'; -import { LAYOUT_TIER_MIDDLE_EDGES, LAYOUT_TIER_MIDDLE_NODES } from '../layout-configurator'; +import { LAYOUT_TIER_MIDDLE_NODES } from '../layout-configurator'; +import { estimateElkLayout, formatLayoutMs, type LayoutEstimate } from '../layout-cost'; import { layoutOnServer } from './elk-server-client'; import type { ElkServerProcess } from './elk-server-process'; import { DEFAULT_ELK_SERVER_TIMEOUT_MS, type ElkServerOptions } from './elk-server-options'; @@ -51,12 +61,61 @@ export function serverCanLayOut(graph: ElkNode): boolean { return asks(graph); } -/** Whether a graph of this size goes to the server under this choice. */ -export function goesToServer(engine: ElkServerOptions['engine'], size: { nodes: number; edges: number }): boolean { +/** + * What elkjs may take for a graph before the server takes it under `auto`: a + * second. elkjs lays out on the extension host's thread, and for that long + * nothing else of the host answers. Under the size rule this one replaces, a + * graph of 150 nodes stayed on elkjs whether it took 0.7 s or 21 s. + */ +export const AUTO_ELKJS_BUDGET_MS = 1000; + +/** + * Whether a graph goes to the server under this choice, by what elkjs is + * estimated to take for it. + * + * The estimate costs layered layouts alone. Nodes another algorithm lays out + * (a force, a tree) are in no estimate, so `auto` keeps the rule it had for + * them: past the size at which the platform's presets change + * (`LAYOUT_TIER_MIDDLE_NODES`), such a graph goes to the server. + */ +export function goesToServer(engine: ElkServerOptions['engine'], estimate: Pick): boolean { if (engine === 'elk-server') { return true; } - return engine === 'auto' && (size.nodes > LAYOUT_TIER_MIDDLE_NODES || size.edges > LAYOUT_TIER_MIDDLE_EDGES); + return engine === 'auto' && (estimate.elkjsMs > AUTO_ELKJS_BUDGET_MS || estimate.unpriced > LAYOUT_TIER_MIDDLE_NODES); +} + +/** + * What elkjs may take for a layout the server did not answer, whatever the + * server's timeout: a minute. + */ +export const ELKJS_TAKEOVER_BUDGET_MS = 60_000; + +/** + * What elkjs may be estimated to take for a layout the server was asked for + * and did not answer: the server's timeout, and no less than a minute. The + * timeout says how long a layout may take on the server, where nothing waits + * on it. A short one (a slow server is to hand over soon) is no reason to + * refuse a graph elkjs lays out in ten seconds, and the estimate is good to a + * factor of two. + */ +export function elkjsTakeoverMs(timeoutMs: number): number { + return Math.max(timeoutMs, ELKJS_TAKEOVER_BUDGET_MS); +} + +/** + * A layout that was not run: the server did not answer, and elkjs would hold + * the host for longer than a layout may take. + */ +export class LayoutRefusedError extends Error { + constructor( + message: string, + /** What elkjs is estimated to take for the graph, in milliseconds. */ + readonly estimateMs: number + ) { + super(message); + this.name = 'LayoutRefusedError'; + } } /** What `ELK.layout` answers a graph of type `T` with: the graph, laid out (elkjs's own declaration). */ @@ -72,21 +131,34 @@ export class SwitchingElk implements ELK { async layout(graph: T, args?: ElkLayoutArguments): Promise> { const size = elkGraphSize(graph); - if (goesToServer(this.options.engine, size) && serverCanLayOut(graph)) { + const estimate = estimateElkLayout(graph); + const what = `${size.nodes} nodes, ${size.edges} edges`; + if (goesToServer(this.options.engine, estimate) && serverCanLayOut(graph)) { const port = await this.server.ensureStarted(); if (port !== undefined) { const started = Date.now(); + const timeoutMs = this.options.timeoutMs ?? DEFAULT_ELK_SERVER_TIMEOUT_MS; try { // The server's layout is written into the graph it was given, as elkjs's is. - const result = await this.layoutOnPort(port, graph, this.options.timeoutMs ?? DEFAULT_ELK_SERVER_TIMEOUT_MS); - console.log(`[dialogram layout] ELK server: ${size.nodes} nodes, ${size.edges} edges in ${Date.now() - started} ms`); + const result = await this.layoutOnPort(port, graph, timeoutMs); + console.log(`[dialogram layout] ELK server: ${what} in ${Date.now() - started} ms (estimated ${estimate.serverMs} ms, elkjs ${estimate.elkjsMs} ms)`); return result as LaidOut; } catch (error) { - console.warn(`[dialogram layout] ${error instanceof Error ? error.message : String(error)}; laying out with elkjs`); + const reason = error instanceof Error ? error.message : String(error); + if (estimate.elkjsMs > elkjsTakeoverMs(timeoutMs)) { + throw new LayoutRefusedError( + `Not laid out: ${reason}, and elkjs would take about ${formatLayoutMs(estimate.elkjsMs)} for ${what}, with every diagram waiting.`, + estimate.elkjsMs + ); + } + console.warn(`[dialogram layout] ${reason}; laying out with elkjs`); } } } - return this.elkjs.layout(graph, args); + const started = Date.now(); + const result = await this.elkjs.layout(graph, args); + console.log(`[dialogram layout] elkjs: ${what} in ${Date.now() - started} ms (estimated ${estimate.elkjsMs} ms)`); + return result; } knownLayoutAlgorithms(): ReturnType { diff --git a/packages/diagram-server/src/server/layout-cost.ts b/packages/diagram-server/src/server/layout-cost.ts new file mode 100644 index 00000000..a596cac8 --- /dev/null +++ b/packages/diagram-server/src/server/layout-cost.ts @@ -0,0 +1,547 @@ +/** + * What a layered layout costs, estimated before it runs. + * + * The node and edge counts of a graph say little about the time its layout + * takes. Every layer an edge skips is a dummy node to the layered algorithm + * of ELK, so a graph of long edges is many times the graph it looks like, and + * placement and crossing minimisation grow faster than the nodes they are + * given. On the default preset elkjs lays out one graph of 150 nodes in 0.7 s + * and another in 21 s. + * + * So a layout is costed by what it is given, pass by pass. A pass is what one + * container lays out, its nodes and the edges among them. The nodes are + * layered by their longest path, as ELK layers them, and the cost of the pass + * is the sum of the layers each edge spans ({@link layerSpan}). + * {@link estimatePassMs} turns a costed pass into milliseconds with the rates + * of an engine ({@link LAYOUT_RATES}). + * + * The estimate reads a plain graph, with no positions and no sizes. That is + * the ELK graph about to be laid out ({@link passesOfElkGraph}), or a graph a + * product builds from its own model for content that is not laid out yet + * (what opening a collapsed container would take). It is good to about a + * factor of two. Its uses need no more than that: which engine takes a graph, + * and whether elkjs may take one the server did not answer + * (`elk-server/switching-elk.ts`). + */ +import type { ElkNode } from 'elkjs'; +import type { LayoutTier } from './layout-configurator'; + +/** An edge between two nodes of one pass, each named by its place among the nodes of the pass. */ +export interface PassEdge { + from: number; + to: number; + /** + * False for an edge whose span is no cost: one that is there to order the + * layers (a chain through the nodes), short by construction. + */ + counted?: boolean; + /** + * False for an edge that does not order the layers: one a product knows + * to run against the flow (a value carried round a loop). Left to the + * estimate, an edge that closes a cycle is found and treated so. + */ + orders?: boolean; +} + +/** What one layout pass is given: its nodes, in the order of the model, and the edges among them. */ +export interface LayoutPass { + nodes: number; + edges: readonly PassEdge[]; +} + +/** A pass, costed: its nodes, and the layers its edges span. */ +export interface PassCost { + cost: number; + nodes: number; +} + +/** + * The layers the counted edges of one pass span, with its nodes layered by the + * longest path over the edges that order them. + * + * Where every ordering edge runs forward in the order of the model, that order + * is a topological one and a single sweep layers the nodes. Otherwise the + * nodes are first put in an order most edges follow ({@link placesInFlow}), + * and an edge against it is turned round, which is what ELK does to the edges + * of a cycle. Either way the work is linear in the pass: a module of a hundred + * thousand operations is costed in well under a second. + */ +export function layerSpan(nodes: number, edges: readonly PassEdge[]): number { + const ordering: PassEdge[] = []; + let forward = true; + for (const edge of edges) { + const { from, to } = edge; + if (edge.orders === false || from === to || !(from >= 0 && from < nodes && to >= 0 && to < nodes)) { + continue; + } + if (to < from) { + forward = false; + } + ordering.push(edge); + } + const place = forward ? undefined : placesInFlow(nodes, ordering); + // The nodes an ordering edge puts after each node. + const later: Array = new Array(nodes); + for (const { from, to } of ordering) { + const turned = place !== undefined && place[from] > place[to]; + const first = turned ? to : from; + (later[first] ??= []).push(turned ? from : to); + } + const layerOf = new Array(nodes).fill(0); + const raise = (node: number): void => { + const next = layerOf[node] + 1; + for (const after of later[node] ?? []) { + if (layerOf[after] < next) { + layerOf[after] = next; + } + } + }; + if (place === undefined) { + for (let node = 0; node < nodes; node++) { + raise(node); + } + } else { + const order = new Int32Array(nodes); + for (let node = 0; node < nodes; node++) { + order[place[node]] = node; + } + for (let at = 0; at < nodes; at++) { + raise(order[at]); + } + } + let span = 0; + for (const edge of edges) { + if (edge.counted === false) { + continue; + } + const from = layerOf[edge.from]; + const to = layerOf[edge.to]; + if (from !== undefined && to !== undefined) { + span += Math.abs(to - from); + } + } + return span; +} + +/** + * The place of each node in an order that most edges follow: the greedy + * heuristic of Eades, Lin and Smyth, which is how ELK chooses the edges of a + * cycle to reverse. A node with no edge left to leave by goes to the end, one + * with none left to arrive by goes to the front, and where neither is left the + * node with the most edges out over edges in goes to the front. The edges + * that run against the order are the ones ELK reverses. + * + * Which edges are reversed decides the depth of the layering, and so the + * cost. Breaking the cycles depth first instead layers a netlist of 1,200 + * cells seven times deeper than ELK draws it. + */ +function placesInFlow(nodes: number, edges: readonly PassEdge[]): Int32Array { + // The edges out of and into each node, as one array a direction. + const outStart = new Int32Array(nodes + 1); + const inStart = new Int32Array(nodes + 1); + for (const { from, to } of edges) { + outStart[from + 1]++; + inStart[to + 1]++; + } + for (let node = 0; node < nodes; node++) { + outStart[node + 1] += outStart[node]; + inStart[node + 1] += inStart[node]; + } + const outOf = new Int32Array(edges.length); + const into = new Int32Array(edges.length); + const outFill = outStart.slice(0, nodes); + const inFill = inStart.slice(0, nodes); + for (const { from, to } of edges) { + outOf[outFill[from]++] = to; + into[inFill[to]++] = from; + } + const outLeft = new Int32Array(nodes); + const inLeft = new Int32Array(nodes); + let most = 0; + for (let node = 0; node < nodes; node++) { + outLeft[node] = outStart[node + 1] - outStart[node]; + inLeft[node] = inStart[node + 1] - inStart[node]; + most = Math.max(most, outLeft[node], inLeft[node]); + } + // The nodes with edges both ways, in a list for each surplus of edges out. + const NONE = -1; + const head = new Int32Array(2 * most + 1).fill(NONE); + const next = new Int32Array(nodes).fill(NONE); + const previous = new Int32Array(nodes).fill(NONE); + const listOf = new Int32Array(nodes).fill(NONE); + let top = NONE; + const list = (node: number): void => { + const at = outLeft[node] - inLeft[node] + most; + listOf[node] = at; + previous[node] = NONE; + next[node] = head[at]; + if (head[at] !== NONE) { + previous[head[at]] = node; + } + head[at] = node; + if (at > top) { + top = at; + } + }; + const unlist = (node: number): void => { + if (previous[node] !== NONE) { + next[previous[node]] = next[node]; + } else { + head[listOf[node]] = next[node]; + } + if (next[node] !== NONE) { + previous[next[node]] = previous[node]; + } + listOf[node] = NONE; + }; + const sources: number[] = []; + const sinks: number[] = []; + for (let node = 0; node < nodes; node++) { + if (inLeft[node] === 0) { + sources.push(node); + } else if (outLeft[node] === 0) { + sinks.push(node); + } else { + list(node); + } + } + const place = new Int32Array(nodes); + const placed = new Uint8Array(nodes); + let front = 0; + let back = nodes - 1; + // Takes a node out: each neighbour loses an edge, and one left with no + // edge in, or none out, is free to be placed in its turn. + const take = (node: number, at: number): void => { + place[node] = at; + placed[node] = 1; + for (let edge = outStart[node]; edge < outStart[node + 1]; edge++) { + const to = outOf[edge]; + if (placed[to]) { + continue; + } + inLeft[to]--; + if (listOf[to] !== NONE) { + unlist(to); + if (inLeft[to] === 0) { + sources.push(to); + } else { + list(to); + } + } + } + for (let edge = inStart[node]; edge < inStart[node + 1]; edge++) { + const from = into[edge]; + if (placed[from]) { + continue; + } + outLeft[from]--; + if (listOf[from] !== NONE) { + unlist(from); + if (outLeft[from] === 0) { + sinks.push(from); + } else { + list(from); + } + } + } + }; + while (front <= back) { + if (sinks.length > 0) { + take(sinks.pop()!, back--); + } else if (sources.length > 0) { + take(sources.pop()!, front++); + } else { + while (head[top] === NONE) { + top--; + } + const node = head[top]; + unlist(node); + take(node, front++); + } + } + return place; +} + +/** A pass, costed. */ +export function costOfPass(pass: LayoutPass): PassCost { + return { cost: layerSpan(pass.nodes, pass.edges), nodes: pass.nodes }; +} + +/** + * What an engine takes for a pass, in milliseconds: for each layer an edge + * spans and for each pair of them (placement by network simplex grows with + * the square of the dummy nodes), for each node and for each pair of nodes + * (the engines differ most there: elkjs grows with the square of a wide + * pass, the server close to its size). A rate an engine does not show is 0. + */ +export interface LayoutRates { + msPerSpanUnit: number; + msPerSpanUnitSquared: number; + msPerNode: number; + msPerNodeSquared: number; +} + +/** The engines a layout runs on. */ +export type LayoutEngineName = 'elkjs' | 'elk-server'; + +/** Rough wall-clock of one pass on an engine with these rates. */ +export function estimatePassMs(pass: PassCost, rates: LayoutRates): number { + const { cost, nodes } = pass; + return Math.round( + cost * rates.msPerSpanUnit + (rates.msPerNode * nodes + rates.msPerNodeSquared * nodes * nodes) + rates.msPerSpanUnitSquared * cost * cost + ); +} + +/** An option of a node of an ELK graph, under its short name or its full one. */ +function optionOf(graph: ElkNode, name: string): string | undefined { + const options = graph.layoutOptions; + const value = options?.[`elk.${name}`] ?? options?.[`org.eclipse.elk.${name}`]; + return typeof value === 'string' ? value : undefined; +} + +/** + * How a container lays its nodes out: in layers, which is what is costed, by + * another algorithm (a force, a tree, a box of rows), or not at all, its nodes + * staying where they are. + */ +function layoutOf(container: ElkNode): 'layered' | 'other' | 'none' { + const algorithm = optionOf(container, 'algorithm'); + if (algorithm === undefined || /(^|\.)layered$/.test(algorithm)) { + return 'layered'; + } + return /(^|\.)fixed$/.test(algorithm) ? 'none' : 'other'; +} + +/** + * The nodes of an ELK graph that another algorithm than the layered one lays + * out. The estimate has no rate for them: it says how many there are, and its + * reader decides by that ({@link LayoutEstimate.unpriced}). + */ +export function unpricedNodesOfElkGraph(graph: ElkNode): number { + let unpriced = 0; + const visit = (container: ElkNode): void => { + const children = container.children ?? []; + if (children.length > 0 && layoutOf(container) === 'other') { + unpriced += children.length; + } + children.forEach(visit); + }; + visit(graph); + return unpriced; +} + +/** + * The passes of an ELK graph: one for each node that holds nodes, with the + * edges between two of them. An edge is found wherever the graph declares it, + * and an end on a port is an end on the port's node. + * + * An edge between a node and a port of its own container runs to the edge of + * the pass. ELK stands a node there for the port, and so does the pass, for + * each port an edge of the inside ends on: a unit drawn with its blocks open + * is laid out with twice the nodes it shows. An edge that leaves its container + * with no port to carry it is left out. + * + * A container that asks for another algorithm than the layered one (nodes + * placed where they are, a box of rows) is no layered pass, and is not costed + * ({@link unpricedNodesOfElkGraph}). + */ +export function passesOfElkGraph(graph: ElkNode): LayoutPass[] { + interface Place { + pass: number; + at: number; + } + /** Where a child, or one of its ports, is in the pass of its container. */ + const placeOf = new Map(); + /** A port of a container, seen from inside: a node at the edge of the pass of that container. */ + const insideOf = new Map(); + const passes: Array<{ nodes: number; edges: PassEdge[] }> = []; + const declared: Array> = []; + const visit = (container: ElkNode): void => { + if (container.edges?.length) { + declared.push(container.edges); + } + const children = container.children ?? []; + if (children.length === 0) { + return; + } + if (layoutOf(container) === 'layered') { + const pass = passes.length; + passes.push({ nodes: children.length, edges: [] }); + children.forEach((child, at) => { + const place = { pass, at }; + placeOf.set(child.id, place); + for (const port of child.ports ?? []) { + placeOf.set(port.id, place); + } + }); + for (const port of container.ports ?? []) { + insideOf.set(port.id, { pass, at: -1 }); + } + } + children.forEach(visit); + }; + visit(graph); + /** The node a port of a container is inside it, made the first time an edge of the inside ends there. */ + const inside = (port: Place): number => (port.at >= 0 ? port.at : (port.at = passes[port.pass].nodes++)); + const ends = (edge: any, many: 'sources' | 'targets', one: 'source' | 'target'): string[] => + Array.isArray(edge[many]) ? edge[many] : typeof edge[one] === 'string' ? [edge[one]] : []; + for (const edges of declared) { + for (const edge of edges) { + for (const source of ends(edge, 'sources', 'source')) { + for (const target of ends(edge, 'targets', 'target')) { + const from = placeOf.get(source); + const to = placeOf.get(target); + const fromInside = insideOf.get(source); + const toInside = insideOf.get(target); + if (from && to && from.pass === to.pass) { + if (from.at !== to.at) { + passes[from.pass].edges.push({ from: from.at, to: to.at }); + } + } else if (fromInside && to && fromInside.pass === to.pass) { + passes[to.pass].edges.push({ from: inside(fromInside), to: to.at }); + } else if (from && toInside && from.pass === toInside.pass) { + passes[from.pass].edges.push({ from: from.at, to: inside(toInside) }); + } + } + } + } + } + return passes; +} + +/** + * The option sets a layout is priced by: the three presets of the + * configurator, and `untangled`, which is the default preset with the + * placement the Untangled and Free Ports layouts ask for + * (`UNTANGLED_ELK_OPTIONS`). + */ +export type LayoutPreset = LayoutTier | 'untangled'; + +/** + * The preset an ELK graph is laid out with, read off the options that carry + * the cost (`layout-configurator.ts`). No crossing minimisation is the fast + * preset and network-simplex placement the default one. Of the rest, a graph + * that keeps the order of its model is the `untangled` one, which takes about + * three times the middle preset, and anything else lays out at the pace of the + * middle preset. Read off the graph, not off its size, so that a layout that + * sets its own options is costed by what it asks for. + */ +export function presetOfElkGraph(graph: ElkNode): LayoutPreset { + if (optionOf(graph, 'layered.crossingMinimization.strategy') === 'NONE') { + return 'fast'; + } + if (optionOf(graph, 'layered.nodePlacement.strategy') === 'NETWORK_SIMPLEX') { + return 'default'; + } + const order = optionOf(graph, 'layered.considerModelOrder.strategy'); + return order !== undefined && order !== 'NONE' ? 'untangled' : 'middle'; +} + +/** What a layout of an ELK graph is estimated to take, on each engine. */ +export interface LayoutEstimate { + /** The nodes of every pass, and the layers their edges span. */ + nodes: number; + cost: number; + preset: LayoutPreset; + elkjsMs: number; + serverMs: number; + /** + * The nodes another algorithm than the layered one lays out. They are in + * neither time: a graph of them alone is estimated at nothing. + */ + unpriced: number; +} + +/** + * Estimate the layout of an ELK graph. The passes are summed: a container is + * a layered layout of its own, whether ELK runs them one after the other or + * in one hierarchy-aware pass. + */ +export function estimateElkLayout( + graph: ElkNode, + rates: Readonly> = LAYOUT_RATES[presetOfElkGraph(graph)] +): LayoutEstimate { + const estimate: LayoutEstimate = { nodes: 0, cost: 0, preset: presetOfElkGraph(graph), elkjsMs: 0, serverMs: 0, unpriced: unpricedNodesOfElkGraph(graph) }; + for (const pass of passesOfElkGraph(graph)) { + const costed = costOfPass(pass); + estimate.nodes += costed.nodes; + estimate.cost += costed.cost; + estimate.elkjsMs += estimatePassMs(costed, rates.elkjs); + estimate.serverMs += estimatePassMs(costed, rates['elk-server']); + } + return estimate; +} + +/** A duration for a message: `850 ms`, `12 s`, `7 min`, `3 h`. */ +export function formatLayoutMs(ms: number): string { + if (ms < 1000) { + return `${Math.round(ms)} ms`; + } + if (ms < 90_000) { + return `${Math.round(ms / 1000)} s`; + } + if (ms < 5_400_000) { + return `${Math.round(ms / 60_000)} min`; + } + return `${Math.round(ms / 3_600_000)} h`; +} + +/** + * The rates of each preset on each engine. + * + * Fitted (`scripts/fit-layout-rates.mjs`) to the layout of 84 generated + * dataflow networks of 30 to 10,000 nodes, from long narrow ones to ones + * whose edges skip most of their layers, and of the 24 smallest again with + * the Untangled options. Each was laid out by elkjs 0.10.0 and by the shipped + * server (ELK 0.10.0, Java 25, warm) with the options the platform gives a + * diagram (`test/layout-rates.measure.test.ts`, + * `test/fixtures/layout-rates/measured.jsonl`; Node 22 on a Xeon Gold 6238T + * at 1.9 GHz, under load). Every time is within a factor of two of its + * estimate, on both engines, but one of 114 ms on the server that is + * estimated at 52 ms. Some of what was measured, in seconds on elkjs and on + * the server: + * + * | preset | nodes | short edges | long edges | + * | --------- | -----: | ----------: | ---------: | + * | default | 60 | 0.31, 0.11 | 2.2, 0.33 | + * | default | 150 | 0.71, 0.23 | 21, 2.5 | + * | untangled | 150 | 0.57, 0.14 | 2.6, 0.41 | + * | middle | 450 | 0.77, 0.21 | 2.8, 0.39 | + * | middle | 1,000 | 1.9, 0.53 | 7.3, 0.94 | + * | fast | 3,500 | 6.7, 1.5 | 11, 2.1 | + * | fast | 10,000 | none, none | 46, 7.6 | + * + * The default preset is the one whose time the span decides: network-simplex + * placement grows with the square of the dummy nodes. Untangled keeps the + * order of the model and places by Brandes and Köpf, at about three times the + * middle preset. The fast preset places simply, and its time follows the + * nodes. At 10,000 nodes elkjs gave no layout of the four deepest of the six + * graphs, and the server none of the deepest: the stack of each engine ends + * first, which no rate tells. + * + * The rates were then checked on seven graphs they were not fitted to, the + * modules of a RISC-V core as written and as synthesised, of 40 to 1,225 + * nodes (`test/fixtures/layout-rates/checked.jsonl`). The estimate is 0.52 to + * 1.53 times the time elkjs took, and 0.40 to 1.36 times the server's. + * + * A product whose diagrams are laid out with other options measures its own + * rates and passes them to {@link estimatePassMs}. + */ +export const LAYOUT_RATES: Readonly>>> = { + default: { + elkjs: { msPerSpanUnit: 1.2, msPerSpanUnitSquared: 0.0073, msPerNode: 0, msPerNodeSquared: 0 }, + 'elk-server': { msPerSpanUnit: 0, msPerSpanUnitSquared: 0.00073, msPerNode: 1.4, msPerNodeSquared: 0 } + }, + middle: { + elkjs: { msPerSpanUnit: 0.42, msPerSpanUnitSquared: 0.000025, msPerNode: 0.94, msPerNodeSquared: 0 }, + 'elk-server': { msPerSpanUnit: 0.047, msPerSpanUnitSquared: 0, msPerNode: 0.41, msPerNodeSquared: 0 } + }, + fast: { + elkjs: { msPerSpanUnit: 0.13, msPerSpanUnitSquared: 0, msPerNode: 1.1, msPerNodeSquared: 0.00018 }, + 'elk-server': { msPerSpanUnit: 0.013, msPerSpanUnitSquared: 0, msPerNode: 0.36, msPerNodeSquared: 0.00002 } + }, + untangled: { + elkjs: { msPerSpanUnit: 1.3, msPerSpanUnitSquared: 0, msPerNode: 1.5, msPerNodeSquared: 0 }, + 'elk-server': { msPerSpanUnit: 0.21, msPerSpanUnitSquared: 0, msPerNode: 0.66, msPerNodeSquared: 0 } + } +}; diff --git a/packages/diagram-server/test/elk-server.test.ts b/packages/diagram-server/test/elk-server.test.ts index a4c06c84..ea1c101c 100644 --- a/packages/diagram-server/test/elk-server.test.ts +++ b/packages/diagram-server/test/elk-server.test.ts @@ -16,17 +16,29 @@ import { createServer, type Server } from 'node:net'; import * as path from 'node:path'; import { PassThrough } from 'node:stream'; import { gunzipSync, gzipSync } from 'node:zlib'; -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import ElkConstructor from 'elkjs/lib/elk.bundled.js'; import type { ELK, ElkNode } from 'elkjs'; import { DefaultElementFilter } from '@eclipse-glsp/layout-elk'; import { FRAME_HEADER_BYTES, FRAME_MAGIC, encodeFrame, layoutOnServer } from '../src/server/elk-server/elk-server-client'; import { ElkServerProcess, type SpawnFunction } from '../src/server/elk-server/elk-server-process'; -import { SwitchingElk, elkGraphSize, goesToServer, serverCanLayOut } from '../src/server/elk-server/switching-elk'; +import { + AUTO_ELKJS_BUDGET_MS, + ELKJS_TAKEOVER_BUDGET_MS, + LayoutRefusedError, + SwitchingElk, + elkGraphSize, + elkjsTakeoverMs, + goesToServer, + serverCanLayOut +} from '../src/server/elk-server/switching-elk'; +import { estimateElkLayout } from '../src/server/layout-cost'; import { createElkFactory, disposeElkServers, sharedElkServerProcess } from '../src/server/elk-server/index'; import { GraphGModelSource } from '../src/model/graph-gmodel-source'; import { convertToGModelRoot } from '../src/server/gmodel-convert'; -import { WorkflowElkLayoutEngine } from '../src/server/elk-layout-engine'; +import { PORT_ORDER_DECLARED, PORT_ORDER_FREE, PORT_ORDER_OPTION, WorkflowElkLayoutEngine } from '../src/server/elk-layout-engine'; +import { runBoundaryFlowLayout } from '../src/operations/boundary-flow-layout'; +import { layoutFromClearedRoutes } from '../src/routing/clear-edge-routes'; import { WorkflowLayoutConfigurator } from '../src/server/layout-configurator'; import { javaMajor } from './java-version'; @@ -187,6 +199,17 @@ function chain(count: number): ElkNode { return { id: 'root', children, edges }; } +/** `count` nodes in a chain, each also read by every tenth node after it: edges that skip most of the layers. */ +function longEdges(count: number): ElkNode { + const graph = chain(count); + for (let from = 0; from < count; from++) { + for (let to = from + 10; to < count; to += 10) { + graph.edges!.push({ id: `l${from}-${to}`, sources: [`n${from}`], targets: [`n${to}`] }); + } + } + return graph; +} + describe('the engine a graph goes to', () => { const elkjs = (): ELK & { calls: number } => { const elk: any = { calls: 0, layout: async (g: ElkNode) => { elk.calls++; return g; } }; @@ -199,12 +222,29 @@ describe('the engine a graph goes to', () => { .toEqual({ nodes: 3, edges: 1 }); }); - it('is the server past the size where the cheaper presets start, under auto', () => { - expect(goesToServer('auto', { nodes: 150, edges: 400 })).toBe(false); - expect(goesToServer('auto', { nodes: 151, edges: 0 })).toBe(true); - expect(goesToServer('auto', { nodes: 10, edges: 401 })).toBe(true); - expect(goesToServer('elk-server', { nodes: 1, edges: 0 })).toBe(true); - expect(goesToServer('elkjs', { nodes: 5000, edges: 9000 })).toBe(false); + it('is the server for a graph elkjs is estimated to be slow on, under auto', () => { + expect(goesToServer('auto', { elkjsMs: AUTO_ELKJS_BUDGET_MS, unpriced: 0 })).toBe(false); + expect(goesToServer('auto', { elkjsMs: AUTO_ELKJS_BUDGET_MS + 1, unpriced: 0 })).toBe(true); + expect(goesToServer('elk-server', { elkjsMs: 0, unpriced: 0 })).toBe(true); + expect(goesToServer('elkjs', { elkjsMs: 3_600_000, unpriced: 0 })).toBe(false); + }); + + it('keeps the size rule for nodes the estimate has no time for, laid out by another algorithm', async () => { + expect(goesToServer('auto', { elkjsMs: 0, unpriced: 150 })).toBe(false); + expect(goesToServer('auto', { elkjsMs: 0, unpriced: 151 })).toBe(true); + expect(goesToServer('elkjs', { elkjsMs: 0, unpriced: 5000 })).toBe(false); + + // A graph placed by forces, as the server has the algorithm: estimated at nothing, and large. + const forced = (count: number): ElkNode => ({ ...chain(count), layoutOptions: { 'elk.algorithm': 'force' } }); + const js = elkjs(); + const sent: ElkNode[] = []; + const elk = new SwitchingElk(js, server(5000), { engine: 'auto' }, async (_port, g) => { sent.push(g); return g; }); + await elk.layout(forced(100)); + await elk.layout(forced(200)); + + expect(estimateElkLayout(forced(200)).elkjsMs).toBe(0); + expect(js.calls).toBe(1); + expect(sent.map(g => g.children!.length)).toEqual([200]); }); it('keeps a small graph on elkjs and never starts the server for it', async () => { @@ -212,19 +252,45 @@ describe('the engine a graph goes to', () => { const java = server(5000); await new SwitchingElk(js, java, { engine: 'auto' }, async g => g).layout(chain(20)); + expect(estimateElkLayout(chain(20)).elkjsMs).toBeLessThan(AUTO_ELKJS_BUDGET_MS); expect(js.calls).toBe(1); expect(java.starts).toBe(0); }); - it('sends a large graph to the server', async () => { + it('sends a graph elkjs would be slow on to the server', async () => { const js = elkjs(); const sent: number[] = []; - await new SwitchingElk(js, server(5000), { engine: 'auto' }, async (port, g) => { sent.push(port); return g; }).layout(chain(200)); + await new SwitchingElk(js, server(5000), { engine: 'auto' }, async (port, g) => { sent.push(port); return g; }).layout(longEdges(300)); + expect(estimateElkLayout(longEdges(300)).elkjsMs).toBeGreaterThan(AUTO_ELKJS_BUDGET_MS); expect(sent).toEqual([5000]); expect(js.calls).toBe(0); }); + it('chooses by what the graph costs, not by its size', async () => { + // Two graphs of as many nodes and edges: one a chain, one whose edges skip most of its layers. + const long = longEdges(300); + const short = chain(300); + for (let i = 0; short.edges!.length < long.edges!.length; i++) { + short.edges!.push({ id: `s${i}`, sources: [`n${i % 299}`], targets: [`n${(i % 299) + 1}`] }); + } + expect(elkGraphSize(short)).toEqual(elkGraphSize(long)); + expect(estimateElkLayout(long).elkjsMs).toBeGreaterThan(estimateElkLayout(short).elkjsMs * 10); + }); + + it('says what it estimated beside what the layout took', async () => { + const said: string[] = []; + const log = vi.spyOn(console, 'log').mockImplementation(line => void said.push(String(line))); + try { + await new SwitchingElk(elkjs(), server(5000), { engine: 'auto' }, async g => g).layout(chain(20)); + await new SwitchingElk(elkjs(), server(5000), { engine: 'elk-server' }, async (_port, g) => g).layout(chain(20)); + } finally { + log.mockRestore(); + } + expect(said[0]).toMatch(/^\[dialogram layout\] elkjs: 20 nodes, 19 edges in \d+ ms \(estimated \d+ ms\)$/); + expect(said[1]).toMatch(/^\[dialogram layout\] ELK server: 20 nodes, 19 edges in \d+ ms \(estimated \d+ ms, elkjs \d+ ms\)$/); + }); + it('keeps a graph on elkjs that asks for an algorithm the server has not, at any depth', async () => { const stress = { id: 'automaton', layoutOptions: { 'elk.algorithm': 'stress' }, children: [{ id: 'a' }, { id: 'b' }] }; expect(serverCanLayOut(stress)).toBe(false); @@ -239,7 +305,7 @@ describe('the engine a graph goes to', () => { expect(java.starts).toBe(0); }); - it('falls back to elkjs when the server cannot start or fails', async () => { + it('falls back to elkjs when the server cannot start or fails, for a graph elkjs finishes in time', async () => { const noServer = elkjs(); await new SwitchingElk(noServer, server(undefined), { engine: 'elk-server' }).layout(chain(3)); const failing = elkjs(); @@ -248,6 +314,51 @@ describe('the engine a graph goes to', () => { expect(noServer.calls).toBe(1); expect(failing.calls).toBe(1); }); + + it('refuses a layout the server did not answer and elkjs would not finish within the same time', async () => { + const js = elkjs(); + const graph = longEdges(300); + const estimated = estimateElkLayout(graph).elkjsMs; + const timedOut = async (): Promise => { throw new Error('the ELK server took longer than 100 ms'); }; + const refused = new SwitchingElk(js, server(5000), { engine: 'auto', timeoutMs: 100 }, timedOut).layout(graph); + + await expect(refused).rejects.toBeInstanceOf(LayoutRefusedError); + await expect(refused).rejects.toMatchObject({ estimateMs: estimated }); + await expect(refused).rejects.toThrow(/^Not laid out: the ELK server took longer than 100 ms, and elkjs would take about .+ for 300 nodes, \d+ edges, with every diagram waiting\.$/); + expect(js.calls).toBe(0); + }); + + it('leaves the same graph to elkjs when elkjs is estimated to finish within the time the server had', async () => { + const js = elkjs(); + const graph = longEdges(300); + const failing = async (): Promise => { throw new Error('the ELK server closed the connection'); }; + await new SwitchingElk(js, server(5000), { engine: 'auto', timeoutMs: estimateElkLayout(graph).elkjsMs }, failing).layout(graph); + + expect(js.calls).toBe(1); + }); + + it('does not refuse by a short timeout a graph elkjs lays out within the minute', async () => { + expect(elkjsTakeoverMs(5000)).toBe(ELKJS_TAKEOVER_BUDGET_MS); + expect(elkjsTakeoverMs(120_000)).toBe(120_000); + + // The server is to hand over after 100 ms, and elkjs needs seconds. + const js = elkjs(); + const graph = longEdges(60); + const estimated = estimateElkLayout(graph).elkjsMs; + expect(estimated).toBeGreaterThan(100); + expect(estimated).toBeLessThan(ELKJS_TAKEOVER_BUDGET_MS); + const timedOut = async (): Promise => { throw new Error('the ELK server took longer than 100 ms'); }; + await new SwitchingElk(js, server(5000), { engine: 'elk-server', timeoutMs: 100 }, timedOut).layout(graph); + + expect(js.calls).toBe(1); + }); + + it('never refuses a graph when there is no server to ask: elkjs is all there is', async () => { + const js = elkjs(); + await new SwitchingElk(js, server(undefined), { engine: 'auto', timeoutMs: 1 }).layout(longEdges(300)); + + expect(js.calls).toBe(1); + }); }); describe('the ELK factory a diagram server gets', () => { @@ -268,6 +379,137 @@ describe('the ELK factory a diagram server gets', () => { }); }); +describe('a layout that was refused', () => { + /** A chain of three tasks, the last reading two values, as the layout engine reads a diagram. */ + function diagram(): { modelState: any; root: any; byId: Map; positions: () => Array<{ x: number; y: number } | undefined> } { + const nodes = Array.from({ length: 3 }, (_, i) => ({ + id: `node:n${i}`, kind: 'task', label: `n${i}`, scope: 'root', + ports: [ + { id: `p:n${i}:in`, name: 'in', direction: 'in' }, + ...(i === 2 ? [{ id: `p:n${i}:also`, name: 'also', direction: 'in' }] : []), + { id: `p:n${i}:out`, name: 'out', direction: 'out' } + ] + })); + const edges = [ + ...nodes.slice(1).map((_, i) => ({ id: `e${i}`, from: `p:n${i}:out`, to: `p:n${i + 1}:in`, scope: 'root' })), + { id: 'e-also', from: 'p:n0:out', to: 'p:n2:also', scope: 'root' } + ]; + const root: any = convertToGModelRoot(new GraphGModelSource().transform({ version: '1', graph: { id: 'wf:chain', nodes, edges } } as any) as any); + const byId = new Map(); + const index = (e: any): void => { byId.set(e.id, e); (e.children ?? []).forEach(index); }; + index(root); + const taskNodes = [...byId.values()].filter(e => e.type?.startsWith?.('node')); + return { + modelState: { root, index: { get: (id: string) => byId.get(id), findByClass: (id: string) => byId.get(id) } }, + root, + byId, + positions: () => taskNodes.map(e => (e.position ? { ...e.position } : undefined)) + }; + } + const refusal = (): LayoutRefusedError => new LayoutRefusedError('Not laid out: the ELK server took longer than 100 ms.', 900_000); + const refusing = (): any => { + const elk: any = { calls: 0, layout: async () => { elk.calls++; throw refusal(); }, terminateWorker: () => undefined }; + return elk; + }; + const engineOf = (elk: any, modelState: any, dispatched: any[] = []): WorkflowElkLayoutEngine => + new WorkflowElkLayoutEngine(() => elk, new DefaultElementFilter(), new WorkflowLayoutConfigurator(), modelState, { dispatch: async (action: any) => void dispatched.push(action) } as any); + + it('is told on the status line of the diagram, moves nothing, and fails the layout', async () => { + const { modelState, positions } = diagram(); + const before = positions(); + const dispatched: any[] = []; + + await expect(engineOf(refusing(), modelState, dispatched).layout()).rejects.toBeInstanceOf(LayoutRefusedError); + + expect(dispatched).toEqual([{ kind: 'status', severity: 'ERROR', message: 'Not laid out: the ELK server took longer than 100 ms.' }]); + expect(positions()).toEqual(before); + }); + + it('says nothing on the status line for a layout that failed otherwise', async () => { + const { modelState } = diagram(); + const failing: any = { layout: async () => { throw new Error('elk went wrong'); }, terminateWorker: () => undefined }; + const dispatched: any[] = []; + + await expect(engineOf(failing, modelState, dispatched).layout()).rejects.toThrow('elk went wrong'); + expect(dispatched).toEqual([]); + }); + + it('is refused at the probe of a Free Ports layout: the engines are asked once, and the reader told once', async () => { + const { modelState, root } = diagram(); + root.layoutOptions = { [PORT_ORDER_OPTION]: PORT_ORDER_FREE }; + const elk = refusing(); + const dispatched: any[] = []; + + await expect(engineOf(elk, modelState, dispatched).layout()).rejects.toBeInstanceOf(LayoutRefusedError); + + // The layout after the probe would wait the server's timeout a second time. + expect(elk.calls).toBe(1); + expect(dispatched).toHaveLength(1); + }); + + it('still lays out when the probe of a Free Ports layout fails otherwise', async () => { + const { modelState, root } = diagram(); + root.layoutOptions = { [PORT_ORDER_OPTION]: PORT_ORDER_FREE }; + const real = new (ElkConstructor as any)({ algorithms: ['layered'] }); + let calls = 0; + const flaky: any = { layout: async (graph: ElkNode) => { if (calls++ === 0) { throw new Error('probe went wrong'); } return real.layout(graph); }, terminateWorker: () => undefined }; + + await engineOf(flaky, modelState).layout(); + expect(calls).toBe(2); + }); + + it('leaves the ports where they were drawn, when the layout was to put them back in the order of the source', async () => { + const { modelState, root, byId } = diagram(); + // Drawn in another order than declared, as a Free Ports layout leaves them. + const first = byId.get('n2_port_in'); + const second = byId.get('n2_port_also'); + [first.position, second.position] = [{ ...second.position }, { ...first.position }]; + const drawn = [{ ...first.position }, { ...second.position }]; + expect(drawn[0].y).toBeGreaterThan(drawn[1].y); + root.layoutOptions = { [PORT_ORDER_OPTION]: PORT_ORDER_DECLARED }; + + await expect(engineOf(refusing(), modelState).layout()).rejects.toBeInstanceOf(LayoutRefusedError); + expect([first.position, second.position]).toEqual(drawn); + + // The layout that runs does put them back. + await engineOf(new (ElkConstructor as any)({ algorithms: ['layered'] }), modelState).layout(); + expect(first.position.y).toBeLessThan(second.position.y); + }); + + it('leaves every edge its route, and no node the constraints of the layout that did not run', async () => { + const { modelState, root, byId } = diagram(); + const routed = byId.get('e0'); + const manual = byId.get('e1'); + routed.routingPoints = [{ x: 10, y: 20 }, { x: 30, y: 20 }]; + manual.routingPoints = [{ x: 50, y: 60 }]; + manual.args = { ...(manual.args ?? {}), 'cal:manualRoute': true }; + const optionsBefore = JSON.stringify([...byId.values()].map(e => e.layoutOptions)); + + await expect(runBoundaryFlowLayout(root, engineOf(refusing(), modelState))).rejects.toBeInstanceOf(LayoutRefusedError); + + expect(routed.routingPoints).toEqual([{ x: 10, y: 20 }, { x: 30, y: 20 }]); + expect(manual.routingPoints).toEqual([{ x: 50, y: 60 }]); + expect(manual.args['cal:manualRoute']).toBe(true); + expect(byId.get('e-also').routingPoints ?? []).toEqual([]); + expect(JSON.stringify([...byId.values()].map(e => e.layoutOptions))).toBe(optionsBefore); + }); + + it('lets a layout that runs replace the routes it cleared', async () => { + const { root, byId } = diagram(); + const edge = byId.get('e0'); + edge.routingPoints = [{ x: 10, y: 20 }]; + edge.args = { ...(edge.args ?? {}), 'cal:manualRoute': true }; + + await layoutFromClearedRoutes(root, async () => { + expect(edge.routingPoints).toBeUndefined(); + edge.routingPoints = [{ x: 1, y: 2 }]; + }); + + expect(edge.routingPoints).toEqual([{ x: 1, y: 2 }]); + expect(edge.args['cal:manualRoute']).toBeUndefined(); + }); +}); + const JAR = path.resolve(__dirname, '../resources/elk-server/elk-server-0.3.0-all.jar'); describe.skipIf(javaMajor() < 17 || !existsSync(JAR))('the shipped ELK server', () => { it('lays out a diagram through the platform’s layout engine', async () => { diff --git a/packages/diagram-server/test/fixtures/layout-rates/checked.jsonl b/packages/diagram-server/test/fixtures/layout-rates/checked.jsonl new file mode 100644 index 00000000..cad5f5ec --- /dev/null +++ b/packages/diagram-server/test/fixtures/layout-rates/checked.jsonl @@ -0,0 +1,7 @@ +{"file":"picorv32.source.json","nodes":290,"edges":1111,"preset":"middle","passNodes":795,"cost":1739,"elkjsMs":2193,"elkjsEstimate":1503,"serverMs":1007,"serverEstimate":402} +{"file":"picorv32.synth.json","nodes":1225,"edges":2093,"preset":"fast","passNodes":1225,"cost":6078,"elkjsMs":2340,"elkjsEstimate":2408,"serverMs":1015,"serverEstimate":550} +{"file":"picorv32_axi_adapter.source.json","nodes":40,"edges":110,"preset":"default","passNodes":101,"cost":151,"elkjsMs":229,"elkjsEstimate":228,"serverMs":144,"serverEstimate":145} +{"file":"picorv32_axi_adapter.synth.json","nodes":76,"edges":87,"preset":"default","passNodes":76,"cost":211,"elkjsMs":1119,"elkjsEstimate":578,"serverMs":239,"serverEstimate":139} +{"file":"picorv32_pcpi_div.synth.json","nodes":128,"edges":188,"preset":"default","passNodes":128,"cost":670,"elkjsMs":4308,"elkjsEstimate":4081,"serverMs":582,"serverEstimate":507} +{"file":"picorv32_pcpi_fast_mul.synth.json","nodes":55,"edges":75,"preset":"default","passNodes":55,"cost":199,"elkjsMs":344,"elkjsEstimate":528,"serverMs":78,"serverEstimate":106} +{"file":"picorv32_pcpi_mul.synth.json","nodes":196,"edges":292,"preset":"middle","passNodes":196,"cost":638,"elkjsMs":322,"elkjsEstimate":462,"serverMs":118,"serverEstimate":110} diff --git a/packages/diagram-server/test/fixtures/layout-rates/measured.jsonl b/packages/diagram-server/test/fixtures/layout-rates/measured.jsonl new file mode 100644 index 00000000..9e3badaf --- /dev/null +++ b/packages/diagram-server/test/fixtures/layout-rates/measured.jsonl @@ -0,0 +1,108 @@ +{"family":"local","nodes":30,"fanIn":1.6,"reach":3,"shuffled":false,"edges":48,"elkNodes":30,"preset":"default","passNodes":30,"cost":60,"elkjsMs":191,"serverMs":65} +{"family":"local","nodes":60,"fanIn":1.6,"reach":3,"shuffled":false,"edges":98,"elkNodes":60,"preset":"default","passNodes":60,"cost":132,"elkjsMs":311,"serverMs":107} +{"family":"local","nodes":100,"fanIn":1.6,"reach":3,"shuffled":false,"edges":162,"elkNodes":100,"preset":"default","passNodes":100,"cost":218,"elkjsMs":508,"serverMs":170} +{"family":"local","nodes":150,"fanIn":1.6,"reach":3,"shuffled":false,"edges":246,"elkNodes":150,"preset":"default","passNodes":150,"cost":332,"elkjsMs":711,"serverMs":226} +{"family":"local","nodes":200,"fanIn":1.6,"reach":3,"shuffled":false,"edges":322,"elkNodes":200,"preset":"middle","passNodes":200,"cost":433,"elkjsMs":396,"serverMs":129} +{"family":"local","nodes":300,"fanIn":1.6,"reach":3,"shuffled":false,"edges":470,"elkNodes":300,"preset":"middle","passNodes":300,"cost":630,"elkjsMs":527,"serverMs":175} +{"family":"local","nodes":450,"fanIn":1.6,"reach":3,"shuffled":false,"edges":707,"elkNodes":450,"preset":"middle","passNodes":450,"cost":940,"elkjsMs":768,"serverMs":206} +{"family":"local","nodes":700,"fanIn":1.6,"reach":3,"shuffled":false,"edges":1112,"elkNodes":700,"preset":"middle","passNodes":700,"cost":1503,"elkjsMs":1295,"serverMs":326} +{"family":"local","nodes":1000,"fanIn":1.6,"reach":3,"shuffled":false,"edges":1598,"elkNodes":1000,"preset":"middle","passNodes":1000,"cost":2191,"elkjsMs":1897,"serverMs":530} +{"family":"local","nodes":1300,"fanIn":1.6,"reach":3,"shuffled":false,"edges":2079,"elkNodes":1300,"preset":"fast","passNodes":1300,"cost":2851,"elkjsMs":1886,"serverMs":569} +{"family":"local","nodes":2000,"fanIn":1.6,"reach":3,"shuffled":false,"edges":3179,"elkNodes":2000,"preset":"fast","passNodes":2000,"cost":4304,"elkjsMs":3328,"serverMs":1021} +{"family":"local","nodes":3500,"fanIn":1.6,"reach":3,"shuffled":false,"edges":5613,"elkNodes":3500,"preset":"fast","passNodes":3500,"cost":7605,"elkjsMs":6676,"serverMs":1510} +{"family":"local","nodes":6000,"fanIn":1.6,"reach":3,"shuffled":false,"edges":9612,"elkNodes":6000,"preset":"fast","passNodes":6000,"cost":12982,"elkjsMs":14426,"serverMs":2805} +{"family":"local","nodes":10000,"fanIn":1.6,"reach":3,"shuffled":false,"edges":16016,"elkNodes":10000,"preset":"fast","passNodes":10000,"cost":21579} +{"family":"near","nodes":30,"fanIn":2.3,"reach":20,"shuffled":false,"edges":67,"elkNodes":30,"preset":"default","passNodes":30,"cost":155,"elkjsMs":502,"serverMs":66} +{"family":"near","nodes":60,"fanIn":2.3,"reach":20,"shuffled":false,"edges":140,"elkNodes":60,"preset":"default","passNodes":60,"cost":335,"elkjsMs":1513,"serverMs":163} +{"family":"near","nodes":100,"fanIn":2.3,"reach":20,"shuffled":false,"edges":234,"elkNodes":100,"preset":"default","passNodes":100,"cost":545,"elkjsMs":3694,"serverMs":386} +{"family":"near","nodes":150,"fanIn":2.3,"reach":20,"shuffled":false,"edges":346,"elkNodes":150,"preset":"default","passNodes":150,"cost":738,"elkjsMs":5634,"serverMs":591} +{"family":"near","nodes":200,"fanIn":2.3,"reach":20,"shuffled":false,"edges":461,"elkNodes":200,"preset":"middle","passNodes":200,"cost":965,"elkjsMs":618,"serverMs":125} +{"family":"near","nodes":300,"fanIn":2.3,"reach":20,"shuffled":false,"edges":688,"elkNodes":300,"preset":"middle","passNodes":300,"cost":1437,"elkjsMs":994,"serverMs":171} +{"family":"near","nodes":450,"fanIn":2.3,"reach":20,"shuffled":false,"edges":1019,"elkNodes":450,"preset":"middle","passNodes":450,"cost":2048,"elkjsMs":1398,"serverMs":231} +{"family":"near","nodes":700,"fanIn":2.3,"reach":20,"shuffled":false,"edges":1596,"elkNodes":700,"preset":"middle","passNodes":700,"cost":3258,"elkjsMs":2542,"serverMs":419} +{"family":"near","nodes":1000,"fanIn":2.3,"reach":20,"shuffled":false,"edges":2291,"elkNodes":1000,"preset":"middle","passNodes":1000,"cost":4778,"elkjsMs":4427,"serverMs":760} +{"family":"near","nodes":1300,"fanIn":2.3,"reach":20,"shuffled":false,"edges":2973,"elkNodes":1300,"preset":"fast","passNodes":1300,"cost":6210,"elkjsMs":2624,"serverMs":555} +{"family":"near","nodes":2000,"fanIn":2.3,"reach":20,"shuffled":false,"edges":4589,"elkNodes":2000,"preset":"fast","passNodes":2000,"cost":9794,"elkjsMs":4433,"serverMs":952} +{"family":"near","nodes":3500,"fanIn":2.3,"reach":20,"shuffled":false,"edges":8055,"elkNodes":3500,"preset":"fast","passNodes":3500,"cost":16962,"elkjsMs":8825,"serverMs":1732} +{"family":"near","nodes":6000,"fanIn":2.3,"reach":20,"shuffled":false,"edges":13797,"elkNodes":6000,"preset":"fast","passNodes":6000,"cost":29209,"elkjsMs":17205,"serverMs":3283} +{"family":"near","nodes":10000,"fanIn":2.3,"reach":20,"shuffled":false,"edges":23017,"elkNodes":10000,"preset":"fast","passNodes":10000,"cost":48181,"serverMs":6104} +{"family":"near-shuffled","nodes":30,"fanIn":2.3,"reach":20,"shuffled":true,"edges":67,"elkNodes":30,"preset":"default","passNodes":30,"cost":155,"elkjsMs":387,"serverMs":56} +{"family":"near-shuffled","nodes":60,"fanIn":2.3,"reach":20,"shuffled":true,"edges":140,"elkNodes":60,"preset":"default","passNodes":60,"cost":335,"elkjsMs":1313,"serverMs":151} +{"family":"near-shuffled","nodes":100,"fanIn":2.3,"reach":20,"shuffled":true,"edges":234,"elkNodes":100,"preset":"default","passNodes":100,"cost":545,"elkjsMs":2341,"serverMs":259} +{"family":"near-shuffled","nodes":150,"fanIn":2.3,"reach":20,"shuffled":true,"edges":346,"elkNodes":150,"preset":"default","passNodes":150,"cost":738,"elkjsMs":4875,"serverMs":547} +{"family":"near-shuffled","nodes":200,"fanIn":2.3,"reach":20,"shuffled":true,"edges":461,"elkNodes":200,"preset":"middle","passNodes":200,"cost":965,"elkjsMs":590,"serverMs":141} +{"family":"near-shuffled","nodes":300,"fanIn":2.3,"reach":20,"shuffled":true,"edges":688,"elkNodes":300,"preset":"middle","passNodes":300,"cost":1437,"elkjsMs":937,"serverMs":200} +{"family":"near-shuffled","nodes":450,"fanIn":2.3,"reach":20,"shuffled":true,"edges":1019,"elkNodes":450,"preset":"middle","passNodes":450,"cost":2048,"elkjsMs":1421,"serverMs":310} +{"family":"near-shuffled","nodes":700,"fanIn":2.3,"reach":20,"shuffled":true,"edges":1596,"elkNodes":700,"preset":"middle","passNodes":700,"cost":3258,"elkjsMs":2569,"serverMs":456} +{"family":"near-shuffled","nodes":1000,"fanIn":2.3,"reach":20,"shuffled":true,"edges":2291,"elkNodes":1000,"preset":"middle","passNodes":1000,"cost":4778,"elkjsMs":4436,"serverMs":656} +{"family":"near-shuffled","nodes":1300,"fanIn":2.3,"reach":20,"shuffled":true,"edges":2973,"elkNodes":1300,"preset":"fast","passNodes":1300,"cost":6210,"elkjsMs":2621,"serverMs":606} +{"family":"near-shuffled","nodes":2000,"fanIn":2.3,"reach":20,"shuffled":true,"edges":4589,"elkNodes":2000,"preset":"fast","passNodes":2000,"cost":9794,"elkjsMs":4371,"serverMs":954} +{"family":"near-shuffled","nodes":3500,"fanIn":2.3,"reach":20,"shuffled":true,"edges":8055,"elkNodes":3500,"preset":"fast","passNodes":3500,"cost":16962,"elkjsMs":8643,"serverMs":1732} +{"family":"near-shuffled","nodes":6000,"fanIn":2.3,"reach":20,"shuffled":true,"edges":13797,"elkNodes":6000,"preset":"fast","passNodes":6000,"cost":29209,"elkjsMs":18592,"serverMs":3405} +{"family":"near-shuffled","nodes":10000,"fanIn":2.3,"reach":20,"shuffled":true,"edges":23017,"elkNodes":10000,"preset":"fast","passNodes":10000,"cost":48181,"serverMs":6049} +{"family":"mid","nodes":30,"fanIn":2.3,"reach":20,"shuffled":true,"edges":67,"elkNodes":30,"preset":"default","passNodes":30,"cost":155,"elkjsMs":349,"serverMs":56} +{"family":"mid","nodes":60,"fanIn":2.3,"reach":20,"shuffled":true,"edges":140,"elkNodes":60,"preset":"default","passNodes":60,"cost":335,"elkjsMs":1274,"serverMs":149} +{"family":"mid","nodes":100,"fanIn":2.3,"reach":20,"shuffled":true,"edges":234,"elkNodes":100,"preset":"default","passNodes":100,"cost":545,"elkjsMs":2304,"serverMs":257} +{"family":"mid","nodes":150,"fanIn":2.3,"reach":20,"shuffled":true,"edges":346,"elkNodes":150,"preset":"default","passNodes":150,"cost":738,"elkjsMs":4859,"serverMs":521} +{"family":"mid","nodes":200,"fanIn":2.3,"reach":25,"shuffled":true,"edges":459,"elkNodes":200,"preset":"middle","passNodes":200,"cost":1037,"elkjsMs":628,"serverMs":111} +{"family":"mid","nodes":300,"fanIn":2.3,"reach":38,"shuffled":true,"edges":687,"elkNodes":300,"preset":"middle","passNodes":300,"cost":1545,"elkjsMs":1031,"serverMs":172} +{"family":"mid","nodes":450,"fanIn":2.3,"reach":56,"shuffled":true,"edges":1018,"elkNodes":450,"preset":"middle","passNodes":450,"cost":2345,"elkjsMs":1700,"serverMs":291} +{"family":"mid","nodes":700,"fanIn":2.3,"reach":88,"shuffled":true,"edges":1596,"elkNodes":700,"preset":"middle","passNodes":700,"cost":4042,"elkjsMs":3002,"serverMs":619} +{"family":"mid","nodes":1000,"fanIn":2.3,"reach":125,"shuffled":true,"edges":2284,"elkNodes":1000,"preset":"middle","passNodes":1000,"cost":6118,"elkjsMs":5070,"serverMs":964} +{"family":"mid","nodes":1300,"fanIn":2.3,"reach":163,"shuffled":true,"edges":2971,"elkNodes":1300,"preset":"fast","passNodes":1300,"cost":8125,"elkjsMs":2804,"serverMs":582} +{"family":"mid","nodes":2000,"fanIn":2.3,"reach":250,"shuffled":true,"edges":4591,"elkNodes":2000,"preset":"fast","passNodes":2000,"cost":12149,"elkjsMs":4581,"serverMs":987} +{"family":"mid","nodes":3500,"fanIn":2.3,"reach":438,"shuffled":true,"edges":8077,"elkNodes":3500,"preset":"fast","passNodes":3500,"cost":24989,"elkjsMs":9700,"serverMs":1822} +{"family":"mid","nodes":6000,"fanIn":2.3,"reach":750,"shuffled":true,"edges":13807,"elkNodes":6000,"preset":"fast","passNodes":6000,"cost":39530,"elkjsMs":19413,"serverMs":3311} +{"family":"mid","nodes":10000,"fanIn":2.3,"reach":1250,"shuffled":true,"edges":22993,"elkNodes":10000,"preset":"fast","passNodes":10000,"cost":72954,"serverMs":6653} +{"family":"far","nodes":30,"fanIn":2.3,"reach":30,"shuffled":false,"edges":67,"elkNodes":30,"preset":"default","passNodes":30,"cost":162,"elkjsMs":364,"serverMs":103} +{"family":"far","nodes":60,"fanIn":2.3,"reach":60,"shuffled":false,"edges":139,"elkNodes":60,"preset":"default","passNodes":60,"cost":420,"elkjsMs":1810,"serverMs":309} +{"family":"far","nodes":100,"fanIn":2.3,"reach":100,"shuffled":false,"edges":231,"elkNodes":100,"preset":"default","passNodes":100,"cost":733,"elkjsMs":7915,"serverMs":753} +{"family":"far","nodes":150,"fanIn":2.3,"reach":150,"shuffled":false,"edges":345,"elkNodes":150,"preset":"default","passNodes":150,"cost":1074,"elkjsMs":10813,"serverMs":1214} +{"family":"far","nodes":200,"fanIn":2.3,"reach":200,"shuffled":false,"edges":463,"elkNodes":200,"preset":"middle","passNodes":200,"cost":1553,"elkjsMs":762,"serverMs":130} +{"family":"far","nodes":300,"fanIn":2.3,"reach":300,"shuffled":false,"edges":690,"elkNodes":300,"preset":"middle","passNodes":300,"cost":2458,"elkjsMs":1387,"serverMs":198} +{"family":"far","nodes":450,"fanIn":2.3,"reach":450,"shuffled":false,"edges":1023,"elkNodes":450,"preset":"middle","passNodes":450,"cost":3752,"elkjsMs":2353,"serverMs":335} +{"family":"far","nodes":700,"fanIn":2.3,"reach":700,"shuffled":false,"edges":1601,"elkNodes":700,"preset":"middle","passNodes":700,"cost":6092,"elkjsMs":4178,"serverMs":788} +{"family":"far","nodes":1000,"fanIn":2.3,"reach":1000,"shuffled":false,"edges":2288,"elkNodes":1000,"preset":"middle","passNodes":1000,"cost":8982,"elkjsMs":6224,"serverMs":872} +{"family":"far","nodes":1300,"fanIn":2.3,"reach":1300,"shuffled":false,"edges":2978,"elkNodes":1300,"preset":"fast","passNodes":1300,"cost":11825,"elkjsMs":3042,"serverMs":581} +{"family":"far","nodes":2000,"fanIn":2.3,"reach":2000,"shuffled":false,"edges":4593,"elkNodes":2000,"preset":"fast","passNodes":2000,"cost":19027,"elkjsMs":5109,"serverMs":960} +{"family":"far","nodes":3500,"fanIn":2.3,"reach":3500,"shuffled":false,"edges":8082,"elkNodes":3500,"preset":"fast","passNodes":3500,"cost":35082,"elkjsMs":10480,"serverMs":1923} +{"family":"far","nodes":6000,"fanIn":2.3,"reach":6000,"shuffled":false,"edges":13807,"elkNodes":6000,"preset":"fast","passNodes":6000,"cost":61251,"elkjsMs":19829,"serverMs":3450} +{"family":"far","nodes":10000,"fanIn":2.3,"reach":10000,"shuffled":false,"edges":22988,"elkNodes":10000,"preset":"fast","passNodes":10000,"cost":104416,"elkjsMs":39001,"serverMs":6967} +{"family":"far-shuffled","nodes":30,"fanIn":2.6,"reach":30,"shuffled":true,"edges":70,"elkNodes":30,"preset":"default","passNodes":30,"cost":153,"elkjsMs":339,"serverMs":115} +{"family":"far-shuffled","nodes":60,"fanIn":2.6,"reach":60,"shuffled":true,"edges":149,"elkNodes":60,"preset":"default","passNodes":60,"cost":430,"elkjsMs":2168,"serverMs":327} +{"family":"far-shuffled","nodes":100,"fanIn":2.6,"reach":100,"shuffled":true,"edges":248,"elkNodes":100,"preset":"default","passNodes":100,"cost":772,"elkjsMs":7285,"serverMs":927} +{"family":"far-shuffled","nodes":150,"fanIn":2.6,"reach":150,"shuffled":true,"edges":385,"elkNodes":150,"preset":"default","passNodes":150,"cost":1260,"elkjsMs":20721,"serverMs":2516} +{"family":"far-shuffled","nodes":200,"fanIn":2.6,"reach":200,"shuffled":true,"edges":518,"elkNodes":200,"preset":"middle","passNodes":200,"cost":1759,"elkjsMs":1099,"serverMs":183} +{"family":"far-shuffled","nodes":300,"fanIn":2.6,"reach":300,"shuffled":true,"edges":771,"elkNodes":300,"preset":"middle","passNodes":300,"cost":2725,"elkjsMs":1577,"serverMs":254} +{"family":"far-shuffled","nodes":450,"fanIn":2.6,"reach":450,"shuffled":true,"edges":1159,"elkNodes":450,"preset":"middle","passNodes":450,"cost":4284,"elkjsMs":2772,"serverMs":388} +{"family":"far-shuffled","nodes":700,"fanIn":2.6,"reach":700,"shuffled":true,"edges":1812,"elkNodes":700,"preset":"middle","passNodes":700,"cost":6945,"elkjsMs":4327,"serverMs":632} +{"family":"far-shuffled","nodes":1000,"fanIn":2.6,"reach":1000,"shuffled":true,"edges":2598,"elkNodes":1000,"preset":"middle","passNodes":1000,"cost":10233,"elkjsMs":7263,"serverMs":936} +{"family":"far-shuffled","nodes":1300,"fanIn":2.6,"reach":1300,"shuffled":true,"edges":3383,"elkNodes":1300,"preset":"fast","passNodes":1300,"cost":13804,"elkjsMs":3437,"serverMs":683} +{"family":"far-shuffled","nodes":2000,"fanIn":2.6,"reach":2000,"shuffled":true,"edges":5188,"elkNodes":2000,"preset":"fast","passNodes":2000,"cost":22020,"elkjsMs":6084,"serverMs":1210} +{"family":"far-shuffled","nodes":3500,"fanIn":2.6,"reach":3500,"shuffled":true,"edges":9084,"elkNodes":3500,"preset":"fast","passNodes":3500,"cost":40051,"elkjsMs":10960,"serverMs":2117} +{"family":"far-shuffled","nodes":6000,"fanIn":2.6,"reach":6000,"shuffled":true,"edges":15616,"elkNodes":6000,"preset":"fast","passNodes":6000,"cost":71357,"elkjsMs":22033,"serverMs":4157} +{"family":"far-shuffled","nodes":10000,"fanIn":2.6,"reach":10000,"shuffled":true,"edges":25970,"elkNodes":10000,"preset":"fast","passNodes":10000,"cost":120962,"elkjsMs":45521,"serverMs":7647} +{"family":"local","nodes":30,"fanIn":1.6,"reach":3,"shuffled":false,"edges":48,"elkNodes":30,"preset":"untangled","passNodes":30,"cost":60,"elkjsMs":202,"serverMs":61} +{"family":"local","nodes":60,"fanIn":1.6,"reach":3,"shuffled":false,"edges":98,"elkNodes":60,"preset":"untangled","passNodes":60,"cost":132,"elkjsMs":284,"serverMs":84} +{"family":"local","nodes":100,"fanIn":1.6,"reach":3,"shuffled":false,"edges":162,"elkNodes":100,"preset":"untangled","passNodes":100,"cost":218,"elkjsMs":428,"serverMs":108} +{"family":"local","nodes":150,"fanIn":1.6,"reach":3,"shuffled":false,"edges":246,"elkNodes":150,"preset":"untangled","passNodes":150,"cost":332,"elkjsMs":571,"serverMs":136} +{"family":"near","nodes":30,"fanIn":2.3,"reach":20,"shuffled":false,"edges":67,"elkNodes":30,"preset":"untangled","passNodes":30,"cost":155,"elkjsMs":249,"serverMs":114} +{"family":"near","nodes":60,"fanIn":2.3,"reach":20,"shuffled":false,"edges":140,"elkNodes":60,"preset":"untangled","passNodes":60,"cost":335,"elkjsMs":495,"serverMs":192} +{"family":"near","nodes":100,"fanIn":2.3,"reach":20,"shuffled":false,"edges":234,"elkNodes":100,"preset":"untangled","passNodes":100,"cost":545,"elkjsMs":899,"serverMs":146} +{"family":"near","nodes":150,"fanIn":2.3,"reach":20,"shuffled":false,"edges":346,"elkNodes":150,"preset":"untangled","passNodes":150,"cost":738,"elkjsMs":1152,"serverMs":186} +{"family":"near-shuffled","nodes":30,"fanIn":2.3,"reach":20,"shuffled":true,"edges":67,"elkNodes":30,"preset":"untangled","passNodes":30,"cost":155,"elkjsMs":235,"serverMs":75} +{"family":"near-shuffled","nodes":60,"fanIn":2.3,"reach":20,"shuffled":true,"edges":140,"elkNodes":60,"preset":"untangled","passNodes":60,"cost":335,"elkjsMs":505,"serverMs":109} +{"family":"near-shuffled","nodes":100,"fanIn":2.3,"reach":20,"shuffled":true,"edges":234,"elkNodes":100,"preset":"untangled","passNodes":100,"cost":545,"elkjsMs":757,"serverMs":167} +{"family":"near-shuffled","nodes":150,"fanIn":2.3,"reach":20,"shuffled":true,"edges":346,"elkNodes":150,"preset":"untangled","passNodes":150,"cost":738,"elkjsMs":1085,"serverMs":222} +{"family":"mid","nodes":30,"fanIn":2.3,"reach":20,"shuffled":true,"edges":67,"elkNodes":30,"preset":"untangled","passNodes":30,"cost":155,"elkjsMs":233,"serverMs":61} +{"family":"mid","nodes":60,"fanIn":2.3,"reach":20,"shuffled":true,"edges":140,"elkNodes":60,"preset":"untangled","passNodes":60,"cost":335,"elkjsMs":505,"serverMs":105} +{"family":"mid","nodes":100,"fanIn":2.3,"reach":20,"shuffled":true,"edges":234,"elkNodes":100,"preset":"untangled","passNodes":100,"cost":545,"elkjsMs":786,"serverMs":158} +{"family":"mid","nodes":150,"fanIn":2.3,"reach":20,"shuffled":true,"edges":346,"elkNodes":150,"preset":"untangled","passNodes":150,"cost":738,"elkjsMs":1111,"serverMs":220} +{"family":"far","nodes":30,"fanIn":2.3,"reach":30,"shuffled":false,"edges":67,"elkNodes":30,"preset":"untangled","passNodes":30,"cost":162,"elkjsMs":251,"serverMs":69} +{"family":"far","nodes":60,"fanIn":2.3,"reach":60,"shuffled":false,"edges":139,"elkNodes":60,"preset":"untangled","passNodes":60,"cost":420,"elkjsMs":653,"serverMs":135} +{"family":"far","nodes":100,"fanIn":2.3,"reach":100,"shuffled":false,"edges":231,"elkNodes":100,"preset":"untangled","passNodes":100,"cost":733,"elkjsMs":1229,"serverMs":226} +{"family":"far","nodes":150,"fanIn":2.3,"reach":150,"shuffled":false,"edges":345,"elkNodes":150,"preset":"untangled","passNodes":150,"cost":1074,"elkjsMs":1768,"serverMs":309} +{"family":"far-shuffled","nodes":30,"fanIn":2.6,"reach":30,"shuffled":true,"edges":70,"elkNodes":30,"preset":"untangled","passNodes":30,"cost":153,"elkjsMs":220,"serverMs":59} +{"family":"far-shuffled","nodes":60,"fanIn":2.6,"reach":60,"shuffled":true,"edges":149,"elkNodes":60,"preset":"untangled","passNodes":60,"cost":430,"elkjsMs":668,"serverMs":128} +{"family":"far-shuffled","nodes":100,"fanIn":2.6,"reach":100,"shuffled":true,"edges":248,"elkNodes":100,"preset":"untangled","passNodes":100,"cost":772,"elkjsMs":1443,"serverMs":241} +{"family":"far-shuffled","nodes":150,"fanIn":2.6,"reach":150,"shuffled":true,"edges":385,"elkNodes":150,"preset":"untangled","passNodes":150,"cost":1260,"elkjsMs":2597,"serverMs":406} diff --git a/packages/diagram-server/test/layout-cost.test.ts b/packages/diagram-server/test/layout-cost.test.ts new file mode 100644 index 00000000..223e32fd --- /dev/null +++ b/packages/diagram-server/test/layout-cost.test.ts @@ -0,0 +1,355 @@ +import { readFileSync } from 'node:fs'; +import * as path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import type { ElkNode } from 'elkjs'; +import { + LAYOUT_RATES, + costOfPass, + estimateElkLayout, + estimatePassMs, + formatLayoutMs, + layerSpan, + passesOfElkGraph, + presetOfElkGraph, + unpricedNodesOfElkGraph, + type LayoutPreset, + type PassEdge +} from '../src/server/layout-cost'; + +/** + * The layout estimate (layout-cost.ts): the layers the edges of a pass span, + * the passes of an ELK graph, and the milliseconds an engine takes for them. + * The rates themselves are measured (`layout-rates.measure.test.ts`); these + * tests hold the arithmetic and the reading of a graph. + */ +const chain = (nodes: number): PassEdge[] => Array.from({ length: nodes - 1 }, (_, at) => ({ from: at, to: at + 1 })); + +describe('the layers the edges of a pass span', () => { + it('is one layer an edge along a chain', () => { + expect(layerSpan(5, chain(5))).toBe(4); + expect(layerSpan(1, [])).toBe(0); + expect(layerSpan(0, [])).toBe(0); + }); + + it('counts every layer an edge skips', () => { + // a → b → c → d, and a → d over the two layers between. + expect(layerSpan(4, [...chain(4), { from: 0, to: 3 }])).toBe(3 + 3); + }); + + it('layers by the longest path, not the shortest', () => { + // d is read by a directly and by c at the end of the chain: it sits after c. + expect(layerSpan(4, [{ from: 0, to: 3 }, ...chain(4)])).toBe(3 + 3); + }); + + it('leaves the span of an edge that only orders the layers out of the cost', () => { + const ordering = chain(4).map(edge => ({ ...edge, counted: false })); + expect(layerSpan(4, ordering)).toBe(0); + expect(layerSpan(4, [...ordering, { from: 0, to: 3 }])).toBe(3); + // Without the chain the same edge spans one layer. + expect(layerSpan(4, [{ from: 0, to: 3 }])).toBe(1); + }); + + it('layers nodes declared against the flow as it layers them declared along it', () => { + const backwards = chain(6).map(edge => ({ from: 5 - edge.from, to: 5 - edge.to })); + expect(layerSpan(6, backwards)).toBe(5); + expect(layerSpan(6, [...backwards, { from: 5, to: 0 }])).toBe(5 + 5); + }); + + it('is the same for a graph whatever order its nodes are declared in', () => { + // A dataflow graph in the order of its flow, then the same graph renumbered. + const nodes = 400; + let state = 7; + const next = (): number => (state = (state * 1103515245 + 12345) % 2147483648) / 2147483648; + const edges: PassEdge[] = []; + for (let to = 1; to < nodes; to++) { + for (let read = 0; read < 2; read++) { + edges.push({ from: Math.floor(next() * to), to }); + } + } + const renumbered = Array.from({ length: nodes }, (_, at) => at).sort(() => next() - 0.5); + const moved = edges.map(edge => ({ from: renumbered[edge.from], to: renumbered[edge.to] })); + + expect(layerSpan(nodes, moved)).toBe(layerSpan(nodes, edges)); + expect(layerSpan(nodes, edges)).toBeGreaterThan(nodes); + }); + + it('takes the edge that closes a cycle out of the layering, and still counts what it spans', () => { + // a → b → c → a: the layers are a, b, c, and c → a runs back over two. + expect(layerSpan(3, [{ from: 0, to: 1 }, { from: 1, to: 2 }, { from: 2, to: 0 }])).toBe(1 + 1 + 2); + // The same cycle met from a node declared after it. + expect(layerSpan(4, [{ from: 2, to: 3 }, { from: 3, to: 1 }, { from: 1, to: 2 }, { from: 0, to: 1 }])).toBe(1 + 1 + 2 + 1); + }); + + it('breaks the cycles of a netlist as ELK does, the registers first', () => { + // Each register is fed by its own logic and feeds it, and the logic of + // the next register. One enable reaches every register. Declared + // register by register, a search in the order of the model walks the + // registers as one chain, and the enable spans all of it. + const registers = 50; + const enable = 0; + const register = (at: number): number => 1 + 2 * at; + const logic = (at: number): number => 2 + 2 * at; + const edges: PassEdge[] = []; + for (let at = 0; at < registers; at++) { + edges.push({ from: enable, to: register(at) }, { from: register(at), to: logic(at) }, { from: logic(at), to: register(at) }); + if (at + 1 < registers) { + edges.push({ from: register(at), to: logic(at + 1) }); + } + } + + // In three layers (the enable, the registers, the logic) every edge spans one. + // The order found is near it. As one chain the span is over 2,500. + expect(edges).toHaveLength(199); + expect(layerSpan(1 + 2 * registers, edges)).toBeLessThan(2 * edges.length); + }); + + it('does not order the layers by an edge the product says runs against the flow', () => { + expect(layerSpan(2, [{ from: 1, to: 0, orders: false }])).toBe(0); + // b → a would put a after b; unordered, a and b keep the layers the chain gives them. + expect(layerSpan(3, [...chain(3), { from: 2, to: 0, orders: false }])).toBe(2 + 2); + }); + + it('ignores an edge of a node on itself and one that names no node of the pass', () => { + expect(layerSpan(2, [{ from: 0, to: 0 }, { from: 0, to: 7 }, { from: -1, to: 1 }, { from: 0, to: 1 }])).toBe(1); + }); + + it('layers a pass of three hundred thousand nodes without recursion, declared either way', () => { + const nodes = 300_000; + expect(layerSpan(nodes, chain(nodes))).toBe(nodes - 1); + expect(layerSpan(nodes, chain(nodes).map(edge => ({ from: nodes - 1 - edge.from, to: nodes - 1 - edge.to })))).toBe(nodes - 1); + }); +}); + +describe('the passes of an ELK graph', () => { + const graph: ElkNode = { + id: 'root', + children: [ + { id: 'a', ports: [{ id: 'a.out' }] }, + { + id: 'group', + ports: [{ id: 'group.in' }], + children: [{ id: 'x', ports: [{ id: 'x.in' }, { id: 'x.out' }] }, { id: 'y', ports: [{ id: 'y.in' }] }, { id: 'z' }] + }, + { id: 'b', ports: [{ id: 'b.in' }] } + ], + edges: [ + { id: 'a-b', sources: ['a.out'], targets: ['b.in'] }, + { id: 'a-group', sources: ['a.out'], targets: ['group.in'] }, + // Declared at the root, between two nodes of the group. + { id: 'x-y', sources: ['x.out'], targets: ['y.in'] }, + { id: 'x-z', sources: ['x'], targets: ['z'] }, + // Into the group from outside: bridged by the group's own port. + { id: 'a-x', sources: ['a.out'], targets: ['x.in'] }, + { id: 'nowhere', sources: ['a.out'], targets: ['gone'] } + ] + }; + + it('is one pass a container, with the edges between two of its nodes', () => { + const [root, group] = passesOfElkGraph(graph); + + expect(root.nodes).toBe(3); + expect(root.edges).toEqual([{ from: 0, to: 2 }, { from: 0, to: 1 }]); + expect(group.nodes).toBe(3); + expect(group.edges).toEqual([{ from: 0, to: 1 }, { from: 0, to: 2 }]); + expect(passesOfElkGraph(graph)).toHaveLength(2); + }); + + it('stands a node at the edge of a pass for each port of the container an edge of the inside ends on', () => { + const open: ElkNode = { + id: 'root', + children: [ + { id: 'a', ports: [{ id: 'a.out' }] }, + { + id: 'unit', + ports: [{ id: 'unit.in' }, { id: 'unit.spare' }, { id: 'unit.out' }], + children: [{ id: 'x', ports: [{ id: 'x.in' }, { id: 'x.out' }] }, { id: 'y', ports: [{ id: 'y.in' }, { id: 'y.out' }] }], + edges: [ + { id: 'in-x', sources: ['unit.in'], targets: ['x.in'] }, + { id: 'in-y', sources: ['unit.in'], targets: ['y.in'] }, + { id: 'x-y', sources: ['x.out'], targets: ['y.in'] }, + { id: 'y-out', sources: ['y.out'], targets: ['unit.out'] } + ] + }, + { id: 'b', ports: [{ id: 'b.in' }] } + ], + edges: [ + { id: 'a-unit', sources: ['a.out'], targets: ['unit.in'] }, + { id: 'unit-b', sources: ['unit.out'], targets: ['b.in'] } + ] + }; + const [root, unit] = passesOfElkGraph(open); + + // Outside, the unit is one node, whichever of its ports an edge ends on. + expect(root).toEqual({ nodes: 3, edges: [{ from: 0, to: 1 }, { from: 1, to: 2 }] }); + // Inside, x and y, then the two ports in use. The spare one is no node. + expect(unit.nodes).toBe(4); + expect(unit.edges).toEqual([{ from: 2, to: 0 }, { from: 2, to: 1 }, { from: 0, to: 1 }, { from: 1, to: 3 }]); + expect(layerSpan(unit.nodes, unit.edges)).toBe(1 + 2 + 1 + 1); + }); + + it('reads an edge of one source and one target as elkjs still accepts it, and every pair of a hyperedge', () => { + const flat: ElkNode = { + id: 'root', + children: [{ id: 'a' }, { id: 'b' }, { id: 'c' }], + edges: [{ id: 'old', source: 'a', target: 'b' } as any, { id: 'hyper', sources: ['a', 'b'], targets: ['c'] }] + }; + expect(passesOfElkGraph(flat)[0].edges).toEqual([{ from: 0, to: 1 }, { from: 0, to: 2 }, { from: 1, to: 2 }]); + }); + + it('is none for a container that is not laid out in layers', () => { + const mixed: ElkNode = { + id: 'root', + layoutOptions: { 'elk.algorithm': 'org.eclipse.elk.layered' }, + children: [ + { id: 'a' }, + { id: 'rows', layoutOptions: { 'elk.algorithm': 'box' }, children: [{ id: 'r1' }, { id: 'r2' }], edges: [{ id: 'r', sources: ['r1'], targets: ['r2'] }] }, + { id: 'kept', layoutOptions: { 'org.eclipse.elk.algorithm': 'fixed' }, children: [{ id: 'k1', children: [{ id: 'deep1' }, { id: 'deep2' }] }] } + ], + edges: [{ id: 'e', sources: ['a'], targets: ['rows'] }] + }; + // The root, and the layered container inside the fixed one. + expect(passesOfElkGraph(mixed).map(pass => [pass.nodes, pass.edges.length])).toEqual([[3, 1], [2, 0]]); + }); + + it('counts the nodes another algorithm lays out, which the estimate has no time for', () => { + const nodes = (count: number, prefix: string): ElkNode[] => Array.from({ length: count }, (_, at) => ({ id: `${prefix}${at}` })); + const forced: ElkNode = { id: 'root', layoutOptions: { 'elk.algorithm': 'force' }, children: nodes(200, 'n') }; + expect(unpricedNodesOfElkGraph(forced)).toBe(200); + expect(estimateElkLayout(forced)).toMatchObject({ nodes: 0, elkjsMs: 0, serverMs: 0, unpriced: 200 }); + + // Nodes kept where they are take no layout, and a layered container is costed. + const mixed: ElkNode = { + id: 'root', + children: [ + { id: 'tree', layoutOptions: { 'org.eclipse.elk.algorithm': 'org.eclipse.elk.mrtree' }, children: nodes(7, 't') }, + { id: 'kept', layoutOptions: { 'elk.algorithm': 'fixed' }, children: nodes(5, 'k') } + ] + }; + expect(unpricedNodesOfElkGraph(mixed)).toBe(7); + expect(estimateElkLayout(mixed)).toMatchObject({ nodes: 2, unpriced: 7 }); + }); + + it('is none for a graph with no nodes', () => { + expect(passesOfElkGraph({ id: 'root' })).toEqual([]); + expect(estimateElkLayout({ id: 'root' })).toMatchObject({ nodes: 0, cost: 0, elkjsMs: 0, serverMs: 0, unpriced: 0 }); + }); +}); + +describe('the preset an ELK graph is laid out with', () => { + it('is read off the options that carry the cost, under either spelling', () => { + expect(presetOfElkGraph({ id: 'r', layoutOptions: { 'elk.layered.nodePlacement.strategy': 'NETWORK_SIMPLEX' } })).toBe('default'); + expect(presetOfElkGraph({ id: 'r', layoutOptions: { 'elk.layered.nodePlacement.strategy': 'BRANDES_KOEPF' } })).toBe('middle'); + expect(presetOfElkGraph({ id: 'r', layoutOptions: { 'org.eclipse.elk.layered.crossingMinimization.strategy': 'NONE', 'elk.layered.nodePlacement.strategy': 'NETWORK_SIMPLEX' } })).toBe('fast'); + expect(presetOfElkGraph({ id: 'r' })).toBe('middle'); + }); + + it('is the untangled one for a graph that keeps the order of its model without network-simplex placement', () => { + // The default preset with the options of Untangled and Free Ports over it. + const untangled = { 'elk.layered.considerModelOrder.strategy': 'NODES_AND_EDGES', 'elk.layered.nodePlacement.strategy': 'BRANDES_KOEPF' }; + expect(presetOfElkGraph({ id: 'r', layoutOptions: untangled })).toBe('untangled'); + // The middle preset gives the order of the model up. + expect(presetOfElkGraph({ id: 'r', layoutOptions: { ...untangled, 'elk.layered.considerModelOrder.strategy': 'NONE' } })).toBe('middle'); + expect(presetOfElkGraph({ id: 'r', layoutOptions: { ...untangled, 'elk.layered.nodePlacement.strategy': 'NETWORK_SIMPLEX' } })).toBe('default'); + }); + + it('prices an untangled layout above the middle preset and, for long edges, far under the default one', () => { + const pass = { cost: 1260, nodes: 150 }; + const ms = (preset: LayoutPreset): number => estimatePassMs(pass, LAYOUT_RATES[preset].elkjs); + expect(ms('untangled')).toBeGreaterThan(2 * ms('middle')); + expect(ms('untangled')).toBeLessThan(ms('default') / 4); + }); +}); + +describe('the milliseconds of a pass', () => { + it('is the span, the nodes and their square at the rates of the engine', () => { + const rates = { msPerSpanUnit: 2, msPerSpanUnitSquared: 0.01, msPerNode: 3, msPerNodeSquared: 0.5 }; + expect(estimatePassMs({ cost: 1000, nodes: 100 }, rates)).toBe(2000 + 10_000 + 300 + 5000); + expect(estimatePassMs({ cost: 0, nodes: 0 }, rates)).toBe(0); + // A product's own rates, with the arithmetic it had before it used the platform's. + expect(estimatePassMs({ cost: 13_108, nodes: 2164 }, { msPerSpanUnit: 1.4, msPerSpanUnitSquared: 0, msPerNode: 0, msPerNodeSquared: 0.02 })) + .toBe(Math.round(13_108 * 1.4 + 0.02 * 2164 * 2164)); + expect(costOfPass({ nodes: 4, edges: [...chain(4), { from: 0, to: 3 }] })).toEqual({ cost: 6, nodes: 4 }); + }); + + it('sums the passes of a graph, at the rates of its preset or at the ones given', () => { + const nested: ElkNode = { + id: 'root', + children: [{ id: 'a' }, { id: 'g', children: [{ id: 'x' }, { id: 'y' }, { id: 'z' }], edges: [{ id: 'e1', sources: ['x'], targets: ['y'] }, { id: 'e2', sources: ['y'], targets: ['z'] }] }], + edges: [{ id: 'e0', sources: ['a'], targets: ['g'] }] + }; + const rates = { + elkjs: { msPerSpanUnit: 10, msPerSpanUnitSquared: 0, msPerNode: 1, msPerNodeSquared: 0 }, + 'elk-server': { msPerSpanUnit: 1, msPerSpanUnitSquared: 0, msPerNode: 0, msPerNodeSquared: 0 } + }; + + expect(estimateElkLayout(nested, rates)).toEqual({ nodes: 5, cost: 3, preset: 'middle', elkjsMs: 10 + 2 + 20 + 3, serverMs: 3, unpriced: 0 }); + const byPreset = estimateElkLayout(nested); + expect(byPreset.elkjsMs).toBe( + estimatePassMs({ cost: 1, nodes: 2 }, LAYOUT_RATES.middle.elkjs) + estimatePassMs({ cost: 2, nodes: 3 }, LAYOUT_RATES.middle.elkjs) + ); + }); + + it('holds every graph of the measurement within a factor of two, on both engines', () => { + // What `layout-rates.measure.test.ts` wrote when the rates were fitted: a line a graph. + const measured = readFileSync(path.join(__dirname, 'fixtures/layout-rates/measured.jsonl'), 'utf8') + .split('\n') + .filter(Boolean) + .map(line => JSON.parse(line) as { family: string; nodes: number; preset: LayoutPreset; passNodes: number; cost: number; elkjsMs?: number; serverMs?: number }); + expect(measured).toHaveLength(84 + 24); + expect(new Set(measured.map(line => line.preset))).toEqual(new Set(['default', 'middle', 'fast', 'untangled'])); + const off: string[] = []; + let held = 0; + for (const line of measured) { + for (const [engine, ms] of [['elkjs', line.elkjsMs], ['elk-server', line.serverMs]] as const) { + // Under 20 ms is the cost of asking; no time is an engine that gave up. + if (typeof ms !== 'number' || ms < 20) { + continue; + } + const estimate = estimatePassMs({ cost: line.cost, nodes: line.passNodes }, LAYOUT_RATES[line.preset][engine]); + if (estimate > ms * 2 || estimate * 2 < ms) { + off.push(`${line.family} ${line.nodes} on ${engine}: ${ms} ms, estimated ${estimate} ms`); + } else { + held++; + } + } + } + // One small graph took the server twice its usual time, once. + expect(off).toEqual(['near 30 on elk-server: 114 ms, estimated 52 ms']); + expect(held).toBeGreaterThan(190); + }); + + it('holds the graphs of a real design, which the rates were not fitted to, within a factor of three', () => { + const checked = readFileSync(path.join(__dirname, 'fixtures/layout-rates/checked.jsonl'), 'utf8') + .split('\n') + .filter(Boolean) + .map(line => JSON.parse(line) as { file: string; preset: LayoutPreset; passNodes: number; cost: number; elkjsMs: number; serverMs: number }); + expect(checked).toHaveLength(7); + for (const line of checked) { + for (const [engine, ms] of [['elkjs', line.elkjsMs], ['elk-server', line.serverMs]] as const) { + const estimate = estimatePassMs({ cost: line.cost, nodes: line.passNodes }, LAYOUT_RATES[line.preset][engine]); + expect(estimate / ms, `${line.file} on ${engine}`).toBeGreaterThan(1 / 3); + expect(estimate / ms, `${line.file} on ${engine}`).toBeLessThan(3); + } + } + }); + + it('has a rate for every preset on both engines, and prices the server under elkjs for a large pass', () => { + const large = { cost: 20_000, nodes: 3_000 }; + for (const preset of ['default', 'middle', 'fast'] as const) { + const { elkjs, 'elk-server': server } = LAYOUT_RATES[preset]; + for (const rates of [elkjs, server]) { + expect(Object.values(rates).every(rate => rate >= 0)).toBe(true); + expect(estimatePassMs(large, rates)).toBeGreaterThan(0); + } + expect(estimatePassMs(large, server)).toBeLessThan(estimatePassMs(large, elkjs)); + } + }); + + it('is told in the unit a reader waits in', () => { + expect(formatLayoutMs(850)).toBe('850 ms'); + expect(formatLayoutMs(12_400)).toBe('12 s'); + expect(formatLayoutMs(89_000)).toBe('89 s'); + expect(formatLayoutMs(7 * 60_000)).toBe('7 min'); + expect(formatLayoutMs(3 * 3_600_000)).toBe('3 h'); + }); +}); diff --git a/packages/diagram-server/test/layout-rates.measure.test.ts b/packages/diagram-server/test/layout-rates.measure.test.ts new file mode 100644 index 00000000..014dcd29 --- /dev/null +++ b/packages/diagram-server/test/layout-rates.measure.test.ts @@ -0,0 +1,273 @@ +/** + * The measurement behind `LAYOUT_RATES` (`src/server/layout-cost.ts`): how + * long elkjs and the shipped ELK server take for graphs of each preset, next + * to what the estimate reads off them. + * + * It is no test of the suite: it runs for half an hour, and only when asked, + * + * DIALOGRAM_MEASURE_LAYOUT=/tmp/rates.jsonl npx vitest run test/layout-rates.measure.test.ts + * + * and writes one JSON line a graph: its family, its nodes and edges, the + * preset the platform chose, the cost the estimate reads, and the + * milliseconds on each engine. The rates are a least-squares fit of those + * lines, preset by preset (`scripts/fit-layout-rates.mjs`). The lines the + * rates in the code were fitted to are `fixtures/layout-rates/measured.jsonl`. + * `DIALOGRAM_MEASURE_PRESETS=untangled` measures the graphs of one preset + * alone. + * + * A graph is a dataflow network of `nodes` nodes, each reading `fanIn` earlier + * ones on average, no further back than `reach`: a short reach gives a long + * narrow graph of short edges, a long one a graph whose edges skip most of + * its layers. `shuffled` declares the nodes in another order than the flow, + * as a netlist does. Each is a document graph, laid out by the platform's own + * engine up to the call of ELK, so it carries the options, ports and sizes a + * product's diagram does. + * + * With `DIALOGRAM_MEASURE_DOCUMENTS=` as well, it measures the graph + * documents of that folder instead (`*.json`, as a producer exports them) and + * writes the estimate beside the time taken: the check of the rates on graphs + * they were not fitted to (`fixtures/layout-rates/checked.jsonl`). + */ +import 'reflect-metadata'; +import { appendFileSync, existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'; +import * as path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import ElkConstructor from 'elkjs/lib/elk.bundled.js'; +import type { ElkNode } from 'elkjs'; +import { DefaultElementFilter } from '@eclipse-glsp/layout-elk'; +import { layoutOnServer } from '../src/server/elk-server/elk-server-client'; +import { ElkServerProcess } from '../src/server/elk-server/elk-server-process'; +import { elkGraphSize } from '../src/server/elk-server/switching-elk'; +import { UNTANGLED_ELK_OPTIONS } from '../src/operations/layout-tuned-handler'; +import { GraphGModelSource } from '../src/model/graph-gmodel-source'; +import { convertToGModelRoot } from '../src/server/gmodel-convert'; +import { WorkflowElkLayoutEngine } from '../src/server/elk-layout-engine'; +import { WorkflowLayoutConfigurator } from '../src/server/layout-configurator'; +import { estimateElkLayout } from '../src/server/layout-cost'; +import { javaMajor } from './java-version'; + +const OUT = process.env.DIALOGRAM_MEASURE_LAYOUT; +const DOCUMENTS = process.env.DIALOGRAM_MEASURE_DOCUMENTS; +const JAR = path.resolve(__dirname, '../resources/elk-server/elk-server-0.3.0-all.jar'); +/** An engine that took this long on a family is not asked for a larger graph of it. */ +/** `DIALOGRAM_MEASURE_PRESETS=untangled,fast`: the presets to measure, when not all of them. */ +const PRESETS = process.env.DIALOGRAM_MEASURE_PRESETS?.split(',').filter(Boolean); +const GIVE_UP_MS = Number(process.env.DIALOGRAM_MEASURE_GIVE_UP_MS ?? 150_000); + +interface Shape { + nodes: number; + fanIn: number; + reach: number; + shuffled: boolean; +} + +/** A small deterministic generator (mulberry32). */ +function random(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** A graph document of this shape. */ +export function documentOf(shape: Shape, seed: number = 1): unknown { + const next = random(seed); + const sources: number[][] = []; + for (let node = 0; node < shape.nodes; node++) { + const wanted = Math.min(node, Math.floor(shape.fanIn) + (next() < shape.fanIn - Math.floor(shape.fanIn) ? 1 : 0)); + const read = new Set(); + for (let tries = 0; read.size < wanted && tries < wanted * 4; tries++) { + read.add(node - 1 - Math.floor(next() * Math.min(node, shape.reach))); + } + sources.push([...read]); + } + const declared = sources.map((_, node) => node); + if (shape.shuffled) { + for (let at = declared.length - 1; at > 0; at--) { + const other = Math.floor(next() * (at + 1)); + [declared[at], declared[other]] = [declared[other], declared[at]]; + } + } + const id = (node: number): string => `node:scope:root:n${node}`; + const nodes = declared.map(node => ({ + id: id(node), + kind: 'instance', + label: `n${node}`, + type: 'unit', + scope: 'scope:root', + meta: {}, + ports: [ + ...sources[node].map((_, at) => ({ direction: 'in', id: `port:${id(node)}:in:${at}`, name: `i${at}`, role: 'data' })), + { direction: 'out', id: `port:${id(node)}:out`, name: 'o', role: 'data' } + ] + })); + const edges = declared.flatMap(node => + sources[node].map((source, at) => ({ + id: `edge:${source}->${node}:${at}`, + from: `port:${id(source)}:out`, + fromNode: id(source), + to: `port:${id(node)}:in:${at}`, + toNode: id(node), + scope: 'scope:root', + meta: {} + })) + ); + return { + version: '1.0', + graph: { + id: 'wf:measure', + meta: {}, + nodes, + edges, + subgraphs: [ + { id: 'scope:root', kind: 'root', parent: null, controlNodeId: null, children: [], nodes: nodes.map(node => node.id), edges: edges.map(edge => edge.id) } + ] + } + }; +} + +/** The ELK graph the platform's layout engine asks a layout of, for a graph document. */ +export async function elkInputOf(document: unknown): Promise { + const root: any = convertToGModelRoot(new GraphGModelSource().transform(document as any) as any); + const byId = new Map(); + const index = (element: any): void => { + byId.set(element.id, element); + (element.children ?? []).forEach(index); + }; + index(root); + const modelState: any = { root, index: { get: (id: string) => byId.get(id), findByClass: (id: string) => byId.get(id) } }; + let captured: ElkNode | undefined; + const capturing = { + layout: (graph: ElkNode) => { + captured = JSON.parse(JSON.stringify(graph)); + return Promise.reject(new Error('captured')); + }, + terminateWorker: () => undefined + }; + const engine = new WorkflowElkLayoutEngine(() => capturing as any, new DefaultElementFilter(), new WorkflowLayoutConfigurator(), modelState); + await Promise.resolve(engine.layout()).catch(() => undefined); + if (!captured) { + throw new Error('the engine asked no layout of ELK'); + } + return captured; +} + +const copy = (graph: ElkNode): ElkNode => JSON.parse(JSON.stringify(graph)); + +async function timed(run: () => Promise): Promise { + const started = performance.now(); + await run(); + return Math.round(performance.now() - started); +} + +/** The shapes measured, smallest first within a family so that a family is dropped once it is too slow. */ +function shapes(): Array { + const sizes = [30, 60, 100, 150, 200, 300, 450, 700, 1000, 1300, 2000, 3500, 6000, 10000]; + const families: Array<{ family: string; fanIn: number; reach: (nodes: number) => number; shuffled: boolean }> = [ + { family: 'local', fanIn: 1.6, reach: () => 3, shuffled: false }, + { family: 'near', fanIn: 2.3, reach: () => 20, shuffled: false }, + { family: 'near-shuffled', fanIn: 2.3, reach: () => 20, shuffled: true }, + { family: 'mid', fanIn: 2.3, reach: nodes => Math.max(20, Math.round(nodes / 8)), shuffled: true }, + { family: 'far', fanIn: 2.3, reach: nodes => nodes, shuffled: false }, + { family: 'far-shuffled', fanIn: 2.6, reach: nodes => nodes, shuffled: true } + ]; + return families.flatMap(family => + sizes.map(nodes => ({ family: family.family, nodes, fanIn: family.fanIn, reach: family.reach(nodes), shuffled: family.shuffled })) + ); +} + +describe.skipIf(!OUT || !DOCUMENTS)('the estimate, on the graph documents of a folder', () => { + it('is set beside the time each engine takes', async () => { + const java = javaMajor() >= 17 && existsSync(JAR); + const server = java ? new ElkServerProcess({ jar: JAR, javaOpts: '-Xmx4g' }) : undefined; + const port = await server?.ensureStarted(); + writeFileSync(OUT!, ''); + try { + const warm = await elkInputOf(documentOf({ nodes: 300, fanIn: 2.3, reach: 20, shuffled: false })); + if (port !== undefined) { + await layoutOnServer(port, copy(warm), 120_000); + await layoutOnServer(port, copy(warm), 120_000); + } + await new (ElkConstructor as any)({ algorithms: ['layered'] }).layout(copy(warm)); + for (const file of readdirSync(DOCUMENTS!).filter(name => name.endsWith('.json')).sort()) { + const input = await elkInputOf(JSON.parse(readFileSync(path.join(DOCUMENTS!, file), 'utf8'))); + const size = elkGraphSize(input); + const estimate = estimateElkLayout(input); + const serverMs = port === undefined ? undefined : await timed(() => layoutOnServer(port, copy(input), GIVE_UP_MS)).catch(() => undefined); + const elkjs = new (ElkConstructor as any)({ algorithms: ['layered'] }); + const elkjsMs = await timed(() => elkjs.layout(copy(input))).catch(() => undefined); + const line = { file, nodes: size.nodes, edges: size.edges, preset: estimate.preset, passNodes: estimate.nodes, cost: estimate.cost, elkjsMs, elkjsEstimate: estimate.elkjsMs, serverMs, serverEstimate: estimate.serverMs }; + appendFileSync(OUT!, `${JSON.stringify(line)}\n`); + // eslint-disable-next-line no-console + console.log(JSON.stringify(line)); + } + } finally { + server?.dispose(); + } + expect(existsSync(OUT!)).toBe(true); + }, 3 * 3600_000); +}); + +describe.skipIf(!OUT || !!DOCUMENTS)('the pace of elkjs and of the ELK server, preset by preset', () => { + it('is measured', async () => { + const java = javaMajor() >= 17 && existsSync(JAR); + const server = java ? new ElkServerProcess({ jar: JAR, javaOpts: '-Xmx4g' }) : undefined; + const port = await server?.ensureStarted(); + writeFileSync(OUT!, ''); + const gaveUp = { elkjs: new Set(), server: new Set() }; + try { + // The JVM compiles what it runs often: one layout first, so the first line is no outlier. + const warm = await elkInputOf(documentOf({ nodes: 300, fanIn: 2.3, reach: 20, shuffled: false })); + if (port !== undefined) { + await layoutOnServer(port, copy(warm), 120_000); + await layoutOnServer(port, copy(warm), 120_000); + } + await new (ElkConstructor as any)({ algorithms: ['layered'] }).layout(copy(warm)); + const inputs = async function* (): AsyncGenerator<{ shape: Shape & { family: string }; input: ElkNode }> { + for (const shape of shapes()) { + const input = await elkInputOf(documentOf(shape)); + yield { shape, input }; + // A graph of the default preset is also laid out as Untangled + // and Free Ports lay it out: their options over the preset. + if (estimateElkLayout(input).preset === 'default') { + yield { shape, input: { ...input, layoutOptions: { ...input.layoutOptions, ...UNTANGLED_ELK_OPTIONS } } }; + } + } + }; + for await (const { shape, input } of inputs()) { + const size = elkGraphSize(input); + const estimate = estimateElkLayout(input); + if (PRESETS && !PRESETS.includes(estimate.preset)) { + continue; + } + const key = `${shape.family} ${estimate.preset}`; + let elkjsMs: number | undefined; + let serverMs: number | undefined; + if (port !== undefined && !gaveUp.server.has(key)) { + serverMs = await timed(() => layoutOnServer(port, copy(input), GIVE_UP_MS * 2)).catch(() => undefined); + if (serverMs === undefined || serverMs > GIVE_UP_MS) { + gaveUp.server.add(key); + } + } + if (!gaveUp.elkjs.has(key)) { + const elkjs = new (ElkConstructor as any)({ algorithms: ['layered'] }); + elkjsMs = await timed(() => elkjs.layout(copy(input))).catch(() => undefined); + if (elkjsMs === undefined || elkjsMs > GIVE_UP_MS) { + gaveUp.elkjs.add(key); + } + } + const line = { ...shape, edges: size.edges, elkNodes: size.nodes, preset: estimate.preset, passNodes: estimate.nodes, cost: estimate.cost, elkjsMs, serverMs }; + appendFileSync(OUT!, `${JSON.stringify(line)}\n`); + // eslint-disable-next-line no-console + console.log(JSON.stringify(line)); + } + } finally { + server?.dispose(); + } + expect(existsSync(OUT!)).toBe(true); + }, 3 * 3600_000); +}); diff --git a/scripts/fit-layout-rates.mjs b/scripts/fit-layout-rates.mjs new file mode 100644 index 00000000..77bd00c3 --- /dev/null +++ b/scripts/fit-layout-rates.mjs @@ -0,0 +1,120 @@ +#!/usr/bin/env node +/** + * Fit the rates of the layout estimate (`LAYOUT_RATES`, + * packages/diagram-server/src/server/layout-cost.ts) to a measurement. + * + * cd packages/diagram-server + * DIALOGRAM_MEASURE_LAYOUT=/tmp/rates.jsonl npx vitest run test/layout-rates.measure.test.ts + * node ../../scripts/fit-layout-rates.mjs /tmp/rates.jsonl + * + * For each preset and engine it fits + * + * ms = cost * msPerSpanUnit + cost² * msPerSpanUnitSquared + * + nodes * msPerNode + nodes² * msPerNodeSquared + * + * by least squares on the relative error, so that a graph of thirty nodes + * weighs as much as one of ten thousand: the estimate is asked whether a + * layout takes a tenth of a second or a minute, at every size. A rate is never + * negative. Of the fits that keep one to four of the terms, the one with the + * smallest error wins, and a term that buys less than a tenth of the error is + * left out. Lines under `--floor` milliseconds (default 20) are left out: + * that is the cost of asking, not of laying out. + * + * It prints the rates as the table of the source file, and for each fit the + * lines the estimate misses by more than a factor of two. + */ +import { readFileSync } from 'node:fs'; + +const args = process.argv.slice(2); +const floorAt = args.indexOf('--floor'); +const floor = floorAt >= 0 ? Number(args.splice(floorAt, 2)[1]) : 20; +if (args.length !== 1) { + console.error('usage: fit-layout-rates.mjs [--floor ]'); + process.exit(2); +} +const lines = readFileSync(args[0], 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line)); + +const TERMS = ['msPerSpanUnit', 'msPerSpanUnitSquared', 'msPerNode', 'msPerNodeSquared']; +const termsOf = line => [line.cost, line.cost * line.cost, line.passNodes, line.passNodes * line.passNodes]; + +/** Solve a small linear system by Gauss-Jordan; undefined when it is singular. */ +function solve(matrix, vector) { + const n = vector.length; + const a = matrix.map((row, i) => [...row, vector[i]]); + for (let col = 0; col < n; col++) { + let pivot = col; + for (let row = col + 1; row < n; row++) { + if (Math.abs(a[row][col]) > Math.abs(a[pivot][col])) { + pivot = row; + } + } + if (Math.abs(a[pivot][col]) < 1e-12) { + return undefined; + } + [a[col], a[pivot]] = [a[pivot], a[col]]; + for (let row = 0; row < n; row++) { + if (row !== col) { + const factor = a[row][col] / a[col][col]; + for (let k = col; k <= n; k++) { + a[row][k] -= factor * a[col][k]; + } + } + } + } + return a.map((row, i) => row[n] / row[i]); +} + +/** Least squares on the relative error over the terms of `kept`. */ +function fit(samples, kept) { + const rows = samples.map(({ terms, ms }) => kept.map(at => terms[at] / ms)); + const normal = kept.map((_, i) => kept.map((_, j) => rows.reduce((sum, row) => sum + row[i] * row[j], 0))); + const rhs = kept.map((_, i) => rows.reduce((sum, row) => sum + row[i], 0)); + const solved = solve(normal, rhs); + if (!solved || solved.some(rate => !(rate >= 0))) { + return undefined; + } + const rates = TERMS.map(() => 0); + kept.forEach((at, i) => (rates[at] = solved[i])); + const error = samples.reduce((sum, { terms, ms }) => { + const estimate = terms.reduce((total, term, at) => total + term * rates[at], 0); + return sum + ((estimate - ms) / ms) ** 2; + }, 0); + return { rates, error: Math.sqrt(error / samples.length), terms: kept.length }; +} + +/** Every choice of terms: the subsets of their places, but the empty one. */ +const SUBSETS = Array.from({ length: (1 << TERMS.length) - 1 }, (_, at) => TERMS.map((_, term) => term).filter(term => (at + 1) & (1 << term))); +const rounded = rate => (rate === 0 ? 0 : Number(rate.toPrecision(2))); + +const table = {}; +for (const preset of ['default', 'middle', 'fast', 'untangled']) { + for (const [engine, field] of [['elkjs', 'elkjsMs'], ['elk-server', 'serverMs']]) { + const samples = lines + .filter(line => line.preset === preset && typeof line[field] === 'number' && line[field] >= floor) + .map(line => ({ line, terms: termsOf(line), ms: line[field] })); + if (samples.length < 4) { + console.log(`# ${preset} ${engine}: ${samples.length} lines, not fitted`); + continue; + } + const fits = SUBSETS.map(kept => fit(samples, kept)).filter(Boolean); + // The fewest terms within a tenth of the best error. + const best = Math.min(...fits.map(candidate => candidate.error)); + const chosen = fits.filter(candidate => candidate.error <= best * 1.1).sort((a, b) => a.terms - b.terms || a.error - b.error)[0]; + const rates = chosen.rates.map(rounded); + (table[preset] ??= {})[engine] = rates; + const estimateOf = terms => Math.round(terms.reduce((total, term, at) => total + term * rates[at], 0)); + const misses = samples.filter(({ terms, ms }) => estimateOf(terms) > ms * 2 || estimateOf(terms) * 2 < ms); + console.log(`# ${preset} ${engine}: ${samples.length} lines, relative error ${chosen.error.toFixed(2)}, ${misses.length} off by more than a factor of two`); + for (const { line, terms, ms } of misses) { + console.log(`# ${line.family} ${line.nodes} nodes ${line.edges} edges cost ${line.cost}: measured ${ms} ms, estimated ${estimateOf(terms)} ms`); + } + } +} +for (const [preset, engines] of Object.entries(table)) { + console.log(` ${preset}: {`); + for (const [engine, rates] of Object.entries(engines)) { + const fields = TERMS.map((name, at) => `${name}: ${rates[at]}`).join(', '); + console.log(` ${engine === 'elkjs' ? 'elkjs' : `'${engine}'`}: { ${fields} },`); + } + console.log(' },'); +}