Files
pipelines/app/lib/features/graph/layout/graph_ranks.dart
T
alan c1f140bc78 feat(app): add deterministic content-sized graph node layout
Pure-Dart SCC ranking and column placement over the landed graph
identities. Every extent and gap is caller supplied; missing
measurements are rejected rather than defaulted.

Focused tests cover linear, diamond, cycle, self-loop, disconnected,
terminal, expanded-text and invalid-input cases.
2026-10-21 16:25:17 +01:00

192 lines
6.5 KiB
Dart

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<String, int> rankOf,
required this.rankCount,
required List<List<String>> components,
}) : rankOf = Map.unmodifiable(rankOf),
components = List.unmodifiable(<List<String>>[
for (final component in components) List.unmodifiable(component),
]);
/// Every definition key's rank, in definition order.
final Map<String, int> 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<List<String>> 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<GraphNode> nodes, List<GraphEdge> edges) {
final indexOf = <String, int>{};
for (var index = 0; index < nodes.length; index += 1) {
indexOf[nodes[index].key] = index;
}
final adjacency = List<List<int>>.generate(nodes.length, (_) => <int>[]);
final seenPairs = <int>{};
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<int>.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<Set<int>>.generate(components.length, (_) => <int>{});
final indegree = List<int>.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<int>.filled(components.length, 0);
final ready = ListQueue<int>();
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 = <List<String>>[
for (final component in components)
<String>[for (final node in component) nodes[node].key],
];
final componentOrder = <int>[
for (var component = 0; component < components.length; component += 1)
component,
]..sort((a, b) => components[a].first.compareTo(components[b].first));
final rankOf = <String, int>{};
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: <List<String>>[
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<List<int>> _components(List<List<int>> adjacency) {
final discovery = List<int>.filled(adjacency.length, -1);
final low = List<int>.filled(adjacency.length, 0);
final onStack = List<bool>.filled(adjacency.length, false);
final stack = <int>[];
final components = <List<int>>[];
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 = <int>[];
while (stack.isNotEmpty) {
final member = stack.removeLast();
onStack[member] = false;
component.add(member);
if (member == node) break;
}
component.sort();
components.add(component);
}
}
}
return components;
}