Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions ext/js/dictionary/term-bank-wasm-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -2890,8 +2890,9 @@ class ParallelTermBankPipelineRun {
* @param {() => boolean} shouldCancel
* @param {{getWorkers: () => Promise<{workers: Worker[]}>, release: (keepWorkers: boolean) => Promise<void>}} 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[][]} */
Expand All @@ -2914,6 +2915,8 @@ class ParallelTermBankPipelineRun {
this._shouldCancel = shouldCancel;
/** @type {{getWorkers: () => Promise<{workers: Worker[]}>, release: (keepWorkers: boolean) => Promise<void>}} */
this._poolLease = poolLease;
/** @type {boolean} */
this._overlapFirstCompressedGroup = overlapFirstCompressedGroup;
/** @type {number} */
this._pipelineGroupsPerWorker = pipelineGroupsPerWorker;
/** @type {Array<{promise: Promise<{chunk: TermBankColumnChunk|null, profile: NonNullable<typeof lastTermBankWasmParseProfile>|null, error: unknown, finishedAt: number, rowCount: number, sourceBytes: number, ownedContentBytes?: number, consume: (() => void)|null}>, resolve: (value: {chunk: TermBankColumnChunk|null, profile: NonNullable<typeof lastTermBankWasmParseProfile>|null, error: unknown, finishedAt: number, rowCount: number, sourceBytes: number, ownedContentBytes?: number, consume: (() => void)|null}) => void}>} */
Expand Down Expand Up @@ -2951,6 +2954,15 @@ class ParallelTermBankPipelineRun {
/** @returns {Promise<boolean>} */
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);
Expand All @@ -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;
Expand Down Expand Up @@ -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);
}

/**
Expand All @@ -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<boolean>}
*/
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';
Expand Down Expand Up @@ -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,
Expand All @@ -3405,6 +3419,7 @@ async function parseTermBankWithWasmColumnChunksParallelSources(sources, version
shouldCancel,
poolLease,
pipelineGroupsPerWorker,
prefetchFirstCompressedGroup,
);
return await run.run();
}
Expand Down
64 changes: 54 additions & 10 deletions test/term-bank-wasm-parser.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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; }
Expand All @@ -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},
Expand All @@ -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);
Expand Down
Loading