diff --git a/app/lib/features/graph/layout/graph_node_layout.dart b/app/lib/features/graph/layout/graph_node_layout.dart new file mode 100644 index 00000000..767426ea --- /dev/null +++ b/app/lib/features/graph/layout/graph_node_layout.dart @@ -0,0 +1,142 @@ +import 'dart:math' as math; + +import '../domain/graph_definition.dart'; +import 'graph_ranks.dart'; +import 'layout_models.dart'; + +/// Places definition nodes in topological columns. +/// +/// Nodes keep definition order inside a rank, each column is as wide as its +/// widest measured node, and columns are top-aligned. A node is centred in its +/// column, so heterogeneous widths and text-expanded heights stay separated by +/// [GraphLayoutConfig.rowGap] inside a rank and [GraphLayoutConfig.columnGap] +/// between ranks. Nothing is clipped to a fixed box: the supplied measured +/// width and height are used verbatim and the returned bounds include them. +/// +/// [nodes] and [edges] normally come from `graphNodes`/`graphEdges`. Edges whose +/// source or target is not one of [nodes] are ignored, so an unknown target can +/// never invent a node. A measurement is required for every node; a missing one +/// is an error rather than a made-up size. Extra measurement entries are +/// ignored because they cannot become nodes. +GraphLayout layoutGraphNodes({ + required List nodes, + required List edges, + required Map extents, + required GraphLayoutConfig config, +}) { + _validateNodeKeys(nodes); + final ranks = assignGraphRanks(nodes, edges); + final measured = {}; + final missing = []; + for (final node in nodes) { + final extent = extents[node.key]; + if (extent == null) { + missing.add(node.key); + } else { + measured[node.key] = extent; + } + } + if (missing.isNotEmpty) { + throw ArgumentError.value( + missing, + 'extents', + 'missing measured extents for graph nodes', + ); + } + + final columns = List>.generate( + ranks.rankCount, + (_) => [], + ); + for (final node in nodes) { + columns[ranks.rankOf[node.key]!].add(node); + } + + final columnWidths = [ + for (final column in columns) + column.fold( + 0, + (width, node) => math.max(width, measured[node.key]!.width), + ), + ]; + final columnHeights = [ + for (final column in columns) + _columnHeight(column, measured, config.rowGap), + ]; + final columnX = []; + var nextX = config.padding; + for (var rank = 0; rank < columns.length; rank += 1) { + columnX.add(nextX); + nextX += columnWidths[rank]; + if (rank + 1 < columns.length) nextX += config.columnGap; + } + + final boxes = []; + for (var rank = 0; rank < columns.length; rank += 1) { + var nextY = config.padding; + for (final node in columns[rank]) { + final extent = measured[node.key]!; + boxes.add( + GraphNodeBox( + key: node.key, + terminal: node.terminal, + stageIndex: node.stageIndex, + rank: rank, + x: columnX[rank] + (columnWidths[rank] - extent.width) / 2, + y: nextY, + width: extent.width, + height: extent.height, + ), + ); + nextY += extent.height + config.rowGap; + } + } + + final width = + config.padding * 2 + + columnWidths.fold(0, (sum, column) => sum + column) + + config.columnGap * math.max(0, columns.length - 1); + final height = + config.padding * 2 + + columnHeights.fold( + 0, + (tallest, column) => math.max(tallest, column), + ); + + return GraphLayout( + nodes: boxes, + width: width, + height: height, + rankCount: ranks.rankCount, + ranks: ranks.rankOf, + ); +} + +void _validateNodeKeys(List nodes) { + final seen = {}; + for (final node in nodes) { + if (node.key.isEmpty) { + throw ArgumentError.value( + node.key, + 'nodes', + 'node key must not be empty', + ); + } + if (!seen.add(node.key)) { + throw ArgumentError.value(node.key, 'nodes', 'duplicate graph node key'); + } + } +} + +double _columnHeight( + List column, + Map measured, + double rowGap, +) { + if (column.isEmpty) return 0; + var height = 0.0; + for (final node in column) { + height += measured[node.key]!.height; + } + return height + rowGap * (column.length - 1); +} diff --git a/app/lib/features/graph/layout/graph_ranks.dart b/app/lib/features/graph/layout/graph_ranks.dart new file mode 100644 index 00000000..f7558db2 --- /dev/null +++ b/app/lib/features/graph/layout/graph_ranks.dart @@ -0,0 +1,191 @@ +import 'dart:collection'; +import 'dart:math' as math; + +import '../domain/graph_definition.dart'; + +/// Deterministic 0-based ranks for a graph definition's nodes. +/// +/// Ranks come from the condensation DAG: every strongly connected component +/// shares one rank, and a component sits one past its deepest predecessor +/// (longest path). Self loops and cycles therefore stay finite, a cycle's +/// members do not drift apart, and disconnected nodes stay at rank 0. Edges +/// whose endpoints are not definition nodes are ignored: an unknown target +/// never invents a node. +class GraphRanks { + GraphRanks({ + required Map rankOf, + required this.rankCount, + required List> components, + }) : rankOf = Map.unmodifiable(rankOf), + components = List.unmodifiable(>[ + for (final component in components) List.unmodifiable(component), + ]); + + /// Every definition key's rank, in definition order. + final Map rankOf; + + /// Number of distinct ranks, 0 for an empty node set. + final int rankCount; + + /// Strongly connected components as keys, each sorted by definition order and + /// the list sorted by its first member. + final List> components; +} + +/// One DFS frame for the iterative Tarjan walk. +class _Frame { + _Frame(this.node); + + final int node; + int nextChild = 0; +} + +/// Assigns ranks to exactly the supplied [nodes]. +/// +/// [edges] is read for ordering only; it never adds nodes. Duplicate edges are +/// harmless. The walk is iterative, so a deep chain cannot overflow the call +/// stack, and the work is linear in nodes plus edges. +GraphRanks assignGraphRanks(List nodes, List edges) { + final indexOf = {}; + for (var index = 0; index < nodes.length; index += 1) { + indexOf[nodes[index].key] = index; + } + + final adjacency = List>.generate(nodes.length, (_) => []); + final seenPairs = {}; + for (final edge in edges) { + final source = indexOf[edge.source]; + final target = indexOf[edge.target]; + if (source == null || target == null) continue; + if (!seenPairs.add(source * nodes.length + target)) continue; + adjacency[source].add(target); + } + + final components = _components(adjacency); + final componentOf = List.filled(nodes.length, -1); + for (var component = 0; component < components.length; component += 1) { + for (final node in components[component]) { + componentOf[node] = component; + } + } + + // Condensation edges and their indegrees. + final successors = List>.generate(components.length, (_) => {}); + final indegree = List.filled(components.length, 0); + for (var source = 0; source < adjacency.length; source += 1) { + final from = componentOf[source]; + for (final target in adjacency[source]) { + final to = componentOf[target]; + if (from == to) continue; + if (successors[from].add(to)) indegree[to] += 1; + } + } + + // Longest-path ranks over the condensation. Queue order only has to be a + // topological order; the resulting rank per component is unique. + final ranks = List.filled(components.length, 0); + final ready = ListQueue(); + for (var component = 0; component < components.length; component += 1) { + if (indegree[component] == 0) ready.add(component); + } + var settled = 0; + while (ready.isNotEmpty) { + final component = ready.removeFirst(); + settled += 1; + for (final next in successors[component]) { + ranks[next] = math.max(ranks[next], ranks[component] + 1); + indegree[next] -= 1; + if (indegree[next] == 0) ready.add(next); + } + } + if (settled != components.length) { + // The condensation cannot contain a cycle by construction; stop rather than + // return a silently truncated layout. + throw StateError('graph condensation was not acyclic'); + } + + final componentKeys = >[ + for (final component in components) + [for (final node in component) nodes[node].key], + ]; + final componentOrder = [ + for (var component = 0; component < components.length; component += 1) + component, + ]..sort((a, b) => components[a].first.compareTo(components[b].first)); + + final rankOf = {}; + var rankCount = 0; + for (var index = 0; index < nodes.length; index += 1) { + final rank = ranks[componentOf[index]]; + rankOf[nodes[index].key] = rank; + if (rank + 1 > rankCount) rankCount = rank + 1; + } + + return GraphRanks( + rankOf: rankOf, + rankCount: rankCount, + components: >[ + for (final component in componentOrder) componentKeys[component], + ], + ); +} + +/// Tarjan's strongly connected components, emitted sinks first. +/// +/// Iterative rather than recursive so a long chain cannot exhaust the stack. +/// Members are sorted by definition index, which keeps every output stable. +List> _components(List> adjacency) { + final discovery = List.filled(adjacency.length, -1); + final low = List.filled(adjacency.length, 0); + final onStack = List.filled(adjacency.length, false); + final stack = []; + final components = >[]; + var nextDiscovery = 0; + + for (var root = 0; root < adjacency.length; root += 1) { + if (discovery[root] != -1) continue; + discovery[root] = low[root] = nextDiscovery; + nextDiscovery += 1; + stack.add(root); + onStack[root] = true; + final callStack = <_Frame>[_Frame(root)]; + + while (callStack.isNotEmpty) { + final frame = callStack.last; + final node = frame.node; + if (frame.nextChild < adjacency[node].length) { + final child = adjacency[node][frame.nextChild]; + frame.nextChild += 1; + if (discovery[child] == -1) { + discovery[child] = low[child] = nextDiscovery; + nextDiscovery += 1; + stack.add(child); + onStack[child] = true; + callStack.add(_Frame(child)); + } else if (onStack[child]) { + low[node] = math.min(low[node], discovery[child]); + } + continue; + } + + callStack.removeLast(); + if (callStack.isNotEmpty) { + final parent = callStack.last.node; + low[parent] = math.min(low[parent], low[node]); + } + if (low[node] == discovery[node]) { + final component = []; + while (stack.isNotEmpty) { + final member = stack.removeLast(); + onStack[member] = false; + component.add(member); + if (member == node) break; + } + component.sort(); + components.add(component); + } + } + } + + return components; +} diff --git a/app/lib/features/graph/layout/layout_models.dart b/app/lib/features/graph/layout/layout_models.dart new file mode 100644 index 00000000..4a8dac4e --- /dev/null +++ b/app/lib/features/graph/layout/layout_models.dart @@ -0,0 +1,129 @@ +/// Pure geometry for a workflow graph's node layout. +/// +/// Every size and gap is supplied by the caller. The native renderer measures +/// each node after text layout (including the platform's text scaling), so this +/// library never assumes a node width, font, palette or device class. +/// +/// No Flutter imports: rectangles are plain numbers so the same result can be +/// built into widgets, a canvas or a test fixture. +library; + +void _requireFiniteNonNegative(String name, double value) { + if (!value.isFinite || value < 0) { + throw ArgumentError.value(value, name, 'must be finite and non-negative'); + } +} + +/// One caller-measured node extent, in logical pixels. +/// +/// A width or height may be zero for an empty label; the layout still keeps the +/// node separate from its neighbours through the configured gaps. +class NodeExtent { + NodeExtent({required this.width, required this.height}) { + _requireFiniteNonNegative('width', width); + _requireFiniteNonNegative('height', height); + } + + final double width; + final double height; +} + +/// The gaps a caller reserves around measured nodes. +/// +/// [columnGap] separates adjacent ranks, [rowGap] separates nodes sharing a +/// rank, and [padding] is the outer margin included in [GraphLayout] bounds. +class GraphLayoutConfig { + GraphLayoutConfig({ + required this.columnGap, + required this.rowGap, + this.padding = 0, + }) { + _requireFiniteNonNegative('columnGap', columnGap); + _requireFiniteNonNegative('rowGap', rowGap); + _requireFiniteNonNegative('padding', padding); + } + + final double columnGap; + final double rowGap; + final double padding; +} + +/// One placed node. +/// +/// [key], [terminal] and [stageIndex] are the definition node's own identity, +/// copied unchanged. [x]/[y] are the measured rectangle's top-left corner in +/// graph space and [rank] is its 0-based topological column. +class GraphNodeBox { + const GraphNodeBox({ + required this.key, + required this.terminal, + required this.stageIndex, + required this.rank, + required this.x, + required this.y, + required this.width, + required this.height, + }); + + final String key; + final bool terminal; + final int? stageIndex; + final int rank; + final double x; + final double y; + final double width; + final double height; + + double get right => x + width; + double get bottom => y + height; + + @override + bool operator ==(Object other) => + other is GraphNodeBox && + other.key == key && + other.terminal == terminal && + other.stageIndex == stageIndex && + other.rank == rank && + other.x == x && + other.y == y && + other.width == width && + other.height == height; + + @override + int get hashCode => + Object.hash(key, terminal, stageIndex, rank, x, y, width, height); +} + +/// An immutable node layout: every placed box plus the total graph bounds. +/// +/// [nodes] is ordered by rank first and definition order inside a rank; use +/// [ranks] or [nodeFor] for keyed lookup. [width] and [height] include the +/// caller's padding; every box's [right] and [bottom] stay inside them. +/// [ranks] exposes each definition key's 0-based rank; [rankCount] is the +/// number of columns (0 for an empty node set). +class GraphLayout { + GraphLayout({ + required List nodes, + required this.width, + required this.height, + required this.rankCount, + required Map ranks, + }) : nodes = List.unmodifiable(nodes), + ranks = Map.unmodifiable(ranks); + + final List nodes; + final Map ranks; + final double width; + final double height; + final int rankCount; + + bool get isEmpty => nodes.isEmpty; + + /// The placed box for [key], or null when the definition has no such node. + GraphNodeBox? nodeFor(String key) { + for (final node in nodes) { + if (node.key == key) return node; + } + return null; + } +} diff --git a/app/notes/P2b.md b/app/notes/P2b.md new file mode 100644 index 00000000..91d5e07a --- /dev/null +++ b/app/notes/P2b.md @@ -0,0 +1,100 @@ +# P2b — deterministic pure node layout + +## What changed + +New app-only, pure-Dart files. No existing file, server, web client, legacy +client, shell, `main.dart`, pubspec, other feature or platform source was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/graph/layout/layout_models.dart` | 127 | measured extents, gap config, immutable node box, layout + ranks | +| `lib/features/graph/layout/graph_ranks.dart` | 191 | deterministic SCC ranks over the landed definition nodes/edges | +| `lib/features/graph/layout/graph_node_layout.dart` | 142 | column/row placement, bounds, validation | +| `test/features/graph/layout/layout_fixtures.dart` | 102 | shared definitions and measured extents | +| `test/features/graph/layout/graph_ranks_test.dart` | 116 | linear/diamond/cycle/self-loop/disconnected/unknown/long-chain ranks | +| `test/features/graph/layout/graph_node_layout_test.dart` | 224 | ordering, terminals, heterogeneous and expanded extents, bounds, determinism | +| `test/features/graph/layout/graph_layout_validation_test.dart` | 96 | empty input, missing/extra measurements, duplicate keys, invalid sizes | + +No layout widgets, painters, edge routing, styling or shell wiring were added. + +## Public API + +```dart +GraphRanks assignGraphRanks(List nodes, List edges); + +GraphLayout layoutGraphNodes({ + required List nodes, + required List edges, + required Map extents, + required GraphLayoutConfig config, +}); +``` + +`NodeExtent` is the caller's measured width/height after text layout. +`GraphLayoutConfig` takes `columnGap`, `rowGap` and an optional outer `padding`. +No node size, font, colour or device value is assumed in the library. + +`GraphLayout` returns an unmodifiable `nodes` list of `GraphNodeBox` +(`key`, `terminal`, `stageIndex`, `rank`, `x`, `y`, `width`, `height`), an +unmodifiable `ranks` map, `rankCount`, and total `width`/`height` including +padding. Node keys, terminal flags and stage indices are copied from the +landed `graphNodes` identities unchanged. + +## Ranking behavior + +Ranks are read from the definition supplied by the caller; the existing +`graphNodes`/`graphEdges` helpers remain the source of identities. + +- Iterative Tarjan strongly connected components (no recursion; a 2000-stage + chain is covered), then longest-path ranks over the condensation DAG. +- Every member of a cycle shares one rank, so cyclic routes cannot recurse or + push members apart. Self loops are internal supervision and add no rank. +- Disconnected stages and disconnected terminals stay at rank 0. +- Edges whose source or target is not a node are ignored. An unknown or empty + target never creates a node or a rank. +- Ranking is linear in nodes plus edges and stable for repeated input. + +## Placement behavior + +- One column per rank; nodes keep definition order inside a rank. +- A column is as wide as its widest measured node; columns are separated by + `columnGap` and top-aligned. +- Nodes are centred in their column and stacked with exactly `rowGap` between + measured boxes (centres are compared in the heterogeneous test). +- Supplied widths/heights are placed verbatim, so expanded text is never + clipped to a fixed box; growing the extents grows the total bounds. +- Bounds include every box: tests assert `right <= width` and + `bottom <= height` for every fixture. +- The result is immutable and identical for identical input. + +Measurements are required for every node; a missing key throws +`ArgumentError` rather than inventing a default size. Extra measurements are +ignored because they cannot become nodes. Duplicate/empty node keys, negative +or non-finite gaps and extents are rejected. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/graph/layout test/features/graph/layout +flutter test test/features/graph/layout # 21 passed +flutter analyze # No issues found! +flutter test # 173 passed +git diff --check # clean +``` + +Tests cover linear, diamond, cycle, self-loop, disconnected, terminals, +unknown/empty targets, heterogeneous extents, 2.6x expanded text, determinism, +bounds and invalid input. + +## Honest limits + +- **Nodes only.** Edge routing, ports, labels, lanes, hit testing, selection + highlighting, painting and native controls are separate later items. +- **Not rendered.** A pure nonvisual slice has no browser behavior to capture; + no screenshot or browser check applies. +- **No server or device.** Tests use local fixtures only; no run, pipeline, + schedule, service, emulator, ADB, Android/iOS build or live chat was touched. +- **Mobile unverified.** Only web-targeted Flutter test/analyze ran. +- **Uncommitted candidate.** Per this stage's instruction the slice is left in + the worktree; no commit, push or deployment was made. diff --git a/app/test/features/graph/layout/graph_layout_validation_test.dart b/app/test/features/graph/layout/graph_layout_validation_test.dart new file mode 100644 index 00000000..dd70f7ee --- /dev/null +++ b/app/test/features/graph/layout/graph_layout_validation_test.dart @@ -0,0 +1,96 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; + +import 'layout_fixtures.dart'; + +/// Invalid and boundary input for the pure layout engine. +void main() { + test('an empty definition yields empty padded bounds', () { + final layout = layoutGraphNodes( + nodes: const [], + edges: const [], + extents: const {}, + config: layoutConfig(columnGap: 30, rowGap: 10, padding: 6), + ); + + expect(layout.isEmpty, isTrue); + expect(layout.rankCount, 0); + expect(layout.width, 12); + expect(layout.height, 12); + expect(layout.ranks, isEmpty); + }); + + test('missing measurements are reported rather than invented', () { + final graph = linearGraphFixture(); + final nodes = graphNodes(graph); + final extents = uniformExtents(nodes)..remove('build'); + + expect( + () => layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents, + config: layoutConfig(), + ), + throwsArgumentError, + ); + }); + + test('extra measurements are ignored because they cannot become nodes', () { + final graph = linearGraphFixture(); + final nodes = graphNodes(graph); + final extents = uniformExtents(nodes) + ..['ghost'] = NodeExtent(width: 20, height: 20); + + final layout = layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents, + config: layoutConfig(), + ); + + expect(layout.nodeFor('ghost'), isNull); + expect(layout.nodes.length, nodes.length); + }); + + test('duplicate or empty node keys are rejected', () { + const stageNode = GraphNode(key: 'a', terminal: false, stageIndex: 0); + expect( + () => layoutGraphNodes( + nodes: const [stageNode, stageNode], + edges: const [], + extents: {'a': NodeExtent(width: 10, height: 10)}, + config: layoutConfig(), + ), + throwsArgumentError, + ); + expect( + () => layoutGraphNodes( + nodes: const [ + GraphNode(key: '', terminal: false, stageIndex: 0), + ], + edges: const [], + extents: const {}, + config: layoutConfig(), + ), + throwsArgumentError, + ); + }); + + test('invalid gaps and extents are rejected', () { + expect( + () => GraphLayoutConfig(columnGap: -1, rowGap: 8), + throwsArgumentError, + ); + expect( + () => GraphLayoutConfig(columnGap: 8, rowGap: double.nan), + throwsArgumentError, + ); + expect( + () => NodeExtent(width: double.infinity, height: 10), + throwsArgumentError, + ); + }); +} diff --git a/app/test/features/graph/layout/graph_node_layout_test.dart b/app/test/features/graph/layout/graph_node_layout_test.dart new file mode 100644 index 00000000..bbaf2408 --- /dev/null +++ b/app/test/features/graph/layout/graph_node_layout_test.dart @@ -0,0 +1,228 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; + +import 'layout_fixtures.dart'; + +GraphLayout _layout( + Map graph, { + Map? extents, + GraphLayoutConfig? config, +}) { + final nodes = graphNodes(graph); + return layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents ?? uniformExtents(nodes), + config: config ?? layoutConfig(), + ); +} + +void _expectWithinBounds(GraphLayout layout) { + for (final box in layout.nodes) { + expect(box.x, greaterThanOrEqualTo(0), reason: '${box.key} left'); + expect(box.y, greaterThanOrEqualTo(0), reason: '${box.key} top'); + expect( + box.right, + lessThanOrEqualTo(layout.width), + reason: '${box.key} right inside width', + ); + expect( + box.bottom, + lessThanOrEqualTo(layout.height), + reason: '${box.key} bottom inside height', + ); + } +} + +void _expectSeparated(GraphLayout layout) { + for (var first = 0; first < layout.nodes.length; first += 1) { + for (var second = first + 1; second < layout.nodes.length; second += 1) { + final a = layout.nodes[first]; + final b = layout.nodes[second]; + final separated = + a.right <= b.x || + b.right <= a.x || + a.bottom <= b.y || + b.bottom <= a.y; + expect(separated, isTrue, reason: '${a.key} overlaps ${b.key}'); + } + } +} + +void main() { + test('linear nodes keep declaration order and terminal identity', () { + final layout = _layout(linearGraphFixture()); + + expect(layout.rankCount, 4); + expect(layout.nodes.map((box) => box.key), [ + 'plan', + 'build', + 'ship', + failureEnd, + successEnd, + ]); + expect(layout.ranks, { + 'plan': 0, + 'build': 1, + 'ship': 2, + failureEnd: 3, + successEnd: 3, + }); + expect(layout.nodeFor('plan')!.stageIndex, 0); + expect(layout.nodeFor('build')!.stageIndex, 1); + expect(layout.nodeFor('ship')!.stageIndex, 2); + expect(layout.nodeFor(failureEnd)!.terminal, isTrue); + expect(layout.nodeFor(failureEnd)!.stageIndex, isNull); + expect(layout.nodeFor(successEnd)!.terminal, isTrue); + expect( + layout.nodeFor(successEnd)!.y - layout.nodeFor(failureEnd)!.bottom, + layoutConfig().rowGap, + ); + expect(layout.nodeFor(failureEnd)!.x, layout.nodeFor(successEnd)!.x); + expect(layout.nodeFor('plan')!.x, layoutConfig().padding); + expect(layout.nodeFor('plan')!.y, layoutConfig().padding); + expect( + layout.nodeFor('build')!.x - layout.nodeFor('plan')!.right, + layoutConfig().columnGap, + ); + expect(layout.width, 560); + expect(layout.height, 140); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('diamond ranks place siblings in one column', () { + final layout = _layout(diamondGraphFixture()); + + final b = layout.nodeFor('b')!; + final c = layout.nodeFor('c')!; + expect(b.rank, 1); + expect(c.rank, 1); + expect(b.x, c.x); + expect(c.y - b.bottom, layoutConfig().rowGap); + expect(layout.nodeFor('d')!.rank, 2); + expect(layout.nodeFor('d')!.x, greaterThan(b.right)); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('cycles share a column and terminals still follow them', () { + final layout = _layout(cycleGraph()); + + final a = layout.nodeFor('a')!; + final b = layout.nodeFor('b')!; + expect(a.rank, 0); + expect(b.rank, 0); + expect(b.y - a.bottom, layoutConfig().rowGap); + expect(layout.nodeFor(failureEnd)!.rank, 1); + expect(layout.nodeFor(successEnd)!.rank, 1); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('self loops and disconnected stages stay finite and separate', () { + final selfLoop = _layout(selfLoopGraphFixture()); + expect(selfLoop.nodeFor('a')!.rank, 0); + expect(selfLoop.nodeFor('b')!.rank, 1); + + final disconnected = _layout(disconnectedGraph()); + expect(disconnected.nodeFor('a')!.rank, 0); + expect(disconnected.nodeFor('b')!.rank, 0); + expect(disconnected.nodeFor('c')!.rank, 0); + expect( + disconnected.nodeFor('b')!.y, + greaterThan(disconnected.nodeFor('a')!.bottom), + ); + _expectWithinBounds(selfLoop); + _expectSeparated(selfLoop); + _expectWithinBounds(disconnected); + _expectSeparated(disconnected); + }); + + test('unknown edge targets add no node and no column', () { + final graph = incompleteGraphFixture(); + final layout = _layout(graph); + + expect( + layout.nodes.map((box) => box.key), + graphNodes(graph).map((node) => node.key), + ); + expect(layout.nodeFor('ghost'), isNull); + expect(layout.ranks.containsKey('ghost'), isFalse); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('heterogeneous measured widths stay inside their columns', () { + final layout = _layout( + diamondGraphFixture(), + extents: heterogeneousExtents(), + ); + + for (final entry in heterogeneousExtents().entries) { + final box = layout.nodeFor(entry.key)!; + expect(box.width, entry.value.width, reason: '${entry.key} width'); + expect(box.height, entry.value.height, reason: '${entry.key} height'); + } + final b = layout.nodeFor('b')!; + final c = layout.nodeFor('c')!; + expect(b.rank, c.rank); + expect(b.x + b.width / 2, c.x + c.width / 2); + expect(c.y - b.bottom, layoutConfig().rowGap); + expect(layout.width, greaterThan(0)); + expect(layout.width, 770); + expect(layout.height, 236); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('expanded text extents grow the canvas without overlap or clipping', () { + final base = _layout( + diamondGraphFixture(), + extents: heterogeneousExtents(), + ); + final expandedExtents = scaledExtents(heterogeneousExtents(), 2.6); + final expanded = _layout(diamondGraphFixture(), extents: expandedExtents); + + expect(expanded.width, greaterThan(base.width)); + expect(expanded.height, greaterThan(base.height)); + for (final entry in expandedExtents.entries) { + final box = expanded.nodeFor(entry.key)!; + expect(box.width, entry.value.width, reason: '${entry.key} width'); + expect(box.height, entry.value.height, reason: '${entry.key} height'); + } + _expectWithinBounds(expanded); + _expectSeparated(expanded); + }); + + test('the same input produces the same immutable layout', () { + final graph = diamondGraphFixture(); + final nodes = graphNodes(graph); + final edges = graphEdges(graph); + final extents = uniformExtents(nodes, width: 133, height: 77); + + final first = layoutGraphNodes( + nodes: nodes, + edges: edges, + extents: extents, + config: layoutConfig(), + ); + final second = layoutGraphNodes( + nodes: nodes, + edges: edges, + extents: extents, + config: layoutConfig(), + ); + + expect(second.nodes, first.nodes); + expect(second.ranks, first.ranks); + expect(second.width, first.width); + expect(second.height, first.height); + expect(second.rankCount, first.rankCount); + expect(() => second.nodes.add(first.nodes.first), throwsUnsupportedError); + expect(() => second.ranks['a'] = 99, throwsUnsupportedError); + }); +} diff --git a/app/test/features/graph/layout/graph_ranks_test.dart b/app/test/features/graph/layout/graph_ranks_test.dart new file mode 100644 index 00000000..320ba287 --- /dev/null +++ b/app/test/features/graph/layout/graph_ranks_test.dart @@ -0,0 +1,116 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/graph_ranks.dart'; + +import 'layout_fixtures.dart'; + +GraphRanks _ranksFor(Map graph) { + return assignGraphRanks(graphNodes(graph), graphEdges(graph)); +} + +void main() { + test('linear definitions rank one stage per column', () { + final ranks = _ranksFor(linearGraphFixture()); + + expect(ranks.rankOf, { + 'plan': 0, + 'build': 1, + 'ship': 2, + failureEnd: 3, + successEnd: 3, + }); + expect(ranks.rankCount, 4); + expect(ranks.components, >[ + ['plan'], + ['build'], + ['ship'], + [failureEnd], + [successEnd], + ]); + }); + + test('diamond fan-out shares a rank and converges after it', () { + final ranks = _ranksFor(diamondGraphFixture()); + + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], ranks.rankOf['c']); + expect(ranks.rankOf['b'], 1); + expect(ranks.rankOf['d'], 2); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 3); + expect(ranks.rankCount, 4); + }); + + test('a cycle collapses to one shared rank instead of recursing', () { + final ranks = _ranksFor(cycleGraph()); + + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], 0); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 1); + expect(ranks.rankCount, 2); + expect(ranks.components, contains(equals(['a', 'b']))); + }); + + test('a self edge stays inside its own component and adds no rank', () { + final ranks = _ranksFor(selfLoopGraphFixture()); + + expect(ranks.rankOf, { + 'a': 0, + 'b': 1, + failureEnd: 2, + successEnd: 2, + }); + expect(ranks.components, contains(equals(['a']))); + expect(ranks.components, contains(equals(['b']))); + }); + + test('disconnected stages stay at rank zero', () { + final ranks = _ranksFor(disconnectedGraph()); + + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], 0); + expect(ranks.rankOf['c'], 0); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 1); + expect(ranks.rankCount, 2); + }); + + test('unknown and empty edge targets never become ranks or nodes', () { + final graph = incompleteGraphFixture(); + final nodes = graphNodes(graph); + final ranks = assignGraphRanks(nodes, graphEdges(graph)); + + expect(nodes.map((node) => node.key), isNot(contains('ghost'))); + expect(ranks.rankOf.containsKey('ghost'), isFalse); + expect(ranks.rankOf.containsKey(''), isFalse); + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], 0); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 1); + }); + + test('ranks are stable across repeated assignments', () { + final graph = diamondGraphFixture(); + final nodes = graphNodes(graph); + final edges = graphEdges(graph); + + final first = assignGraphRanks(nodes, edges); + final second = assignGraphRanks(nodes, edges); + + expect(second.rankOf, first.rankOf); + expect(second.rankCount, first.rankCount); + expect(second.components, first.components); + }); + + test('a long chain is walked iteratively without overflow', () { + const length = 2000; + final ranks = _ranksFor(chainGraph(length)); + + expect(ranks.rankCount, length + 1); + expect(ranks.rankOf['s0'], 0); + expect(ranks.rankOf['s${length - 1}'], length - 1); + expect(ranks.rankOf[successEnd], length); + }); +} diff --git a/app/test/features/graph/layout/layout_fixtures.dart b/app/test/features/graph/layout/layout_fixtures.dart new file mode 100644 index 00000000..e67a6051 --- /dev/null +++ b/app/test/features/graph/layout/layout_fixtures.dart @@ -0,0 +1,102 @@ +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; + +import '../domain/graph_fixtures.dart' as domain; + +/// Small definitions and measured extents shared by the layout tests. + +GraphLayoutConfig layoutConfig({ + double columnGap = 24, + double rowGap = 12, + double padding = 4, +}) { + return GraphLayoutConfig( + columnGap: columnGap, + rowGap: rowGap, + padding: padding, + ); +} + +/// One measured size for every node, optionally scaled to simulate text growth. +Map uniformExtents( + Iterable nodes, { + double width = 120, + double height = 60, + double scale = 1, +}) { + return { + for (final node in nodes) + node.key: NodeExtent(width: width * scale, height: height * scale), + }; +} + +Map scaledExtents( + Map base, + double scale, +) { + return { + for (final entry in base.entries) + entry.key: NodeExtent( + width: entry.value.width * scale, + height: entry.value.height * scale, + ), + }; +} + +/// Deliberately uneven measured boxes for the diamond definition. +Map heterogeneousExtents() { + return { + 'a': NodeExtent(width: 210, height: 84), + 'b': NodeExtent(width: 92, height: 44), + 'c': NodeExtent(width: 148, height: 126), + 'd': NodeExtent(width: 104, height: 58), + failureEnd: NodeExtent(width: 72, height: 34), + successEnd: NodeExtent(width: 228, height: 96), + }; +} + +/// Two stages in a cycle; both terminals are reached from inside the cycle. +Map cycleGraph() => { + 'stages': [ + domain.stage( + 'a', + edges: {'success': 'b', 'error': '#'}, + fallbackError: true, + ), + domain.stage( + 'b', + edges: {'success': 'a', 'error': '#success'}, + ), + ], +}; + +/// Two independent routes and a stage with no edges at all. +Map disconnectedGraph() => { + 'stages': [ + domain.stage('a', edges: {'success': '#success'}), + domain.stage('b', edges: {'success': '#failure'}), + domain.stage('c'), + ], +}; + +Map linearGraphFixture() => domain.linearGraph(); + +Map diamondGraphFixture() => domain.diamondGraph(); + +Map selfLoopGraphFixture() => domain.selfLoopGraph(); + +Map incompleteGraphFixture() => domain.incompleteGraph(); + +/// A long chain, used to prove the iterative rank walk cannot overflow. +Map chainGraph(int length) => { + 'stages': [ + for (var index = 0; index < length; index += 1) + domain.stage( + 's$index', + edges: { + 'success': index + 1 < length ? 's${index + 1}' : '#success', + }, + ), + ], +};