From b56d01c3a51cf4cbc66b861f953965daf2bcc88d Mon Sep 17 00:00:00 2001 From: suguanYang Date: Fri, 20 Nov 2026 21:31:14 -0800 Subject: [PATCH] Support frozen initial ingestion in the Node SDK --- .changeset/frozen-ingestion-result.md | 7 ++ README.md | 58 +++++++++---- docs/streamed-parsed-document-sync.md | 44 +++++----- src/client.ts | 1 + src/index.ts | 2 + .../__tests__/directory-wire.test.ts | 38 +++++---- src/resources/__tests__/enhancement.test.ts | 37 ++++++--- .../__tests__/ingestion-wire.test.ts | 81 +++++++++++++++++++ src/resources/documents.ts | 2 +- src/resources/jobs.ts | 10 +-- src/types/document.ts | 10 +-- src/types/job.ts | 22 ++++- src/types/params.ts | 25 +++++- 13 files changed, 252 insertions(+), 85 deletions(-) create mode 100644 .changeset/frozen-ingestion-result.md create mode 100644 src/resources/__tests__/ingestion-wire.test.ts diff --git a/.changeset/frozen-ingestion-result.md b/.changeset/frozen-ingestion-result.md new file mode 100644 index 0000000..be83618 --- /dev/null +++ b/.changeset/frozen-ingestion-result.md @@ -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. diff --git a/README.md b/README.md index 1ac24b5..02ffccc 100644 --- a/README.md +++ b/README.md @@ -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({ @@ -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 } @@ -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, @@ -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 diff --git a/docs/streamed-parsed-document-sync.md b/docs/streamed-parsed-document-sync.md index c620b72..1ac26c8 100644 --- a/docs/streamed-parsed-document-sync.md +++ b/docs/streamed-parsed-document-sync.md @@ -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 }); @@ -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 @@ -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 diff --git a/src/client.ts b/src/client.ts index 10d0e04..e46acd3 100644 --- a/src/client.ts +++ b/src/client.ts @@ -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, diff --git a/src/index.ts b/src/index.ts index cdefaac..3461d9f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -20,6 +20,7 @@ export type { JobResult, JobStatus, JobError, + JobEnrichmentFailedEvent, JobSnapshot, JobSnapshotObject, JobSnapshotDelivery, @@ -63,6 +64,7 @@ export type { LlmModelsConfig, LlmProviderConfig, WebhookConfig, + WebhookEventType, CreateJobParams, UploadParams, WaitOptions, diff --git a/src/resources/__tests__/directory-wire.test.ts b/src/resources/__tests__/directory-wire.test.ts index 26a1c14..0bb81fa 100644 --- a/src/resources/__tests__/directory-wire.test.ts +++ b/src/resources/__tests__/directory-wire.test.ts @@ -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 => { 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; @@ -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 : [], }), ); }); @@ -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(); + 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', diff --git a/src/resources/__tests__/enhancement.test.ts b/src/resources/__tests__/enhancement.test.ts index 7aa2d09..b989097 100644 --- a/src/resources/__tests__/enhancement.test.ts +++ b/src/resources/__tests__/enhancement.test.ts @@ -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().toEqualTypeOf< + string | undefined + >(); + expect(event.event_id).toBe('event-2'); }); it('projects additive snake case snapshot fields and URL expiry through the HTTP conversion', () => { diff --git a/src/resources/__tests__/ingestion-wire.test.ts b/src/resources/__tests__/ingestion-wire.test.ts new file mode 100644 index 0000000..11ce1a2 --- /dev/null +++ b/src/resources/__tests__/ingestion-wire.test.ts @@ -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 => { + 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((resolve, reject): void => { + server.close((error): void => (error ? reject(error) : resolve())); + server.closeAllConnections(); + }); + } +}); diff --git a/src/resources/documents.ts b/src/resources/documents.ts index 8051d4e..b362724 100644 --- a/src/resources/documents.ts +++ b/src/resources/documents.ts @@ -41,7 +41,7 @@ export class Documents extends BaseResource { return this.httpClient.get(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, diff --git a/src/resources/jobs.ts b/src/resources/jobs.ts index a59a937..b4ca85f 100644 --- a/src/resources/jobs.ts +++ b/src/resources/jobs.ts @@ -2,7 +2,6 @@ import { BaseResource } from './base.js'; import type { Job, JobResult, - JobEnhancementRetryResult, JobSnapshotDelivery, JobSnapshotObjectAccess, JobSnapshotObjectAccessBatch, @@ -112,13 +111,6 @@ export class Jobs extends BaseResource { return this.httpClient.download(access.downloadUrl, { signal: options?.signal }); } - /** Renew unfinished enhancement without creating another ingestion. */ - async retryEnhancement(jobId: string): Promise { - return this.httpClient.post( - this.endpoint(`/jobs/${jobId}/enrichment/retry`), - ); - } - /** * Upload file for a job */ @@ -142,7 +134,7 @@ export class Jobs extends BaseResource { } /** - * Wait for job completion + * Wait until the initial parsed result is searchable or the job fails. */ async wait(jobId: string, options?: WaitOptions): Promise { return pollJobStatus(this.httpClient, jobId, options); diff --git a/src/types/document.ts b/src/types/document.ts index 6b16c1d..020e10c 100644 --- a/src/types/document.ts +++ b/src/types/document.ts @@ -60,13 +60,13 @@ export interface DocumentListResponse { pagination: DocumentListPagination; } -/** A revision-fenced read of the initial directory; this never triggers refinement. */ +/** A revision-fenced read of the latest published directory. */ export interface DocumentDirectoryParams { readonly jobResultId?: string; readonly namespace?: string; } -/** One recognized chapter, including descendants available before Fine. */ +/** One section in the published directory. */ export interface DocumentDirectorySection { readonly sectionId: string; readonly parentSectionId: string | null; @@ -78,18 +78,18 @@ export interface DocumentDirectorySection { readonly pageNums: readonly number[]; } -/** Immutable initial directory. Version zero explicitly means not ready yet. */ +/** The latest published directory. Version zero means the initial directory is pending. */ export interface DocumentDirectoryResponse { readonly documentId: string; readonly jobId: string; readonly jobResultId: string; readonly namespace: string; - readonly directoryVersion: 0 | 1; + readonly directoryVersion: number; readonly directoryCommittedAt: Date | null; readonly sections: readonly DocumentDirectorySection[]; } -/** Raw webhook JSON, delivered independently of parse completion and Fine. */ +/** Raw webhook JSON for the first published directory, delivered independently of job completion. */ export interface DocumentDirectoryReadyEvent { readonly event: 'job.document.directory_ready'; readonly event_id: string; diff --git a/src/types/job.ts b/src/types/job.ts index be29ee1..ec25695 100644 --- a/src/types/job.ts +++ b/src/types/job.ts @@ -47,8 +47,11 @@ export interface JobError { * Job status response with full details */ export interface JobResult { + /** Legacy document-wide enhancement state, when returned by an older publisher. */ enhancement?: JobEnhancement; + /** Retained immutable result snapshots, including historical generations. */ snapshots?: readonly JobSnapshot[]; + /** The published snapshot. New progressive PDF and PPTX jobs keep their baseline pin. */ currentSnapshotId?: string; /** Unique job identifier */ jobId: string; @@ -95,7 +98,7 @@ export interface JobResult { readonly isFailed: boolean; } -/** Background work does not change an already completed ingestion job. */ +/** Legacy public state for document-wide enhancement. */ export interface JobEnhancement { readonly status: 'pending' | 'running' | 'complete' | 'failed'; readonly canRetry: boolean; @@ -145,7 +148,18 @@ export interface JobSnapshotObjectAccessBatch extends Omit[]; } -export interface JobEnhancementRetryResult { - readonly jobId: string; - readonly enhancement: JobEnhancement; +/** Raw webhook JSON for one failed enrichment attempt after ingestion completion. */ +export interface JobEnrichmentFailedEvent { + readonly event: 'job.enrichment.failed'; + readonly event_id: string; + readonly job_id: string; + readonly document_id: string; + readonly job_result_id: string; + readonly unit_id: string; + readonly attempt: number; + readonly can_retry: boolean; + readonly error: { + readonly code: string; + readonly message?: string; + }; } diff --git a/src/types/params.ts b/src/types/params.ts index e0836c0..e9f4552 100644 --- a/src/types/params.ts +++ b/src/types/params.ts @@ -1,5 +1,7 @@ import type { ReadStream } from 'fs'; import type { KnowhereAssetStorageOptions } from './storage.js'; +import type { DocumentDirectoryReadyEvent } from './document.js'; +import type { JobEnrichmentFailedEvent } from './job.js'; /** * Parsing model options @@ -35,12 +37,25 @@ export interface ParsingParams { addFragDesc?: string; } +/** + * Webhook events accepted by the job creation API, including legacy notifications. + */ +export type WebhookEventType = + | 'job.parsed' + | 'job.completed' + | 'job.failed' + | 'job.enrichment.completed' + | DocumentDirectoryReadyEvent['event'] + | JobEnrichmentFailedEvent['event']; + /** * Webhook configuration */ export interface WebhookConfig { - /** Webhook URL to notify on job completion */ + /** Webhook URL for job notifications */ url: string; + /** Select a nonempty list to override the server's default notifications. */ + events?: readonly WebhookEventType[]; } /** @@ -106,8 +121,10 @@ export interface CreateJobParams { dataId?: string; /** Retrieval namespace for the canonical document */ namespace?: string; - /** Existing document identifier when updating a published document */ + /** Existing document identifier for Demo Catalog and legacy publishers. */ documentId?: string; + /** Existing document exempted from duplicate admission when creating its replacement. */ + replacesDocumentId?: string; /** Display metadata to copy onto the published document */ documentMetadata?: DocumentMetadata; /** Parsing configuration */ @@ -180,8 +197,10 @@ export interface ParseParams { dataId?: string; /** Retrieval namespace for the canonical document */ namespace?: string; - /** Existing document identifier when updating a published document */ + /** Existing document identifier for Demo Catalog and legacy publishers. */ documentId?: string; + /** Existing document exempted from duplicate admission when creating its replacement. */ + replacesDocumentId?: string; /** Display metadata to copy onto the published document */ documentMetadata?: DocumentMetadata; /** Additional fragment description */