Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
perf(ui): lay out the system map on one placement edge per card pair (#4627)
Raghav Chamadiya903aed5838c5
diff --git a/packages/ui/__tests__/workspace/system-map-level-layout.test.ts b/packages/ui/__tests__/workspace/system-map-level-layout.test.tsindex 64bf9d99e..5c0cb7fdf 100644--- a/packages/ui/__tests__/workspace/system-map-level-layout.test.ts+++ b/packages/ui/__tests__/workspace/system-map-level-layout.test.ts@@ -8,10 +8,13 @@ import {LEVEL_NODE_SIZES,ROOT_SCOPE,fitContainer,+ PLACEMENT_EDGES_PER_CARD,orderByPrevious,+ placementEdges,planLevelLayout,planSignature,} from "../../src/workspace/system-map/layout-scopes";+import { makeSyntheticSystemGraph } from "./fixtures/synthetic-system-graph";import {computeLevelLayout,createLayoutCache,@@ -104,6 +107,46 @@ describe("planLevelLayout", () => {});});+describe("placementEdges", () => {+ const w = (source: string, target: string, links: number) => [`${source}>${target}`, { source, target, links }] as const;++ it("keeps one edge per card pair, pointing the way most links go", () => {+ const edges = placementEdges(new Map([w("a", "b", 2), w("b", "a", 5), w("a", "c", 1)]), 3);+ expect(edges.map((e) => e.id)).toEqual(["a>c", "b>a"]);+ });++ it("keeps the strongest pairs, two per card, whatever order the weights came in", () => {+ const pairs = [w("a", "b", 9), w("c", "d", 1), w("a", "c", 4), w("b", "d", 4), w("a", "d", 2)];+ const forward = placementEdges(new Map(pairs), 2);+ expect(forward.map((e) => e.id)).toEqual(["a>b", "a>c", "a>d", "b>d"]);+ expect(placementEdges(new Map([...pairs].reverse()), 2)).toEqual(forward);+ });++ it("never leaves a linked card edgeless, however strong a hub's other pairs are", () => {+ const hub = ["x", "y", "z", "w"].flatMap((o) => [w("hub", o, 50), w(o, "hub", 40)]);+ const leaves = [w("leaf1", "leaf2", 1), w("leaf3", "x", 1)];+ const edges = placementEdges(new Map([...hub, ...leaves]), 2, 1);+ const ends = new Set(edges.flatMap((e) => [e.source, e.target]));+ for (const id of ["hub", "x", "y", "z", "w", "leaf1", "leaf2", "leaf3"]) expect(ends.has(id), id).toBe(true);+ });++ it("points a pair with equal links both ways from the lower id", () => {+ expect(placementEdges(new Map([w("b", "a", 3), w("a", "b", 3)]), 2).map((e) => e.id)).toEqual(["a>b"]);+ });++ it("caps a dense 300-service estate at two placement edges per card", () => {+ const g = makeSyntheticSystemGraph({ services: 300, edges: 3000, groups: 30, seed: 300 });+ const groups = [...new Set(g.nodes.map((n) => n.group!))].map((id) => ({ id }));+ const view = buildLevelView({ ...g, groups });+ const plan = planLevelLayout(view.nodes, g.edges);+ expect(plan.root.nodes).toHaveLength(30);+ expect(plan.root.edges.length).toBeLessThanOrEqual(30 * PLACEMENT_EDGES_PER_CARD);+ // One per pair: never both directions between two cards.+ const pairs = new Set(plan.root.edges.map((e) => [e.source, e.target].sort().join("|")));+ expect(pairs.size).toBe(plan.root.edges.length);+ });+});+describe("orderByPrevious", () => {const n = (id: string) => ({ id, width: 1, height: 1 });it("puts known nodes first in reading order, then new ones in drawn order", () => {diff --git a/packages/ui/src/workspace/system-map/layout-scopes.ts b/packages/ui/src/workspace/system-map/layout-scopes.tsindex d3be34645..f51d6f087 100644--- a/packages/ui/src/workspace/system-map/layout-scopes.ts+++ b/packages/ui/src/workspace/system-map/layout-scopes.ts@@ -13,7 +13,7 @@import type { C4LayoutEdge, C4LayoutNode, C4LayoutPosition } from "../../c4/layout/elk-c4-layout";import { compareIds } from "./bands";-import { edgeFamilyOf } from "./edge-families";+import { edgeFamilyOf, linkWeight } from "./edge-families";import type { DrawnNode, LevelsEdge } from "./level-types";interface Size {@@ -49,7 +49,7 @@ export interface LayoutScope {id: string;/** In drawn order. In the root, an open container has a zero size until its interior is laid out. */nodes: C4LayoutNode[];- /** One per ordered pair of drawn ids, in id order. */+ /** Placement edges: at most one per pair of drawn ids, the strongest kept, in id order. */edges: C4LayoutEdge[];}@@ -110,10 +110,66 @@ function liftEdge(e: LevelsEdge, { parentOf, drawnAt }: Placement): [string, strreturn rs === rt ? null : [ROOT_SCOPE, rs, rt];}+/**+ * A scope's placement-edge budget per card, on average: the scope keeps at+ * most this times its card count, and a hub card may hold more than its+ * share. ELK's layered layout grows with edges far faster than with cards:+ * a 30-card estate over a 3,000-edge graph lifts to about 750 card pairs,+ * which took ELK about 50 s; capped at 60 edges it is well under 100 ms.+ */+export const PLACEMENT_EDGES_PER_CARD = 2;++/**+ * One edge per unordered card pair, pointing the way most links go (ties to+ * the lower id first). Every card first keeps its strongest pair, so no+ * linked card is left edgeless in layer 0 (a hub may take several of these);+ * the rest of a budget of `perCard` times the card count goes to the strongest remaining pairs, ties by id.+ * Layers follow the kept edges only, so a weak drawn connector may run+ * against them. Deterministic and independent of input order.+ */+export function placementEdges(+ weights: ReadonlyMap<string, { source: string; target: string; links: number }>,+ cards: number,+ perCard: number = PLACEMENT_EDGES_PER_CARD,+): C4LayoutEdge[] {+ const pairs = new Map<string, { source: string; target: string; links: number; net: number }>();+ for (const w of weights.values()) {+ const forward = compareIds(w.source, w.target) < 0;+ const key = forward ? `${w.source}\u0000${w.target}` : `${w.target}\u0000${w.source}`;+ let p = pairs.get(key);+ if (!p) {+ const [a, b] = forward ? [w.source, w.target] : [w.target, w.source];+ pairs.set(key, (p = { source: a, target: b, links: 0, net: 0 }));+ }+ p.links += w.links;+ p.net += forward ? w.links : -w.links;+ }+ const ranked = [...pairs.values()].map((p) => {+ const [source, target] = p.net >= 0 ? [p.source, p.target] : [p.target, p.source];+ return { id: `${source}>${target}`, source, target, links: p.links };+ });+ ranked.sort((x, y) => y.links - x.links || compareIds(x.id, y.id));+ const kept = new Set<(typeof ranked)[number]>();+ const linked = new Set<string>();+ for (const r of ranked) {+ if (linked.has(r.source) && linked.has(r.target)) continue;+ kept.add(r);+ linked.add(r.source).add(r.target);+ }+ const budget = Math.ceil(cards * perCard);+ for (const r of ranked) {+ if (kept.size >= budget) break;+ kept.add(r);+ }+ return [...kept].map(({ id, source, target }) => ({ id, source, target })).sort((x, y) => compareIds(x.id, y.id));+}++type PairWeights = Map<string, { source: string; target: string; links: number }>;+/*** Scopes for an estate, group or between view (focus uses fixed columns).* `edges` are the graph's system edges, each lifted to the drawn ids that- * show its ends.+ * show its ends and summed per card pair (see `placementEdges`).*/export function planLevelLayout(nodes: readonly DrawnNode[],@@ -121,10 +177,10 @@ export function planLevelLayout(sizes: LevelNodeSizes = LEVEL_NODE_SIZES,): LevelLayoutPlan {const placed = placement(nodes);- const scopes = new Map<string, { nodes: C4LayoutNode[]; edges: Map<string, C4LayoutEdge> }>();+ const scopes = new Map<string, { nodes: C4LayoutNode[]; weights: PairWeights }>();const scope = (id: string) => {let s = scopes.get(id);- if (!s) scopes.set(id, (s = { nodes: [], edges: new Map() }));+ if (!s) scopes.set(id, (s = { nodes: [], weights: new Map() }));return s;};scope(ROOT_SCOPE);@@ -135,13 +191,16 @@ export function planLevelLayout(const lifted = shapesLayout(e) ? liftEdge(e, placed) : null;if (!lifted) continue;const [scopeId, source, target] = lifted;+ const weights = scope(scopeId).weights;const id = `${source}>${target}`;- scope(scopeId).edges.set(id, { id, source, target });+ const w = weights.get(id);+ if (w) w.links += linkWeight(e);+ else weights.set(id, { source, target, links: linkWeight(e) });}const toScope = (id: string): LayoutScope => {const s = scopes.get(id)!;- return { id, nodes: s.nodes, edges: [...s.edges.values()].sort((a, b) => compareIds(a.id, b.id)) };+ return { id, nodes: s.nodes, edges: placementEdges(s.weights, s.nodes.length) };};const interiors = [...scopes.keys()].filter((id) => id !== ROOT_SCOPE && scopes.get(id)!.nodes.length > 0);return { interiors: interiors.map(toScope), root: toScope(ROOT_SCOPE) };diff --git a/packages/ui/src/workspace/system-map/level-layout.ts b/packages/ui/src/workspace/system-map/level-layout.tsindex 988bf1a40..44cd9a7fa 100644--- a/packages/ui/src/workspace/system-map/level-layout.ts+++ b/packages/ui/src/workspace/system-map/level-layout.ts@@ -29,9 +29,13 @@ import type { LevelsEdge } from "./level-types";export type LevelPositions = Map<string, C4LayoutPosition>;-/** ELK options added to the C4 defaults for the map: keep the input order where crossings allow. */+/**+ * ELK options added to the C4 defaults for the map: keep the cards' input+ * (previous) order where crossings allow. Node order only: placement edges+ * go to ELK in id order, which carries no meaning to preserve.+ */export const LEVEL_LAYOUT_OPTIONS: Record<string, string> = {- "elk.layered.considerModelOrder.strategy": "NODES_AND_EDGES",+ "elk.layered.considerModelOrder.strategy": "PREFER_NODES",};/** Scope layouts by signature, least recently used dropped first. */