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
42 changes: 34 additions & 8 deletions ext/js/dictionary/dictionary-database.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ import {
import {TermContentIntegrityError, TermContentOpfsStore} from './term-content-opfs-store.js';
import {TermContentImmutableFileStore} from './term-content-immutable-file-store.js';
import {skipLegacyEligibilitySelector} from './term-content-legacy-eligibility.js';
import {isRawTermContentTrainingSelector} from './term-content-optimization-candidate-source.js';
import {assertTermContentOptimizationHeadroom} from './term-content-optimization-headroom.js';
import {ContentPhysicalFileIntegrityError, parseContentPhysicalFile, TermContentPhysicalFileStore} from './term-content-physical-file-store.js';
import {createContentLayoutResolver} from './term-content-layout.js';
Expand Down Expand Up @@ -5115,7 +5114,7 @@ void 0 :
*/
createOnlineContentOptimizationRunner(batch = {}) {
/** @typedef {import('./term-content-optimization-controller.js').OptimizationJob} Job */
const strategyVersion = 'fastcover-f18-level3-16k-w64k-v2';
const strategyVersion = 'fastcover-f18-level3-16k-w64k-v3-raw-entry';
/** @type {import('./term-content-optimization-controller.js').OptimizationHost['getJob']} */
const getJob = (jobId) => {
this._assertOnlineContentMutationReady();
Expand Down Expand Up @@ -5192,6 +5191,7 @@ void 0 :
strategy: 2,
level: 3,
strategyVersion,
compatibleStrategyVersions: ['fastcover-f18-level3-16k-w64k-v2'],
host: {
getJob,
nextRetryAt: () => this._asNullableNumber(this._requireDb().selectValue(
Expand Down Expand Up @@ -5314,13 +5314,34 @@ void 0 :
Array.isArray(summary) || Reflect.get(summary, 'importSuccess') !== true) { continue; }
const generation = this._getSummaryStorageGenerationId(summary, title);
if (generation.length === 0 || generation.length > 256) { continue; }
const exists = db.selectValue(
'SELECT 1 FROM termContentOptimizationJobs WHERE dictionaryGeneration = $generation AND strategyVersion = $version',
{$generation: generation, $version: strategyVersion},
const history = db.selectObjects(
'SELECT strategyVersion, phase, checkpointJson FROM termContentOptimizationJobs WHERE dictionaryGeneration = $generation',
{$generation: generation},
);
if (exists !== 1) {
return {jobId: 'zstd-' + crypto.randomUUID(), dictionaryTitle: title, dictionaryGeneration: generation};
if (history.some((job) => job.strategyVersion === strategyVersion)) { continue; }
if (history.length > 0) {
// A completed generation has already been optimized. Only
// reconsider old v2 no-gain jobs that found no trainable
// frames; v2 skipped raw references before discovery.
if (history.some((job) => job.phase === 'completed' || job.phase === 'failed')) { continue; }
const reconsiderable = history.some((job) => {
if (job.strategyVersion !== 'fastcover-f18-level3-16k-w64k-v2' || job.phase !== 'no-gain') { return false; }
const checkpoint = /** @type {unknown} */ (this._safeParseJson(this._asString(job.checkpointJson), null));
if (!checkpoint || typeof checkpoint !== 'object' || Array.isArray(checkpoint)) { return false; }
const sampler = /** @type {unknown} */ (Reflect.get(checkpoint, 'sampler'));
const samplerSummary = sampler && typeof sampler === 'object' ? /** @type {unknown} */ (Reflect.get(sampler, 'summary')) : null;
const entries = samplerSummary && typeof samplerSummary === 'object' ? /** @type {unknown} */ (Reflect.get(samplerSummary, 'entries')) : null;
const samples = /** @type {unknown} */ (Reflect.get(checkpoint, 'samples'));
// Existing v2 jobs may omit the optional inactive flag.
const legacyProbe = /** @type {unknown} */ (Reflect.get(checkpoint, 'legacyProbe'));
return (typeof legacyProbe === 'undefined' || legacyProbe === false) &&
Reflect.get(checkpoint, 'publishedBatches') === 0 &&
Reflect.get(checkpoint, 'sampleMode') === 'summary' && entries === 0 &&
Array.isArray(samples) && samples.length === 0;
});
if (!reconsiderable) { continue; }
}
return {jobId: 'zstd-' + crypto.randomUUID(), dictionaryTitle: title, dictionaryGeneration: generation};
}
}
}
Expand Down Expand Up @@ -5818,7 +5839,7 @@ null :
signal,
...(legacyProbe ?
{skipSelector: skipLegacyEligibilitySelector} :
{skipSelector: isRawTermContentTrainingSelector, maxBlockReferences: blockRangeRows}),
{maxBlockReferences: blockRangeRows}),
isGenerationCurrent: () => this._getOnlineContentOptimizationTarget({dictionaryTitle: target.title,
dictionaryGeneration: job.dictionaryGeneration}) !== null,
});
Expand Down Expand Up @@ -6344,6 +6365,11 @@ db.selectObjects(
* @returns {Promise<import('./term-content-layout.js').FrameIdentity|null>}
*/
async _findOnlineContentFrameOverride(query, snapshot, readResources = null) {
// Import-owned references may be read just beyond the leased root's
// committed high-water mark. They still live in the staging store and
// have no immutable frame metadata yet.
if (!Number.isSafeInteger(query.logicalOffset) || query.logicalOffset < 0 ||
query.logicalOffset >= snapshot.logicalHighWater) { return null; }
const window = await this.getOnlineContentLayoutWindow(query.logicalOffset, snapshot, readResources);
if (window === null) { throw new Error('Immutable content frame metadata is unavailable'); }
/** @type {import('./term-content-layout.js').Frame|null} */
Expand Down
126 changes: 114 additions & 12 deletions ext/js/dictionary/term-content-block-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export {wrapCompressedTermContentBlock} from './term-content-block-envelope.js';
* @property {(requests: Array<{offset: number, length: number}>) => Promise<TermContentSliceResult[]>} readSlicesDetailed
* @property {(identity: TermContentFrameIdentity) => Promise<TermContentResolvedFrame|null>} resolveFrame
* @property {number} [logicalHighWater] Committed end under the leased root.
* @property {(query: {kind: 'legacy-entry', logicalOffset: number, recordLength: number, originalCodecId: string|null}) => Promise<TermContentFrameIdentity|null>} [findFrameOverride] Looks up replacement identity before inspecting retired source bytes.
* @property {(query: {kind: 'legacy-entry'|'raw-entry', logicalOffset: number, recordLength: number, originalCodecId: string|null}) => Promise<TermContentFrameIdentity|null>} [findFrameOverride] Looks up replacement identity before reading retired source bytes.
* @property {() => TermContentReadContext} fork
* @property {() => void} release
* @property {string} [rootKey] Stable immutable root identity for sharing pending I/O.
Expand Down Expand Up @@ -493,6 +493,8 @@ RAW_TERM_CONTENT_BLOCK_REFERENCE_BYTES;
/** @type {Array<{index: number, request: {contentOffset: number, contentLength: number, contentDictName: string}, compact: boolean|null, compressionDictName: string|null|undefined, sliceLength: number}>} */
const sliceRequests = [];
/** @type {Array<{index: number, request: {contentOffset: number, contentLength: number, contentDictName: string}}>} */
const rawRequests = [];
/** @type {Array<{index: number, request: {contentOffset: number, contentLength: number, contentDictName: string}}>} */
const legacyRequests = [];
for (let index = 0; index < requests.length; ++index) {
const request = requests[index];
Expand All @@ -503,13 +505,12 @@ RAW_TERM_CONTENT_BLOCK_REFERENCE_BYTES;
legacyRequests.push({index, request});
continue;
}
sliceRequests.push({
index,
request,
compact: null,
compressionDictName,
sliceLength: contentLength,
});
if (readContext === null) {
// Preserve the existing bulk read path when no immutable root is active.
sliceRequests.push({index, request, compact: null, compressionDictName, sliceLength: contentLength});
continue;
}
rawRequests.push({index, request});
continue;
}
const compact = contentDictName === RAW_TERM_CONTENT_DIRECT_BLOCK_DICT_NAME_PREFIX ||
Expand Down Expand Up @@ -583,15 +584,17 @@ await (readContext ?? this._contentStore).readSlicesDetailed(sliceRequests.map((
}

const groupList = [...groups.values()];
const [groupSettled, legacySettled] = await Promise.all([Promise.allSettled(groupList.map(async ({cacheKey, reference, compressionDictName, context}) => {
const [groupSettled, legacySettled, rawResults] = await Promise.all([Promise.allSettled(groupList.map(async ({cacheKey, reference, compressionDictName, context}) => {
const cached = this._cache.get(cacheKey);
if (typeof cached !== 'undefined') { return cached; }
const block = await this._getOrLoadBlock(cacheKey, reference, compressionDictName, context, readContext);
if (block === null) {
throw new TermContentReadError('temporarilyUnavailable', 'Term content block could not be loaded');
}
return block;
})), Promise.allSettled(legacyRequests.map(async ({request}) => await this._readLegacyEntry(request.contentOffset, request.contentLength, request.contentDictName, readContext)))]);
})),
Promise.allSettled(legacyRequests.map(async ({request}) => await this._readLegacyEntry(request.contentOffset, request.contentLength, request.contentDictName, readContext))),
this._readRawEntryBatch(rawRequests, readContext)]);
if (generation !== this._cacheGeneration) {
return requests.map(() => this._createInvalidatedReadFailure());
}
Expand All @@ -601,6 +604,9 @@ await (readContext ?? this._contentStore).readSlicesDetailed(sliceRequests.map((
this._createReadFailure(settled.reason) :
{status: 'ok', bytes: settled.value};
}
for (let i = 0; i < rawRequests.length; ++i) {
results[rawRequests[i].index] = rawResults[i];
}
for (let i = 0; i < groupList.length; ++i) {
const group = groupList[i];
const settled = groupSettled[i];
Expand All @@ -624,6 +630,72 @@ await (readContext ?? this._contentStore).readSlicesDetailed(sliceRequests.map((
return results;
}

/**
* Keeps ordinary raw batch reads in one root-backed I/O batch. Only spans
* with a published raw-entry override enter the frame decoder path.
* @param {Array<{index: number, request: {contentOffset: number, contentLength: number, contentDictName: string}}>} requests
* @param {TermContentReadContext|null} readContext
* @returns {Promise<Array<{status: 'ok', bytes: Uint8Array}|{status: 'temporarilyUnavailable'|'corrupt', reason: string}>>}
*/
async _readRawEntryBatch(requests, readContext) {
if (requests.length === 0) { return []; }
const findFrameOverride = readContext?.findFrameOverride;
const matches = typeof findFrameOverride === 'function' ?
await Promise.allSettled(requests.map(({request}) => findFrameOverride.call(readContext, {kind: 'raw-entry',
logicalOffset: request.contentOffset,
recordLength: request.contentLength,
originalCodecId: null}))) :
null;
/** @type {Array<{index: number, request: {contentOffset: number, contentLength: number, contentDictName: string}}>} */
const direct = [];
/** @type {Array<{index: number, request: {contentOffset: number, contentLength: number, contentDictName: string}, identity: TermContentFrameIdentity}>} */
const overridden = [];
const results = new Array(requests.length);
for (let i = 0; i < requests.length; ++i) {
const {request} = requests[i];
const match = matches?.[i];
if (match?.status === 'rejected') {
results[i] = this._createReadFailure(match.reason);
} else if (typeof match === 'undefined' || match.value === null) {
direct.push({index: i, request});
} else {
overridden.push({index: i, request, identity: match.value});
}
}
const directSlices = direct.length === 0 ?
[] :
await (readContext ?? this._contentStore).readSlicesDetailed(direct.map(({request}) => ({
offset: request.contentOffset,
length: request.contentLength,
})));
if (directSlices.length !== direct.length) { throw new Error('Raw content batch read returned an invalid result count'); }
for (let i = 0; i < direct.length; ++i) {
const slice = directSlices[i];
results[direct[i].index] = slice.status === 'error' ?
this._createReadFailure(slice.error) :
(slice.status === 'unavailable' ?
{status: 'temporarilyUnavailable', reason: 'Term content could not be read from OPFS'} :
{status: 'ok', bytes: slice.bytes});
}
const settledOverrides = await Promise.allSettled(overridden.map(async ({request, identity}) => {
const bytes = await this._getOrLoadFrame(
JSON.stringify(['raw-entry', request.contentOffset, request.contentLength]),
identity,
{contentOffset: request.contentOffset, contentLength: request.contentLength, contentDictName: request.contentDictName},
readContext,
);
if (!(bytes instanceof Uint8Array)) { throw new TermContentReadError('temporarilyUnavailable', 'Term content could not be read from OPFS'); }
return bytes;
}));
for (let i = 0; i < settledOverrides.length; ++i) {
const settled = settledOverrides[i];
results[overridden[i].index] = settled.status === 'rejected' ?
this._createReadFailure(settled.reason) :
{status: 'ok', bytes: settled.value};
}
return results;
}

/**
* @param {number} contentOffset
* @param {number} contentLength
Expand All @@ -638,7 +710,8 @@ await (readContext ?? this._contentStore).readSlicesDetailed(sliceRequests.map((
if (!RAW_CONTENT_SELECTORS.has(contentDictName)) {
return {status: 'ok', bytes: await this._readLegacyEntry(contentOffset, contentLength, contentDictName, readContext)};
}
const bytes = await (readContext ?? this._contentStore).readSlice(contentOffset, contentLength);
const bytes = await this._readRawEntry(contentOffset, contentLength, contentDictName, readContext);
this._assertReadGeneration(generation);
if (!(bytes instanceof Uint8Array)) {
throw new TermContentReadError('temporarilyUnavailable', 'Term content could not be read from OPFS');
}
Expand Down Expand Up @@ -681,6 +754,35 @@ await (readContext ?? this._contentStore).readSlicesDetailed(sliceRequests.map((
return {status: 'ok', bytes: block.subarray(reference.entryOffset, entryEnd)};
}

/**
* Reads a raw selector under the same immutable root lease as compressed
* frames. An unchanged root returns the original bytes; an online override
* is decoded by _loadFrame before it reaches the existing raw parser.
* @param {number} contentOffset
* @param {number} contentLength
* @param {string} contentDictName
* @param {TermContentReadContext|null} readContext
* @returns {Promise<Uint8Array>}
*/
async _readRawEntry(contentOffset, contentLength, contentDictName, readContext) {
const override = await readContext?.findFrameOverride?.({kind: 'raw-entry',
logicalOffset: contentOffset,
recordLength: contentLength,
originalCodecId: null}) ?? null;
const bytes = override === null ?
await (readContext ?? this._contentStore).readSlice(contentOffset, contentLength) :
await this._getOrLoadFrame(
JSON.stringify(['raw-entry', contentOffset, contentLength]),
override,
{contentOffset, contentLength, contentDictName},
readContext,
);
if (!(bytes instanceof Uint8Array)) {
throw new TermContentReadError('temporarilyUnavailable', 'Term content could not be read from OPFS');
}
return bytes;
}

/**
* Legacy record lengths do not define their compressed spans. Discover
* exact frame boundaries without reading past the committed root.
Expand Down Expand Up @@ -981,7 +1083,7 @@ await readContext.resolveFrame(identity) :
if (onlineFrame !== null && codecId !== null && codecId !== 'jmdict') {
options.codecSource = 'immutable-layout';
}
block = decompressTermContentZstd(compressed, codecId, options);
block = identity.kind === 'raw-entry' && codecId === null ? new Uint8Array(compressed) : decompressTermContentZstd(compressed, codecId, options);
if (!(block instanceof Uint8Array)) { throw new TypeError('Zstd decoder returned non-byte data'); }
} catch (error) {
this._recordError('term-content-block-decompress-error', {
Expand Down
Loading
Loading