diff --git a/ext/js/dictionary/dictionary-database.js b/ext/js/dictionary/dictionary-database.js index 35795dc34d..b032af5a84 100644 --- a/ext/js/dictionary/dictionary-database.js +++ b/ext/js/dictionary/dictionary-database.js @@ -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'; @@ -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(); @@ -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( @@ -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}; } } } @@ -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, }); @@ -6344,6 +6365,11 @@ db.selectObjects( * @returns {Promise} */ 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} */ diff --git a/ext/js/dictionary/term-content-block-store.js b/ext/js/dictionary/term-content-block-store.js index 625604ccbf..1c803eb446 100644 --- a/ext/js/dictionary/term-content-block-store.js +++ b/ext/js/dictionary/term-content-block-store.js @@ -52,7 +52,7 @@ export {wrapCompressedTermContentBlock} from './term-content-block-envelope.js'; * @property {(requests: Array<{offset: number, length: number}>) => Promise} readSlicesDetailed * @property {(identity: TermContentFrameIdentity) => Promise} resolveFrame * @property {number} [logicalHighWater] Committed end under the leased root. - * @property {(query: {kind: 'legacy-entry', logicalOffset: number, recordLength: number, originalCodecId: string|null}) => Promise} [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} [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. @@ -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]; @@ -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 || @@ -583,7 +584,7 @@ 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); @@ -591,7 +592,9 @@ await (readContext ?? this._contentStore).readSlicesDetailed(sliceRequests.map(( 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()); } @@ -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]; @@ -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>} + */ + 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 @@ -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'); } @@ -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} + */ + 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. @@ -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', { diff --git a/ext/js/dictionary/term-content-layout.js b/ext/js/dictionary/term-content-layout.js index d8ee36a583..a67996e943 100644 --- a/ext/js/dictionary/term-content-layout.js +++ b/ext/js/dictionary/term-content-layout.js @@ -18,8 +18,13 @@ const MAX_REGIONS = 2; const MAX_REGION_BYTES = 128 * 1024 * 1024; const MAX_DICTIONARY_BYTES = 112640; -const MAX_ROWS = 16384; -const MAX_TOTAL_ROWS = 32768; + +export const MAX_CONTENT_LAYOUT_ROWS = 16384; + +export const MAX_CONTENT_LAYOUT_TOTAL_ROWS = 32768; + +const MAX_ROWS = MAX_CONTENT_LAYOUT_ROWS; +const MAX_TOTAL_ROWS = MAX_CONTENT_LAYOUT_TOTAL_ROWS; const MAX_MANIFEST_BYTES = 1024 * 1024; const MAX_METADATA_BYTES = 2 * MAX_MANIFEST_BYTES; const FRAME_FIELDS = 'kind logicalOffset recordLength sourceStoredLength originalCodecId expectedDecodedLength originalEnvelope fileId physicalOffset storedLength codecId envelope decodedLength decodedDigest'; @@ -42,7 +47,7 @@ export class SupersededCompressedRangeError extends Error { } /** @typedef {{fileId: string, physicalOffset: number, length: number}} PhysicalSpan */ -/** @typedef {{kind: 'block'|'legacy-entry'|'shared-glossary', logicalOffset: number, recordLength: number, sourceStoredLength: number, originalCodecId: string|null, expectedDecodedLength: number|null, originalEnvelope: 'mbc2'|'none'}} FrameIdentity */ +/** @typedef {{kind: 'block'|'legacy-entry'|'raw-entry'|'shared-glossary', logicalOffset: number, recordLength: number, sourceStoredLength: number, originalCodecId: string|null, expectedDecodedLength: number|null, originalEnvelope: 'mbc2'|'none'}} FrameIdentity */ /** @typedef {{logicalOffset: number, length: number, fileId: string, physicalOffset: number}} Extent */ /** @typedef {{logicalOffset: number, length: number, frameLogicalOffset: number}} RemovedRange */ /** @typedef {FrameIdentity & {fileId: string, physicalOffset: number, storedLength: number, codecId: string, envelope: 'mbc2'|'none', decodedLength: number, decodedDigest: string}} Frame */ @@ -418,7 +423,7 @@ function envelope(value) { */ function copyIdentity(row) { const kind = row.kind; - if (kind !== 'block' && kind !== 'legacy-entry' && kind !== 'shared-glossary') { throw new TypeError('Unknown frame kind'); } + if (kind !== 'block' && kind !== 'legacy-entry' && kind !== 'raw-entry' && kind !== 'shared-glossary') { throw new TypeError('Unknown frame kind'); } /** @type {FrameIdentity} */ const result = { kind, @@ -430,6 +435,7 @@ function copyIdentity(row) { originalEnvelope: envelope(row.originalEnvelope), }; if (kind !== 'legacy-entry' && result.recordLength !== result.sourceStoredLength) { throw new TypeError('Exact source length differs from original block or artifact record length'); } + if (kind === 'raw-entry' && (result.originalCodecId !== null || result.originalEnvelope !== 'none' || result.expectedDecodedLength !== result.sourceStoredLength)) { throw new TypeError('Raw entry identity has compressed source metadata'); } if (result.originalEnvelope === 'mbc2' && result.sourceStoredLength <= 12) { throw new TypeError('Original MBC2 envelope has no compressed frame'); } end(result.logicalOffset, result.sourceStoredLength); return result; diff --git a/ext/js/dictionary/term-content-legacy-eligibility.js b/ext/js/dictionary/term-content-legacy-eligibility.js index 98efb7b71a..62397a9651 100644 --- a/ext/js/dictionary/term-content-legacy-eligibility.js +++ b/ext/js/dictionary/term-content-legacy-eligibility.js @@ -35,7 +35,7 @@ const RAW_SELECTORS = new Set(['raw', 'raw-v2', 'raw-v3', 'raw-v4', 'raw-v6']); */ export function skipLegacyEligibilitySelector(selector) { const blockCodec = getRawTermContentBlockCompressionDictName(selector); - return RAW_SELECTORS.has(selector) || getLegacyTermContentZstdCodecId(blockCodec ?? selector) !== null; + return getLegacyTermContentZstdCodecId(blockCodec ?? selector) !== null; } /** @@ -67,11 +67,20 @@ export async function probeLegacyTermContentFrame(source, item, signal, cursor = exactExtent = true; } else { const {entryContentOffset, entryContentLength, entryContentDictName} = item.reference; - if (skipLegacyEligibilitySelector(entryContentDictName)) { return {kind: 'skip'}; } if (!Number.isSafeInteger(entryContentOffset) || entryContentOffset < 0 || !Number.isSafeInteger(entryContentLength) || entryContentLength <= 0) { throw new ZstdFrameInspectionError('Invalid legacy term content reference'); } + if (RAW_SELECTORS.has(entryContentDictName)) { + if (entryContentOffset > source.logicalHighWater - entryContentLength) { + throw new ZstdFrameInspectionError('Raw legacy term content reference exceeds its source'); + } + // Raw bytes can be trained directly after immutable-root activation. + return {kind: 'eligible'}; + } + if (skipLegacyEligibilitySelector(entryContentDictName)) { + return {kind: 'skip'}; + } frameOffset = entryContentOffset; if (typeof getRawTermContentBlockCompressionDictName(entryContentDictName) !== 'undefined') { const compact = entryContentDictName === RAW_TERM_CONTENT_DIRECT_BLOCK_DICT_NAME_PREFIX || diff --git a/ext/js/dictionary/term-content-optimization-batch-store.js b/ext/js/dictionary/term-content-optimization-batch-store.js index d8335b0095..1fcd65777a 100644 --- a/ext/js/dictionary/term-content-optimization-batch-store.js +++ b/ext/js/dictionary/term-content-optimization-batch-store.js @@ -19,6 +19,7 @@ import {parseJson} from '../core/json.js'; import {arrayBufferDigest} from '../core/utilities.js'; import {parseOnlineContentFrameDescriptor} from './term-content-optimization-checkpoint.js'; import {TermContentOptimizationIntegrityError, TermContentOptimizationUnsupportedFrameError} from './term-content-optimization-controller.js'; +import {MAX_CONTENT_LAYOUT_ROWS, MAX_CONTENT_LAYOUT_TOTAL_ROWS} from './term-content-layout.js'; import {iterateContentRepackCopyChunks, planContentRegionRepack} from './term-content-region-repack-planner.js'; /** @typedef {import('./term-content-optimization-controller.js').OptimizationJob} Job */ @@ -54,6 +55,8 @@ import {iterateContentRepackCopyChunks, planContentRegionRepack} from './term-co */ const MAX_FRAMES = 255; +const MAX_LAYOUT_ADDED_ROWS_PER_FRAME = 5; +const MAX_LAYOUT_BATCH_OVERHEAD_ROWS = 8; const MAX_CODEC_BYTES = 16 * 1024 * 1024; // Canonical frames are decoded one at a time. The retained in-memory spool // consists only of compressed improvements, bounded by admitted stored bytes. @@ -109,6 +112,25 @@ export class TermContentOptimizationBatchStore { this._check(job, signal); const first = source.regions[0]; const second = source.regions[1]; + const rowCount = source.window.manifests.length + source.window.externalFrames.length + source.window.files.length + + source.window.physicalFiles.length + source.window.codecs.length + source.window.manifests.reduce((total, manifest) => total + manifest.extents.length + manifest.blocks.length + manifest.removed.length, 0); + let frameCapacity = Math.floor((MAX_CONTENT_LAYOUT_TOTAL_ROWS - rowCount - MAX_LAYOUT_BATCH_OVERHEAD_ROWS) / + MAX_LAYOUT_ADDED_ROWS_PER_FRAME); + frameCapacity = Math.min( + frameCapacity, + MAX_CONTENT_LAYOUT_ROWS - source.window.files.length - 3, + MAX_CONTENT_LAYOUT_ROWS - source.window.physicalFiles.length - 3, + 8 - source.window.codecs.length, + ); + for (const manifest of source.window.manifests) { + frameCapacity = Math.min( + frameCapacity, + MAX_CONTENT_LAYOUT_ROWS - manifest.extents.length, + MAX_CONTENT_LAYOUT_ROWS - manifest.blocks.length, + MAX_CONTENT_LAYOUT_ROWS - manifest.removed.length, + ); + } + if (frameCapacity <= 0) { return null; } const firstEnd = first.logicalStart + first.logicalLength; const maximumEnd = second ? second.logicalStart + second.logicalLength : firstEnd; let count = 0; @@ -118,7 +140,7 @@ export class TermContentOptimizationBatchStore { for (const frame of observed) { const {logicalOffset, sourceStoredLength} = frame.identity; if (logicalOffset < first.logicalStart) { throw new TermContentOptimizationIntegrityError('Repack frame precedes its source region'); } - if (count === MAX_FRAMES || logicalOffset >= firstEnd) { break; } + if (count === MAX_FRAMES || count === frameCapacity || logicalOffset >= firstEnd) { break; } const end = logicalOffset + sourceStoredLength; if (end > maximumEnd || frame.decodedLength === null || frame.decodedLength > MAX_CODEC_BYTES || frame.storedLength > MAX_CODEC_BYTES) { diff --git a/ext/js/dictionary/term-content-optimization-candidate-source.js b/ext/js/dictionary/term-content-optimization-candidate-source.js index 983a1a9a78..c49b54adf9 100644 --- a/ext/js/dictionary/term-content-optimization-candidate-source.js +++ b/ext/js/dictionary/term-content-optimization-candidate-source.js @@ -90,7 +90,13 @@ export async function inspectTermContentTrainingReference(source, reference, sig } if (isRawTermContentTrainingSelector(selector)) { if (cursor !== null) { throw new TypeError('Unexpected legacy cursor on raw content'); } - return {kind: 'skip', reason: 'raw'}; + return await eligible(source, {kind: 'raw-entry', + logicalOffset: offset, + recordLength: length, + sourceStoredLength: length, + originalCodecId: null, + expectedDecodedLength: length, + originalEnvelope: 'none'}, signal, length); } const blockCodec = getRawTermContentBlockCompressionDictName(selector); if (typeof blockCodec !== 'undefined') { diff --git a/ext/js/dictionary/term-content-optimization-checkpoint.js b/ext/js/dictionary/term-content-optimization-checkpoint.js index 0b95a3ee54..e925b9e9a5 100644 --- a/ext/js/dictionary/term-content-optimization-checkpoint.js +++ b/ext/js/dictionary/term-content-optimization-checkpoint.js @@ -104,7 +104,7 @@ export function parseOnlineContentFrameDescriptor(value) { const frame = record(value, ['identity', 'physicalKey', 'storedLength', 'codecId', 'envelope', 'decodedLength', 'decodedDigest']); const source = record(frame.identity, ['kind', 'logicalOffset', 'recordLength', 'sourceStoredLength', 'originalCodecId', 'expectedDecodedLength', 'originalEnvelope']); const kind = source.kind; - if (kind !== 'block' && kind !== 'legacy-entry' && kind !== 'shared-glossary') { throw new TypeError('Invalid optimization frame kind'); } + if (kind !== 'block' && kind !== 'legacy-entry' && kind !== 'raw-entry' && kind !== 'shared-glossary') { throw new TypeError('Invalid optimization frame kind'); } const logicalOffset = integer(source.logicalOffset); const recordLength = integer(source.recordLength, 1); const sourceStoredLength = integer(source.sourceStoredLength, 1); @@ -115,6 +115,7 @@ export function parseOnlineContentFrameDescriptor(value) { const storedLength = integer(frame.storedLength, 1); const decodedLength = frame.decodedLength === null ? null : integer(frame.decodedLength, 1); if ((kind !== 'legacy-entry' && recordLength !== sourceStoredLength) || + (kind === 'raw-entry' && (originalCodecId !== null || originalEnvelope !== 'none' || expectedDecodedLength !== sourceStoredLength)) || (expectedDecodedLength !== null && expectedDecodedLength !== decodedLength) || typeof frame.physicalKey !== 'string' || frame.physicalKey.length === 0 || frame.physicalKey.length > ONLINE_CONTENT_FRAME_ROW_BYTES || (frame.decodedDigest !== null && (typeof frame.decodedDigest !== 'string' || !/^[a-f0-9]{64}$/.test(frame.decodedDigest))) || diff --git a/ext/js/dictionary/term-content-optimization-controller.js b/ext/js/dictionary/term-content-optimization-controller.js index b2dd4157fe..b995e9aba7 100644 --- a/ext/js/dictionary/term-content-optimization-controller.js +++ b/ext/js/dictionary/term-content-optimization-controller.js @@ -420,10 +420,10 @@ function matchesReceipt(actual, expected) { */ export class TermContentOptimizationController { /** - * @param {{host: OptimizationHost, strategyVersion: string, dictionaryCapacity: number, strategy: number, level: number, createTrainer?: () => Trainer, now?: () => number}} options + * @param {{host: OptimizationHost, strategyVersion: string, compatibleStrategyVersions?: string[], dictionaryCapacity: number, strategy: number, level: number, createTrainer?: () => Trainer, now?: () => number}} options * @throws {TypeError} If required adapters or resource bounds are missing. */ - constructor({host, strategyVersion, dictionaryCapacity, strategy, level, createTrainer = () => new ZstdTrainerWorkerOwner(), now = Date.now}) { + constructor({host, strategyVersion, compatibleStrategyVersions = [], dictionaryCapacity, strategy, level, createTrainer = () => new ZstdTrainerWorkerOwner(), now = Date.now}) { const methods = ['getJob', 'findCandidate', 'createJob', @@ -442,7 +442,9 @@ export class TermContentOptimizationController { 'measureBatch', 'publishBatch', 'reclaimStep']; - if (!host || methods.some((key) => typeof Reflect.get(host, key) !== 'function') || + if (!Array.isArray(compatibleStrategyVersions) || compatibleStrategyVersions.some((value) => typeof value !== 'string' || !/^[a-zA-Z0-9._:-]{1,128}$/.test(value)) || + new Set(compatibleStrategyVersions).size !== compatibleStrategyVersions.length || compatibleStrategyVersions.includes(strategyVersion) || + !host || methods.some((key) => typeof Reflect.get(host, key) !== 'function') || typeof strategyVersion !== 'string' || !/^[a-zA-Z0-9._:-]{1,128}$/.test(strategyVersion) || !Number.isSafeInteger(dictionaryCapacity) || dictionaryCapacity < 1024 || dictionaryCapacity > MAX_DICTIONARY_BYTES || !Number.isSafeInteger(strategy) || strategy < 0 || strategy > 2 || @@ -453,6 +455,8 @@ export class TermContentOptimizationController { this._host = host; /** @type {string} */ this._strategyVersion = strategyVersion; + /** @type {Set} */ + this._compatibleStrategyVersions = new Set(compatibleStrategyVersions); /** @type {number} */ this._dictionaryCapacity = dictionaryCapacity; /** @type {number} */ @@ -532,7 +536,7 @@ export class TermContentOptimizationController { throw new TypeError('Durable training sampler belongs to a different job'); } const effectivePhase = job.phase === 'deferred' ? state.resumePhase : job.phase; - const strategyCurrent = job.strategyVersion === this._strategyVersion && + const strategyCurrent = (job.strategyVersion === this._strategyVersion || this._compatibleStrategyVersions.has(job.strategyVersion)) && state.parameters.dictionaryCapacity === this._dictionaryCapacity && state.parameters.strategy === this._strategy && state.parameters.level === this._level; if (!strategyCurrent && (effectivePhase !== 'reclaim' || state.afterReclaim === 'recompress')) { // An unsupported strategy cannot become available through diff --git a/ext/js/dictionary/term-content-optimization-frame-reader.js b/ext/js/dictionary/term-content-optimization-frame-reader.js index 7d920b94b2..9eb489accd 100644 --- a/ext/js/dictionary/term-content-optimization-frame-reader.js +++ b/ext/js/dictionary/term-content-optimization-frame-reader.js @@ -136,6 +136,7 @@ export class TermContentOptimizationFrameReader { } check(); if (cursor !== input.byteLength) { throw new Error('Private frame stream ended before its immutable observation'); } + if (expected.identity.kind === 'raw-entry') { return input; } codec = this._createCodec(); const decoded = await codec.run({id: 0, action: 'decode', diff --git a/test/dictionary-database-online-optimization-schema.test.js b/test/dictionary-database-online-optimization-schema.test.js index 2099c47a8d..c359abbfa2 100644 --- a/test/dictionary-database-online-optimization-schema.test.js +++ b/test/dictionary-database-online-optimization-schema.test.js @@ -1713,6 +1713,73 @@ test('matched generations complete with no layout activation and a replacement g expect(connection.selectValue('PRAGMA user_version')).toBe(11); }); +test('raw-only strategy re-admits v2 no-gain generations only when discovery found no frames', async () => { + const {database, connection} = await createLayoutDatabase(0); + const strategy = 'fastcover-f18-level3-16k-w64k-v3-raw-entry'; + const v2 = 'fastcover-f18-level3-16k-w64k-v2'; + const putDictionary = (/** @type {string} */ title, /** @type {string} */ generation) => connection.exec({ + sql: 'INSERT INTO dictionaries(title, version, summaryJson) VALUES (?, 1, ?)', + bind: [title, JSON.stringify({title, importSuccess: true, storageGenerationId: generation})], + }); + const putHistory = (/** @type {string} */ generation, /** @type {string} */ phase, /** @type {object} */ checkpoint, /** @type {string} */ version = v2) => connection.exec({ + sql: 'INSERT INTO termContentOptimizationJobs(jobId, dictionaryTitle, dictionaryGeneration, strategyVersion, phase, cursorJson, checkpointJson, updatedAt) VALUES (?, ?, ?, ?, ?, ?, ?, 1)', + bind: ['history-' + generation, 'Corpus-' + generation, generation, version, phase, 'null', JSON.stringify(checkpoint)], + }); + const emptyV2Discovery = {publishedBatches: 0, sampleMode: 'summary', sampler: {summary: {entries: 0}}, samples: []}; + + putDictionary('Corpus-empty', 'generation-empty'); + putHistory('generation-empty', 'no-gain', emptyV2Discovery); + expect(database._findOnlineContentOptimizationCandidate(strategy)).toMatchObject({ + dictionaryTitle: 'Corpus-empty', dictionaryGeneration: 'generation-empty', + }); + connection.exec({sql: 'DELETE FROM dictionaries WHERE title = ?', bind: ['Corpus-empty']}); + + putDictionary('Corpus-explicit-false', 'generation-explicit-false'); + putHistory('generation-explicit-false', 'no-gain', {...emptyV2Discovery, legacyProbe: false}); + expect(database._findOnlineContentOptimizationCandidate(strategy)).toMatchObject({ + dictionaryTitle: 'Corpus-explicit-false', dictionaryGeneration: 'generation-explicit-false', + }); + connection.exec({sql: 'DELETE FROM dictionaries WHERE title = ?', bind: ['Corpus-explicit-false']}); + + putDictionary('Corpus-active-probe', 'generation-active-probe'); + putHistory('generation-active-probe', 'no-gain', {...emptyV2Discovery, legacyProbe: true}); + putDictionary('Corpus-invalid-probe', 'generation-invalid-probe'); + putHistory('generation-invalid-probe', 'no-gain', {...emptyV2Discovery, legacyProbe: null}); + expect(database._findOnlineContentOptimizationCandidate(strategy)).toBeNull(); + + putDictionary('Corpus-completed', 'generation-completed'); + putHistory('generation-completed', 'completed', emptyV2Discovery); + expect(database._findOnlineContentOptimizationCandidate(strategy)).toBeNull(); + + putDictionary('Corpus-sampled', 'generation-sampled'); + putHistory('generation-sampled', 'no-gain', {...emptyV2Discovery, sampler: {summary: {entries: 4}}}); + expect(database._findOnlineContentOptimizationCandidate(strategy)).toBeNull(); + + putDictionary('Corpus-current', 'generation-current'); + putHistory('generation-current', 'no-gain', emptyV2Discovery, strategy); + expect(database._findOnlineContentOptimizationCandidate(strategy)).toBeNull(); +}); + +test('production discovery retains bounded raw-selector references after an earlier v2 no-gain receipt', async () => { + const {database, connection, job} = await createJobFixture(); + connection.exec({ + sql: 'INSERT INTO termContentOptimizationJobs(jobId, dictionaryTitle, dictionaryGeneration, strategyVersion, phase, cursorJson, checkpointJson, updatedAt) VALUES (?, ?, ?, ?, ?, ?, ?, 1)', + bind: ['old-v2-no-gain', job.dictionaryTitle, job.dictionaryGeneration, 'fastcover-f18-level3-16k-w64k-v2', 'no-gain', 'null', JSON.stringify({legacyProbe: false, publishedBatches: 0, sampleMode: 'summary', sampler: {summary: {entries: 0}}, samples: []})], + }); + const reference = {recordId: 12, entryContentOffset: 0, entryContentLength: 3, entryContentDictName: 'raw-v2'}; + const iterate = vi.spyOn(database._termRecordStore, 'iterateContentReferences').mockImplementation(async (_name, _generation, _cursor, options) => { + expect(options.skipSelector).toBeUndefined(); + return {references: [reference], cursor: null, done: true, bytesRead: 3}; + }); + const currentJob = database.getOnlineContentOptimizationJobs().find((entry) => entry.jobId === job.jobId); + if (!currentJob) { throw new Error('Missing discovery owner'); } + const page = await database.readOnlineContentOptimizationDiscoveryPage(currentJob, null, new AbortController().signal); + if (!('items' in page)) { throw new Error('Discovery page did not retain its references'); } + expect(page.items).toEqual([{kind: 'reference', reference}]); + expect(page.done).toBe(false); + expect(iterate).toHaveBeenCalledOnce(); +}); + test('a replaced dictionary invalidates its legacy proof inside the activation transaction', async () => { const {database, connection, job} = await createJobFixture(); connection.exec('PRAGMA user_version = 10'); @@ -1731,6 +1798,17 @@ test('a replaced dictionary invalidates its legacy proof inside the activation t expect(adopt).not.toHaveBeenCalled(); }); +test('frame override lookup falls back to import staging at the leased root high-water mark', async () => { + const {database} = await createLayoutDatabase(4); + const getWindow = vi.spyOn(database, 'getOnlineContentLayoutWindow'); + const snapshot = {rootId: 'root-fixture', epoch: 1, logicalHighWater: 4}; + for (const logicalOffset of [4, 8]) { + await expect(database._findOnlineContentFrameOverride({kind: 'raw-entry', logicalOffset, recordLength: 3, originalCodecId: null}, snapshot)) + .resolves.toBeNull(); + } + expect(getWindow).not.toHaveBeenCalled(); +}); + test.each(['missing-closure', 'missing-registry', 'missing-sidecar', 'wrong-bytes', 'valid'])('resolved private codec treats sidecar integrity strictly: %s', async (mode) => { const {database, connection} = await createLayoutDatabase(4); diff --git a/test/term-content-block-read-context.test.js b/test/term-content-block-read-context.test.js index 78e437b611..47b9405faa 100644 --- a/test/term-content-block-read-context.test.js +++ b/test/term-content-block-read-context.test.js @@ -26,10 +26,10 @@ let contextFactoryId = 0; /** * @param {Map} references * @param {(identity: Identity) => Promise} resolve - * @param {{referenceGate?: Promise, isCurrentFrame?: (identity: Identity, physicalKey: string) => Promise, isCurrentFrameLayout?: (identity: Identity, layoutId: string) => Promise, isCurrentRange?: (offset: number, length: number) => Promise}} [options] + * @param {{referenceGate?: Promise, findFrameOverride?: (query: {kind: 'legacy-entry'|'raw-entry', logicalOffset: number, recordLength: number, originalCodecId: string|null}) => Promise, isCurrentFrame?: (identity: Identity, physicalKey: string) => Promise, isCurrentFrameLayout?: (identity: Identity, layoutId: string) => Promise, isCurrentRange?: (offset: number, length: number) => Promise}} [options] * @returns {{acquire: () => ReadContext, counts: {live: number, acquired: number, forks: number, released: number}}} */ -function contextFactory(references, resolve, {referenceGate, isCurrentFrame, isCurrentFrameLayout, isCurrentRange} = {}) { +function contextFactory(references, resolve, {referenceGate, findFrameOverride, isCurrentFrame, isCurrentFrameLayout, isCurrentRange} = {}) { const counts = {live: 0, acquired: 0, forks: 0, released: 0}; const rootKey = `test-root-${++contextFactoryId}`; /** @@ -66,6 +66,10 @@ function contextFactory(references, resolve, {referenceGate, isCurrentFrame, isC assertOwned(); return frame; }, + async findFrameOverride(query) { + assertOwned(); + return findFrameOverride ? await findFrameOverride(query) : null; + }, fork() { assertOwned(); ++counts.forks; @@ -355,7 +359,7 @@ test('the current replacement transient failure keeps its own taxonomy after a s expect(old.counts.live + current.counts.live).toBe(0); }); -test('raw scalar and batch reads use a single leased context without frame loaders', async () => { +test('raw scalar and batch reads use one leased context while preserving direct byte reads', async () => { const resolve = vi.fn(async () => { throw new Error('Raw bytes unexpectedly resolved as a frame'); }); const factory = contextFactory(new Map([[1, new Uint8Array([7])]]), resolve); const store = blockStore(); @@ -366,6 +370,27 @@ test('raw scalar and batch reads use a single leased context without frame loade expect(resolve).not.toHaveBeenCalled(); }); +test.each([true, false])('keeps later raw rows in mixed batches with override lookup %s', async (withFinder) => { + const resolve = vi.fn(async () => frame('mixed:frame')); + const factory = contextFactory(new Map([[1, reference()], [2, new Uint8Array([7])]]), resolve); + const store = blockStore(); + store.setReadContextProvider(() => { + const context = factory.acquire(); + if (!withFinder) { delete context.findFrameOverride; } + return context; + }); + expect(await store.readDetailed(2, 1, 'raw')).toEqual({status: 'ok', bytes: new Uint8Array([7])}); + expect(await store.readDetailedBatch([ + {contentOffset: 1, contentLength: 3, contentDictName: 'raw-block-v1'}, + {contentOffset: 2, contentLength: 1, contentDictName: 'raw'}, + ])).toEqual([ + {status: 'ok', bytes: new Uint8Array([1, 2, 3])}, + {status: 'ok', bytes: new Uint8Array([7])}, + ]); + expect(resolve).toHaveBeenCalledTimes(1); + expect(factory.counts.live).toBe(0); +}); + test('provider failures remain temporary and null providers preserve legacy reads', async () => { const store = blockStore(); store.setReadContextProvider(() => { throw new Error('Lease admission unavailable'); }); diff --git a/test/term-content-layout.test.js b/test/term-content-layout.test.js index 582b9b50a5..721dfa62f9 100644 --- a/test/term-content-layout.test.js +++ b/test/term-content-layout.test.js @@ -104,6 +104,28 @@ describe('bounded immutable content layout', () => { }); }); + test('resolves exact raw-entry identities through an immutable replacement layout', () => { + const input = fixture(); + Object.assign(input.manifests[0].blocks[0], { + kind: 'raw-entry', + recordLength: 6, + sourceStoredLength: 6, + expectedDecodedLength: 6, + originalEnvelope: 'none', + decodedLength: 6, + }); + const resolver = createContentLayoutResolver(input); + const raw = identity({kind: 'raw-entry', recordLength: 6, expectedDecodedLength: 6}); + expect(resolver.resolveFrame(raw)).toMatchObject({ + identity: raw, + sourceStoredLength: 6, + spans: [{fileId: 'data', physicalOffset: 14, length: 4}], + codecId: 'custom', + decodedLength: 6, + }); + expect(() => resolver.resolveFrame({...raw, originalCodecId: 'jmdict'})).toThrow(/Raw entry identity/); + }); + test.each([[8, 1], [7, 2], [0, 20], [13, 2]])('reports superseded bytes without calling healthy holes corruption (%s,%s)', (offset, length) => { const resolver = createContentLayoutResolver(fixture()); expect(() => resolver.resolveLogical(offset, length)).toThrow(SupersededCompressedRangeError); diff --git a/test/term-content-legacy-eligibility.test.js b/test/term-content-legacy-eligibility.test.js index 160af3b7ff..c44e7e2ed6 100644 --- a/test/term-content-legacy-eligibility.test.js +++ b/test/term-content-legacy-eligibility.test.js @@ -47,12 +47,19 @@ test('proves the stored codec from the frame header before activation', async () }, signal)).resolves.toEqual({kind: 'eligible'}); }); -test('skips preset and raw references but separately checks the shared artifact extent', async () => { +test('skips preset references, admits bounded raw references, and checks shared artifact extent', async () => { const signal = new AbortController().signal; - for (const name of ['jmdict', 'raw-block-v2:jmdict', 'raw-v4']) { + for (const name of ['jmdict', 'raw-block-v2:jmdict']) { const matched = {...legacy, reference: {...legacy.reference, entryContentDictName: name}}; await expect(probeLegacyTermContentFrame(source(new Uint8Array(0)), matched, signal)).resolves.toEqual({kind: 'skip'}); } + for (const name of ['raw', 'raw-v2', 'raw-v3', 'raw-v4', 'raw-v6']) { + const matched = {...legacy, reference: {...legacy.reference, entryContentDictName: name}}; + await expect(probeLegacyTermContentFrame(source(new Uint8Array(3)), matched, signal)).resolves.toEqual({kind: 'eligible'}); + } + await expect(probeLegacyTermContentFrame(source(new Uint8Array(2)), { + ...legacy, reference: {...legacy.reference, entryContentDictName: 'raw-v2'}, + }, signal)).rejects.toThrow(/exceeds its source/); const artifact = {kind: /** @type {const} */ ('artifact'), artifact: { contentOffset: 0, contentLength: generic.length, contentDictName: 'raw-v4', uncompressedLength: 3, diff --git a/test/term-content-optimization-candidate-source.test.js b/test/term-content-optimization-candidate-source.test.js index 0eca4e8721..7fdbcc3307 100644 --- a/test/term-content-optimization-candidate-source.test.js +++ b/test/term-content-optimization-candidate-source.test.js @@ -123,13 +123,28 @@ test('actual resolved codec excludes custom frames even when the legacy selector expect(f.describe[0].originalCodecId).toBeNull(); }); -test.each(['raw', 'raw-v2', 'raw-v3', 'raw-v4', 'raw-v6'])('raw entry selector %s never becomes a compression frame', async (selector) => { - const f = fixture(new Uint8Array(0)); +test.each(['raw', 'raw-v2', 'raw-v3', 'raw-v4', 'raw-v6'])('raw entry selector %s becomes a canonical raw training frame', async (selector) => { + const f = fixture(new Uint8Array(64)); await expect(inspectTermContentTrainingReference(f.source, reference(selector), new AbortController().signal)) - .resolves.toEqual({kind: 'skip', reason: 'raw'}); + .resolves.toMatchObject({kind: 'frame', + frame: {identity: {kind: 'raw-entry', + logicalOffset: 0, + recordLength: 64, + sourceStoredLength: 64, + originalCodecId: null, + expectedDecodedLength: 64, + originalEnvelope: 'none'}}}); expect(f.readSlice).toHaveLength(0); expect(f.findOverride).toHaveLength(0); - expect(f.describe).toHaveLength(0); + expect(f.describe).toHaveLength(1); +}); + +test('mixed raw and precompressed references retain distinct source identities', async () => { + const f = blockFixture(encodeRawTermContentCompactBlockReference(200, 64, 256, 0)); + const raw = await inspectTermContentTrainingReference(f.source, reference('raw-v2', 80, 32), new AbortController().signal); + const compressed = await inspectTermContentTrainingReference(f.source, reference('raw-block-v2', 32), new AbortController().signal); + expect(raw).toMatchObject({kind: 'frame', frame: {identity: {kind: 'raw-entry', logicalOffset: 80, sourceStoredLength: 32}}}); + expect(compressed).toMatchObject({kind: 'frame', frame: {identity: {kind: 'block', logicalOffset: 200, sourceStoredLength: 64}}}); }); test('invalid compact reference bounds fail before any frame can be checkpointed', async () => { diff --git a/test/term-content-optimization-checkpoint.test.js b/test/term-content-optimization-checkpoint.test.js index e8f26b47d6..0ccbc31a01 100644 --- a/test/term-content-optimization-checkpoint.test.js +++ b/test/term-content-optimization-checkpoint.test.js @@ -37,6 +37,21 @@ test('generalized frames preserve decoded versus physical length and exact repla expect(owned.identity.sourceStoredLength).toBe(100); }); +test('raw-entry frame identity survives durable checkpoint replay with exact raw length', () => { + const original = frame(); + original.identity = {kind: 'raw-entry', + logicalOffset: 2 ** 34, + recordLength: 512, + sourceStoredLength: 512, + originalCodecId: null, + expectedDecodedLength: 512, + originalEnvelope: 'none'}; + original.storedLength = 512; + original.decodedLength = 512; + const row = encodeOnlineContentFrameCheckpoint(original); + expect(decodeOnlineContentFrameCheckpoint(row)).toEqual(original); +}); + test('encoded byte admission counts UTF-8 rather than JavaScript code units', () => { expect(() => encodeOnlineContentFrameCheckpoint({...frame(), physicalKey: 'あ'.repeat(7000)})).toThrow(RangeError); }); diff --git a/test/term-content-optimization-controller.test.js b/test/term-content-optimization-controller.test.js index 50439ef48c..e5a8ec4603 100644 --- a/test/term-content-optimization-controller.test.js +++ b/test/term-content-optimization-controller.test.js @@ -661,6 +661,21 @@ test('deferred reclaim survives a strategy and parameter update without retraini expect(f.state.writes).toBe(0); }); +test('compatible in-flight strategy can finish under the raw-entry upgrade', async () => { + const f = fixture(); + if (f.state.job === null) { throw new Error('Missing fixture job'); } + const previousStrategy = 'fastcover-f18-level3-16k-w64k-v2'; + f.state.job.strategyVersion = previousStrategy; + f.state.job.checkpoint.sampler.identity = f.state.job.dictionaryGeneration + ':' + previousStrategy; + const controller = new TermContentOptimizationController({host: f.host, + strategyVersion: 'fastcover-f18-level3-16k-w64k-v3-raw-entry', + compatibleStrategyVersions: ['fastcover-f18-level3-16k-w64k-v2'], + ...parameters, + now: () => f.state.now}); + await controller.runStep(signal()); + expect(f.state.job?.phase).toBe('sample'); +}); + test('an awaited stale callback cannot defer a successor checkpoint of the same job', async () => { const f = fixture(); f.host.readDiscovery = async (job) => { diff --git a/test/term-content-optimization-frame-reader.test.js b/test/term-content-optimization-frame-reader.test.js index 41c82f5423..4e306ce11a 100644 --- a/test/term-content-optimization-frame-reader.test.js +++ b/test/term-content-optimization-frame-reader.test.js @@ -93,6 +93,23 @@ test('reads an owned decoded window through private streamed input and a disposa expect(f.state).toMatchObject({acquired: 1, released: 1, created: 1, closed: 1}); }); +test('reads raw-entry training bytes as canonical bytes without invoking Zstd', async () => { + const f = fixture(); + f.frame.identity = {kind: 'raw-entry', + logicalOffset: 0, + recordLength: 32, + sourceStoredLength: 32, + originalCodecId: null, + expectedDecodedLength: 32, + originalEnvelope: 'none'}; + f.frame.storedLength = 32; + f.state.observed = {...f.frame}; + f.state.chunks = [f.decoded]; + const bytes = await f.reader.readWindow(f.job, f.frame, 5, 4, new AbortController().signal); + expect(bytes).toEqual(new Uint8Array([5, 6, 7, 8])); + expect(f.state).toMatchObject({acquired: 1, released: 1, created: 0, closed: 0}); +}); + test.each(['unknown-length', 'giant-input', 'giant-decoded'])('defers %s before allocating input or acquiring a source lease', async (kind) => { const f = fixture(); if (kind === 'unknown-length') { f.frame.decodedLength = null; } diff --git a/test/term-content-raw-online-frame.test.js b/test/term-content-raw-online-frame.test.js new file mode 100644 index 0000000000..5fb8e66203 --- /dev/null +++ b/test/term-content-raw-online-frame.test.js @@ -0,0 +1,234 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ + +import {beforeEach, expect, test, vi} from 'vitest'; +import {TermContentBlockStore, wrapCompressedTermContentBlock} from '../ext/js/dictionary/term-content-block-store.js'; +import {TermContentOpfsStore} from '../ext/js/dictionary/term-content-opfs-store.js'; +import {decompressTermContentZstd} from '../ext/js/dictionary/zstd-term-content.js'; +import {deferPromise} from '../ext/js/core/utilities.js'; + +vi.mock('../ext/js/dictionary/zstd-term-content.js', () => ({ + beginCompressWrappedTermContentZstdSpansBatch: vi.fn(), + compressTermContentZstd: vi.fn(), + compressWrappedTermContentZstdBatch: vi.fn(), + compressWrappedTermContentZstdBlocks: vi.fn(), + compressWrappedTermContentZstdSpansBatch: vi.fn(), + decompressTermContentZstd: vi.fn((bytes) => bytes), +})); + +beforeEach(() => { vi.mocked(decompressTermContentZstd).mockClear(); }); + +/** + * @param {(offset: number, length: number) => Promise} readSlice + * @returns {TermContentBlockStore} + */ +function createStore(readSlice) { + const contentStore = new TermContentOpfsStore(); + vi.spyOn(contentStore, 'readSlice').mockImplementation(readSlice); + return new TermContentBlockStore(contentStore); +} + +test('routes raw selector lookup through the immutable frame and keeps canonical bytes', async () => { + /** @type {Uint8Array} */ + const canonical = new Uint8Array([1, 2, 3]); + const staged = wrapCompressedTermContentBlock(canonical); + const sourceRead = vi.fn(async () => { throw new Error('Raw source should be resolved by the leased root'); }); + const frameRelease = vi.fn(); + /** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentFrameIdentity} */ + const expectedIdentity = {kind: 'raw-entry', + logicalOffset: 8, + recordLength: canonical.byteLength, + sourceStoredLength: canonical.byteLength, + originalCodecId: null, + expectedDecodedLength: canonical.byteLength, + originalEnvelope: 'none'}; + const findFrameOverrideCallback = /** @type {NonNullable} */ (async (/** @type {{kind: 'legacy-entry'|'raw-entry', logicalOffset: number, recordLength: number, originalCodecId: string|null}} */ query) => { + expect(query).toEqual({kind: 'raw-entry', logicalOffset: 8, recordLength: canonical.byteLength, originalCodecId: null}); + return expectedIdentity; + }); + const findFrameOverride = vi.fn(findFrameOverrideCallback); + const resolveFrameCallback = /** @type {NonNullable} */ (async (/** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentFrameIdentity} */ identity) => { + expect(identity).toEqual(expectedIdentity); + return /** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentResolvedFrame} */ ({bytes: staged, + codecId: 'manabitan-zstd-' + 'a'.repeat(64), + envelope: 'mbc2', + decodedLength: canonical.byteLength, + physicalKey: 'root:frame', + release: frameRelease}); + }); + const resolveFrame = vi.fn(resolveFrameCallback); + /** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentReadContext} */ + const context = { + findFrameOverride, + resolveFrame, + readSlice: sourceRead, + readSlicesDetailed: async () => [], + fork() { return this; }, + release: vi.fn(), + }; + const store = createStore(sourceRead); + store.setReadContextProvider(() => context); + + await expect(store.readDetailed(8, canonical.byteLength, 'raw-v2')).resolves.toEqual({status: 'ok', bytes: canonical}); + expect(context.findFrameOverride).toHaveBeenCalledOnce(); + expect(context.resolveFrame).toHaveBeenCalledOnce(); + expect(sourceRead).not.toHaveBeenCalled(); + expect(decompressTermContentZstd).toHaveBeenCalledWith( + canonical, + 'manabitan-zstd-' + 'a'.repeat(64), + {defaultHeapSize: canonical.byteLength, maxOutputSize: canonical.byteLength, codecSource: 'immutable-layout'}, + ); + expect(frameRelease).toHaveBeenCalledOnce(); +}); + +test('raw compatibility reads remain byte-for-byte when no immutable root is active', async () => { + /** @type {Uint8Array} */ + const canonical = new Uint8Array([7, 8, 9]); + const readSliceCallback = /** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentReadContext['readSlice']} */ (async (offset, length) => canonical.slice(offset, offset + length)); + const readSlice = vi.fn(readSliceCallback); + const store = createStore(readSlice); + await expect(store.readDetailed(0, canonical.byteLength, 'raw-v3')).resolves.toEqual({status: 'ok', bytes: canonical}); + expect(readSlice).toHaveBeenCalledWith(0, canonical.byteLength); + expect(decompressTermContentZstd).not.toHaveBeenCalled(); +}); + +test('single raw read falls back to import staging when its leased root has no frame window', async () => { + /** @type {Uint8Array} */ + const staging = new Uint8Array([4, 5, 6]); + const findFrameOverride = vi.fn(async () => null); + /** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentReadContext} */ + const context = { + logicalHighWater: 3, + findFrameOverride, + readSlice: vi.fn(/** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentReadContext['readSlice']} */ (async (offset, length) => staging.slice(offset - 3, offset - 3 + length))), + readSlicesDetailed: async () => [], + resolveFrame: async () => null, + fork() { return this; }, + release: vi.fn(), + }; + const store = createStore(async () => null); + store.setReadContextProvider(() => context); + await expect(store.readDetailed(3, 3, 'raw-v2')).resolves.toEqual({status: 'ok', bytes: staging}); + expect(findFrameOverride).toHaveBeenCalledOnce(); + expect(context.readSlice).toHaveBeenCalledWith(3, 3); +}); + +test('batches ordinary raw slices while resolving only mixed raw overrides through frames', async () => { + /** @type {Uint8Array} */ + const direct = new Uint8Array([1, 2, 3]); + /** @type {Uint8Array} */ + const compressed = new Uint8Array([4, 5, 6]); + /** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentFrameIdentity} */ + const overrideIdentity = {kind: 'raw-entry', + logicalOffset: 3, + recordLength: compressed.byteLength, + sourceStoredLength: compressed.byteLength, + originalCodecId: null, + expectedDecodedLength: compressed.byteLength, + originalEnvelope: 'none'}; + const release = vi.fn(); + /** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentReadContext['readSlicesDetailed']} */ + const readSlicesDetailed = vi.fn(/** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentReadContext['readSlicesDetailed']} */ (async () => [{status: /** @type {const} */ ('ok'), bytes: direct}])); + /** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentReadContext} */ + const context = { + findFrameOverride: async (/** @type {{logicalOffset: number}} */ {logicalOffset}) => (logicalOffset === 3 ? overrideIdentity : null), + resolveFrame: async () => ({bytes: wrapCompressedTermContentBlock(compressed), + codecId: 'manabitan-zstd-' + 'c'.repeat(64), + envelope: 'mbc2', + decodedLength: compressed.byteLength, + physicalKey: 'root:raw-override', + release}), + readSlice: async () => { throw new Error('The root should provide batched direct reads'); }, + readSlicesDetailed, + fork() { return this; }, + release: vi.fn(), + }; + const store = createStore(async () => { throw new Error('Unexpected source read'); }); + store.setReadContextProvider(() => context); + const result = await store.readDetailedBatch([ + {contentOffset: 0, contentLength: direct.byteLength, contentDictName: 'raw-v2'}, + {contentOffset: 3, contentLength: compressed.byteLength, contentDictName: 'raw-v4'}, + ]); + expect(result).toEqual([{status: 'ok', bytes: direct}, {status: 'ok', bytes: compressed}]); + expect(readSlicesDetailed).toHaveBeenCalledOnce(); + expect(release).toHaveBeenCalledOnce(); + expect(decompressTermContentZstd).toHaveBeenCalledOnce(); +}); + +test('batched raw read falls back to import staging when a span starts at the leased high-water mark', async () => { + /** @type {Uint8Array} */ + const staging = new Uint8Array([4, 5, 6]); + /** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentReadContext} */ + const context = { + logicalHighWater: 3, + findFrameOverride: vi.fn(async () => null), + readSlice: vi.fn(/** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentReadContext['readSlice']} */ (async (offset, length) => staging.slice(offset - 3, offset - 3 + length))), + readSlicesDetailed: vi.fn(/** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentReadContext['readSlicesDetailed']} */ (async (requests) => requests.map(({offset, length}) => ({status: /** @type {const} */ ('ok'), bytes: staging.slice(offset - 3, offset - 3 + length)})))), + resolveFrame: async () => null, + fork() { return this; }, + release: vi.fn(), + }; + const store = createStore(async () => null); + store.setReadContextProvider(() => context); + await expect(store.readDetailedBatch([{contentOffset: 3, contentLength: 3, contentDictName: 'raw-v2'}])) + .resolves.toEqual([{status: 'ok', bytes: staging}]); + expect(context.findFrameOverride).toHaveBeenCalledOnce(); + expect(context.readSlicesDetailed).toHaveBeenCalledWith([{offset: 3, length: 3}]); +}); + +test('an in-flight raw read keeps its old root while later reads observe cutover', async () => { + /** @type {Uint8Array} */ + const canonical = new Uint8Array([4, 5, 6]); + const staged = wrapCompressedTermContentBlock(canonical); + /** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentFrameIdentity} */ + const identity = {kind: 'raw-entry', + logicalOffset: 40, + recordLength: canonical.byteLength, + sourceStoredLength: canonical.byteLength, + originalCodecId: null, + expectedDecodedLength: canonical.byteLength, + originalEnvelope: 'none'}; + const start = /** @type {import('core').DeferredPromiseDetails} */ (deferPromise()); + const releaseOld = /** @type {import('core').DeferredPromiseDetails} */ (deferPromise()); + /** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentReadContext} */ + const oldContext = { + findFrameOverride: async () => { + start.resolve(); + await releaseOld.promise; + return null; + }, + readSlice: async () => canonical, + readSlicesDetailed: async () => [], + resolveFrame: async () => null, + fork() { return this; }, + release: vi.fn(), + }; + const newFrameRelease = vi.fn(); + /** @type {import('../ext/js/dictionary/term-content-block-store.js').TermContentReadContext} */ + const newContext = { + findFrameOverride: async () => identity, + resolveFrame: async () => ({bytes: staged, + codecId: 'manabitan-zstd-' + 'b'.repeat(64), + envelope: 'mbc2', + decodedLength: canonical.byteLength, + physicalKey: 'new-root:compressed', + release: newFrameRelease}), + readSlice: async () => { throw new Error('New raw source should come from its root replacement'); }, + readSlicesDetailed: async () => [], + fork() { return this; }, + release: vi.fn(), + }; + const sourceRead = vi.fn(async () => { throw new Error('Unexpected unleased raw read'); }); + const store = createStore(sourceRead); + store.setReadContextProvider(() => oldContext); + const oldRead = store.readDetailed(identity.logicalOffset, identity.recordLength, 'raw-v6'); + await start.promise; + store.setReadContextProvider(() => newContext); + releaseOld.resolve(); + await expect(oldRead).resolves.toEqual({status: 'ok', bytes: canonical}); + + store.clearCache(); + await expect(store.readDetailed(identity.logicalOffset, identity.recordLength, 'raw-v6')) + .resolves.toEqual({status: 'ok', bytes: canonical}); + expect(newFrameRelease).toHaveBeenCalledOnce(); + expect(sourceRead).not.toHaveBeenCalled(); +});