Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

fix(trace-flamegraph): prevent layout hang on very wide traces (#11578)

Aditya Singheec1c45e3fae
diff --git a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/__tests__/computeVisualLayout.test.ts b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/__tests__/computeVisualLayout.test.ts
index 53a0eb5ff5..6467422537 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/__tests__/computeVisualLayout.test.ts
+++ b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/__tests__/computeVisualLayout.test.ts
@@ -1,6 +1,9 @@
import { FlamegraphSpan } from 'types/api/trace/getTraceFlamegraph';
-import { computeVisualLayout } from '../computeVisualLayout';
+import {
+ computeVisualLayout,
+ WIDE_GROUP_THRESHOLD,
+} from '../computeVisualLayout';
function makeSpan(
overrides: Partial<FlamegraphSpan> & {
@@ -472,4 +475,177 @@ describe('computeVisualLayout', () => {
expect(aRow).toBeGreaterThan(1); // must NOT be at row 1
expect(aRow).toBe(3); // next free row after B at row 2 (A overlaps B)
});
+
+ // --- Wide-group fast path (> WIDE_GROUP_THRESHOLD siblings) ---
+ // Past the threshold the layout switches to exact overlap-only packing to
+ // avoid the O(N^2) connector-avoidance spiral. These lock in correctness and
+ // the no-overlap invariant at scale.
+
+ function noRowHasOverlap(
+ layout: ReturnType<typeof computeVisualLayout>,
+ ): void {
+ for (const row of layout.visualRows) {
+ const sorted = [...row].sort((a, b) => a.timestamp - b.timestamp);
+ for (let i = 1; i < sorted.length; i++) {
+ const prevEnd = sorted[i - 1].timestamp + sorted[i - 1].durationNano / 1e6;
+ expect(sorted[i].timestamp).toBeGreaterThanOrEqual(prevEnd);
+ }
+ }
+ }
+
+ it('should pack thousands of sequential leaf siblings into 1 row (wide path)', () => {
+ const root = makeSpan({ spanId: 'root', timestamp: 0, durationNano: 1e12 });
+ const kids: FlamegraphSpan[] = [];
+ // 2000 strictly sequential (non-overlapping) children
+ for (let i = 0; i < 2000; i++) {
+ kids.push(
+ makeSpan({
+ spanId: `k${i}`,
+ parentSpanId: 'root',
+ timestamp: i * 10,
+ durationNano: 5e6, // 5ms, ends before next starts
+ }),
+ );
+ }
+
+ const layout = computeVisualLayout([[root], kids]);
+
+ expect(layout.spanToVisualRow['root']).toBe(0);
+ expect(layout.totalVisualRows).toBe(2); // all siblings share row 1
+ for (const k of kids) {
+ expect(layout.spanToVisualRow[k.spanId]).toBe(1);
+ }
+ noRowHasOverlap(layout);
+ });
+
+ it('should pack thousands of fully-overlapping leaf siblings without violations (wide path)', () => {
+ const root = makeSpan({ spanId: 'root', timestamp: 0, durationNano: 1e12 });
+ const kids: FlamegraphSpan[] = [];
+ // 1000 children all spanning the same window → each needs its own row
+ for (let i = 0; i < 1000; i++) {
+ kids.push(
+ makeSpan({
+ spanId: `k${i}`,
+ parentSpanId: 'root',
+ timestamp: 0,
+ durationNano: 100e6,
+ }),
+ );
+ }
+
+ const layout = computeVisualLayout([[root], kids]);
+
+ expect(layout.totalVisualRows).toBe(1001); // root + 1000 stacked rows
+ expect(Object.keys(layout.spanToVisualRow)).toHaveLength(1001);
+ noRowHasOverlap(layout);
+ });
+
+ it('should keep non-leaf subtrees adjacent within a wide mixed group (wide path)', () => {
+ const root = makeSpan({ spanId: 'root', timestamp: 0, durationNano: 1e12 });
+ const kids: FlamegraphSpan[] = [];
+ for (let i = 0; i < 1000; i++) {
+ kids.push(
+ makeSpan({
+ spanId: `k${i}`,
+ parentSpanId: 'root',
+ timestamp: i * 10,
+ durationNano: 5e6,
+ }),
+ );
+ }
+ // One of the wide siblings has a child of its own
+ const grandchild = makeSpan({
+ spanId: 'gc',
+ parentSpanId: 'k500',
+ timestamp: 5000,
+ durationNano: 2e6,
+ });
+
+ const layout = computeVisualLayout([[root], kids, [grandchild]]);
+
+ const parentRow = layout.spanToVisualRow['k500'];
+ const gcRow = layout.spanToVisualRow['gc'];
+ expect(gcRow - parentRow).toBe(1); // subtree adjacency preserved
+ expect(Object.keys(layout.spanToVisualRow)).toHaveLength(1002);
+ noRowHasOverlap(layout);
+ });
+
+ // --- Regression guards for the wide-trace layout spiral ---
+ // The pre-fix algorithm's connector-avoidance checks formed a positive-
+ // feedback loop on wide SCATTERED groups (short spans spread across the
+ // parent window with modest concurrency): each pushed-down child stamped
+ // connector points on intermediate rows, pushing later children even
+ // higher. Sequential and fully-overlapping groups (tests above) do NOT
+ // trigger it — these two shapes do, and encode its failure signatures.
+
+ function makeScatteredStar(
+ childCount: number,
+ spacingMs: number,
+ durationMs: number,
+ ): FlamegraphSpan[][] {
+ const root = makeSpan({
+ spanId: 'root',
+ timestamp: 0,
+ durationNano: (childCount * spacingMs + durationMs) * 1e6,
+ });
+ const kids: FlamegraphSpan[] = [];
+ for (let i = 0; i < childCount; i++) {
+ kids.push(
+ makeSpan({
+ spanId: `k${i}`,
+ parentSpanId: 'root',
+ timestamp: i * spacingMs,
+ durationNano: durationMs * 1e6,
+ }),
+ );
+ }
+ return [[root], kids];
+ }
+
+ it('should not spiral row count on a scattered group just above the threshold', () => {
+ // Children of 50ms each, starting every 10ms → max temporal concurrency
+ // is 6 (each span overlaps the next 5). The old algorithm spiraled this
+ // shape to ~1 row per child; overlap-only packing needs ~7 including the
+ // root. Sized just above WIDE_GROUP_THRESHOLD so a regression fails fast
+ // (sub-second) rather than burning CI time.
+ const count = WIDE_GROUP_THRESHOLD + 88;
+ const layout = computeVisualLayout(makeScatteredStar(count, 10, 50));
+
+ expect(Object.keys(layout.spanToVisualRow)).toHaveLength(count + 1);
+ // Generous slack over the optimal ~7 — but orders of magnitude below the
+ // one-row-per-child the spiral produced.
+ expect(layout.totalVisualRows).toBeLessThan(30);
+ noRowHasOverlap(layout);
+ });
+
+ it('should be faster through the fast path despite one extra span', () => {
+ // Identical scattered shape on both sides of the gate: THRESHOLD children
+ // run the original connector-avoidance path, THRESHOLD + 1 run the
+ // overlap-only fast path. With one MORE span to place, the fast path can
+ // only win because the algorithm is cheaper — a self-calibrating
+ // comparison (same machine, same process) with no absolute time budget.
+ // On this shape the avoidance path spirals (~tens of ms) while the fast
+ // path stays ~1ms, so the margin is well past timer noise. Also guards
+ // the gate itself: if everything routed to one path, one extra span can
+ // never be faster.
+ const avoidancePathInput = makeScatteredStar(WIDE_GROUP_THRESHOLD, 10, 50);
+ const fastPathInput = makeScatteredStar(WIDE_GROUP_THRESHOLD + 1, 10, 50);
+
+ // Warm-up runs so JIT compilation doesn't skew either side.
+ computeVisualLayout(avoidancePathInput);
+ computeVisualLayout(fastPathInput);
+
+ const timeOf = (input: FlamegraphSpan[][]): number => {
+ const start = performance.now();
+ computeVisualLayout(input);
+ return performance.now() - start;
+ };
+
+ // Best-of-3 per side to shave off GC pauses and scheduler noise.
+ const RUNS = [0, 1, 2];
+ const avoidanceMs = Math.min(...RUNS.map(() => timeOf(avoidancePathInput)));
+ const fastMs = Math.min(...RUNS.map(() => timeOf(fastPathInput)));
+
+ expect(fastMs).toBeLessThan(avoidanceMs);
+ });
});
diff --git a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/computeVisualLayout.ts b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/computeVisualLayout.ts
index ca97b89878..48547600f7 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/computeVisualLayout.ts
+++ b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/computeVisualLayout.ts
@@ -18,6 +18,82 @@ export interface VisualLayout {
totalVisualRows: number;
}
+// Above this many siblings under one parent, the connector-avoidance refinement
+// (Checks 2 & 3) is both visually meaningless — the row is already a dense wall —
+// and quadratic: every child deposits a connector point on each intermediate row,
+// which pushes later children even higher, which deposits more points. That
+// feedback loop inflates a layout needing ~50 rows to thousands and never
+// finishes on wide traces. Past the threshold we pack by overlap only.
+// Exported so the regression tests stay anchored to the real gate value.
+export const WIDE_GROUP_THRESHOLD = 512;
+
+/**
+ * Segment tree over rows that answers "lowest row index >= `from` whose smallest
+ * span start-time is >= `end`" in O(log rows). Used to place a large group of
+ * leaf siblings by overlap only: because siblings are processed in descending
+ * start order, every already-placed span on a row starts at or after the current
+ * one, so [start, end] overlaps a row iff some span there starts before `end` —
+ * i.e. the row is free iff its minimum start >= end. Each node stores the max of
+ * its subtree's per-row minimum starts so a free row can be found by descent.
+ */
+class LowestFreeRow {
+ private readonly size: number;
+
+ private readonly tree: Float64Array;
+
+ constructor(rows: number) {
+ let size = 1;
+ while (size < rows) {
+ size *= 2;
+ }
+ this.size = size;
+ this.tree = new Float64Array(size * 2).fill(Infinity);
+ }
+
+ place(row: number, start: number): void {
+ let i = row + this.size;
+ // A row's key is the minimum start among its spans. Children are processed
+ // in descending start order so a leaf's start is the new minimum, but a
+ // non-leaf subtree's descendant can land on a row out of order — take min.
+ if (start >= this.tree[i]) {
+ return;
+ }
+ this.tree[i] = start;
+ for (i >>= 1; i >= 1; i >>= 1) {
+ const next = Math.max(this.tree[2 * i], this.tree[2 * i + 1]);
+ if (this.tree[i] === next) {
+ break;
+ }
+ this.tree[i] = next;
+ }
+ }
+
+ lowestFrom(from: number, end: number): number {
+ return this.descend(1, 0, this.size - 1, from, end);
+ }
+
+ private descend(
+ node: number,
+ lo: number,
+ hi: number,
+ from: number,
+ end: number,
+ ): number {
+ if (hi < from || this.tree[node] < end) {
+ return -1;
+ }
+ if (lo === hi) {
+ return lo;
+ }
+ const mid = (lo + hi) >> 1;
+ const left = this.descend(2 * node, lo, mid, from, end);
+ if (left !== -1) {
+ return left;
+ }
+ return this.descend(2 * node + 1, mid + 1, hi, from, end);
+ }
+}
+
/**
* Computes an overlap-safe visual layout for flamegraph spans using DFS ordering.
*
@@ -214,7 +290,53 @@ export function computeVisualLayout(spans: FlamegraphSpan[][]): VisualLayout {
arr.push(point);
}
+ // Fast path for a parent with a very large group of children: pack by overlap
+ // only (descending greedy), skipping the quadratic connector-avoidance that
+ // spirals at this scale. Leaf children — the bulk of a wide trace — are placed
+ // in O(log rows) via the segment tree; the rare non-leaf subtree falls back to
+ // findPlacement against the shared interval map. Both structures are kept in
+ // sync so each placement sees all prior occupancy. Same ShapeEntry[] contract.
+ function computeWideShape(
+ rootSpan: FlamegraphSpan,
+ children: FlamegraphSpan[],
+ ): ShapeEntry[] {
+ const shape: ShapeEntry[] = [{ span: rootSpan, relativeRow: 0 }];
+ const localIntervals = new Map<number, Array<[number, number]>>();
+ // Children occupy relative rows 1..children.length in the worst case.
+ const finder = new LowestFreeRow(children.length + 2);
+
+ const occupy = (row: number, span: FlamegraphSpan): void => {
+ const s = span.timestamp;
+ const e = span.timestamp + span.durationNano / 1e6;
+ shape.push({ span, relativeRow: row });
+ addIntervalTo(localIntervals, row, s, e);
+ finder.place(row, s);
+ };
+
+ for (const child of children) {
+ if (childrenMap.has(child.spanId)) {
+ // Non-leaf: place its whole subtree shape as a unit via findPlacement.
+ const childShape = computeSubtreeShape(child);
+ const offset = findPlacement(childShape, 1, localIntervals);
+ for (const entry of childShape) {
+ occupy(entry.relativeRow + offset, entry.span);
+ }
+ } else {
+ const end = child.timestamp + child.durationNano / 1e6;
+ occupy(finder.lowestFrom(1, end), child);
+ }
+ }
+
+ return shape;
+ }
+
function computeSubtreeShape(rootSpan: FlamegraphSpan): ShapeEntry[] {
+ const children = childrenMap.get(rootSpan.spanId);
+
+ if (children && children.length > WIDE_GROUP_THRESHOLD) {
+ return computeWideShape(rootSpan, children);
+ }
+
const localIntervals = new Map<number, Array<[number, number]>>();
const localConnectorPoints = new Map<number, number[]>();
const shape: ShapeEntry[] = [];
@@ -225,7 +347,6 @@ export function computeVisualLayout(spans: FlamegraphSpan[][]): VisualLayout {
shape.push({ span: rootSpan, relativeRow: 0 });
addIntervalTo(localIntervals, 0, rootStart, rootEnd);
- const children = childrenMap.get(rootSpan.spanId);
if (children) {
for (const child of children) {
const childShape = computeSubtreeShape(child);
diff --git a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/hooks/useVisualLayoutWorker.ts b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/hooks/useVisualLayoutWorker.ts
index 0a25c6ea50..9369850d80 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/hooks/useVisualLayoutWorker.ts
+++ b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/hooks/useVisualLayoutWorker.ts
@@ -94,7 +94,7 @@ export function useVisualLayoutWorker(spans: FlamegraphSpan[][]): {
cleanup();
};
- // Timeout: if worker doesn't respond in 30s, terminate and error
+ // Timeout: if worker doesn't respond in 15s, terminate and error
const WORKER_TIMEOUT_MS = 15000;
const timeoutId = setTimeout(() => {
if (requestIdRef.current === currentId && isComputingRef.current) {