@eltjs/vectorizer 0.13.7 → 0.13.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
  npm install @eltjs/vectorizer @eltjs/elt @eltjs/elt-sqlite @zukhruf/retrieval
7
7
  ```
8
8
 
9
- `@eltjs/vectorizer/sqlite` writes the contract into a SQLite file. Postgres and SQL Server come later, each in its own subpath.
9
+ `@eltjs/vectorizer/sqlite` writes the contract into a SQLite file, `@eltjs/vectorizer/postgresql` into a Postgres database ([Search in Postgres](#search-in-postgres)), and `@eltjs/vectorizer/sqlserver` into a SQL Server database ([Search in SQL Server](#search-in-sql-server)).
10
10
 
11
11
  ## Search the rows of a table
12
12
 
@@ -392,6 +392,358 @@ The output:
392
392
  monday.txt:0 "Call the cooperative about the cold store." 0 42
393
393
  ```
394
394
 
395
+ ## Search in Postgres
396
+
397
+ `@eltjs/vectorizer/postgresql` writes the same contract into the database of a `PostgresDestination` of [elt-postgresql](../destinations/postgresql/README.md), and the Postgres retrievers of `@zukhruf/retrieval` read it. The server needs pgvector, for example the image `pgvector/pgvector:pg18`. The destination creates the extension `vector` when the database has none.
398
+
399
+ ```sh
400
+ npm install @eltjs/vectorizer @eltjs/elt @eltjs/elt-postgresql @zukhruf/retrieval postgres
401
+ ```
402
+
403
+ The program loads the tasks of "Search the rows of a table" into Postgres, and searches them as that program does. `DATABASE_URL` names the database. It gives the passages and scores of the SQLite program. postgres.js reads a `bigint` as text, so the counts of `docs_status` are text.
404
+
405
+ ```ts
406
+ import type {
407
+ EmbeddingModelV4,
408
+ EmbeddingModelV4CallOptions,
409
+ EmbeddingModelV4Result,
410
+ } from '@ai-sdk/provider';
411
+ import { ContextWindow, FusionRetriever } from '@zukhruf/retrieval';
412
+ import {
413
+ PgvectorEmbeddingRetriever,
414
+ PgvectorKeywordRetriever,
415
+ PostgresPassageStore,
416
+ type PostgresSession,
417
+ } from '@zukhruf/retrieval/postgres';
418
+ import { countTokens } from 'gpt-tokenizer/encoding/cl100k_base';
419
+ import postgres from 'postgres';
420
+
421
+ import { Connection, Copy, IterableSource, Pipeline } from '@eltjs/elt';
422
+ import {
423
+ PostgresDestination,
424
+ PostgresSyncHistory,
425
+ } from '@eltjs/elt-postgresql';
426
+ import { Vectorizer } from '@eltjs/vectorizer/postgresql';
427
+
428
+ // A local embedding model with no network, as in the first example.
429
+ class LetterModel implements EmbeddingModelV4 {
430
+ readonly specificationVersion = 'v4';
431
+ readonly provider = 'readme';
432
+ readonly modelId = 'letters';
433
+ readonly maxEmbeddingsPerCall = undefined;
434
+ readonly supportsParallelCalls = true;
435
+
436
+ async doEmbed({
437
+ values,
438
+ }: EmbeddingModelV4CallOptions): Promise<EmbeddingModelV4Result> {
439
+ return {
440
+ embeddings: values.map((text) =>
441
+ Array.from(
442
+ { length: 26 },
443
+ (_, letter) =>
444
+ [...text.toLowerCase()].filter(
445
+ (character) => character.charCodeAt(0) - 97 === letter,
446
+ ).length,
447
+ ),
448
+ ),
449
+ warnings: [],
450
+ };
451
+ }
452
+ }
453
+
454
+ const tasks = [
455
+ {
456
+ name: 'fix-git',
457
+ title: 'Fix a broken git history',
458
+ body: 'A rebase went wrong and two commits are lost. Find them in the reflog and put them back on main.',
459
+ category: 'software-engineering',
460
+ },
461
+ {
462
+ name: 'train-fasttext',
463
+ title: 'Train a fastText model',
464
+ body: 'Train a text classifier on the reviews in the data folder, and save a model of less than 150 MB.',
465
+ category: 'model-training',
466
+ },
467
+ {
468
+ name: 'git-multibranch',
469
+ title: 'Deploy two git branches',
470
+ body: 'Set up a git server where a push to main or dev deploys that branch to its own web folder.',
471
+ category: 'system-administration',
472
+ },
473
+ ];
474
+
475
+ // A database whose server has pgvector, such as the image
476
+ // pgvector/pgvector:pg18.
477
+ const url = process.env['DATABASE_URL'] ?? 'postgres://localhost/tasks';
478
+ const model = new LetterModel();
479
+ const source = new IterableSource({
480
+ identity: 'terminal-bench',
481
+ streams: {
482
+ tasks: {
483
+ description: 'The tasks of Terminal-Bench 2.',
484
+ jsonSchema: {
485
+ type: 'object',
486
+ description: 'A task.',
487
+ properties: {
488
+ name: { type: 'string', description: 'The name of the task.' },
489
+ title: { type: 'string', description: 'Its title.' },
490
+ body: { type: 'string', description: 'What it asks.' },
491
+ category: { type: 'string', description: 'Its category.' },
492
+ },
493
+ required: ['name', 'title', 'body', 'category'],
494
+ },
495
+ primaryKey: ['name'],
496
+ snapshot: () => tasks,
497
+ },
498
+ },
499
+ });
500
+ const destination = new PostgresDestination({ url });
501
+ const table = destination.table('tasks');
502
+ const vectorizer = new Vectorizer({
503
+ into: destination,
504
+ from: table,
505
+ name: 'docs',
506
+ description: 'The tasks of Terminal-Bench 2.',
507
+ key: 'name',
508
+ loading: { columns: ['title', 'body'] },
509
+ chunking: {
510
+ tokenizer: { name: 'cl100k_base', count: countTokens },
511
+ maxTokens: 16,
512
+ overlapTokens: 0,
513
+ },
514
+ embedding: { model, dimensions: 26, clock: globalThis },
515
+ metadata: ['category'],
516
+ });
517
+
518
+ await new Pipeline({
519
+ clock: globalThis,
520
+ history: new PostgresSyncHistory({ url }),
521
+ connections: [
522
+ new Connection({
523
+ name: 'terminal-bench',
524
+ source,
525
+ destination,
526
+ steps: [
527
+ new Copy(source.streams.tasks, table, {
528
+ syncMode: 'full_refresh',
529
+ destinationSyncMode: 'overwrite_dedup',
530
+ }),
531
+ ],
532
+ }),
533
+ ],
534
+ derived: [vectorizer],
535
+ }).run();
536
+
537
+ // The retrievers send their SQL through a session that the host writes over
538
+ // its own driver, here postgres.js.
539
+ const sql = postgres(url, { max: 1 });
540
+ try {
541
+ const session: PostgresSession = {
542
+ query: async (text, parameters) => [
543
+ ...(await sql.unsafe(
544
+ text,
545
+ parameters.map((value) =>
546
+ typeof value === 'number' ? value : String(value),
547
+ ),
548
+ )),
549
+ ],
550
+ };
551
+ const store = new PostgresPassageStore({
552
+ session,
553
+ schema: vectorizer.contract.schema,
554
+ passages: vectorizer.contract.passages,
555
+ });
556
+ const meaning = new PgvectorEmbeddingRetriever({
557
+ store,
558
+ vectors: vectorizer.contract.vectors,
559
+ model,
560
+ });
561
+ const words = new PgvectorKeywordRetriever({
562
+ store,
563
+ index: vectorizer.contract.index,
564
+ });
565
+ const search = new FusionRetriever({ retrievers: [meaning, words] });
566
+
567
+ const found = await search.retrieve('deploy git branches', { topK: 3 });
568
+ for (const { passage, score } of found)
569
+ console.log(passage.id, passage.metadata['category'], score.toFixed(4));
570
+
571
+ const [widened] = await new ContextWindow({
572
+ store,
573
+ windowSize: 5,
574
+ }).postprocess(found, 'deploy git branches');
575
+ console.log(JSON.stringify(widened?.passage.text));
576
+
577
+ console.log({ ...(await sql`SELECT * FROM marts.docs_status`)[0] });
578
+ } finally {
579
+ await sql.end();
580
+ }
581
+ ```
582
+
583
+ The output:
584
+
585
+ ```text
586
+ git-multibranch:0 system-administration 0.0328
587
+ git-multibranch:1 system-administration 0.0161
588
+ fix-git:2 software-engineering 0.0159
589
+ "Deploy two git branches\nSet up a git server where a push to main or dev deploys that branch to its own web folder."
590
+ {
591
+ state: 'current',
592
+ as_of: 2026-11-24T18:47:45.867Z,
593
+ pending_sources: '0',
594
+ pending_vectors: '0'
595
+ }
596
+ ```
597
+
598
+ - `vectorizer.contract` is `{ schema: 'marts', passages, vectors, index: { column, configuration } }`, the options of `PostgresPassageStore`, `PgvectorEmbeddingRetriever` and `PgvectorKeywordRetriever`. The retrievers send their SQL through a `PostgresSession`, which the host writes over its own driver.
599
+ - Every relation of the contract is a view in `marts`, so a reader with `SELECT` on the views of `marts` searches. The views read the raw tables in `_warehouse` with the rights of their owner, and the reader may not read `_warehouse` itself.
600
+ - The keyword index is the table `_warehouse.raw_docs_keywords`: `id text COLLATE "C"` (its primary key), `source`, `seq`, `text`, and `keywords`, a `tsvector` that Postgres generates from the text with the text search configuration `keywords.configuration`, `'english'` when absent. A GIN index indexes `keywords`. The passages view gives `keywords`, and the retrievers leave it out of the metadata. A change of the configuration makes the table again at the next refresh. See [ADR 0002](./docs/adr/0002-the-keyword-index-is-a-member-that-keeps-a-keywords-table-and-its-full-text-index-in-step.md).
601
+ - `indexing: { vectors }` declares the index of the vectors: `hnsw({ m?, efConstruction? })` of elt-postgresql, an HNSW index with `vector_cosine_ops`, when absent, or `'none'`, which compares every vector.
602
+ - While another model embeds the vectors again in place, a search with the model of the few vectors not made again yet still gives its `topK`: the retriever sets `hnsw.iterative_scan`, so the scan of the HNSW index goes on until enough vectors of its model pass.
603
+ - The views find each row by an index: HNSW for the vectors, GIN for the keywords, the index on `part_hash` of the parts, and the key of the source row in the type of its key column. See [ADR 0001](./docs/adr/0001-the-vectorizer-writes-the-passage-contract-of-zukhruf-retrieval-one-subpath-per-engine.md).
604
+ - postgres.js reads a `bigint` as text, so the source of a key of the columns `site` and an integer `id` is `["s1","7"]`.
605
+
606
+ ## Search in SQL Server
607
+
608
+ `@eltjs/vectorizer/sqlserver` writes the same contract into the database of an `SqlServerDestination` of [elt-sqlserver](../destinations/sqlserver/README.md), and the SQL Server retrievers of `@zukhruf/retrieval` read it.
609
+
610
+ ```sh
611
+ npm install @eltjs/vectorizer @eltjs/elt @eltjs/elt-sqlserver @zukhruf/retrieval mssql
612
+ ```
613
+
614
+ ```ts
615
+ import { FusionRetriever } from '@zukhruf/retrieval';
616
+ import {
617
+ SqlServerEmbeddingRetriever,
618
+ SqlServerKeywordRetriever,
619
+ SqlServerPassageStore,
620
+ } from '@zukhruf/retrieval/sqlserver';
621
+ import { countTokens } from 'gpt-tokenizer/encoding/cl100k_base';
622
+ import mssql from 'mssql';
623
+
624
+ import { Connection, Copy, IterableSource, Pipeline } from '@eltjs/elt';
625
+ import {
626
+ SqlServerCheckpointStore,
627
+ SqlServerDestination,
628
+ SqlServerSyncHistory,
629
+ } from '@eltjs/elt-sqlserver';
630
+ import { Vectorizer } from '@eltjs/vectorizer/sqlserver';
631
+
632
+ // The LetterModel class and the tasks array of "Search the rows of a table".
633
+ const model = new LetterModel();
634
+ const login = {
635
+ server: 'localhost',
636
+ port: 1433,
637
+ database: 'tasks',
638
+ user: 'elt_writer',
639
+ password: '…',
640
+ trustServerCertificate: true,
641
+ };
642
+ const source = new IterableSource({
643
+ identity: 'terminal-bench',
644
+ streams: {
645
+ tasks: {
646
+ description: 'The tasks of Terminal-Bench 2.',
647
+ jsonSchema: {
648
+ type: 'object',
649
+ description: 'A task.',
650
+ properties: {
651
+ name: { type: 'string', description: 'The name of the task.' },
652
+ title: { type: 'string', description: 'Its title.' },
653
+ body: { type: 'string', description: 'What it asks.' },
654
+ category: { type: 'string', description: 'Its category.' },
655
+ },
656
+ required: ['name', 'title', 'body', 'category'],
657
+ },
658
+ primaryKey: ['name'],
659
+ snapshot: () => tasks,
660
+ },
661
+ },
662
+ });
663
+ const destination = new SqlServerDestination({ login });
664
+ const table = destination.table('tasks');
665
+ const vectorizer = new Vectorizer({
666
+ into: destination,
667
+ from: table,
668
+ name: 'docs',
669
+ description: 'The tasks of Terminal-Bench 2.',
670
+ key: 'name',
671
+ loading: { columns: ['title', 'body'] },
672
+ chunking: {
673
+ tokenizer: { name: 'cl100k_base', count: countTokens },
674
+ maxTokens: 16,
675
+ overlapTokens: 0,
676
+ },
677
+ embedding: { model, dimensions: 26, clock: globalThis },
678
+ metadata: ['category'],
679
+ keywords: { language: 1033 },
680
+ indexing: { vectors: 'none' },
681
+ });
682
+
683
+ await new Pipeline({
684
+ clock: globalThis,
685
+ history: new SqlServerSyncHistory({ login }),
686
+ connections: [
687
+ new Connection({
688
+ name: 'terminal-bench',
689
+ source,
690
+ destination,
691
+ checkpoints: new SqlServerCheckpointStore({ login }),
692
+ steps: [
693
+ new Copy(source.streams.tasks, table, {
694
+ syncMode: 'full_refresh',
695
+ destinationSyncMode: 'overwrite_dedup',
696
+ }),
697
+ ],
698
+ }),
699
+ ],
700
+ derived: [vectorizer],
701
+ }).run();
702
+
703
+ // A reader needs only SELECT on the schema marts.
704
+ const pool = await new mssql.ConnectionPool({
705
+ ...login,
706
+ user: 'reader',
707
+ }).connect();
708
+ const session = {
709
+ query: async (sql: string, parameters: Readonly<Record<string, unknown>>) => {
710
+ const request = pool.request();
711
+ for (const [name, value] of Object.entries(parameters))
712
+ request.input(name, value);
713
+ return (await request.query(sql)).recordset ?? [];
714
+ },
715
+ };
716
+ const store = new SqlServerPassageStore({
717
+ session,
718
+ schema: vectorizer.contract.schema,
719
+ passages: vectorizer.contract.passages,
720
+ });
721
+ const search = new FusionRetriever({
722
+ retrievers: [
723
+ new SqlServerEmbeddingRetriever({
724
+ store,
725
+ vectors: vectorizer.contract.vectors,
726
+ model,
727
+ }),
728
+ new SqlServerKeywordRetriever({ store, index: vectorizer.contract.index }),
729
+ ],
730
+ });
731
+ for (const { passage, score } of await search.retrieve('deploy git branches'))
732
+ console.log(passage.id, passage.metadata.category, score.toFixed(4));
733
+ await pool.close();
734
+ ```
735
+
736
+ This program did not run when this section was written, so no output is pasted here. SQL Server 2025 runs only where Docker runs amd64 natively, and on the Mac of the build Docker emulates amd64, which Microsoft does not support (the tests skip there, #5469). `src/sqlserver.test.ts` makes the same calls with SQL Server 2025 and Full-Text Search, and CI runs it on amd64. This follows elt-sqlserver, whose recipe of a vector index ran on Azure SQL Database because the container could not run it.
737
+
738
+ - `vectorizer.contract` is `{ schema: 'marts', passages, vectors, index: { table } }`, the options of `SqlServerPassageStore`, `SqlServerEmbeddingRetriever` and `SqlServerKeywordRetriever`.
739
+ - Every relation of the contract is in `marts`, so a reader with `GRANT SELECT ON SCHEMA::marts` searches. The views read the raw tables in `_warehouse` through the ownership chain, and the reader may not read `_warehouse` itself.
740
+ - The keyword index is the base table `marts.docs_keywords`: `id NVARCHAR(450) COLLATE Latin1_General_100_BIN2` (its primary key, the full-text key), `source`, `seq` and `text NVARCHAR(MAX)`. A full-text index on `text` has `STOPLIST = OFF`, `CHANGE_TRACKING AUTO` and the language of `keywords.language`, an LCID: 1033 (English) when absent. `CONTAINSTABLE` reads this table, not a view. See [ADR 0002](./docs/adr/0002-the-keyword-index-is-a-member-that-keeps-a-keywords-table-and-its-full-text-index-in-step.md).
741
+ - A run ends only when the full-text index holds its passages: the keyword index is `current` only when SQL Server shows no population that runs and no change that waits. So a search after `run()` finds each passage.
742
+ - Ids and sources compare in binary, so the sources `a` and `A` are two source rows and give the passages `a:0` and `A:0`, also in a database whose collation ignores case.
743
+ - `indexing: { vectors: 'none' }` is the only declaration of the vectors index. A search compares every vector with `VECTOR_DISTANCE`. The DiskANN index of SQL Server 2025 waits for zukhruf #5475.
744
+ - A server with no Full-Text Search fails the keyword index with a `SqlServerSetupError`, of failure type `config`, before it makes the table. On Linux, install the package `mssql-server-fts`. Azure SQL Database has Full-Text Search.
745
+ - A passage id has at most 450 characters, the most that a full-text key of SQL Server holds. A source row whose passage ids would be longer is a rule failure of its own: its row of `docs_chunks` is `failed`, with an error that names the length and the limit, and `derived_status` counts it in `failed`. The other rows go on. Give the vectorizer a shorter source key.
746
+
395
747
  ## The relations
396
748
 
397
749
  A vectorizer named `docs` refreshes these members, in this order, in the file of its source. Each is a derived dataset of elt-sqlite with its own row of `derived_status`.
@@ -428,7 +780,7 @@ When the model or its `dimensions` change, the next refresh makes each vector ag
428
780
 
429
781
  ## Rules and failures
430
782
 
431
- - The constructor refuses, with a `TypeError` that names it, a metadata column that has the name of a column of the passages (`rowid`, `id`, `source`, `seq`, `start`, `end` or `text`, in any ASCII case), and a metadata column or a key column that is listed twice.
783
+ - The constructor refuses, with a `TypeError` that names it, a metadata column that has the name of a column of the passages (`rowid`, `id`, `source`, `seq`, `start`, `end` or `text` on SQLite, and `keywords` in place of `rowid` on Postgres, in any ASCII case), and a metadata column or a key column that is listed twice.
432
784
  - Before it reads, the pipeline refuses a vectorizer whose table no copy loads into its file, and a key, metadata or loading column that the stream or the target does not declare. The run rejects with a `TypeError`.
433
785
  - The name of the vectorizer and the name of each relation count in the check of distinct names of the pipeline.
434
786
  - A vectorizer fails as one dataset of the pipeline ([elt ADR 0034](../elt/docs/adr/0034-a-composite-dataset-refreshes-its-members-in-order-as-one-dataset.md)): the first member that fails stops the members after it, the copies and the other datasets go on, and the refresh after the next pass tries it again. A run rejects with the `DerivedDatasetError` of the vectorizer, whose `cause` is the `DerivedDatasetError` of the member. `docs_status` then has the state `failed`.
@@ -449,7 +801,7 @@ When the model or its `dimensions` change, the next refresh makes each vector ag
449
801
  ## Development
450
802
 
451
803
  ```sh
452
- npx nx run vectorizer:test # builds, then runs src/sqlite.test.ts
804
+ npx nx run vectorizer:test # builds, then runs the tests of each subpath; SQL Server 2025 runs only where Docker runs amd64 natively
453
805
  npx nx run vectorizer:typecheck # formats, lints, then type checks
454
806
  ```
455
807
 
@@ -460,4 +812,13 @@ src/
460
812
  passage-rules.ts the rules of the passages: the chunks of Chunking by source, or one part for each row
461
813
  sqlite/vectorizer.ts Vectorizer: the members and the views of SQLite
462
814
  sqlite/keyword-index.ts KeywordIndex: the keywords table, its FTS5 table and its triggers
815
+ postgresql.ts the subpath /postgresql
816
+ postgresql/vectorizer.ts Vectorizer: the members and the views of Postgres
817
+ postgresql/keyword-index.ts KeywordIndex: the keywords table with its generated tsvector and GIN index
818
+ sqlserver.ts the subpath /sqlserver
819
+ sqlserver/vectorizer.ts Vectorizer: the members and the views of SQL Server
820
+ sqlserver/keyword-index.ts KeywordIndex: the keywords table in marts and its full-text index
821
+ copies.ts the copies of the pipeline into the destination of a vectorizer
822
+ declared-columns.ts the check that the stream declares each column that the vectorizer reads
823
+ testing/letter-model.ts LetterModel, the embedding model of the tests
463
824
  ```
@@ -0,0 +1,2 @@
1
+ import type { Connection, Copy, Destination, Target } from '@eltjs/elt';
2
+ export declare function copiesInto<Into extends Target>(connections: readonly Connection<Into>[], holds: (destination: Destination<Into>) => boolean): readonly Copy<Into>[];
package/dist/copies.js ADDED
@@ -0,0 +1,8 @@
1
+ // The copies of the pipeline that load into the destination that holds a
2
+ // vectorizer's relations, which holds tells by the engine's own test: the
3
+ // same SQLite file, or the same Postgres database.
4
+ export function copiesInto(connections, holds) {
5
+ return connections
6
+ .filter(({ destination }) => holds(destination))
7
+ .flatMap(({ steps }) => steps);
8
+ }
@@ -0,0 +1,18 @@
1
+ import type { Copy, Target } from '@eltjs/elt';
2
+ import { type Loading, type SourceKey } from './options.ts';
3
+ type SourceTable = Target & {
4
+ readonly name: string;
5
+ readonly columns: readonly {
6
+ readonly name: string;
7
+ }[];
8
+ };
9
+ export declare function refuseUndeclaredColumns<Into extends SourceTable>({ vectorizer, from, copies, destination, key, metadata, loading, }: {
10
+ readonly vectorizer: string;
11
+ readonly from: Into;
12
+ readonly copies: readonly Copy<Into>[];
13
+ readonly destination: string;
14
+ readonly key: SourceKey;
15
+ readonly metadata: readonly string[];
16
+ readonly loading: Loading;
17
+ }): void;
18
+ export {};
@@ -0,0 +1,23 @@
1
+ import { keyColumns } from './options.js';
2
+ // Refuses, before any read, a vectorizer whose table no copy into its
3
+ // destination loads, and a key, metadata or loading column that the copy's
4
+ // stream or the table does not declare. copies are the copies into the
5
+ // destination of the vectorizer, which each engine finds by its own test
6
+ // (copiesInto), and destination names that destination in the refusal, such
7
+ // as the path of a SQLite file.
8
+ export function refuseUndeclaredColumns({ vectorizer, from, copies, destination, key, metadata, loading, }) {
9
+ const copy = copies.find(({ to }) => to === from);
10
+ if (copy === undefined)
11
+ throw new TypeError(`Vectorizer ${vectorizer} reads ${from.name}, which no copy of the pipeline loads into ${destination}`);
12
+ const declared = new Set([
13
+ ...Object.keys(copy.from.jsonSchema.properties ?? {}),
14
+ ...from.columns.map(({ name }) => name),
15
+ ]);
16
+ for (const column of [
17
+ ...keyColumns(key),
18
+ ...metadata,
19
+ ...('columns' in loading ? loading.columns : [loading.file]),
20
+ ])
21
+ if (!declared.has(column))
22
+ throw new TypeError(`Vectorizer ${vectorizer} reads the column ${column} of ${from.name}, which the stream ${copy.from.name} does not declare`);
23
+ }
@@ -2,12 +2,17 @@ import { Chunking } from '@eltjs/chunking';
2
2
  import { type LoadedRow, type RuleValues, TableRule, type TableRuleResult } from '@eltjs/elt';
3
3
  import { type ChunkingOptions, type SourceKey } from './options.ts';
4
4
  export declare function sourceOf(key: SourceKey): (row: LoadedRow) => string | null;
5
- export declare function passageRule({ key, fields, chunking, }: {
5
+ type PassageInput = string | {
6
+ readonly source: string;
7
+ readonly text: string;
8
+ };
9
+ export declare function passageRule({ key, fields, chunking, maxIdLength, }: {
6
10
  readonly key: SourceKey;
7
11
  readonly fields: readonly [string, ...string[]];
8
12
  readonly chunking: ChunkingOptions;
13
+ readonly maxIdLength?: number;
9
14
  }): PassageChunks | OnePart;
10
- export declare class PassageChunks extends TableRule<string, Chunking['output'], Chunking['place']> {
15
+ export declare class PassageChunks extends TableRule<PassageInput, Chunking['output'], Chunking['place']> {
11
16
  #private;
12
17
  readonly key: {
13
18
  name: string;
@@ -17,17 +22,18 @@ export declare class PassageChunks extends TableRule<string, Chunking['output'],
17
22
  readonly place: Chunking['place'];
18
23
  readonly batch: number;
19
24
  readonly concurrency: number;
20
- constructor({ key, fields, chunking, }: {
25
+ constructor({ key, fields, chunking, maxIdLength, }: {
21
26
  key: SourceKey;
22
27
  fields: readonly [string, ...string[]];
23
28
  chunking: Exclude<ChunkingOptions, 'none'>;
29
+ maxIdLength: number | undefined;
24
30
  });
25
31
  read(row: LoadedRow): {
26
32
  readonly key: string;
27
- readonly input: string;
33
+ readonly input: PassageInput;
28
34
  } | null;
29
35
  identity(): Promise<string>;
30
- compute(texts: readonly string[]): Promise<readonly TableRuleResult<RuleValues<Chunking['output']> & RuleValues<Chunking['place']>>[]>;
36
+ compute(inputs: readonly PassageInput[]): Promise<readonly TableRuleResult<RuleValues<Chunking['output']> & RuleValues<Chunking['place']>>[]>;
31
37
  }
32
38
  declare const whole: {
33
39
  readonly text: {
@@ -45,7 +51,7 @@ declare const span: {
45
51
  readonly description: 'The offset after the last code point of the passage: the count of code points of the text.';
46
52
  };
47
53
  };
48
- export declare class OnePart extends TableRule<string, typeof whole, typeof span> {
54
+ export declare class OnePart extends TableRule<PassageInput, typeof whole, typeof span> {
49
55
  #private;
50
56
  readonly key: {
51
57
  name: string;
@@ -69,15 +75,16 @@ export declare class OnePart extends TableRule<string, typeof whole, typeof span
69
75
  };
70
76
  readonly batch = 32;
71
77
  readonly concurrency = 1;
72
- constructor({ key, fields, }: {
78
+ constructor({ key, fields, maxIdLength, }: {
73
79
  key: SourceKey;
74
80
  fields: readonly [string, ...string[]];
81
+ maxIdLength: number | undefined;
75
82
  });
76
83
  read(row: LoadedRow): {
77
84
  readonly key: string;
78
- readonly input: string;
85
+ readonly input: PassageInput;
79
86
  } | null;
80
87
  identity(): Promise<string>;
81
- compute(texts: readonly string[]): Promise<readonly TableRuleResult<RuleValues<typeof whole> & RuleValues<typeof span>>[]>;
88
+ compute(inputs: readonly PassageInput[]): Promise<readonly TableRuleResult<RuleValues<typeof whole> & RuleValues<typeof span>>[]>;
82
89
  }
83
90
  export {};
@@ -27,11 +27,13 @@ export function sourceOf(key) {
27
27
  };
28
28
  }
29
29
  // The rule that cuts the text of the fields of each source row: the chunks of
30
- // @eltjs/chunking, or one passage for each row.
31
- export function passageRule({ key, fields, chunking, }) {
30
+ // @eltjs/chunking, or one passage for each row. maxIdLength: the most UTF-16
31
+ // units of a passage id <source>:<seq> that the destination holds, such as
32
+ // 450 on SQL Server; none when absent.
33
+ export function passageRule({ key, fields, chunking, maxIdLength, }) {
32
34
  return chunking === 'none'
33
- ? new OnePart({ key, fields })
34
- : new PassageChunks({ key, fields, chunking });
35
+ ? new OnePart({ key, fields, maxIdLength })
36
+ : new PassageChunks({ key, fields, chunking, maxIdLength });
35
37
  }
36
38
  // The chunks of Chunking, keyed by the source of each row (a Decorator):
37
39
  // Chunking cuts and names what made the chunks; the vectorizer reads the key,
@@ -45,7 +47,8 @@ export class PassageChunks extends TableRule {
45
47
  #chunking;
46
48
  #source;
47
49
  #fields;
48
- constructor({ key, fields, chunking, }) {
50
+ #maxIdLength;
51
+ constructor({ key, fields, chunking, maxIdLength, }) {
49
52
  super();
50
53
  this.#chunking = new Chunking({ ...chunking, key: source.name, fields });
51
54
  this.output = this.#chunking.output;
@@ -54,16 +57,18 @@ export class PassageChunks extends TableRule {
54
57
  this.concurrency = this.#chunking.concurrency;
55
58
  this.#source = sourceOf(key);
56
59
  this.#fields = Object.freeze([...fields]);
60
+ this.#maxIdLength = maxIdLength;
57
61
  Object.freeze(this);
58
62
  }
59
63
  read(row) {
60
- return readPassage(row, this.#source, this.#fields);
64
+ return readPassage(row, this.#source, this.#fields, this.#maxIdLength);
61
65
  }
62
66
  identity() {
63
67
  return this.#chunking.identity();
64
68
  }
65
- compute(texts) {
66
- return this.#chunking.compute(texts);
69
+ async compute(inputs) {
70
+ const results = await this.#chunking.compute(inputs.map(textOf));
71
+ return results.map((result, index) => fitIds(inputs[index], result, this.#maxIdLength));
67
72
  }
68
73
  }
69
74
  const whole = {
@@ -95,29 +100,57 @@ export class OnePart extends TableRule {
95
100
  concurrency = 1;
96
101
  #source;
97
102
  #fields;
98
- constructor({ key, fields, }) {
103
+ #maxIdLength;
104
+ constructor({ key, fields, maxIdLength, }) {
99
105
  super();
100
106
  this.#source = sourceOf(key);
101
107
  this.#fields = Object.freeze([...fields]);
108
+ this.#maxIdLength = maxIdLength;
102
109
  Object.freeze(this);
103
110
  }
104
111
  read(row) {
105
- return readPassage(row, this.#source, this.#fields);
112
+ return readPassage(row, this.#source, this.#fields, this.#maxIdLength);
106
113
  }
107
114
  // The code makes every passage, so its version names them (elt ADR 0005).
108
115
  async identity() {
109
116
  return `${manifest.name}@${manifest.version} none`;
110
117
  }
111
- async compute(texts) {
112
- return texts.map((text) => ({
113
- parts: [{ text, start: 0, end: [...text].length }],
114
- }));
118
+ async compute(inputs) {
119
+ return inputs.map((input) => {
120
+ const text = textOf(input);
121
+ return fitIds(input, { parts: [{ text, start: 0, end: [...text].length }] }, this.#maxIdLength);
122
+ });
115
123
  }
116
124
  }
117
- function readPassage(row, source, fields) {
125
+ // The source and the text of a row as the input of a passage rule: the text
126
+ // alone when the ids have no most length, so the input hash of a host with no
127
+ // limit stays the hash of its text.
128
+ function readPassage(row, source, fields, maxIdLength) {
118
129
  const key = source(row);
119
130
  if (key === null)
120
131
  return null;
121
132
  const text = rowText(row, fields);
122
- return text === null ? null : { key, input: text };
133
+ if (text === null)
134
+ return null;
135
+ return {
136
+ key,
137
+ input: maxIdLength === undefined ? text : { source: key, text },
138
+ };
139
+ }
140
+ const textOf = (input) => typeof input === 'object' ? input.text : String(input);
141
+ // The result of an input, or a rule failure of the input when the id of its
142
+ // last passage, <source>:<seq>, has more UTF-16 units than maxIdLength, the
143
+ // unit that NVARCHAR(n) of SQL Server counts. The other inputs go on, and no
144
+ // part of the input reaches the keyword index.
145
+ function fitIds(input, result, maxIdLength) {
146
+ if (maxIdLength === undefined ||
147
+ typeof input !== 'object' ||
148
+ !('parts' in result))
149
+ return result;
150
+ const length = `${input.source}:${result.parts.length - 1}`.length;
151
+ return length > maxIdLength
152
+ ? {
153
+ error: `The passage ids of this source row have up to ${length} characters, more than ${maxIdLength}, the most that the passage ids of the destination hold: give the vectorizer a shorter source key.`,
154
+ }
155
+ : result;
123
156
  }
@@ -0,0 +1,18 @@
1
+ import { type Connection, DerivedDataset, type PipelineClock } from '@eltjs/elt';
2
+ import { PostgresDestination, type PostgresTable } from '@eltjs/elt-postgresql';
3
+ export declare class KeywordIndex extends DerivedDataset<PostgresTable> {
4
+ #private;
5
+ readonly name: string;
6
+ readonly qualifiedName: string;
7
+ constructor({ into, name, parts, configuration, }: {
8
+ into: PostgresDestination;
9
+ name: string;
10
+ parts: string;
11
+ configuration: string;
12
+ });
13
+ validate(connections: readonly Connection<PostgresTable>[]): void;
14
+ refresh({ clock, signal, }: {
15
+ readonly clock: PipelineClock;
16
+ readonly signal?: AbortSignal;
17
+ }): Promise<void>;
18
+ }