diff --git a/.changeset/bounded-archive-segments.md b/.changeset/bounded-archive-segments.md new file mode 100644 index 0000000..d37c04c --- /dev/null +++ b/.changeset/bounded-archive-segments.md @@ -0,0 +1,9 @@ +--- +'@ontos-ai/knowhere-sdk': patch +--- + +Interrupt active archive transfers at the segment deadline, persist the contiguous completed prefix, and return a resumable pending result. Caller cancellation and checkpoint failures remain errors. + +Validate duplicate ZIP resource names before starting uploads. Reuse byte-identical resources after SHA-256 verification and reject conflicting resources without partial writes. + +Keep canonical resource hashes consistent during immutable snapshot checksum verification while validating every physical ZIP entry's CRC and size. diff --git a/src/storage/__tests__/streamed-sync-concurrency.test.ts b/src/storage/__tests__/streamed-sync-concurrency.test.ts index 0680500..812926c 100644 --- a/src/storage/__tests__/streamed-sync-concurrency.test.ts +++ b/src/storage/__tests__/streamed-sync-concurrency.test.ts @@ -5,6 +5,7 @@ import { randomBytes } from 'node:crypto'; import { ZipReader, configure, type FileEntry } from '@zip.js/zip.js'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { Knowledge } from '../../knowledge/knowledge.js'; +import type { KnowledgeSyncParsedDocumentResponse } from '../../knowledge/types.js'; import type { Knowhere } from '../../client.js'; import type { ParsedDocumentObject, @@ -26,7 +27,10 @@ interface Fixture { readonly finished: string[]; readonly lengths: Map; readonly fetch: ReturnType; - readonly sync: (limits?: ParsedDocumentStorageLimits, signal?: AbortSignal) => Promise; + readonly sync: ( + limits?: ParsedDocumentStorageLimits, + signal?: AbortSignal, + ) => Promise; readonly getPeak: () => number; } @@ -42,6 +46,7 @@ async function createFixture( readonly wrapErrors?: boolean; readonly onStart?: (path: string) => void; readonly delays?: Readonly>; + readonly duplicateEntry?: 'identical' | 'conflicting'; } = {}, ): Promise { const zip: JSZip = new JSZip(); @@ -56,10 +61,28 @@ async function createFixture( ? `body-${index}`.repeat(262144) : `body-${index}`, ); + if (options.duplicateEntry) { + zip.file('images/first.png', 'original-image'); + zip.file( + 'images/other.png', + options.duplicateEntry === 'identical' ? 'original-image' : 'modified-image', + ); + } const archive: Uint8Array = await zip.generateAsync({ type: 'uint8array', compression: 'DEFLATE', }); + if (options.duplicateEntry) { + const buffer: Buffer = Buffer.from(archive.buffer, archive.byteOffset, archive.byteLength); + const originalName: Buffer = Buffer.from('images/other.png'); + const repeatedName: Buffer = Buffer.from('images/first.png'); + for ( + let offset: number = buffer.indexOf(originalName); + offset !== -1; + offset = buffer.indexOf(originalName, offset + repeatedName.length) + ) + buffer.set(repeatedName, offset); + } const fetchMock: ReturnType = vi.fn( (input: unknown, init?: RequestInit): Promise => { const range: string | null = new Headers(init?.headers).get('range'); @@ -159,7 +182,7 @@ async function createFixture( lengths, fetch: fetchMock, getPeak: (): number => peak, - sync: (limits, signal): Promise => + sync: (limits, signal): Promise => syncRemoteResultArchive({ documentId: 'document', revisionKey: 'revision', @@ -177,7 +200,173 @@ afterEach(() => { vi.unstubAllGlobals(); }); +function readCancellationReason(signal: AbortSignal | undefined): Error { + const reason: unknown = signal?.reason; + return reason instanceof Error ? reason : new Error('Fixture transfer cancelled'); +} + +function createSegmentDeadline(): AbortController { + const controller: AbortController = new AbortController(); + const createTimeout: typeof AbortSignal.timeout = AbortSignal.timeout.bind(AbortSignal); + vi.spyOn(AbortSignal, 'timeout').mockImplementation( + (milliseconds: number): AbortSignal => + milliseconds === 60_000 ? controller.signal : createTimeout(milliseconds), + ); + return controller; +} + describe('bounded parsed archive concurrency', () => { + it.each([false, true])( + 'verifies an immutable snapshot containing byte-identical repeated resources with cache %s', + async (cache: boolean) => { + const fixture: Fixture = await createFixture({ + fileCount: 0, + duplicateEntry: 'identical', + cache, + }); + const synchronize = (): Promise => + syncRemoteResultArchive({ + documentId: 'document', + revisionKey: 'snapshot', + jobId: 'job', + resultUrl: 'https://archive.example/result.zip', + storage: fixture.storage, + cacheResultArchive: cache, + snapshot: { + snapshotId: 'snapshot', + stage: 'final', + jobId: 'job', + jobResultId: 'result', + documentId: 'document', + checksum: createHash('sha256').update(fixture.archive).digest('hex'), + resultUrl: 'https://archive.example/result.zip', + resultUrlExpiresAt: new Date('2030-01-01'), + }, + }); + await expect(synchronize()).resolves.toMatchObject({ completed: true }); + await expect(synchronize()).resolves.toMatchObject({ completed: true }); + }, + ); + + it('continues across byte-identical duplicate archive resources', async () => { + const fixture: Fixture = await createFixture({ fileCount: 0, duplicateEntry: 'identical' }); + for (let segment: number = 0; segment < 4; segment += 1) { + const result: KnowledgeSyncParsedDocumentResponse = await fixture.sync({ + maxEntriesPerSync: 1, + }); + if (result.completed) break; + } + expect(fixture.progress.at(-1)).toMatchObject({ status: 'completed', nextArchiveEntry: 3 }); + expect( + fixture.started.filter((path: string): boolean => path === 'images/first.png'), + ).toHaveLength(1); + expect(Buffer.from(fixture.objects.get('images/first.png') ?? []).toString()).toBe( + 'original-image', + ); + }); + + it('rejects conflicting duplicate paths before starting uploads', async () => { + const fixture: Fixture = await createFixture({ fileCount: 0, duplicateEntry: 'conflicting' }); + await expect(fixture.sync()).rejects.toThrow('Duplicate parsed result path'); + expect(fixture.started).toHaveLength(0); + expect(fixture.progress).toHaveLength(0); + }); + + it('reports checkpoint failure instead of acknowledging a deadline handoff', async () => { + const fixture: Fixture = await createFixture(); + const deadline: AbortController = createSegmentDeadline(); + let hasHeldEntry: boolean = false; + const checkpointFailure: Error = new Error('Checkpoint persistence unavailable'); + const write = fixture.storage.writeObjectStream?.bind(fixture.storage); + if (!write) throw new Error('Fixture requires streaming storage.'); + fixture.storage.writeObjectStream = async ( + params: ParsedDocumentWriteObjectStreamParams, + ): Promise => { + if (params.path === 'file-1.txt') { + hasHeldEntry = true; + await new Promise((_resolve, reject) => { + params.signal?.addEventListener( + 'abort', + () => reject(readCancellationReason(params.signal)), + { + once: true, + }, + ); + }); + } + return write(params); + }; + fixture.storage.writeSyncProgress = (): Promise => Promise.reject(checkpointFailure); + const pending: Promise = fixture.sync( + { + archiveSyncDeadlineMs: 60_000, + maxConcurrentFiles: 3, + checkpointFileInterval: 100, + checkpointIntervalMs: 60_000, + }, + AbortSignal.timeout(2_000), + ); + await vi.waitFor(() => { + expect(hasHeldEntry).toBe(true); + expect(fixture.finished).toContain('file-0.txt'); + }); + deadline.abort(new DOMException('Segment budget expired', 'TimeoutError')); + await expect(pending).rejects.toBe(checkpointFailure); + expect(fixture.objects.has('.knowhere-sdk/commit.json')).toBe(false); + }); + + it('checkpoints the contiguous prefix when an active entry reaches the segment deadline and resumes', async () => { + const fixture: Fixture = await createFixture(); + const deadline: AbortController = createSegmentDeadline(); + let hasHeldEntry: boolean = false; + const write = fixture.storage.writeObjectStream?.bind(fixture.storage); + if (!write) throw new Error('Fixture requires streaming storage.'); + fixture.storage.writeObjectStream = async ( + params: ParsedDocumentWriteObjectStreamParams, + ): Promise => { + if (params.path === 'file-1.txt') { + hasHeldEntry = true; + await new Promise((_resolve, reject) => { + if (params.signal?.aborted) reject(readCancellationReason(params.signal)); + else + params.signal?.addEventListener( + 'abort', + () => reject(readCancellationReason(params.signal)), + { + once: true, + }, + ); + }); + } + return write(params); + }; + const pending: Promise = fixture.sync( + { + archiveSyncDeadlineMs: 60_000, + maxConcurrentFiles: 3, + checkpointFileInterval: 10, + checkpointIntervalMs: 60_000, + }, + AbortSignal.timeout(2_000), + ); + await vi.waitFor(() => { + expect(hasHeldEntry).toBe(true); + expect(fixture.finished).toContain('file-0.txt'); + }); + deadline.abort(new DOMException('Segment budget expired', 'TimeoutError')); + await expect(pending).resolves.toMatchObject({ completed: false, revisionKey: 'revision' }); + expect(fixture.progress.at(-1)).toMatchObject({ status: 'running', nextArchiveEntry: 3 }); + expect(fixture.objects.has('.knowhere-sdk/commit.json')).toBe(false); + const alreadyCopied: string[] = fixture.finished.slice(0, 3); + fixture.storage.writeObjectStream = write; + await expect(fixture.sync()).resolves.toMatchObject({ completed: true }); + expect(fixture.progress.at(-1)).toMatchObject({ status: 'completed', nextArchiveEntry: 10 }); + for (const path of alreadyCopied) + expect( + fixture.finished.filter((finished: string): boolean => finished === path), + ).toHaveLength(1); + }); + it('copies Range entries concurrently and provides the expected uncompressed length', async () => { const fixture: Fixture = await createFixture({ delays: { 'manifest.json': 20 } }); await fixture.sync({ maxConcurrentFiles: 3, checkpointFileInterval: 4 }); diff --git a/src/storage/sequential-parsed-document-archive.ts b/src/storage/sequential-parsed-document-archive.ts index 0b5bb3b..5b3d208 100644 --- a/src/storage/sequential-parsed-document-archive.ts +++ b/src/storage/sequential-parsed-document-archive.ts @@ -18,6 +18,11 @@ import { type StreamedSyncParams, } from './streamed-parsed-document-sync.js'; +interface SequentialEntryChecksum { + readonly checksum: number; + readonly size: number; +} + export async function openSequentialArchive( params: StreamedSyncParams, identity: string, @@ -54,7 +59,8 @@ export async function openSequentialArchive( } const input: Readable = Readable.fromWeb(body); const parser = Parse({ forceStream: true }); - const checksums: Map = new Map(); + const checksums: Map = new Map(); + let decodedEntryCount: number = 0; let archiveSize: number = 0; const archiveHash = createHash('sha256'); // unzipper extracts sequentially, but does not verify CRCs. Spool compressed bytes to disk @@ -124,7 +130,10 @@ export async function openSequentialArchive( controller.enqueue(chunk); }, flush(): void { - checksums.set(path, { checksum, size }); + const entries: SequentialEntryChecksum[] = checksums.get(path) ?? []; + entries.push({ checksum, size }); + checksums.set(path, entries); + decodedEntryCount += 1; }, }), ); @@ -141,16 +150,20 @@ export async function openSequentialArchive( const files = (await reader.getEntries()).filter( (entry): entry is FileEntry => !entry.directory && isSnapshotPath(entry.filename), ); - if (files.length !== checksums.size) + if (files.length !== decodedEntryCount) throw new Error('Parsed result ZIP directory does not match sequential entries.'); for (const entry of files) { - const actual = checksums.get(normalizeResultPath(entry.filename)); - if ( - !actual || - actual.checksum !== entry.signature || - actual.size !== entry.uncompressedSize - ) + const candidates: SequentialEntryChecksum[] | undefined = checksums.get( + normalizeResultPath(entry.filename), + ); + const index: number = + candidates?.findIndex( + (actual: SequentialEntryChecksum): boolean => + actual.checksum === entry.signature && actual.size === entry.uncompressedSize, + ) ?? -1; + if (index < 0) throw new Error(`Invalid parsed result ZIP checksum or size: ${entry.filename}`); + candidates?.splice(index, 1); } } finally { await reader.close(); diff --git a/src/storage/streamed-parsed-document-sync.ts b/src/storage/streamed-parsed-document-sync.ts index c68bfd9..bcbb46d 100644 --- a/src/storage/streamed-parsed-document-sync.ts +++ b/src/storage/streamed-parsed-document-sync.ts @@ -1,5 +1,5 @@ import type { ReadableStreamReadResult } from 'node:stream/web'; -import { createHash } from 'crypto'; +import { createHash, type Hash } from 'crypto'; import type { JobSnapshot } from '../types/job.js'; import { ValidationError } from '../errors/index.js'; import { ArchiveCacheTransportError } from './archive-cache-transport-error.js'; @@ -78,9 +78,12 @@ export async function syncRemoteResultArchive( const checkpointFileInterval: number = params.limits?.checkpointFileInterval ?? 1; const checkpointIntervalMs: number = params.limits?.checkpointIntervalMs ?? 2_000; const controller: AbortController = new AbortController(); - const signal: AbortSignal = params.signal - ? AbortSignal.any([params.signal, controller.signal]) - : controller.signal; + const deadline: AbortSignal = AbortSignal.timeout(deadlineMs); + const signal: AbortSignal = AbortSignal.any([ + controller.signal, + deadline, + ...(params.signal ? [params.signal] : []), + ]); const openingParams: StreamedSyncParams = { ...params, signal }; const previous: ParsedDocumentSyncProgress | null = await params.storage.readSyncProgress(params); const openedSource: ArchiveSource = await openArchive(openingParams, previous); @@ -316,6 +319,21 @@ export async function syncRemoteResultArchive( const hasCacheTransportFailure: boolean = isArchiveCacheTransportFailure(error) || isArchiveCacheTransportFailure(failure); if (hasCacheTransportFailure) archiveCacheBypassed = true; + const hasReachedSegmentDeadline: boolean = + deadline.aborted && + !params.signal?.aborted && + (failure === deadline.reason || error === deadline.reason); + if (hasReachedSegmentDeadline) { + // Active writers have settled. Persist only their contiguous prefix before + // handing off; a failed checkpoint remains an error rather than success. + await flushProgress(true, true); + return { + documentId: params.documentId, + revisionKey: params.revisionKey, + snapshot: params.snapshot, + completed: false, + }; + } await flushProgress(true, true).catch((): void => undefined); if (hasCacheTransportFailure) { await persistArchiveCacheBypass( @@ -587,6 +605,10 @@ async function openArchiveTransport( ), ) .digest('hex'); + const canonicalFiles: readonly FileEntry[] = await deduplicateArchiveEntries( + files, + rangeSignal, + ); return { signal: rangeSignal, identity: previous?.archiveIdentity === identity ? identity : archiveIdentity, @@ -605,7 +627,7 @@ async function openArchiveTransport( : undefined, canSkipEntries: previous?.archiveIdentity !== identity, entries: (function* (): Generator { - for (const entry of files) { + for (const entry of canonicalFiles) { let entryRead: RangeEntryRead | undefined; yield { path: normalizeResultPath(entry.filename), @@ -631,6 +653,48 @@ async function openArchiveTransport( } } +/** Repeated ZIP names are safe only after their decoded bytes match. Preserve + * the original directory identity so prefixes saved before the duplicate resume. */ +async function deduplicateArchiveEntries( + entries: readonly FileEntry[], + signal: AbortSignal, +): Promise { + const canonical: Map = new Map(); + const hashes: Map = new Map(); + const readHash = async (entry: FileEntry): Promise => { + const existing: string | undefined = hashes.get(entry); + if (existing !== undefined) return existing; + const hash: Hash = createHash('sha256'); + await entry.getData( + new WritableStream({ + write(chunk): void { + signal.throwIfAborted(); + hash.update(chunk); + }, + }), + { signal, checkCrc32: true, useWebWorkers: false }, + ); + const result: string = hash.digest('hex'); + hashes.set(entry, result); + return result; + }; + for (const entry of entries) { + signal.throwIfAborted(); + const path: string = normalizeResultPath(entry.filename); + const existing: FileEntry | undefined = canonical.get(path); + if (existing === undefined) { + canonical.set(path, entry); + continue; + } + if ( + existing.uncompressedSize !== entry.uncompressedSize || + (await readHash(existing)) !== (await readHash(entry)) + ) + throw new Error(`Duplicate parsed result path: ${path}`); + } + return [...canonical.values()]; +} + function readRangeEntry( entry: FileEntry, signal: AbortSignal | undefined, @@ -752,6 +816,7 @@ async function verifyArchiveChecksum( const { openSequentialArchive } = await import('./sequential-parsed-document-archive.js'); const source: ArchiveSource = await openSequentialArchive(params, identity, validateResponse); let entryIndex: number = 0; + const verifiedEntryHashes: Map = new Map(); try { for await (const entry of source.entries) { const hash = createHash('sha256'); @@ -763,10 +828,17 @@ async function verifyArchiveChecksum( .update(entry.path) .update(hash.digest()) .digest('hex'); + const existingHash: string | undefined = verifiedEntryHashes.get(entry.path); + if (existingHash !== undefined) { + if (existingHash !== entryHash) + throw new Error(`Duplicate parsed result path: ${entry.path}`); + continue; + } if (expectedEntryHashes[entryIndex] !== entryHash) throw new Error( 'Parsed snapshot archive entry changed between extraction and checksum verification.', ); + verifiedEntryHashes.set(entry.path, entryHash); entryIndex += 1; } if (entryIndex !== expectedEntryHashes.length) diff --git a/src/types/storage.ts b/src/types/storage.ts index ce8dcf7..2664e43 100644 --- a/src/types/storage.ts +++ b/src/types/storage.ts @@ -163,7 +163,7 @@ export interface ParsedDocumentStorageLimits { readonly checkpointFileInterval?: number; /** Maximum scheduling interval between checkpoints (default 2000ms). */ readonly checkpointIntervalMs?: number; - /** ZIP copy budget checked between entries (default 120000ms). */ + /** ZIP copy budget including active transfers; expiry checkpoints and yields (default 120000ms). */ readonly archiveSyncDeadlineMs?: number; readonly remotePageSize?: number; readonly maxPagesPerSync?: number;