perf: round 10 — auth alloc purge, parent-herd batching, query-shape pack, NC 304s
Benchmark-gated (benches/ROUND10.md; every change carries a BEFORE/AFTER harness with equivalence/safety gates — two designs were rejected or rewritten by their own benches before adoption): - Auth hot path: TokenClaims/CurrentUser display fields to Arc<str>, role to inline SmolStr end-to-end (Bearer, cookie, Basic-auth cache) — 4→1 allocs per authenticated request, 3→0 per warm DAV request; JWT Encoding/Decoding/Validation built once. - Cold shared-album herd: leader-inline parent batching in PgAclEngine (+ cascade try_get_with single-flight) — 100→2 parent queries per 100-thumb cold herd, herd wall 1.9x, sequential + warm paths unchanged, all ROUND8/9 safety gates plus new herd-equivalence gates. - Query-shape pack: share download double-fetch 2→1 (2.18x), contact-group COUNT(*) 14.9x, save_faces UNNEST 3.9x, playlist reorder UNNEST 63.7x (now atomic), search files∥folders join! 1.45x, move drive-lookup join! 2.14x, trash partial (drive_id, trashed_at) indexes, CalDAV event-gate narrow read, favorites/recents binary-decode port, dead count_files removed. - NC surface: preview + avatar honour If-None-Match (e2e: 5 KB and 197 KB → 0 bytes per revalidation), avatar WebP→PNG transcode memoised, PROPFIND/trashbin integer+date emits on stack formatters, folder-header enrichment join!, chunk-PUT retry stat folded into create_new open. - common::fmt integer rendering rewritten on the std 2-digit LUT after the round's own bench caught the div-loop losing to to_string (16.1 ns vs 22.5; speeds every prior-round call site). - Micro-pack: WebDAV scope probe borrow-only, ShareService base_url snapshot, cookie_secure OnceLock, Arc'd AES-GCM cipher, stack request-id, tantivy analyzer clone dropped. - SPA: search stale-guard + AbortController (10→1 completed round-trips, stale-clobber gone), getFolder in-flight dedup, gridColumns matchMedia hoist (10k→0 style reads). Backend: cargo fmt + clippy -D warnings clean, 524 tests green. Frontend: npm run check clean, 301 vitest green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018DdM7V7M3QPW7HEHg3gLov
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
|
||||
vi.mock('$lib/api/client', () => ({ apiFetch: vi.fn(), apiJson: vi.fn() }));
|
||||
|
||||
import { apiJson } from '$lib/api/client';
|
||||
import type { FolderItem } from '$lib/api/types';
|
||||
import { getFolder } from './folders';
|
||||
|
||||
/**
|
||||
* Benchmark gate for the in-flight dedup in {@link getFolder}.
|
||||
*
|
||||
* Audit finding: on a cold deep-link the breadcrumb builder and the files
|
||||
* view's drive-id resolver both call `getFolder(currentFolderId)` in the same
|
||||
* frame — two identical concurrent `GET /api/folders/{id}` round-trips per
|
||||
* navigation. The fix keeps a `Map<id, Promise>` of in-flight requests (the
|
||||
* `resolveUser` pattern) so concurrent duplicates share one fetch, while
|
||||
* SEQUENTIAL calls still hit the network every time (freshness unchanged).
|
||||
*
|
||||
* Gates:
|
||||
* 1. Two concurrent calls for the same id → exactly ONE network call, both
|
||||
* callers get the same result.
|
||||
* 2. Sequential calls (second after the first settled) → two network calls
|
||||
* (no staleness introduced).
|
||||
* 3. Distinct ids in flight do not cross-talk.
|
||||
*/
|
||||
|
||||
const mockedApiJson = vi.mocked(apiJson);
|
||||
|
||||
function folder(id: string): FolderItem {
|
||||
return { id, name: `Folder ${id}` } as unknown as FolderItem;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockedApiJson.mockReset();
|
||||
});
|
||||
|
||||
describe('getFolder in-flight dedup (benchmark gate)', () => {
|
||||
it('concurrent duplicate calls collapse to one request', async () => {
|
||||
let release!: (v: FolderItem) => void;
|
||||
mockedApiJson.mockImplementation(
|
||||
() => new Promise<FolderItem>((r) => (release = r)) as Promise<never>
|
||||
);
|
||||
|
||||
const a = getFolder('f1');
|
||||
const b = getFolder('f1');
|
||||
expect(mockedApiJson).toHaveBeenCalledTimes(1); // the dedup win
|
||||
|
||||
release(folder('f1'));
|
||||
const [ra, rb] = await Promise.all([a, b]);
|
||||
expect(ra).toEqual(rb);
|
||||
expect(ra.id).toBe('f1');
|
||||
console.log(
|
||||
`[bench] cold deep-link double-fetch: requests BEFORE=2 AFTER=${mockedApiJson.mock.calls.length}`
|
||||
);
|
||||
});
|
||||
|
||||
it('sequential calls still refetch (freshness preserved)', async () => {
|
||||
mockedApiJson.mockResolvedValue(folder('f2') as never);
|
||||
await getFolder('f2');
|
||||
await getFolder('f2');
|
||||
expect(mockedApiJson).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('distinct ids resolve independently', async () => {
|
||||
mockedApiJson.mockImplementation(((url: string) => {
|
||||
const id = String(url).split('/').pop() ?? '';
|
||||
return Promise.resolve(folder(id));
|
||||
}) as never);
|
||||
const [x, y] = await Promise.all([getFolder('fx'), getFolder('fy')]);
|
||||
expect(x.id).toBe('fx');
|
||||
expect(y.id).toBe('fy');
|
||||
expect(mockedApiJson).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('a failed in-flight request clears the slot so a retry refetches', async () => {
|
||||
mockedApiJson.mockRejectedValueOnce(new Error('boom') as never);
|
||||
await expect(getFolder('f3')).rejects.toThrow('boom');
|
||||
mockedApiJson.mockResolvedValue(folder('f3') as never);
|
||||
await expect(getFolder('f3')).resolves.toMatchObject({ id: 'f3' });
|
||||
});
|
||||
});
|
||||
@@ -88,10 +88,26 @@ export function getFolderName(id: string): string | undefined {
|
||||
return folderNames.get(id);
|
||||
}
|
||||
|
||||
export async function getFolder(id: string): Promise<FolderItem> {
|
||||
const folder = await apiJson<FolderItem>(`/api/folders/${id}`, NO_CACHE);
|
||||
rememberFolderName(folder.id, folder.name);
|
||||
return folder;
|
||||
// In-flight dedup (the `resolveUser` pattern): on a cold deep-link the
|
||||
// breadcrumb builder and the drive-id resolver both request the same folder
|
||||
// concurrently — collapse duplicates into one GET. Entries only live while
|
||||
// the request is in flight, so freshness semantics are unchanged.
|
||||
const folderInflight = new Map<string, Promise<FolderItem>>();
|
||||
|
||||
export function getFolder(id: string): Promise<FolderItem> {
|
||||
const inflight = folderInflight.get(id);
|
||||
if (inflight) return inflight;
|
||||
const request = (async () => {
|
||||
try {
|
||||
const folder = await apiJson<FolderItem>(`/api/folders/${id}`, NO_CACHE);
|
||||
rememberFolderName(folder.id, folder.name);
|
||||
return folder;
|
||||
} finally {
|
||||
folderInflight.delete(id);
|
||||
}
|
||||
})();
|
||||
folderInflight.set(id, request);
|
||||
return request;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -19,6 +19,8 @@ export interface SearchOptions {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
sortBy?: SortBy;
|
||||
/** Abort the request when a newer search supersedes it. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export function searchFiles(query: string, opts: SearchOptions = {}): Promise<SearchResults> {
|
||||
@@ -38,7 +40,10 @@ export function searchFiles(query: string, opts: SearchOptions = {}): Promise<Se
|
||||
params.append('limit', String(opts.limit ?? 100));
|
||||
params.append('offset', String(opts.offset ?? 0));
|
||||
params.append('sort_by', opts.sortBy ?? 'relevance');
|
||||
return apiJson<SearchResults>(`/api/search?${params.toString()}`, { credentials: 'same-origin' });
|
||||
return apiJson<SearchResults>(`/api/search?${params.toString()}`, {
|
||||
credentials: 'same-origin',
|
||||
signal: opts.signal
|
||||
});
|
||||
}
|
||||
|
||||
/** A single autocomplete suggestion returned by the lightweight suggest endpoint. */
|
||||
@@ -50,6 +55,8 @@ export interface SearchSuggestions {
|
||||
export interface SuggestOptions {
|
||||
folderId?: string;
|
||||
limit?: number;
|
||||
/** Abort the request when a newer keystroke supersedes it. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -65,7 +72,8 @@ export function searchSuggest(
|
||||
if (opts.folderId) params.append('folder_id', opts.folderId);
|
||||
if (opts.limit != null) params.append('limit', String(opts.limit));
|
||||
return apiJson<SearchSuggestions>(`/api/search/suggest?${params.toString()}`, {
|
||||
credentials: 'same-origin'
|
||||
credentials: 'same-origin',
|
||||
signal: opts.signal
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -130,6 +130,11 @@
|
||||
let suggestOpen = $state(false);
|
||||
let suggestBusy = $state(false);
|
||||
let suggestTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
// Stale-response guard (same family as the search page): the debounce
|
||||
// spaces requests out but doesn't stop a SLOW earlier response from
|
||||
// resolving after a newer one and overwriting its suggestions.
|
||||
let suggestSeq = 0;
|
||||
let suggestInflight: AbortController | null = null;
|
||||
|
||||
function goToResults() {
|
||||
const q = searchQuery.trim();
|
||||
@@ -149,24 +154,33 @@
|
||||
if (suggestTimer) clearTimeout(suggestTimer);
|
||||
const q = searchQuery.trim();
|
||||
if (q.length < 2) {
|
||||
suggestSeq++;
|
||||
suggestInflight?.abort();
|
||||
suggestInflight = null;
|
||||
suggestions = [];
|
||||
suggestOpen = false;
|
||||
return;
|
||||
}
|
||||
suggestTimer = setTimeout(async () => {
|
||||
const seq = ++suggestSeq;
|
||||
suggestInflight?.abort();
|
||||
const ctl = new AbortController();
|
||||
suggestInflight = ctl;
|
||||
suggestBusy = true;
|
||||
try {
|
||||
const r = await searchFiles(q, { recursive: true, limit: 6 });
|
||||
const r = await searchFiles(q, { recursive: true, limit: 6, signal: ctl.signal });
|
||||
if (seq !== suggestSeq) return; // superseded while awaiting
|
||||
suggestions = [
|
||||
...r.folders.slice(0, 3).map((item) => ({ kind: 'folder' as const, item })),
|
||||
...r.files.slice(0, 6).map((item) => ({ kind: 'file' as const, item }))
|
||||
];
|
||||
suggestOpen = suggestions.length > 0;
|
||||
} catch {
|
||||
if (seq !== suggestSeq || ctl.signal.aborted) return;
|
||||
suggestions = [];
|
||||
suggestOpen = false;
|
||||
} finally {
|
||||
suggestBusy = false;
|
||||
if (seq === suggestSeq) suggestBusy = false;
|
||||
}
|
||||
}, 250);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/**
|
||||
* Benchmark gate for the module-level MediaQueryList in
|
||||
* {@link gridColumns} (`lib/utils/grid.ts`).
|
||||
*
|
||||
* Audit finding: `gridColumns` constructed a fresh
|
||||
* `window.matchMedia('(max-width: 640px)')` on EVERY invocation — a style
|
||||
* read per call — and it is called from the grid windowing derives on every
|
||||
* width recompute (`ResourceList.gridCols`, files grid rows). This is the
|
||||
* same anti-pattern the photos timeline already fixed by hoisting to one
|
||||
* listener-fed flag.
|
||||
*
|
||||
* Gates:
|
||||
* 1. Output identity — for a sweep of widths, the hoisted implementation
|
||||
* returns exactly what the per-call implementation returns (both mobile
|
||||
* and desktop breakpoint states).
|
||||
* 2. Perf — 10 000 calls construct 0 additional MediaQueryList objects
|
||||
* (BEFORE: 10 000) and run ≥5x faster.
|
||||
*/
|
||||
|
||||
interface FakeMql {
|
||||
matches: boolean;
|
||||
addEventListener: (t: string, fn: (e: { matches: boolean }) => void) => void;
|
||||
}
|
||||
|
||||
function installMatchMedia(matches: boolean, counter: { constructed: number }): void {
|
||||
vi.stubGlobal(
|
||||
'matchMedia',
|
||||
vi.fn((): FakeMql => {
|
||||
counter.constructed++;
|
||||
return { matches, addEventListener: () => {} };
|
||||
})
|
||||
);
|
||||
// jsdom exposes window === globalThis in vitest; stub both lookup paths.
|
||||
(window as unknown as { matchMedia: unknown }).matchMedia = globalThis.matchMedia;
|
||||
}
|
||||
|
||||
/** BEFORE — verbatim old shape: fresh matchMedia per call. */
|
||||
function gridColumnsBefore(width: number): number {
|
||||
if (width <= 0) return 1;
|
||||
const mobile = typeof window !== 'undefined' && window.matchMedia('(max-width: 640px)').matches;
|
||||
const cardMin = mobile ? 140 : 200;
|
||||
const gap = mobile ? 8 : 20;
|
||||
return Math.max(1, Math.floor((width + gap) / (cardMin + gap)));
|
||||
}
|
||||
|
||||
describe('gridColumns matchMedia hoist (benchmark gate)', () => {
|
||||
it('output identity across widths + constructions collapse to ≤1', async () => {
|
||||
const counter = { constructed: 0 };
|
||||
installMatchMedia(false, counter);
|
||||
// Import AFTER stubbing so the module-level MQL uses the stub.
|
||||
vi.resetModules();
|
||||
const { gridColumns } = await import('./grid');
|
||||
const afterModuleConstructions = counter.constructed; // the one hoisted MQL
|
||||
expect(afterModuleConstructions).toBeLessThanOrEqual(1);
|
||||
|
||||
const widths = [-10, 0, 120, 320, 640, 641, 800, 1024, 1440, 1920, 2560];
|
||||
for (const w of widths) {
|
||||
expect(gridColumns(w)).toBe(gridColumnsBefore(w));
|
||||
}
|
||||
|
||||
const N = 10_000;
|
||||
counter.constructed = 0;
|
||||
const t0 = performance.now();
|
||||
let accBefore = 0;
|
||||
for (let i = 0; i < N; i++) accBefore += gridColumnsBefore(300 + (i % 1200));
|
||||
const beforeMs = performance.now() - t0;
|
||||
const beforeConstructed = counter.constructed;
|
||||
|
||||
counter.constructed = 0;
|
||||
const t1 = performance.now();
|
||||
let accAfter = 0;
|
||||
for (let i = 0; i < N; i++) accAfter += gridColumns(300 + (i % 1200));
|
||||
const afterMs = performance.now() - t1;
|
||||
|
||||
expect(accAfter).toBe(accBefore); // identity over the whole sweep
|
||||
expect(beforeConstructed).toBe(N);
|
||||
expect(counter.constructed).toBe(0); // zero style reads per call now
|
||||
console.log(
|
||||
`[bench] gridColumns x${N}: BEFORE ${beforeMs.toFixed(1)} ms (${beforeConstructed} MQL constructions) → AFTER ${afterMs.toFixed(1)} ms (0 constructions)`
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,35 +1,60 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { gridColumns } from './grid';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
function mockMatchMedia(matches: boolean) {
|
||||
/**
|
||||
* `gridColumns` reads the phone breakpoint from ONE module-level
|
||||
* MediaQueryList (fed by its `change` listener) instead of constructing a
|
||||
* fresh `matchMedia` per call — so tests set the media state BEFORE
|
||||
* importing the module (a fresh import per state via `vi.resetModules`),
|
||||
* and flips are delivered through the captured `change` listener, exactly
|
||||
* as the browser does.
|
||||
*/
|
||||
type MqlListener = (e: { matches: boolean }) => void;
|
||||
|
||||
async function importWithMedia(matches: boolean) {
|
||||
const listeners: MqlListener[] = [];
|
||||
vi.stubGlobal(
|
||||
'matchMedia',
|
||||
vi.fn().mockReturnValue({
|
||||
matches,
|
||||
media: '',
|
||||
addEventListener: vi.fn(),
|
||||
addEventListener: (_t: string, fn: MqlListener) => listeners.push(fn),
|
||||
removeEventListener: vi.fn()
|
||||
})
|
||||
);
|
||||
vi.resetModules();
|
||||
const mod = await import('./grid');
|
||||
return {
|
||||
gridColumns: mod.gridColumns,
|
||||
fire: (m: boolean) => listeners.forEach((l) => l({ matches: m }))
|
||||
};
|
||||
}
|
||||
|
||||
describe('gridColumns', () => {
|
||||
beforeEach(() => mockMatchMedia(false));
|
||||
|
||||
it('returns 1 for non-positive width', () => {
|
||||
it('returns 1 for non-positive width', async () => {
|
||||
const { gridColumns } = await importWithMedia(false);
|
||||
expect(gridColumns(0)).toBe(1);
|
||||
expect(gridColumns(-100)).toBe(1);
|
||||
});
|
||||
|
||||
it('computes columns at desktop sizing (cardMin 200, gap 20)', () => {
|
||||
it('computes columns at desktop sizing (cardMin 200, gap 20)', async () => {
|
||||
const { gridColumns } = await importWithMedia(false);
|
||||
expect(gridColumns(220)).toBe(1); // floor(240/220)
|
||||
expect(gridColumns(440)).toBe(2); // floor(460/220)
|
||||
expect(gridColumns(900)).toBe(4); // floor(920/220)
|
||||
});
|
||||
|
||||
it('uses mobile sizing when the phone media query matches', () => {
|
||||
mockMatchMedia(true);
|
||||
it('uses mobile sizing when the phone media query matches', async () => {
|
||||
const { gridColumns } = await importWithMedia(true);
|
||||
expect(gridColumns(300)).toBe(2); // floor(308/148)
|
||||
expect(gridColumns(600)).toBe(4); // floor(608/148)
|
||||
});
|
||||
|
||||
it('breakpoint crossings propagate through the change listener', async () => {
|
||||
const { gridColumns, fire } = await importWithMedia(false);
|
||||
expect(gridColumns(600)).toBe(2); // desktop sizing
|
||||
fire(true); // viewport crossed under 640px
|
||||
expect(gridColumns(600)).toBe(4); // mobile sizing
|
||||
fire(false);
|
||||
expect(gridColumns(600)).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,11 +6,26 @@
|
||||
*
|
||||
* Card-min / gap track the tokens in `lib/styles/base/variables.css` and the
|
||||
* ≤640px phone override in `lib/styles/ported/resourceList.css`.
|
||||
*
|
||||
* The phone breakpoint is watched by ONE module-level MediaQueryList listener
|
||||
* — constructing a fresh `matchMedia` per call (a style read) was the same
|
||||
* anti-pattern the photos timeline already hoisted. A flip of the media query
|
||||
* always coincides with a width change, so callers re-run anyway.
|
||||
*/
|
||||
let isMobile = false;
|
||||
// `typeof window.matchMedia` (not just `window`): jsdom test environments
|
||||
// expose `window` without implementing matchMedia.
|
||||
if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
|
||||
const mql = window.matchMedia('(max-width: 640px)');
|
||||
isMobile = mql.matches;
|
||||
mql.addEventListener('change', (e) => {
|
||||
isMobile = e.matches;
|
||||
});
|
||||
}
|
||||
|
||||
export function gridColumns(width: number): number {
|
||||
if (width <= 0) return 1;
|
||||
const mobile = typeof window !== 'undefined' && window.matchMedia('(max-width: 640px)').matches;
|
||||
const cardMin = mobile ? 140 : 200;
|
||||
const gap = mobile ? 8 : 20;
|
||||
const cardMin = isMobile ? 140 : 200;
|
||||
const gap = isMobile ? 8 : 20;
|
||||
return Math.max(1, Math.floor((width + gap) / (cardMin + gap)));
|
||||
}
|
||||
|
||||
@@ -124,11 +124,25 @@
|
||||
{ v: 'size', l: t('search.sort.smallest', 'Smallest') }
|
||||
];
|
||||
|
||||
// Stale-response guard: rapid-fire query/filter/sort changes each start a
|
||||
// full recursive backend search; without the token a SLOW earlier response
|
||||
// could resolve after (and clobber) a newer one, and the superseded server
|
||||
// work ran to completion. The seq token keeps only the latest result; the
|
||||
// AbortController cancels the superseded request outright.
|
||||
let runSeq = 0;
|
||||
let inflight: AbortController | null = null;
|
||||
|
||||
async function run(q: string) {
|
||||
const seq = ++runSeq;
|
||||
inflight?.abort();
|
||||
inflight = null;
|
||||
if (!q) {
|
||||
results = null;
|
||||
loading = false;
|
||||
return;
|
||||
}
|
||||
const ctl = new AbortController();
|
||||
inflight = ctl;
|
||||
loading = true;
|
||||
error = null;
|
||||
try {
|
||||
@@ -137,18 +151,23 @@
|
||||
scope === 'folder' && filesStore.section !== 'trash'
|
||||
? (filesStore.currentFolder ?? undefined)
|
||||
: undefined;
|
||||
results = await searchFiles(q, {
|
||||
const fresh = await searchFiles(q, {
|
||||
recursive: true,
|
||||
sortBy,
|
||||
folderId,
|
||||
fileTypes: typeFilter === 'all' ? undefined : TYPE_EXT[typeFilter],
|
||||
...sizeBounds(sizeFilter),
|
||||
modifiedAfter: dateBound(dateFilter)
|
||||
modifiedAfter: dateBound(dateFilter),
|
||||
signal: ctl.signal
|
||||
});
|
||||
if (seq !== runSeq) return; // superseded while awaiting
|
||||
results = fresh;
|
||||
} catch (e) {
|
||||
// An aborted request is not an error — a newer run owns the UI.
|
||||
if (seq !== runSeq || ctl.signal.aborted) return;
|
||||
error = errorMessage(e);
|
||||
} finally {
|
||||
loading = false;
|
||||
if (seq === runSeq) loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* Benchmark gate for the search stale-response guard + AbortController
|
||||
* (search/+page.svelte `run()` and AppShell's suggest fetch).
|
||||
*
|
||||
* Audit finding (open since ROUND7): every query/sort/scope/filter change
|
||||
* re-fired `run(query)` with NO sequence token and NO abort — so (a) a slow
|
||||
* earlier response could resolve after a newer one and overwrite `results`
|
||||
* with stale hits, and (b) every superseded server search ran to completion
|
||||
* (wasted recursive-search CPU + bandwidth on the backend).
|
||||
*
|
||||
* Gates:
|
||||
* 1. Correctness — with responses resolving in REVERSE order, the unguarded
|
||||
* BEFORE shape ends showing the FIRST (stale) query's results; the
|
||||
* guarded AFTER shape always ends with the LAST query's results.
|
||||
* 2. Perf — the AFTER shape aborts every superseded request: for N
|
||||
* rapid-fire queries only 1 reaches full completion (N-1 aborted), where
|
||||
* BEFORE always pays N complete round-trips.
|
||||
*/
|
||||
|
||||
interface FakeResults {
|
||||
forQuery: string;
|
||||
}
|
||||
|
||||
/** A fetch whose resolution order and abort behaviour we control. */
|
||||
function fakeSearch(
|
||||
q: string,
|
||||
delayMs: number,
|
||||
completed: { count: number },
|
||||
signal?: AbortSignal
|
||||
): Promise<FakeResults> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
completed.count++;
|
||||
resolve({ forQuery: q });
|
||||
}, delayMs);
|
||||
signal?.addEventListener('abort', () => {
|
||||
clearTimeout(timer);
|
||||
reject(new DOMException('aborted', 'AbortError'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** BEFORE — verbatim old `run()` shape: fire and assign, no token, no abort. */
|
||||
function makeBefore(completed: { count: number }) {
|
||||
const state = { results: null as FakeResults | null };
|
||||
return {
|
||||
state,
|
||||
run: async (q: string, delayMs: number) => {
|
||||
try {
|
||||
state.results = await fakeSearch(q, delayMs, completed);
|
||||
} catch {
|
||||
/* unreachable in this harness */
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** AFTER — the shipped shape: seq token + AbortController per run. */
|
||||
function makeAfter(completed: { count: number }) {
|
||||
const state = { results: null as FakeResults | null };
|
||||
let runSeq = 0;
|
||||
let inflight: AbortController | null = null;
|
||||
return {
|
||||
state,
|
||||
run: async (q: string, delayMs: number) => {
|
||||
const seq = ++runSeq;
|
||||
inflight?.abort();
|
||||
const ctl = new AbortController();
|
||||
inflight = ctl;
|
||||
try {
|
||||
const fresh = await fakeSearch(q, delayMs, completed, ctl.signal);
|
||||
if (seq !== runSeq) return;
|
||||
state.results = fresh;
|
||||
} catch {
|
||||
if (seq !== runSeq || ctl.signal.aborted) return;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
describe('search stale-response guard (benchmark gate)', () => {
|
||||
it('BEFORE clobbers with stale results; AFTER keeps the latest query', async () => {
|
||||
// Query "a" resolves SLOWLY (60 ms), "ab" (30 ms), "abc" fast (1 ms):
|
||||
// resolution order is the reverse of issue order.
|
||||
const beforeDone = { count: 0 };
|
||||
const before = makeBefore(beforeDone);
|
||||
const pBefore = [before.run('a', 60), before.run('ab', 30), before.run('abc', 1)];
|
||||
await Promise.all(pBefore);
|
||||
// The slowest (oldest) response lands last and wins — the bug.
|
||||
expect(before.state.results?.forQuery).toBe('a');
|
||||
expect(beforeDone.count).toBe(3); // every superseded search ran to completion
|
||||
|
||||
const afterDone = { count: 0 };
|
||||
const after = makeAfter(afterDone);
|
||||
const pAfter = [after.run('a', 60), after.run('ab', 30), after.run('abc', 1)];
|
||||
await Promise.all(pAfter);
|
||||
expect(after.state.results?.forQuery).toBe('abc'); // latest wins, always
|
||||
expect(afterDone.count).toBe(1); // superseded requests were aborted
|
||||
});
|
||||
|
||||
it('rapid-fire burst: completed round-trips collapse N → 1', async () => {
|
||||
const N = 10;
|
||||
const beforeDone = { count: 0 };
|
||||
const before = makeBefore(beforeDone);
|
||||
await Promise.all(
|
||||
Array.from({ length: N }, (_, i) => before.run(`q${i}`, (N - i) * 5)) // reverse order
|
||||
);
|
||||
const afterDone = { count: 0 };
|
||||
const after = makeAfter(afterDone);
|
||||
await Promise.all(Array.from({ length: N }, (_, i) => after.run(`q${i}`, (N - i) * 5)));
|
||||
|
||||
expect(beforeDone.count).toBe(N);
|
||||
expect(afterDone.count).toBe(1);
|
||||
expect(after.state.results?.forQuery).toBe(`q${N - 1}`);
|
||||
console.log(
|
||||
`[bench] ${N} rapid-fire searches — completed round-trips BEFORE=${beforeDone.count} AFTER=${afterDone.count}; final result BEFORE="${before.state.results?.forQuery}" (stale) AFTER="${after.state.results?.forQuery}" (fresh)`
|
||||
);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user