Repository navigation
Expand file tree
/
Copy pathpgvector-adapter.ts
More file actions
1679 lines (1601 loc) · 77.7 KB
/
Copy pathpgvector-adapter.ts
File metadata and controls
1679 lines (1601 loc) · 77.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
import { createHash } from 'node:crypto';
import type {
AdapterContext,
AdapterEmbeddingDescriptor,
AdapterIndexStatus,
AdapterListDocumentsOptions,
AdapterListDocumentsPage,
AdapterSearchOptions,
IEmbedder,
IKnowledgeAdapter,
} from '@objectstack/spec/contracts';
import type { KnowledgeDocument, KnowledgeHit } from '@objectstack/spec/ai';
import {
DEFAULT_KNOWLEDGE_SCHEMA,
GENERATION_TABLE,
type GenerationState,
PASSAGE_TSVECTOR,
SAFE_IDENTIFIER,
TS_CONFIG,
containsOperator,
containsPattern,
isWordTerm,
keywordIndexDdl,
keywordIndexName,
keywordTerms,
metadataIndexDdl,
metadataIndexName,
metadataScopeForms,
qualified,
schemaDdl,
vectorLiteral,
vectorTable,
vectorTableDdl,
} from './sql.js';
import { searchRefusalOf } from './errors.js';
/** One answer of a query: its rows. */
export interface PgQueryResult<R = Record<string, unknown>> {
rows: R[];
}
/** What the adapter needs of a checked-out connection: a query, and its release. */
export interface PgClientLike {
query<R = Record<string, unknown>>(text: string, params?: unknown[]): Promise<PgQueryResult<R>>;
release(err?: Error | boolean): void;
}
/**
* What the adapter needs of a connection pool (`pg.Pool` has it — see
* `poolFromPg`): a one-shot query, which takes a connection and gives it back,
* and a checkout for a transaction.
*/
export interface PgPoolLike {
query<R = Record<string, unknown>>(text: string, params?: unknown[]): Promise<PgQueryResult<R>>;
connect(): Promise<PgClientLike>;
/**
* A connection of its own, outside the pool, which `release` closes. A build
* holds its source's builder lock (a session advisory lock) on one for as
* long as it runs, so a long build never takes a pooled connection from the
* writes. Absent: the lock is held on a pooled connection from `connect`.
*/
connectSession?(): Promise<PgClientLike>;
}
/** Options of {@link PgvectorKnowledgeAdapter}. */
export interface PgvectorKnowledgeAdapterOptions {
/** Adapter id, the value of `KnowledgeSource.adapter`. @default 'pgvector' */
id?: string;
/**
* The pool the store queries through. Absent: the store has no database,
* and every call answers `SERVICE_UNAVAILABLE` naming `unavailable`.
*/
pool?: PgPoolLike;
/** Why there is no pool, said by every call when `pool` is absent. */
unavailable?: string;
/**
* The embedder the store calls, or a getter read at each call (the kernel's
* `embedder` service may register after this adapter). Its `dimensions`
* choose the passage table; its `model` and `dimensions` are what the
* adapter reports to the knowledge service's index fingerprint.
*/
embedder: IEmbedder | (() => IEmbedder | undefined);
/**
* The schema the store's tables live in.
* @default 'os_knowledge'
*/
schema?: string;
/**
* Text put before every QUERY before it is embedded, for an asymmetric
* model that embeds questions and passages differently (BGE's
* `'Represent this sentence for searching relevant passages: '`). Passages
* are embedded as they are. It changes no stored vector, so it is not part
* of the index fingerprint (ADR-0161 K8, item 15).
*/
queryPrefix?: string;
/**
* How long a build may go without a call of its own (a call whose
* `ctx.reason` is `'reindex'`: the listing, a page written, a removal)
* before its builder lock is let go, so a build that stopped part-way on a
* process that keeps running does not keep every other process from
* building the source. Event-sync writes do not count as progress. A process
* that stops lets go at once. @default 900000 (15 minutes)
*/
buildLockIdleMs?: number;
/** How many passage rows of a replaced generation one DELETE removes. @default 1000 */
deleteBatchSize?: number;
/**
* The longest a search's ranking statement may run, in milliseconds:
* PostgreSQL's `statement_timeout`, set with `SET LOCAL` in the statement's
* own transaction (so it holds behind a transaction-mode pooler and never
* outlives the statement). A statement past it is stopped by the server and
* the search refused `TIMEOUT` (504). @default 10000
*/
statementTimeoutMs?: number;
/** Where the adapter reports what it cannot hand to a caller: an old generation it could not delete. */
logger?: { warn?(message: string): void };
}
/** The ADR-0112 code of a write or a search refused under another fingerprint (ADR-0161 K7, rules 4 and 5). */
export const KNOWLEDGE_REBUILD_REQUIRED = 'KNOWLEDGE_REBUILD_REQUIRED';
/** The standard ADR-0112 code of a build refused because another process is building the source. */
const LOCK_CONFLICT = 'LOCK_CONFLICT';
/** How many times {@link PgvectorKnowledgeAdapter.upsert} plans a batch again when a concurrent write removed a passage it meant to keep. */
const UPSERT_ATTEMPTS = 3;
/** How many times {@link PgvectorKnowledgeAdapter.search} runs again when the active generation was switched under it. */
const SEARCH_ATTEMPTS = 3;
/** The standard ADR-0112 code of a search whose source's index was switched under it on every attempt. */
const CONCURRENT_MODIFICATION = 'CONCURRENT_MODIFICATION';
/** The `k` of reciprocal rank fusion: a passage at rank `r` of a leg adds `1 / (k + r)` to its score. */
export const RRF_K = 60;
/**
* The retrieval modes this adapter runs, and its default (ADR-0161, the dated
* note of 2026-11-30 under K8): all three, `hybrid` when a source declares none.
* A report, not configuration; the default does not move with what the
* database offers.
*/
export const RETRIEVAL = Object.freeze({
modes: Object.freeze(['vector', 'keyword', 'hybrid'] as const),
default: 'hybrid' as const,
});
/** The default of {@link PgvectorKnowledgeAdapterOptions.statementTimeoutMs}, in milliseconds. */
export const DEFAULT_STATEMENT_TIMEOUT_MS = 10_000;
/** A generation row: one complete index of one source under one fingerprint. */
interface GenerationRow {
generation: number;
fingerprint: string | null;
recipe_hash: string | null;
dim: number;
state: GenerationState;
}
/** A source's generations: the active one, the one under construction, and those being deleted. */
interface SourceGenerations {
active?: GenerationRow;
building?: GenerationRow;
retired: GenerationRow[];
}
/** A source's builder lock this adapter holds: the session it is held on, its key, and its idle timer. */
interface BuilderLock {
client: PgClientLike;
key: string;
timer?: ReturnType<typeof setTimeout>;
}
/** What the store learned when it became ready. */
interface Readiness {
/** The schema the `vector` extension is installed in, quoted for SQL. */
extensionSchema: string;
/** The extension's version. */
version: string;
}
/**
* `PgvectorKnowledgeAdapter` — an `IKnowledgeAdapter` on PostgreSQL with the
* pgvector extension: the open vector store for self-hosted deployments
* (cloud ADR-0119 D5; ADR-0161 Execution, row 8a).
*
* ## Storage
*
* In its own schema ({@link DEFAULT_KNOWLEDGE_SCHEMA}, outside the
* connection's `search_path`, so no table can collide with an object table or
* be read as schema drift): a generation table, `knowledge_generation` (source,
* generation, fingerprint, recipe hash, vector width, model, state), and one
* passage table per vector width, `knowledge_vec_d<width>`, created the first
* time a width is written. A passage row holds its source, generation, chunk
* and document ids, record id, organization, text, title, heading path,
* document hash, chunk hash, metadata and vector. The text is stored: it is
* as sensitive as the record it came from, and it is in every backup of the database.
*
* ## Search
*
* Two legs, merged by reciprocal rank fusion (`k` = {@link RRF_K}) before the
* knowledge service re-checks each hit as the caller. Each leg ranks at most
* `topK` passages; a passage's score is the sum of `1 / (k + rank)` over the
* legs that rank it, divided by the score of a passage first in every leg
* that runs, so it lies in `(0, 1]`. Both legs run in one statement, so in one
* snapshot.
*
* The search's retrieval mode (`AdapterSearchOptions.retrieval`, {@link
* RETRIEVAL}) names the legs that run: `hybrid` (the default) both, `vector`
* the vector leg alone, `keyword` the keyword leg alone — the leg left out is
* not written into the statement. Under one leg a passage's score is
* `61 / (60 + rank)`, so the first is 1. `keyword` does not embed the query:
* the keyword leg's passages of equal score are ranked by chunk id, and a
* query with no terms answers nothing.
*
* - The vector leg: an exact scan by cosine distance — no approximate index,
* so a 3072-wide model works (pgvector's HNSW index stops at 2000
* dimensions; adding one is an operator's step, documented with the
* package). A passage whose cosine similarity is not positive is not ranked
* by it.
* - The keyword leg: the query's terms (`keywordTerms`). A word of three
* characters or more is matched as a phrase (`phraseto_tsquery`) on the
* passage's `simple` `tsvector`, which a GIN expression index serves; a
* shorter term (「出差」), or one holding a Han, kana or Hangul character —
* which the parser never splits, so a `tsvector` holds the whole run as one
* word — as a substring over the rows in scope: by `LIKE` for a term
* without a cased letter, by `ILIKE` otherwise. A passage's keyword score sums,
* over the terms it holds, the term's BM25 inverse document frequency among
* the rows in scope, so a term most passages hold weighs little.
*
* The organization filter (ADR-0161 K8, item 9), the record scope (item 17)
* and the metadata-equality `filter` are one `WHERE`, run in both legs before
* either ranks. The keyword index of a passage table made before it existed
* is made by the first call that writes or searches that table.
*
* ## Generations (ADR-0161 K7; K8, item 8)
*
* A generation row holds the fingerprint its passages were built under. A
* source holds one `active` generation, the one searched, and, while a build
* under another fingerprint runs, one `building` generation beside it — one
* of each per source, by two unique indexes. A source that holds nothing
* takes the first fingerprint it is handed as its active one, and passage
* rows of the source left without a generation row are deleted as any
* generation opens: a generation never adopts vectors of another fingerprint.
*
* - `beginBuild` takes the source's builder lock (below), then: under the
* active fingerprint it rebuilds inside the active generation; under the
* fingerprint of the generation under construction it takes that one up
* with what it already holds (a build is RESUMABLE: the walk skips every
* document whose hash the new generation already holds); under a third it
* retires the one under construction and opens a new one.
* - A write carrying `ctx.index` goes to the generation of that fingerprint:
* during a build, event-sync writes carry the new fingerprint and land in
* the new generation only. A write whose fingerprint neither holds is
* refused `KNOWLEDGE_REBUILD_REQUIRED`, and nothing is written to the
* active generation under another fingerprint.
* - A search carrying another fingerprint than the active one's is refused
* `KNOWLEDGE_REBUILD_REQUIRED` and never answered from the active
* generation; while the generation of the searched fingerprint is under
* construction, the refusal says the source is being rebuilt.
* - `completeBuild`, after the walk and its purge, makes the generation under
* construction active and the old one `retired` in one transaction, then
* deletes the retired generation's passages in batches
* ({@link PgvectorKnowledgeAdapterOptions.deleteBatchSize} rows per
* statement) and its row last. A deletion that stops part-way is finished
* by the source's next build; a retired generation is never searched.
* Under the active fingerprint it records the recipe hash.
*
* ## One builder per source
*
* `beginBuild` takes a PostgreSQL session advisory lock on the source (a key
* hashed from the schema and the source id), on a connection of its own
* ({@link PgPoolLike.connectSession}), and holds it until `completeBuild`.
* A second `beginBuild` from another process is refused `LOCK_CONFLICT`
* (409) and its walk does not run. The lock goes when the build completes,
* when the process or its connection dies (PostgreSQL frees it), or after
* {@link PgvectorKnowledgeAdapterOptions.buildLockIdleMs} without a call of
* the build (event-sync writes do not count), so a walk that failed on a
* running process does not hold it. A session advisory lock belongs to one
* server session: the store needs a direct or session-mode connection, never
* a transaction-mode pooler; a release the session no longer held is logged.
* The knowledge service runs one walk of a source at a time, so a lock this
* adapter still holds when it begins a build again is the earlier build's,
* and is kept for the new one.
*
* ## Writes
*
* The adapter takes the service's passages (`capabilities.chunks`) and hashes
* the text of each (`chunk_hash`). A passage whose hash is already stored is
* not embedded again: its row's metadata is rewritten; when that row is gone
* by the time the write runs (a concurrent write removed it), the batch is
* planned again, so the passage is embedded rather than lost. Every embed call
* runs before a connection is taken for the write, so no pooled connection
* waits on the embedder.
*
* ## When the database is not ready
*
* Without the `vector` extension (and the right to create it), or without the
* right to create the schema, the adapter creates nothing; every call answers
* `SERVICE_UNAVAILABLE`, `healthCheck` answers `ok: false` with the SQL to run
* by hand, and the next call tries again. A database it cannot reach is
* reported as unreachable, with no SQL.
*
* ## What a caller reads
*
* A refusal's message is one sentence: no driver text, no SQL, no schema
* name. Operator text travels in the error's `remedy`, which `healthCheck`,
* the plugin's boot warning and the knowledge service's reindex result and
* log show.
*/
export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
readonly id: string;
readonly capabilities = { chunks: true, retrieval: RETRIEVAL } as const;
private readonly pool?: PgPoolLike;
private readonly unavailable?: string;
private readonly resolveEmbedder: () => IEmbedder | undefined;
private readonly schema: string;
private readonly queryPrefix: string;
private readonly buildLockIdleMs: number;
private readonly deleteBatchSize: number;
private readonly statementTimeoutMs: number;
private readonly logger?: { warn?(message: string): void };
private readiness?: Readiness;
/** Widths whose passage table this adapter has created or found. */
private readonly tables = new Set<number>();
/** Widths whose passage table's keyword index this adapter has created or found. */
private readonly keyed = new Set<number>();
/** Widths whose passage table's metadata index this adapter has found or created. */
private readonly metadataIndexed = new Set<number>();
/** Widths whose passage table's metadata index this adapter could not create: searched by a scan, warned once. */
private readonly metadataUnindexed = new Set<number>();
/** The builder locks this adapter holds, by source id. */
private readonly builders = new Map<string, BuilderLock>();
/**
* The builds this adapter began and has not ended, by source id: the
* generation each one builds into. A build's writes, removals and
* completion are refused once its lock is gone (the fence).
*/
private readonly builds = new Map<string, number>();
constructor(opts: PgvectorKnowledgeAdapterOptions) {
this.id = opts.id ?? 'pgvector';
this.pool = opts.pool;
this.unavailable = opts.unavailable;
const embedder = opts.embedder;
this.resolveEmbedder = typeof embedder === 'function' ? embedder : () => embedder;
this.schema = opts.schema ?? DEFAULT_KNOWLEDGE_SCHEMA;
if (!SAFE_IDENTIFIER.test(this.schema)) {
throw new Error(
`knowledge-pgvector: schema '${this.schema}' is not a lower-case identifier (letters, digits, underscores).`,
);
}
this.queryPrefix = opts.queryPrefix ?? '';
this.buildLockIdleMs = opts.buildLockIdleMs ?? 15 * 60 * 1000;
this.deleteBatchSize = opts.deleteBatchSize ?? 1000;
if (!Number.isInteger(this.deleteBatchSize) || this.deleteBatchSize < 1) {
throw new RangeError(`knowledge-pgvector: deleteBatchSize must be a positive integer, got ${String(opts.deleteBatchSize)}`);
}
this.statementTimeoutMs = opts.statementTimeoutMs ?? DEFAULT_STATEMENT_TIMEOUT_MS;
if (!Number.isSafeInteger(this.statementTimeoutMs) || this.statementTimeoutMs < 1) {
throw new RangeError(
`knowledge-pgvector: statementTimeoutMs must be a positive integer, got ${String(opts.statementTimeoutMs)}`,
);
}
this.logger = opts.logger;
}
/** What the adapter reports about its embedder (ADR-0161 K8, item 6), read now. */
get embedding(): AdapterEmbeddingDescriptor | undefined {
const embedder = this.resolveEmbedder();
if (!embedder) return undefined;
return {
dimensions: embedder.dimensions,
...(embedder.model === undefined ? {} : { model: embedder.model }),
...(embedder.maxInputTokens === undefined ? {} : { maxInputTokens: embedder.maxInputTokens }),
};
}
async upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise<void> {
if (docs.length === 0) return;
this.requirePool();
const readiness = await this.ready();
const embedder = this.requireEmbedder();
// A build's page is embedded only while its builder lock holds.
await this.fenceBuild(ctx);
this.touchBuilderLock(ctx);
// An unchanged passage is rewritten in place, keeping its vector. When its
// row is gone by the time the write runs (a concurrent rewrite of the same
// document removed it), or its generation was switched or retired, the
// write is rolled back and planned again, so the passage is embedded and
// inserted, into the generation that holds the fingerprint now, rather
// than lost.
for (let attempt = 1; ; attempt++) {
const generation = (await this.writeTarget(ctx, embedder, true))!;
await this.ensureVectorTable(generation.dim, readiness);
const missing = await this.writePassages(docs, ctx.source.name, generation, readiness, embedder);
if (missing === undefined) return;
if (attempt >= UPSERT_ATTEMPTS) {
throw new Error(
`knowledge-pgvector: ${missing} of source '${ctx.source.name}' was removed by a concurrent write ` +
`${UPSERT_ATTEMPTS} times while this write ran; nothing of this batch was written. Retry the write.`,
);
}
}
}
/**
* One attempt of {@link upsert}: read the stored chunk hashes, embed what
* changed, write in one transaction. Answers `undefined` when written, or
* what was gone (the transaction is rolled back): an unchanged passage's
* row, or the generation itself, retired or replaced while the embedder
* answered. The generation row is share-locked for the transaction, so a
* switch or a retirement waits for the write and the batched deletion that
* follows it sees every row the write put there.
*/
private async writePassages(
docs: KnowledgeDocument[],
sourceId: string,
generation: GenerationRow,
readiness: Readiness,
embedder: IEmbedder,
): Promise<string | undefined> {
const pool = this.requirePool();
const table = qualified(this.schema, vectorTable(generation.dim));
const planned = docs.map((doc) => ({
doc,
passages: passagesOf(doc).map((p) => ({ ...p, hash: chunkHash(p.content) })),
}));
const stored = new Map<string, string>();
const existing = await pool.query<{ chunk_id: string; chunk_hash: string }>(
`SELECT chunk_id, chunk_hash FROM ${table} WHERE source_id = $1 AND generation = $2 AND document_id = ANY($3::text[])`,
[sourceId, generation.generation, docs.map((d) => d.id)],
);
for (const row of existing.rows) stored.set(row.chunk_id, row.chunk_hash);
// Embed what changed, before any connection is taken for the write.
const toEmbed = planned.flatMap((p) => p.passages).filter((p) => stored.get(p.id) !== p.hash);
const vectors = toEmbed.length === 0 ? [] : await embedder.embed(toEmbed.map((p) => p.content));
if (vectors.length !== toEmbed.length) {
throw new Error(
`knowledge-pgvector: the embedder answered ${vectors.length} vector(s) for ${toEmbed.length} passage(s); nothing was written.`,
);
}
const vectorOf = new Map<string, number[]>();
toEmbed.forEach((p, i) => {
const v = vectors[i];
if (!Array.isArray(v) || v.length !== generation.dim) {
throw new Error(
`knowledge-pgvector: the embedder answered a ${Array.isArray(v) ? v.length : 'missing'}-wide vector for ` +
`passage '${p.id}', and this source's index holds ${generation.dim}-wide vectors; nothing was written.`,
);
}
vectorOf.set(p.id, v);
});
let missing: string | undefined;
const written = await this.transaction(async (client) => {
const target = await client.query(
`SELECT 1 FROM ${qualified(this.schema, GENERATION_TABLE)}
WHERE source_id = $1 AND generation = $2 AND fingerprint IS NOT DISTINCT FROM $3 AND dim = $4
AND state IN ('active', 'building')
FOR SHARE`,
[sourceId, generation.generation, generation.fingerprint, generation.dim],
);
if (target.rows.length === 0) {
missing = `generation ${generation.generation}`;
return false;
}
for (const { doc, passages } of planned) {
await client.query(
`DELETE FROM ${table} WHERE source_id = $1 AND generation = $2 AND document_id = $3 AND NOT (chunk_id = ANY($4::text[]))`,
[sourceId, generation.generation, doc.id, passages.map((p) => p.id)],
);
for (const p of passages) {
const common = [
sourceId,
generation.generation,
p.id,
doc.id,
doc.sourceRecordId ?? null,
doc.organizationId ?? null,
p.content,
doc.title ?? null,
doc.docHash ?? null,
p.hash,
JSON.stringify(doc.metadata ?? {}),
p.headingPath === undefined ? null : JSON.stringify(p.headingPath),
];
const vector = vectorOf.get(p.id);
if (vector === undefined) {
// Unchanged text: the stored vector stands; the rest of the row is rewritten.
const updated = await client.query(
`UPDATE ${table} SET document_id = $4, source_record_id = $5, organization_id = $6, content = $7, title = $8,
doc_hash = $9, chunk_hash = $10, metadata = $11::jsonb, heading_path = $12::jsonb
WHERE source_id = $1 AND generation = $2 AND chunk_id = $3 AND chunk_hash = $10
RETURNING chunk_id`,
common,
);
if (updated.rows.length === 0) {
missing = `passage '${p.id}'`;
return false;
}
} else {
await client.query(
`INSERT INTO ${table} (source_id, generation, chunk_id, document_id, source_record_id, organization_id, content,
title, doc_hash, chunk_hash, metadata, heading_path, embedding)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::jsonb, $12::jsonb, $13::${readiness.extensionSchema}.vector)
ON CONFLICT (source_id, generation, chunk_id) DO UPDATE SET document_id = EXCLUDED.document_id,
source_record_id = EXCLUDED.source_record_id, organization_id = EXCLUDED.organization_id,
content = EXCLUDED.content, title = EXCLUDED.title, doc_hash = EXCLUDED.doc_hash,
chunk_hash = EXCLUDED.chunk_hash, metadata = EXCLUDED.metadata, heading_path = EXCLUDED.heading_path,
embedding = EXCLUDED.embedding`,
[...common, vectorLiteral(vector)],
);
}
}
}
return true;
});
return written ? undefined : missing;
}
async delete(documentIds: string[], ctx: AdapterContext): Promise<void> {
if (documentIds.length === 0) return;
const pool = this.requirePool();
await this.ready();
await this.fenceBuild(ctx);
this.touchBuilderLock(ctx);
// From every generation of the source: a removed document leaves them all.
const widths = await pool.query<{ dim: number }>(
`SELECT DISTINCT dim FROM ${qualified(this.schema, GENERATION_TABLE)} WHERE source_id = $1`,
[ctx.source.name],
);
for (const { dim } of widths.rows) {
if (!(await this.tableExists(Number(dim)))) continue;
await pool.query(
`DELETE FROM ${qualified(this.schema, vectorTable(Number(dim)))} WHERE source_id = $1 AND document_id = ANY($2::text[])`,
[ctx.source.name, documentIds],
);
}
}
async listDocuments(ctx: AdapterContext, opts: AdapterListDocumentsOptions): Promise<AdapterListDocumentsPage> {
if (!Number.isInteger(opts.limit) || opts.limit < 1) {
throw new RangeError(`listDocuments: limit must be a positive integer, got ${String(opts.limit)}`);
}
const pool = this.requirePool();
await this.ready();
// The embedder first, as on every other call: without one the service's
// fingerprint carries no model or width, and comparing it would refuse a
// healthy index as one to rebuild. No embedder is SERVICE_UNAVAILABLE.
const embedder = this.requireEmbedder();
this.touchBuilderLock(ctx);
// The generation the writes go to (ADR-0161 K8, item 1): during a build,
// the one under construction, so the walk skips what it already holds.
const generation = await this.writeTarget(ctx, embedder, false);
if (!generation || !(await this.tableExists(generation.dim))) return { documents: [] };
// In byte order ("C"), both the order and the cursor's comparison, so a
// cursor stays valid whatever the database's collation.
const params: unknown[] = [ctx.source.name, generation.generation, opts.limit + 1];
const after = opts.cursor === undefined ? '' : `AND document_id COLLATE "C" > $4`;
if (opts.cursor !== undefined) params.push(opts.cursor);
const page = await pool.query<{ document_id: string; doc_hash: string | null }>(
`SELECT document_id, max(doc_hash) AS doc_hash FROM ${qualified(this.schema, vectorTable(generation.dim))}
WHERE source_id = $1 AND generation = $2 ${after}
GROUP BY document_id ORDER BY document_id COLLATE "C" LIMIT $3`,
params,
);
const rows = page.rows.slice(0, opts.limit);
return {
documents: rows.map((r) => (r.doc_hash === null ? { documentId: r.document_id } : { documentId: r.document_id, docHash: r.doc_hash })),
...(page.rows.length > opts.limit ? { nextCursor: rows[rows.length - 1].document_id } : {}),
};
}
async search(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]> {
// An empty organization set ranks nothing (ADR-0161 K8, item 9).
if (opts.organizationIds !== undefined && opts.organizationIds.length === 0) return [];
// A record scope with no term that has ids ranks nothing (ADR-0161 K8, item 17).
if (opts.scope !== undefined && !opts.scope.some((term) => term.ids.length > 0)) return [];
try {
return await this.searchAttempts(query, opts);
} catch (err) {
// A failure of the database is a coded refusal, never an empty answer
// (see `errors.ts`): the knowledge service skips a source whose search
// throws an uncoded error, and its caller would read "nothing matches".
throw searchRefusalOf(err, opts.source.name, { statementTimeoutMs: this.statementTimeoutMs });
}
}
/**
* The question as {@link search} embeds it: the query prefix, then the
* query, through the embedder (ADR-0161, the dated note of 2026-12-01 under
* K8). Neither changes from source to source, so one vector serves every
* source of this instance.
*/
async embedQuery(query: string): Promise<number[]> {
const [embedded] = await this.requireEmbedder().embed([`${this.queryPrefix}${query}`]);
return embedded;
}
/** {@link search}'s attempts: again while a completed build switches the source's index under it. */
private async searchAttempts(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]> {
for (let attempt = 1; ; attempt++) {
const hits = await this.searchAttempt(query, opts);
if (hits !== undefined) return hits;
if (attempt >= SEARCH_ATTEMPTS) {
throw Object.assign(
new Error(
`Knowledge source '${opts.source.name}' switched to a newly built index ${SEARCH_ATTEMPTS} times during one search; retry it.`,
),
{ code: CONCURRENT_MODIFICATION, status: 409 },
);
}
}
}
/**
* One attempt of {@link search}. Answers `undefined` when the generation it
* ranked was switched out by a completed build between the read of the
* generations and the ranking (the ranking statement holds only while its
* generation is the active one, so it never reads a generation whose
* passages are being deleted).
*/
private async searchAttempt(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[] | undefined> {
this.requirePool();
const readiness = await this.ready();
// The embedder first: without one the service's fingerprint carries no
// model or width, and comparing it would refuse a healthy index as one to
// rebuild. No embedder is SERVICE_UNAVAILABLE, as on every other call.
const embedder = this.requireEmbedder();
const { active: generation, building } = await this.generations(opts.source.name);
if (!generation) return [];
// Vectors of two fingerprints are never ranked against each other (K7,
// rule 5); while the searched fingerprint's generation is being built, the
// refusal says so.
const searched = opts.index?.fingerprint;
if (searched !== undefined && generation.fingerprint !== searched) {
throw rebuildRequired(opts.source.name, building !== undefined && building.fingerprint === searched);
}
if (embedder.dimensions !== generation.dim) {
throw rebuildRequired(opts.source.name, building !== undefined && building.dim === embedder.dimensions);
}
if (!(await this.tableExists(generation.dim))) return [];
const topK = Math.max(0, Math.floor(opts.topK));
if (topK === 0) return [];
// The legs the search's mode runs (ADR-0161, the dated note of 2026-11-30
// under K8); the service hands only a mode this adapter lists, and any
// other is refused, never run on a scale it was not built for.
const mode = opts.retrieval?.mode ?? RETRIEVAL.default;
if (!(RETRIEVAL.modes as readonly string[]).includes(mode)) {
throw Object.assign(
new Error(
`knowledge-pgvector does not run the retrieval mode '${String(mode)}': it runs ` +
`${RETRIEVAL.modes.map((m) => `'${m}'`).join(', ')}.`,
),
{ code: 'VALIDATION_ERROR', status: 400 },
);
}
// The query is embedded before a connection is taken, after every refusal
// above — never under `keyword`, which makes no query vector. A search the
// knowledge service hands `queryVector` asks it here instead, so a refusal
// above costs no embedding call (ADR-0161, the dated note of 2026-12-01
// under K8); its answer serves the search's other calls and is never changed.
let vector: readonly number[] = [];
if (mode !== 'keyword') {
const embedded = opts.queryVector === undefined ? await this.embedQuery(query) : await opts.queryVector();
if (!Array.isArray(embedded) || embedded.length !== generation.dim) {
throw new Error(
`knowledge-pgvector: the embedder answered a ${Array.isArray(embedded) ? embedded.length : 'missing'}-wide query ` +
`vector, and this source's index holds ${generation.dim}-wide vectors.`,
);
}
vector = embedded;
}
const vectorLeg = mode !== 'keyword' && !vector.every((x) => x === 0);
const terms = mode === 'vector' ? [] : keywordTerms(query);
if (!vectorLeg && terms.length === 0) return [];
if (terms.length > 0) await this.ensureKeywordIndex(generation.dim);
const ext = readiness.extensionSchema;
const table = qualified(this.schema, vectorTable(generation.dim));
// One WHERE for both legs: the source's active generation, the
// organization filter, the record scope and the metadata filter, each
// bound as values.
const params: unknown[] = [opts.source.name, generation.generation];
const where = [
'source_id = $1',
'generation = $2',
// Holds only while the generation is the active one: a completed build
// retires it and then deletes its passages, after this statement's
// snapshot or before it, never inside it.
`EXISTS (SELECT 1 FROM ${qualified(this.schema, GENERATION_TABLE)} g
WHERE g.source_id = $1 AND g.generation = $2 AND g.state = 'active')`,
];
if (opts.organizationIds !== undefined) {
params.push(opts.organizationIds);
where.push(`organization_id = ANY($${params.length}::text[])`);
}
if (opts.scope !== undefined) {
// The record scope (ADR-0161 K8, item 17), a union of terms, beside the
// organization filter so `topK` is filled from in-scope documents. Ids
// and field names go as bound parameters. A `metadata` term holds for a
// stored string or number equal to an id as text, or a list with such an
// element; a missing value or any other kind holds for nothing. It is
// written twice: as containment, a superset the metadata index serves
// (`metadataScopeForms`), so only the passages in scope are read and
// ranked, and as that exact match on each passage the index finds.
const scopeTerms: string[] = [];
for (const term of opts.scope) {
if (term.ids.length === 0) continue;
params.push(term.ids);
const ids = `$${params.length}::text[]`;
if (term.kind === 'record') {
scopeTerms.push(`source_record_id = ANY(${ids})`);
continue;
}
await this.ensureMetadataIndex(generation.dim);
params.push(term.field);
const value = `(metadata -> $${params.length}::text)`;
params.push(metadataScopeForms(term.field, term.ids));
scopeTerms.push(
`(metadata @> ANY($${params.length}::jsonb[]) AND ` +
`EXISTS (SELECT 1 FROM jsonb_array_elements(CASE jsonb_typeof(${value}) WHEN 'array' THEN ${value} ` +
`ELSE jsonb_build_array(${value}) END) AS e(v) ` +
`WHERE jsonb_typeof(e.v) IN ('string', 'number') AND e.v #>> '{}' = ANY(${ids})))`,
);
}
where.push(`(${scopeTerms.join(' OR ')})`);
}
for (const [key, value] of Object.entries(opts.filter ?? {})) {
params.push(key, JSON.stringify(value === undefined ? null : value));
where.push(`(metadata -> $${params.length - 1}) = $${params.length}::jsonb`);
}
const inScope = where.join(' AND ');
params.push(topK);
const limit = `$${params.length}`;
const ctes: string[] = [];
const legs: string[] = [];
let vectorParam = 0;
if (vectorLeg) {
params.push(vectorLiteral(vector));
vectorParam = params.length;
ctes.push(`vec AS (
SELECT chunk_id, row_number() OVER (ORDER BY distance, chunk_id) AS pos FROM (
SELECT chunk_id, embedding OPERATOR(${ext}.<=>) $${params.length}::${ext}.vector AS distance
FROM ${table} WHERE ${inScope}
) ranked WHERE distance < 1 ORDER BY distance, chunk_id LIMIT ${limit})`);
legs.push('SELECT chunk_id, pos AS vpos, NULL::bigint AS kpos FROM vec');
}
if (terms.length > 0) {
// A term's match, written twice: on the row's columns where the index
// can serve it, and on the candidate's tsvector, computed once per row.
const onRow: string[] = [];
const onCandidate: string[] = [];
for (const term of terms) {
if (isWordTerm(term)) {
params.push(term);
const query = `phraseto_tsquery(${TS_CONFIG}, $${params.length}::text)`;
onRow.push(`${PASSAGE_TSVECTOR} @@ ${query}`);
onCandidate.push(`v.tsv @@ ${query}`);
} else {
params.push(containsPattern(term));
const op = containsOperator(term);
onRow.push(`content ${op} $${params.length}::text`);
onCandidate.push(`c.content ${op} $${params.length}::text`);
}
}
// Each term's IDF is computed once per search, in `idf`, and a candidate's
// score multiplies its hits by those weights: written per row, the 16
// `ln()` terms of a CJK question ran on every candidate. The arithmetic
// stays `numeric`, so every score, and so every tie, is the per-row one.
const score = onCandidate.map((_, i) => `h.h${i} * w.w${i}`).join(' + ');
ctes.push(
// Passages of equal keyword score are ranked by cosine distance, so the
// keyword leg never reorders by chunk id what the vector leg ranks.
`cand AS (SELECT chunk_id, content, ${vectorLeg ? `embedding OPERATOR(${ext}.<=>) $${vectorParam}::${ext}.vector` : '0'} AS distance
FROM ${table} WHERE ${inScope} AND (${onRow.join(' OR ')}))`,
`hits AS (SELECT c.chunk_id, c.distance, ${onCandidate.map((m, i) => `(${m})::int AS h${i}`).join(', ')}
FROM cand c CROSS JOIN LATERAL (SELECT ${PASSAGE_TSVECTOR.replace('content', 'c.content')} AS tsv) v)`,
`stats AS (SELECT (SELECT count(*) FROM ${table} WHERE ${inScope}) AS n,
${onCandidate.map((_, i) => `coalesce(sum(h${i}), 0) AS d${i}`).join(', ')} FROM hits)`,
`idf AS MATERIALIZED (SELECT ${onCandidate
.map((_, i) => `ln(1.0 + (n - d${i} + 0.5) / (d${i} + 0.5)) AS w${i}`)
.join(', ')} FROM stats)`,
`kw AS (
SELECT chunk_id, row_number() OVER (ORDER BY score DESC, distance, chunk_id) AS pos FROM (
SELECT h.chunk_id, h.distance, ${score} AS score FROM hits h CROSS JOIN idf w
) scored ORDER BY score DESC, distance, chunk_id LIMIT ${limit})`,
);
legs.push('SELECT chunk_id, NULL::bigint AS vpos, pos AS kpos FROM kw');
}
const result = await this.searchStatement<{
chunk_id: string;
document_id: string;
source_record_id: string | null;
content: string;
title: string | null;
metadata: Record<string, unknown> | null;
doc_hash: string | null;
heading_path: string[] | null;
vpos: string | number | null;
kpos: string | number | null;
}>(
`WITH ${ctes.join(',\n')}
SELECT p.chunk_id, p.document_id, p.source_record_id, p.content, p.title, p.metadata, p.doc_hash,
p.heading_path, u.vpos, u.kpos
FROM (SELECT chunk_id, min(vpos) AS vpos, min(kpos) AS kpos FROM (${legs.join(' UNION ALL ')}) l
GROUP BY chunk_id) u
JOIN ${table} p ON p.source_id = $1 AND p.generation = $2 AND p.chunk_id = u.chunk_id`,
params,
);
if (result.rows.length === 0) {
// No hit, or a generation switched out meanwhile: read which.
const now = await this.generations(opts.source.name);
if (now.active?.generation !== generation.generation) return undefined;
}
return fuse(result.rows, topK, mode === 'hybrid' ? 2 : 1).map(({ row: r, score }) => ({
chunkId: r.chunk_id,
documentId: r.document_id,
sourceId: opts.source.name,
...(r.source_record_id === null ? {} : { sourceRecordId: r.source_record_id }),
score,
snippet: r.content,
...(r.title === null ? {} : { title: r.title }),
metadata: r.metadata ?? {},
// The stored hash, as given (ADR-0161 K8, item 3): the service's
// record-level freshness check compares it with the record as it reads now.
...(r.doc_hash === null ? {} : { docHash: r.doc_hash }),
// The passage's heading path, when the splitter gave it one (item 14).
...(Array.isArray(r.heading_path) ? { headingPath: r.heading_path } : {}),
}));
}
async indexStatus(ctx: AdapterContext): Promise<AdapterIndexStatus> {
this.requirePool();
await this.ready();
const { active, building } = await this.generations(ctx.source.name);
const status: AdapterIndexStatus = {};
if (active?.fingerprint != null) status.fingerprint = active.fingerprint;
if (active?.recipe_hash != null) status.recipeHash = active.recipe_hash;
if (building !== undefined) status.building = true;
return status;
}
/**
* The start of a complete build (ADR-0161 K7, rule 3). Takes the source's
* builder lock — refused `LOCK_CONFLICT` while another process holds it —
* then rebuilds inside the active generation, takes up the generation under
* construction for this fingerprint (resumed: what it holds is kept), or
* opens one beside the active generation. A generation under construction
* for another fingerprint is abandoned: retired, and deleted in batches —
* also when the fingerprint went back to the active one's, so a reverted
* change leaves no generation behind. So is any generation a switch left
* retired. The generation taken is the one this build writes into and
* completes.
*/
async beginBuild(ctx: AdapterContext): Promise<void> {
const index = requireIndex(ctx, 'beginBuild');
this.requirePool();
const readiness = await this.ready();
const embedder = this.requireEmbedder();
const sourceId = ctx.source.name;
await this.takeBuilderLock(sourceId);
try {
const target = await this.inTransaction(async (client) => {
const { active, building } = await this.generations(sourceId, client, true);
const fits = (g: GenerationRow | undefined): boolean =>
g !== undefined && g.fingerprint === index.fingerprint && g.dim === embedder.dimensions;
if (building !== undefined && fits(building)) return building;
// A build of another fingerprint left unfinished: abandoned, one per source.
if (building !== undefined) await this.retire(client, sourceId, building.generation);
if (active !== undefined && fits(active)) return active;
// A source that holds nothing takes the fingerprint as its active one;
// beside an active generation, the new one is built aside.
return this.openGeneration(client, sourceId, index.fingerprint, embedder, active === undefined ? 'active' : 'building');
});
await this.ensureVectorTable(target.dim, readiness);
await this.sweepRetired(sourceId);
this.builds.set(sourceId, target.generation);
} catch (err) {
this.builds.delete(sourceId);
await this.releaseBuilderLock(sourceId);
throw err;
}
}
/**
* The end of a complete build (ADR-0161 K8, item 8 c), called after the walk
* and its purge. The generation built under `ctx.index.fingerprint` becomes
* the active one and records the recipe hash; the generation it replaces is
* retired in the same transaction, then its passages are deleted in batches
* and its row last. Under the active fingerprint, the recipe hash is
* recorded. The builder lock is let go either way.
*
* Only the build this adapter began completes, and only the generation it
* began: a build whose builder lock is gone (let go after its idle time, or
* its session ended), whose generation was dropped (`dropSource`, in any
* process), or whose generation is no longer the one under this
* fingerprint, is refused `LOCK_CONFLICT` (409) and switches, records and
* deletes nothing — another process may have taken the source up since.
*/
async completeBuild(ctx: AdapterContext): Promise<void> {
const index = requireIndex(ctx, 'completeBuild');
this.requirePool();
await this.ready();
const sourceId = ctx.source.name;
try {
const mine = this.builds.get(sourceId);
if (mine === undefined || !(await this.holdsBuilderLock(sourceId))) throw builderLost(sourceId);
await this.inTransaction(async (client) => {
const { active, building } = await this.generations(sourceId, client, true);
const t = qualified(this.schema, GENERATION_TABLE);
// The generation this build began is gone (the source was dropped) or
// is no longer the one under this fingerprint (another build replaced it).
if (active?.generation !== mine && building?.generation !== mine) throw buildEnded(sourceId);
const target =
building !== undefined && building.fingerprint === index.fingerprint
? building
: active !== undefined && active.fingerprint === index.fingerprint ? active : undefined;
if (target !== undefined && target.generation !== mine) throw buildEnded(sourceId);
if (building !== undefined && building.fingerprint === index.fingerprint) {
// The switch: one statement retires the old generation, the next
// makes the new one active (one active row per source at a time).
if (active) await this.retire(client, sourceId, active.generation);
await client.query(`UPDATE ${t} SET state = 'active', recipe_hash = $3 WHERE source_id = $1 AND generation = $2`, [
sourceId,
building.generation,
index.recipeHash,
]);
return;
}
if (active !== undefined && active.fingerprint === index.fingerprint) {
await client.query(`UPDATE ${t} SET recipe_hash = $3 WHERE source_id = $1 AND generation = $2`, [
sourceId,
active.generation,
index.recipeHash,
]);
return;
}
throw new Error(
`completeBuild: source '${sourceId}' holds no generation under this fingerprint; call beginBuild first.`,
);
});
try {
await this.sweepRetired(sourceId);
} catch (err) {
// The switch is recorded and the old generation is never searched
// again; only its rows are left. Not the caller's failure.
this.logger?.warn?.(
`knowledge-pgvector: the replaced index of source '${sourceId}' was not fully deleted (${errorText(err)}); ` +
'it is never searched, and the source\'s next build deletes the rest.',
);
}
} finally {
this.builds.delete(sourceId);
await this.releaseBuilderLock(sourceId);
}
}
/**
* Everything held for the source is removed (ADR-0161 K8, item 4). Every
* generation — the active one, and one under construction — is retired in
* one transaction, so from its commit no search and no write finds one;
* then the passages are deleted in batches and each generation row last, as
* a replaced generation's are. A builder lock this adapter holds for the
* source is let go. A source it holds nothing for is no error. A drop that
* stops after the commit leaves retired generations: never searched, and
* deleted by the next drop or the next build of that key.
*
* A build of the source running in another process, holding its builder
* lock, does not hold the drop back: its generation is retired with the
* rest, and its next write, listing or completion is refused
* `LOCK_CONFLICT` and ends it (see `writeTarget`), so it never brings the
* source back. The drop first locks the source's generation rows, waiting
* for a transaction that holds them (a build opening or switching a
* generation); the retirement is then one statement of its own, so it also
* retires a generation that transaction opened, which the locking read
* could not see.
*/
async dropSource(ctx: AdapterContext): Promise<void> {
this.requirePool();
await this.ready();
const sourceId = ctx.source.name;
try {
await this.inTransaction(async (client) => {
await this.generations(sourceId, client, true);
await client.query(
`UPDATE ${qualified(this.schema, GENERATION_TABLE)} SET state = 'retired' WHERE source_id = $1 AND state <> 'retired'`,
[sourceId],
);
});
await this.sweepRetired(sourceId);
} finally {
await this.releaseBuilderLock(sourceId);