Skip to content

Commit 5374c11

Browse files
fix(ui): make file-link label disambiguation near-linear (#124258)
* fix(ui): make file-link label disambiguation near-linear shortestFileLabels rescanned every path list at each suffix depth to find the shortest unambiguous label, which is quadratic in path count. A Markdown message with thousands of distinct file references could stall the chat renderer. Replace the repeated scan with one reversed-segment suffix trie built per render, so each path's label depth is found with one child lookup per depth instead of a comparison against every other path. Output is unchanged. Fixes #124230 * test(ui): assert file-label lookup cost stays linear Add a deterministic performance-contract regression for shortestFileLabels: count Map#get calls via vi.spyOn while the trie runs at two path-count scales and assert the growth stays linear (generous band) rather than the pre-fix O(n^2) full-list rescan's quadratic signature. No wall-clock timing, so it can't flake under CI load; verified locally that it fails deterministically against the pre-fix implementation and passes clean against the fix.
1 parent 3bb7fdd commit 5374c11

2 files changed

Lines changed: 100 additions & 14 deletions

File tree

‎ui/src/components/file-kind.ts‎

Lines changed: 41 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,42 @@ export function fileKindForPath(path: string): FileKind {
108108
return FILE_KIND_BY_EXTENSION[extension] ?? "file";
109109
}
110110

111+
type SuffixTrieNode = {
112+
pathCount: number;
113+
children: Map<string, SuffixTrieNode>;
114+
};
115+
116+
// One reversed-segment trie indexes every path's suffixes together, so the
117+
// per-path depth search below never rescans the other paths: it descends one
118+
// child lookup per depth instead of comparing against every other path at
119+
// every depth. Model-controlled Markdown can carry thousands of distinct
120+
// paths, so this keeps label derivation near-linear in total path length
121+
// rather than quadratic in path count.
122+
function insertReversedSegments(root: SuffixTrieNode, segments: readonly string[]): void {
123+
let node = root;
124+
for (let i = segments.length - 1; i >= 0; i--) {
125+
const segment = segments[i]!;
126+
let child = node.children.get(segment);
127+
if (!child) {
128+
child = { pathCount: 0, children: new Map() };
129+
node.children.set(segment, child);
130+
}
131+
node = child;
132+
node.pathCount += 1;
133+
}
134+
}
135+
136+
function shortestUniqueSuffixDepth(root: SuffixTrieNode, segments: readonly string[]): number {
137+
let node = root;
138+
for (let depth = 1; depth <= segments.length; depth++) {
139+
node = node.children.get(segments[segments.length - depth]!) ?? node;
140+
if (node.pathCount === 1 || depth === segments.length) {
141+
return depth;
142+
}
143+
}
144+
return segments.length;
145+
}
146+
111147
/**
112148
* Shortest unambiguous label per path: the basename alone when it is unique
113149
* among the supplied paths, otherwise the smallest trailing run of segments
@@ -119,22 +155,14 @@ export function shortestFileLabels(paths: readonly string[]): Map<string, string
119155
const segmentsByPath = new Map(
120156
unique.map((path) => [path, path.split(PATH_SEPARATOR_RE).filter(Boolean)]),
121157
);
122-
const suffixKey = (segments: readonly string[], depth: number) =>
123-
segments.slice(-depth).join("/");
158+
const suffixTrie: SuffixTrieNode = { pathCount: 0, children: new Map() };
159+
for (const segments of segmentsByPath.values()) {
160+
insertReversedSegments(suffixTrie, segments);
161+
}
124162
const labels = new Map<string, string>();
125163
for (const path of unique) {
126164
const segments = segmentsByPath.get(path) ?? [];
127-
let depth = 1;
128-
while (
129-
depth < segments.length &&
130-
unique.some(
131-
(other) =>
132-
other !== path &&
133-
suffixKey(segmentsByPath.get(other) ?? [], depth) === suffixKey(segments, depth),
134-
)
135-
) {
136-
depth += 1;
137-
}
165+
const depth = shortestUniqueSuffixDepth(suffixTrie, segments);
138166
// Render the suffix with the separator the path itself used so a Windows
139167
// path never reads as a POSIX one.
140168
labels.set(path, segments.slice(-depth).join(path.includes("\\") ? "\\" : "/"));

‎ui/src/components/markdown-links.test.ts‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Control UI tests cover markdown link rendering: autolinking, file links, and link marks.
2-
import { describe, expect, it } from "vitest";
2+
import { describe, expect, it, vi } from "vitest";
3+
import { shortestFileLabels } from "./file-kind.ts";
34
import { toSanitizedMarkdownHtml } from "./markdown.ts";
45

56
function htmlFragment(html: string): HTMLElement {
@@ -424,6 +425,63 @@ describe("toSanitizedMarkdownHtml links", () => {
424425
]);
425426
});
426427

428+
it("keeps labels correct and distinct across thousands of paths", () => {
429+
// A model-controlled message can reference thousands of distinct files.
430+
// The regression this guards against is quadratic label derivation, so
431+
// this pairs an all-unique-basename set (no repeated suffix growth)
432+
// with a colliding-basename set (forced suffix growth) at the same
433+
// cardinality; both must resolve correctly, not just quickly.
434+
const distinctPaths = Array.from(
435+
{ length: 4000 },
436+
(_, i) => `src/pkg${i % 50}/mod${i}/file${i}.ts`,
437+
);
438+
const distinctLabels = shortestFileLabels(distinctPaths);
439+
expect(distinctLabels.size).toBe(distinctPaths.length);
440+
for (const path of distinctPaths) {
441+
expect(distinctLabels.get(path)).toBe(path.slice(path.lastIndexOf("/") + 1));
442+
}
443+
444+
const collidingPaths = Array.from({ length: 4000 }, (_, i) => `pkg${i}/shared/index.ts`);
445+
const collidingLabels = shortestFileLabels(collidingPaths);
446+
expect(collidingLabels.size).toBe(collidingPaths.length);
447+
expect(new Set(collidingLabels.values()).size).toBe(collidingPaths.length);
448+
for (const path of collidingPaths) {
449+
expect(collidingLabels.get(path)).toBe(path);
450+
}
451+
});
452+
453+
it("keeps per-path lookup cost linear as path count grows (performance contract)", () => {
454+
// Wall-clock timing flakes under CI load, so this asserts the actual
455+
// performance contract structurally: count every Map#get call made while
456+
// shortestFileLabels runs. The trie makes a fixed number of child
457+
// lookups per path segment (one per segment on insert, one per resolved
458+
// suffix depth on lookup), so total lookups scale with path count, not
459+
// its square. The pre-fix full-list rescan (#124230) re-read every other
460+
// path's segments inside `unique.some(...)` at every depth, which cost
461+
// O(n^2) lookups for this same all-unique-basename shape -- 8x the paths
462+
// there costs ~64x the lookups, far outside the linear band asserted
463+
// below, so a regression back to that scan fails this test every run.
464+
const countMapLookups = (pathCount: number): number => {
465+
const paths = Array.from(
466+
{ length: pathCount },
467+
(_, i) => `src/pkg${i % 50}/mod${i}/file${i}.ts`,
468+
);
469+
const getSpy = vi.spyOn(Map.prototype, "get");
470+
try {
471+
shortestFileLabels(paths);
472+
return getSpy.mock.calls.length;
473+
} finally {
474+
getSpy.mockRestore();
475+
}
476+
};
477+
478+
const small = countMapLookups(500);
479+
const large = countMapLookups(4000); // 8x the paths
480+
481+
expect(large).toBeGreaterThan(small * 4);
482+
expect(large).toBeLessThan(small * 16);
483+
});
484+
427485
it.each([
428486
["README.md", "markdown"],
429487
["package.json", "package"],

0 commit comments

Comments
 (0)