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
9 changes: 9 additions & 0 deletions .changeset/bounded-archive-segments.md
Original file line number Diff line number Diff line change
@@ -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.
193 changes: 191 additions & 2 deletions src/storage/__tests__/streamed-sync-concurrency.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -26,7 +27,10 @@ interface Fixture {
readonly finished: string[];
readonly lengths: Map<string, number | undefined>;
readonly fetch: ReturnType<typeof vi.fn>;
readonly sync: (limits?: ParsedDocumentStorageLimits, signal?: AbortSignal) => Promise<unknown>;
readonly sync: (
limits?: ParsedDocumentStorageLimits,
signal?: AbortSignal,
) => Promise<KnowledgeSyncParsedDocumentResponse>;
readonly getPeak: () => number;
}

Expand All @@ -42,6 +46,7 @@ async function createFixture(
readonly wrapErrors?: boolean;
readonly onStart?: (path: string) => void;
readonly delays?: Readonly<Record<string, number>>;
readonly duplicateEntry?: 'identical' | 'conflicting';
} = {},
): Promise<Fixture> {
const zip: JSZip = new JSZip();
Expand All @@ -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<typeof vi.fn> = vi.fn(
(input: unknown, init?: RequestInit): Promise<Response> => {
const range: string | null = new Headers(init?.headers).get('range');
Expand Down Expand Up @@ -159,7 +182,7 @@ async function createFixture(
lengths,
fetch: fetchMock,
getPeak: (): number => peak,
sync: (limits, signal): Promise<unknown> =>
sync: (limits, signal): Promise<KnowledgeSyncParsedDocumentResponse> =>
syncRemoteResultArchive({
documentId: 'document',
revisionKey: 'revision',
Expand All @@ -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<KnowledgeSyncParsedDocumentResponse> =>
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<ParsedDocumentWriteObjectResult> => {
if (params.path === 'file-1.txt') {
hasHeldEntry = true;
await new Promise<void>((_resolve, reject) => {
params.signal?.addEventListener(
'abort',
() => reject(readCancellationReason(params.signal)),
{
once: true,
},
);
});
}
return write(params);
};
fixture.storage.writeSyncProgress = (): Promise<void> => Promise.reject(checkpointFailure);
const pending: Promise<KnowledgeSyncParsedDocumentResponse> = 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<ParsedDocumentWriteObjectResult> => {
if (params.path === 'file-1.txt') {
hasHeldEntry = true;
await new Promise<void>((_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<KnowledgeSyncParsedDocumentResponse> = 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 });
Expand Down
31 changes: 22 additions & 9 deletions src/storage/sequential-parsed-document-archive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -54,7 +59,8 @@ export async function openSequentialArchive(
}
const input: Readable = Readable.fromWeb(body);
const parser = Parse({ forceStream: true });
const checksums: Map<string, { readonly checksum: number; readonly size: number }> = new Map();
const checksums: Map<string, SequentialEntryChecksum[]> = 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
Expand Down Expand Up @@ -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;
},
}),
);
Expand All @@ -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();
Expand Down
Loading
Loading