From 31954a3625fe4e53f04ef86f29c62692c9e851e5 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Sun, 29 Nov 2026 02:13:34 -0500 Subject: [PATCH] Overlap bounded first compressed term group --- ext/js/dictionary/term-bank-wasm-parser.js | 23 ++++++-- test/term-bank-wasm-parser.test.js | 64 ++++++++++++++++++---- 2 files changed, 73 insertions(+), 14 deletions(-) diff --git a/ext/js/dictionary/term-bank-wasm-parser.js b/ext/js/dictionary/term-bank-wasm-parser.js index 751fc38b43..a359bec032 100644 --- a/ext/js/dictionary/term-bank-wasm-parser.js +++ b/ext/js/dictionary/term-bank-wasm-parser.js @@ -2890,8 +2890,9 @@ class ParallelTermBankPipelineRun { * @param {() => boolean} shouldCancel * @param {{getWorkers: () => Promise<{workers: Worker[]}>, release: (keepWorkers: boolean) => Promise}} poolLease * @param {number} pipelineGroupsPerWorker + * @param {boolean} overlapFirstCompressedGroup */ - constructor(sources, groups, totalBytes, version, onChunk, options, shouldCancel, poolLease, pipelineGroupsPerWorker) { + constructor(sources, groups, totalBytes, version, onChunk, options, shouldCancel, poolLease, pipelineGroupsPerWorker, overlapFirstCompressedGroup) { /** @type {ParallelTermBankSource[]} */ this._sources = sources; /** @type {ParallelTermBankSource[][]} */ @@ -2914,6 +2915,8 @@ class ParallelTermBankPipelineRun { this._shouldCancel = shouldCancel; /** @type {{getWorkers: () => Promise<{workers: Worker[]}>, release: (keepWorkers: boolean) => Promise}} */ this._poolLease = poolLease; + /** @type {boolean} */ + this._overlapFirstCompressedGroup = overlapFirstCompressedGroup; /** @type {number} */ this._pipelineGroupsPerWorker = pipelineGroupsPerWorker; /** @type {Array<{promise: Promise<{chunk: TermBankColumnChunk|null, profile: NonNullable|null, error: unknown, finishedAt: number, rowCount: number, sourceBytes: number, ownedContentBytes?: number, consume: (() => void)|null}>, resolve: (value: {chunk: TermBankColumnChunk|null, profile: NonNullable|null, error: unknown, finishedAt: number, rowCount: number, sourceBytes: number, ownedContentBytes?: number, consume: (() => void)|null}) => void}>} */ @@ -2951,6 +2954,15 @@ class ParallelTermBankPipelineRun { /** @returns {Promise} */ async run() { try { + this._createSlots(); + // Begin just the first byte-balanced group before worker startup. + // This overlaps bounded ZIP reads with module compilation and + // worker readiness without opening the wider lead window early. + if (this._overlapFirstCompressedGroup) { + this._throwIfStopped(); + this._maxLeadGroups = 1; + this._activateLeadSources(); + } const [{workers}] = await waitForParallelWork([this._poolLease.getWorkers()], this._shouldCancel); this._throwIfStopped(); await this._runPipeline(workers); @@ -2969,7 +2981,6 @@ class ParallelTermBankPipelineRun { /** @param {Worker[]} workers */ async _runPipeline(workers) { - this._createSlots(); this._maxLeadGroups = Math.max(1, workers.length * this._pipelineGroupsPerWorker); if (this._groups.length >= this._maxLeadGroups * MIN_WINDOWS_FOR_INCREMENTAL_SOURCE_ACTIVATION) { this._nextSourceActivationGroupIndex = 0; @@ -3327,7 +3338,7 @@ export async function parseTermBankWithWasmColumnChunksParallelCompressedLazy(so estimatedBytes: estimatedByteLengths[index], resolvedAt: 0, })); - return await parseTermBankWithWasmColumnChunksParallelSources(sources, version, onChunk, options, shouldCancel, true); + return await parseTermBankWithWasmColumnChunksParallelSources(sources, version, onChunk, options, shouldCancel, true, true); } /** @@ -3337,9 +3348,10 @@ export async function parseTermBankWithWasmColumnChunksParallelCompressedLazy(so * @param {TermBankColumnParserOptions} options * @param {() => boolean} shouldCancel * @param {boolean} [lazy=false] + * @param {boolean} [overlapFirstCompressedGroup=false] * @returns {Promise} */ -async function parseTermBankWithWasmColumnChunksParallelSources(sources, version, onChunk, options, shouldCancel, lazy = false) { +async function parseTermBankWithWasmColumnChunksParallelSources(sources, version, onChunk, options, shouldCancel, lazy = false, overlapFirstCompressedGroup = false) { lastParallelParserSkipReason = null; if (sources.length < 4) { lastParallelParserSkipReason = 'source-count'; @@ -3395,6 +3407,8 @@ async function parseTermBankWithWasmColumnChunksParallelSources(sources, version return false; } + const prefetchFirstCompressedGroup = overlapFirstCompressedGroup && + groups[0].reduce((size, {estimatedBytes}) => size + estimatedBytes, 0) <= LAZY_PARALLEL_SOURCE_TARGET_GROUP_BYTES; const run = new ParallelTermBankPipelineRun( sources, groups, @@ -3405,6 +3419,7 @@ async function parseTermBankWithWasmColumnChunksParallelSources(sources, version shouldCancel, poolLease, pipelineGroupsPerWorker, + prefetchFirstCompressedGroup, ); return await run.run(); } diff --git a/test/term-bank-wasm-parser.test.js b/test/term-bank-wasm-parser.test.js index f3909aa8d3..3998acc854 100644 --- a/test/term-bank-wasm-parser.test.js +++ b/test/term-bank-wasm-parser.test.js @@ -2029,14 +2029,15 @@ describe('term-bank WASM parser', () => { } }); - maybeTest.each(['cancel', 'shared-prewarm', 'callback-error', 'ready-race'])( - 'settles cancellation during parser worker startup: %s', + maybeTest.each(['cancel', 'shared-prewarm', 'callback-error', 'ready-race', 'source-error', 'startup-error', 'oversize'])( + 'settles compressed startup overlap and cleanup: %s', async (mode) => { /** @type {StartupWorker[]} */ const instances = []; let initialized = () => {}; const initializationStarted = new Promise((resolve) => { initialized = () => resolve(void 0); }); let ready = false; + let startupFailureOnce = true; let cancelled = false; let sourceLoads = 0; let sinkCalls = 0; @@ -2064,7 +2065,14 @@ describe('term-bank WASM parser', () => { postMessage(/** @type {WorkerMessage} */ message) { if (message.type !== 'initialize') { throw new Error('Dispatched parse before startup finished'); } initialized(); - if (ready || mode === 'ready-race') { + if (mode === 'startup-error' && startupFailureOnce) { + queueMicrotask(() => { + startupFailureOnce = false; + emitWorkerMessage(this.listeners, {type: 'initialization-error', error: {message: 'Injected startup failure'}}); + }); + return; + } + if (ready || mode === 'ready-race' || mode === 'source-error') { queueMicrotask(() => { emitWorkerMessage(this.listeners, {type: 'ready'}); if (mode === 'ready-race') { cancelled = true; } @@ -2078,9 +2086,20 @@ describe('term-bank WASM parser', () => { vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval']}); vi.stubGlobal('Worker', StartupWorker); const prewarm = mode === 'shared-prewarm' ? prewarmParallelTermBankParser() : null; - const parse = parseTermBankWithWasmColumnChunksParallelLazy( - Array.from({length: 4}, () => async () => { ++sourceLoads; return textEncoder.encode('[]'); }), - [2, 2, 2, 2], + const parse = parseTermBankWithWasmColumnChunksParallelCompressedLazy( + Array.from({length: 4}, () => async () => { + ++sourceLoads; + if (mode === 'source-error') { throw new Error('Prefetched source failed'); } + return { + bytes: textEncoder.encode('[]'), + compressionMethod: 0, + compressedSize: 2, + uncompressedSize: 2, + signature: 0, + filename: 'term_bank_1.json', + }; + }), + [mode === 'oversize' ? 25 * 1024 * 1024 : 2, 2, 2, 2], 3, () => { ++sinkCalls; }, {emitContentSlab: true}, @@ -2094,13 +2113,38 @@ describe('term-bank WASM parser', () => { }); try { await initializationStarted; - cancelled = true; - await vi.advanceTimersByTimeAsync(250); + if (mode === 'oversize') { + expect(sourceLoads).toBe(0); + } else { + expect(sourceLoads).toBeGreaterThan(0); + expect(sourceLoads).toBeLessThan(4); + } + if (mode === 'source-error') { + await parse; + } else { + cancelled = true; + await vi.advanceTimersByTimeAsync(250); + } expect(settled).toBe(true); - expect(failure).toMatchObject(mode === 'callback-error' ? {message: callbackError.message} : {name: 'AbortError'}); + switch (mode) { + case 'source-error': + expect(failure).toMatchObject({message: 'Prefetched source failed'}); + break; + case 'startup-error': + expect(failure).toBeInstanceOf(Error); + break; + case 'callback-error': + expect(failure).toMatchObject({message: callbackError.message}); + break; + default: + expect(failure).toMatchObject({name: 'AbortError'}); + break; + } await parse; if (prewarm !== null) { await expect(prewarm).resolves.toBe(false); } - expect(sourceLoads).toBe(0); + // Cancellation prevents parse dispatch and sink calls. An + // oversized group has not started reading during startup. + if (mode === 'oversize') { expect(sourceLoads).toBe(0); } expect(sinkCalls).toBe(0); expect(instances.length).toBeGreaterThanOrEqual(2); expect(instances.every((worker) => worker.terminated)).toBe(true);