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
7 changes: 7 additions & 0 deletions .changeset/frozen-ingestion-result.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@ontos-ai/knowhere-sdk': major
---

Remove `jobs.retryEnhancement`. New ingestion jobs complete once their initial result is searchable. Progressive PDF and PPTX jobs expose one frozen baseline snapshot. Historical baseline and final snapshots remain readable by ID.

Use `replacesDocumentId` to submit a private replacement job with a new document ID. Read integer directory versions through `documents.getStructure` and explicitly select `job.enrichment.failed` in `webhook.events` to receive per-attempt failure notifications.
58 changes: 42 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ const result = await client.jobs.load(jobResult);
Published documents are queryable through the retrieval API after a job
finishes. `client.jobs.create(...)` may return a planned `documentId`; persist
`jobResult.documentId` after publication as the canonical value if you need to
update or archive the same document later.
read, replace, or archive the document.

```typescript
const job = await client.jobs.create({
Expand All @@ -300,11 +300,11 @@ if (!documentId) {

console.log(documentId);

// Read all initially recognized chapters without waiting for Fine or copying assets.
// Read the latest published directory without copying assets or starting enrichment.
const directory = await client.documents.getStructure(documentId, {
namespace: 'support-center',
});
if (directory.directoryVersion === 1) {
if (directory.directoryVersion > 0) {
console.log(directory.sections); // physical pageNums are 1-based
}

Expand Down Expand Up @@ -369,15 +369,24 @@ reference.metadata;
Audio and video documents are speech transcripts; their citations carry
`timeRanges` in milliseconds so you can seek the recording.

Use `documentId` to update or archive a document:
To reparse a private document, use `replacesDocumentId` when creating the job.
Knowhere uses that ID to allow the same original in the same authorized
namespace. The job publishes a new document. Synchronize its result and adopt
its new `documentId` before archiving the previous document. The job creation
parameter `documentId` remains available for Demo Catalog and legacy servers.

```typescript
const updateJob = await client.jobs.create({
const replacementJob = await client.jobs.create({
sourceType: 'url',
sourceUrl: 'https://example.com/manual-v2.pdf',
documentId,
sourceUrl: 'https://example.com/manual.pdf',
namespace: 'support-center',
replacesDocumentId: documentId,
});
const replacement = await client.jobs.wait(replacementJob.jobId);
// Synchronize the result and persist replacement.documentId before archiving documentId.
```

```typescript
const documents = await client.documents.list({
namespace: 'support-center',
page: 1,
Expand Down Expand Up @@ -408,15 +417,32 @@ if (chunks.chunks[0]) {
console.log(archived.status);
```

Progressive parsing delivers `job.document.directory_ready` once logically per
parsed revision, independently of baseline and final completion. Retries retain
the same `event_id`; consumers should apply them idempotently and pass the
event's `job_result_id` and `namespace` to `getStructure`. Version zero means
the directory is pending. Version one includes every recognized descendant,
including an empty directory when no hierarchy was found. A structure read
does not trigger Fine or download page images. Raw webhook types are exported
as `DocumentDirectoryReadyEvent`; SDK responses use camelCase and parse the
directory timestamp into a `Date`.
Progressive parsing delivers `job.document.directory_ready` for the first
directory, independently of `job.completed`. Redelivery preserves `event_id`.
Pass the event's `job_result_id` and `namespace` to `getStructure` to read the
latest directory for that revision. Version zero means the initial directory
is pending. Version one is the first published tree. Higher integer versions
identify updated trees. SDK responses use camelCase and parse the directory
timestamp into a `Date`.

Set `webhook.events` when you want an explicit subscription. On servers with
the new ingestion contract, include `job.enrichment.failed` to receive failed
enrichment attempts alongside the ingestion and first-directory notifications.

```typescript
await client.startParse({
url: 'https://example.com/manual.pdf',
webhook: {
url: 'https://example.com/knowhere-callback',
events: ['job.completed', 'job.failed', 'job.document.directory_ready', 'job.enrichment.failed'],
},
});
```

The SDK exports `DocumentDirectoryReadyEvent` and `JobEnrichmentFailedEvent`
for the raw callback JSON. A failure event identifies the affected unit and
attempt. Use `event_id` to deduplicate redelivery. The ingestion remains complete
when a later enrichment attempt fails.

### Local Knowledge Tools

Expand Down
44 changes: 25 additions & 19 deletions docs/streamed-parsed-document-sync.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,14 +182,19 @@ allocations, and garbage-collection/native-allocation variance; they do not
establish a safe concurrency limit for a deployed application. Storage adapters
must preserve stream backpressure for the same memory behavior.

## Progressive ingestion snapshots
## Initial result and historical snapshots

Progressive Jobs add `enhancement`, `snapshots`, and `currentSnapshotId`. Each
`JobSnapshot` contains an opaque `snapshotId`, `stage`, real upstream
`jobResultId`, document/job identity, SHA-256 `checksum`, `resultUrl`, and
`resultUrlExpiresAt`. Baseline and final may share one upstream Job Result.
`jobs.retryEnhancement(jobId)` calls the authenticated bodyless enrichment retry
command and returns `{ jobId, enhancement }`; it does not create an ingestion.
On the new ingestion contract, `jobs.wait(jobId)` returns when the initial
result is searchable. For progressive PDF and PPTX jobs, `currentSnapshotId`
pins the baseline snapshot for that ingestion. Its archive stays fixed as
enrichment adds searchable content. Full ingestion completes with its full
result package.

Each `JobSnapshot` contains an opaque `snapshotId`, `stage`, upstream
`jobResultId`, document and job identity, SHA-256 `checksum`, `resultUrl`,
and `resultUrlExpiresAt`. Legacy progressive responses may include
`enhancement` and separate baseline and final descriptors. Those descriptors
can share one upstream Job Result.

```typescript
const copied = await knowledge.syncParsedDocument({ jobId, documentId });
Expand All @@ -213,19 +218,21 @@ with a separate sequential spool whose exact ZIP bytes pass SHA-256 validation.
This adds one archive download on a completing Range invocation, with bounded
memory and temporary disk usage proportional to the compressed archive. It does
not rely on HTTP validators proving that two downloads contain the same bytes.
Completed progressive copies validate remote entry hashes and checksum without
Completed pinned copies validate remote entry hashes and checksum without
rewriting committed content. A later `retainResultArchive` request can repair a
missing optional archive; retained ZIP bytes come from that verified spool.
Legacy/full copies retain the explicit rebuild behavior described above.

After a current snapshot commits, ordinary local read/grep/outline operations use
its durable reader pointer. An incomplete or failed final copy leaves baseline
current. A late baseline completion cannot supersede a committed final snapshot
of the same upstream revision. Explicit `revisionKey` reads retain their selected
content and assets; a missing pinned local snapshot cannot fall back to live
content, including before the first progressive copy completes. Sync the retained
snapshot before reading it. A later committed full-mode reparse also advances the
ordinary reader pointer while explicit historical snapshot reads stay pinned. Keep the storage objects and checkpoint keys for both stages.
After a current snapshot commits, ordinary local read, grep, and outline
operations use its durable reader pointer. Explicit `revisionKey` reads use the
selected local content and assets. Sync the retained snapshot before reading
it. Keep the storage objects and checkpoint keys for historical revisions.

When syncing a legacy response with both baseline and final snapshots, the
baseline remains current while the final copy is incomplete. Once the final
copy commits, it remains current for that upstream revision even if a late
baseline copy finishes afterward. A later published full-mode revision can also
advance the reader pointer while historical snapshot reads stay pinned.

Commits remain version 1 and add optional `snapshotId`, `jobResultId`, `checksum`,
and `stage`. Checkpoints add `snapshotChecksum` and `upstreamJobResultId`; adapters
Expand All @@ -238,9 +245,8 @@ revision; adapters should treat all revision/path keys as SDK-owned opaque keys.

Historical Job synchronization retains an immutable, explicitly pinned snapshot and
only advances ordinary reads when that Job still owns the published document.
A completed baseline remains locally readable while final synchronization is pending,
even if the upstream final archive is already available. Reads with a revision key
remain pinned and do not change the ordinary reader selection.
Reads with a revision key use the selected snapshot without changing the
ordinary reader selection.

Current-pointer writes are serialized per document across Knowledge clients sharing
the same storage adapter instance. The generic adapter exposes unconditional object
Expand Down
1 change: 1 addition & 0 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ export class Knowhere {
dataId: params.dataId,
namespace: params.namespace,
documentId: params.documentId,
replacesDocumentId: params.replacesDocumentId,
documentMetadata: params.documentMetadata,
parsingParams: buildParsingParams(params),
llmConfig: params.llmConfig,
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export type {
JobResult,
JobStatus,
JobError,
JobEnrichmentFailedEvent,
JobSnapshot,
JobSnapshotObject,
JobSnapshotDelivery,
Expand Down Expand Up @@ -63,6 +64,7 @@ export type {
LlmModelsConfig,
LlmProviderConfig,
WebhookConfig,
WebhookEventType,
CreateJobParams,
UploadParams,
WaitOptions,
Expand Down
38 changes: 23 additions & 15 deletions src/resources/__tests__/directory-wire.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
import { createServer, type Server } from 'node:http';
import { once } from 'node:events';
import { expect, it } from 'vitest';
import { expect, expectTypeOf, it } from 'vitest';
import { Knowhere } from '../../index.js';

it('decodes directory wire fields and dates while sending revision and namespace fences', async () => {
it.each([0, 1, 3])('reads pinned directory version %i', async (version: number): Promise<void> => {
let receivedUrl: string | undefined;
let authorization: string | undefined;
const wireSections = [
{
section_id: 'section-one',
parent_section_id: null,
section_path: 'Chapter',
section_title: null,
section_level: 1,
sort_order: 0,
page_nums: [1, 2],
},
] as const;
const server: Server = createServer((request, response): void => {
receivedUrl = request.url;
authorization = request.headers.authorization;
Expand All @@ -16,19 +27,9 @@ it('decodes directory wire fields and dates while sending revision and namespace
job_id: 'job-one',
job_result_id: 'result-one',
namespace: 'project/one',
directory_version: 1,
directory_committed_at: '2026-10-29T17:00:00+00:00',
sections: [
{
section_id: 'section-one',
parent_section_id: null,
section_path: 'Chapter',
section_title: null,
section_level: 1,
sort_order: 0,
page_nums: [1, 2],
},
],
directory_version: version,
directory_committed_at: version > 0 ? '2026-10-29T17:00:00+00:00' : null,
sections: version > 0 ? wireSections : [],
}),
);
});
Expand All @@ -46,10 +47,17 @@ it('decodes directory wire fields and dates while sending revision and namespace
jobResultId: 'result-one',
namespace: 'project/one',
});
expectTypeOf(directory.directoryVersion).toEqualTypeOf<number>();
expect(directory.directoryVersion).toBe(version);
expect(receivedUrl).toBe(
'/v2/documents/doc-one/structure?job_result_id=result-one&namespace=project%2Fone',
);
expect(authorization).toBe('Bearer test-key');
if (version === 0) {
expect(directory.directoryCommittedAt).toBeNull();
expect(directory.sections).toEqual([]);
return;
}
expect(directory.directoryCommittedAt).toEqual(new Date('2026-10-29T17:00:00Z'));
expect(directory.sections[0]).toEqual({
sectionId: 'section-one',
Expand Down
37 changes: 24 additions & 13 deletions src/resources/__tests__/enhancement.test.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
import { describe, expect, it, vi } from 'vitest';
import { describe, expect, expectTypeOf, it } from 'vitest';
import { Knowhere, type JobEnrichmentFailedEvent } from '../../index.js';
import { keysToCamel, parseDates } from '../../lib/utils.js';
import { HttpClient } from '../../lib/http-client.js';
import { Jobs } from '../jobs.js';

describe('enhancement retry', () => {
it('posts no body to the enrichment retry command and returns its current state', async () => {
const http = new HttpClient({ baseURL: 'https://api.example', apiKey: 'test' });
const response = {
jobId: 'job_test',
enhancement: { status: 'running', canRetry: false, attempt: 2, error: null },
};
const post = vi.spyOn(http, 'post').mockResolvedValue(response);
expect(await new Jobs(http).retryEnhancement('job_test')).toEqual(response);
expect(post).toHaveBeenCalledWith('/v2/jobs/job_test/enrichment/retry');
describe('enrichment compatibility', () => {
it('omits the manual enhancement retry command', (): void => {
const client: Knowhere = new Knowhere({ apiKey: 'test' });
expect('retryEnhancement' in client.jobs).toBe(false);
});

it('types the raw failure event by failed attempt', (): void => {
const event = {
event: 'job.enrichment.failed',
event_id: 'event-2',
job_id: 'job-test',
document_id: 'doc-test',
job_result_id: 'result-test',
unit_id: 'chapter-3',
attempt: 2,
can_retry: true,
error: { code: 'INDEXING_FAILED' },
} satisfies JobEnrichmentFailedEvent;
expectTypeOf<JobEnrichmentFailedEvent['error']['message']>().toEqualTypeOf<
string | undefined
>();
expect(event.event_id).toBe('event-2');
});

it('projects additive snake case snapshot fields and URL expiry through the HTTP conversion', () => {
Expand Down
81 changes: 81 additions & 0 deletions src/resources/__tests__/ingestion-wire.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { once } from 'node:events';
import { createServer, type Server } from 'node:http';
import { buffer } from 'node:stream/consumers';
import { expect, it } from 'vitest';
import { Knowhere, type WebhookConfig } from '../../index.js';

it('submits a replacement admission hint and the explicit Hipo event selection', async (): Promise<void> => {
const webhook: WebhookConfig = {
url: 'https://example.com/knowhere-callback',
events: [
'job.completed',
'job.failed',
'job.document.directory_ready',
'job.enrichment.failed',
],
};
const requests: unknown[] = [];
const server: Server = createServer((request, response): void => {
void buffer(request).then((body): void => {
const params: unknown = JSON.parse(body.toString());
requests.push(params);
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(
JSON.stringify({
job_id: 'job-replacement',
status: 'pending',
source_type: 'url',
created_at: '2026-11-20T12:00:00Z',
document_id: 'doc-new',
}),
);
});
});
try {
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const address = server.address();
if (address === null || typeof address === 'string') throw new Error('Expected a TCP address');
const client: Knowhere = new Knowhere({
baseURL: `http://127.0.0.1:${address.port}`,
apiKey: 'test-key',
maxRetries: 0,
});
const job = await client.startParse({
url: 'https://example.com/original.pdf',
namespace: 'project',
replacesDocumentId: 'doc-old',
webhook,
});
await client.jobs.create({
sourceType: 'url',
sourceUrl: 'https://example.com/demo.pdf',
namespace: '__knowhere_demo__',
dataId: 'catalog-entry',
documentId: 'doc-demo',
webhook: { url: webhook.url },
});

expect(job.documentId).toBe('doc-new');
expect(requests[0]).toMatchObject({
source_url: 'https://example.com/original.pdf',
namespace: 'project',
replaces_document_id: 'doc-old',
webhook,
});
expect(requests[0]).not.toHaveProperty('document_id');
expect(requests[1]).toMatchObject({
namespace: '__knowhere_demo__',
data_id: 'catalog-entry',
document_id: 'doc-demo',
webhook: { url: webhook.url },
});
expect(requests[1]).not.toHaveProperty('replaces_document_id');
expect(requests[1]).not.toHaveProperty('webhook.events');
} finally {
await new Promise<void>((resolve, reject): void => {
server.close((error): void => (error ? reject(error) : resolve()));
server.closeAllConnections();
});
}
});
2 changes: 1 addition & 1 deletion src/resources/documents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export class Documents extends BaseResource {
return this.httpClient.get<Document>(this.endpoint(`/documents/${documentId}`));
}

/** Read the initial chapter directory without downloading assets or triggering Fine. */
/** Read the latest published directory without downloading assets or triggering enrichment. */
async getStructure(
documentId: string,
params?: DocumentDirectoryParams,
Expand Down
Loading
Loading