Skip to content

Latest commit

 

History

History
137 lines (90 loc) · 14.4 KB

README.md

File metadata and controls

137 lines (90 loc) · 14.4 KB

@objectstack/knowledge-pgvector

IKnowledgeAdapter on PostgreSQL with the pgvector extension — the open vector store for self-hosted ObjectStack deployments. It takes the knowledge service's passages, embeds them with the kernel's embedder service, stores passages and vectors in PostgreSQL, and answers search() with two legs — an exact cosine scan and a keyword match on a tsvector — merged by reciprocal rank fusion.

import { ObjectKernel } from '@objectstack/core';
import { KnowledgeServicePlugin } from '@objectstack/service-knowledge';
import { KnowledgePgvectorPlugin } from '@objectstack/knowledge-pgvector';

const kernel = new ObjectKernel();
kernel.use(new KnowledgeServicePlugin({
  sources: [{ name: 'task_notes', label: 'Notes', adapter: 'pgvector',
    source: { kind: 'object', object: 'task', content: ['notes'] }}],
}));
kernel.use(new KnowledgePgvectorPlugin());

A source is usually a knowledge_source metadata item (a *.knowledge-source.ts file in an app, or one authored in Studio) that names this adapter with adapter: 'pgvector'; the sources option above registers one from code.

Options

Option Default
id 'pgvector' The adapter id a source names in adapter.
url the platform database A postgres:// URL. Absent: OS_DATABASE_URL (else the legacy DATABASE_URL) when it is PostgreSQL.
schema 'os_knowledge' The schema the store's tables live in.
poolMax the setting OS_KNOWLEDGE_POOL_MAX, else 20 Connections in the store's own pool, per process (per replica). See Pool size and time limit.
connectTimeoutMs 5000 How long a new connection may take before it fails, and how long a search waits for a free connection of the pool; boot waits on the store's first check.
statementTimeoutMs the setting OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS, else 10000 The longest a search's ranking statement may run, in milliseconds (PostgreSQL's statement_timeout).
queryPrefix '' Text put before every query before it is embedded (BGE's 'Represent this sentence for searching relevant passages: '). Passages are embedded as they are.
embedder the kernel's embedder service The embedder to call.

Which database, and where

The store is in ONE database: the url given, else the platform's when that is PostgreSQL. Where organizations have databases of their own, the store is still that one database; organizations are kept apart by the organization_id column, which every search filters on in SQL before ranking.

Its tables are in their own schema, os_knowledge — never the connection's own schema, where object tables live and which the platform's schema-drift checks read:

  • knowledge_generation — one row per source and generation: the index fingerprint it was built under, the recipe hash, the vector width, the model.
  • knowledge_vec_d<width> — one passage table per vector width (knowledge_vec_d1536, knowledge_vec_d3072, …), created the first time a width is written.

Rows are keyed by the source's index key: its name, or for a source a package ships, the knowledge service's spelling of that package and name (so two packages' sources of one name are two indexes). Two deployments that share one database — staging and production, say — must each set their own schema, or a source name they both use would be one index.

When a source stops being served (its metadata item was removed, or a package now holds its name), the knowledge service calls dropSource: every generation of the source is retired in one transaction, so nothing searches or writes it from then on, and its passages are then deleted in batches, the generation rows last.

Setup when the connection may not create them

On boot the plugin creates the vector extension (if it is missing and the connection may), the schema and the generation table. When it cannot, the plugin still registers and boot goes on: it warns with the SQL to run, its healthCheck answers ok: false with that SQL, and every call answers SERVICE_UNAVAILABLE (one sentence; the SQL and the driver's text go only to the health check, the boot warning and the log) until a database owner has run:

CREATE EXTENSION IF NOT EXISTS vector;
CREATE SCHEMA IF NOT EXISTS "os_knowledge";
-- and the generation table, as the warning prints it

The next call retries; no restart is needed. A database the plugin cannot reach is reported as unreachable, with the driver's error and no SQL.

Search

Two legs in one statement (one snapshot), merged by reciprocal rank fusion (RRF, k = 60) before the knowledge service re-checks each hit as the caller. Each leg ranks at most topK passages; a hit's score is the sum of 1 / (60 + rank) over the legs that rank it, divided by that of a passage first in both, so it lies in (0, 1]: 1 for first in both legs, 0.5 for first in one alone. The organization filter, the record scope and the metadata filter are one WHERE, run in both legs before either ranks.

  • Keyword leg. The query is split into terms at white space and punctuation; a hyphen, dot, slash, underscore, #, @ or + inside a term keeps it whole, so X-200 is one term (at most 16 terms). A run of Han, kana or Hangul inside a term is cut into overlapping pieces of three characters and of two (a run of two is one piece, a run of one is dropped), so a question written without spaces is still matched word by word; a figure or a code next to a run (2000, X-200) stays one term. Under the cap the figures, codes and words come first, then the pieces of three characters, then those of two. A word of three characters or more is matched as a phrase (phraseto_tsquery('simple', …)) on the passage's to_tsvector('simple', content), which a GIN expression index (knowledge_vec_d<width>_content_tsv) serves. The simple configuration lower-cases and neither stems nor drops stop words, so a code or a name matches as written. A shorter term (「出差」), and a term holding a Han, kana or Hangul character — which the parser never splits, so a tsvector holds a whole run of them as one word — is matched as a substring over the rows in scope: by content LIKE '%…%' when the term holds no cased letter (a piece of Han, kana or Hangul, a figure), where case folding could find nothing more, and by content 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 word most passages hold weighs little.
  • Keyword index. An expression index: no column is added and no row rewritten, and PostgreSQL keeps it in step with every write. It is made with the passage table; a table made by a release without one gets it from the first write or search of that width (CREATE INDEX IF NOT EXISTS, which blocks writes to the table while it builds).
  • Vector leg. An exact cosine scan; a passage whose cosine similarity is not positive is not ranked by it.

Pool size and time limit

Two settings, read from the environment at boot when the plugin option is not given (a plugin option wins):

Setting Default
OS_KNOWLEDGE_POOL_MAX 20 Connections in the store's own pool, in each process.
OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS 10000 The longest a search's ranking statement may run.

A value that is not a positive integer stops the boot, naming the setting; a blank one reads as unset.

Sizing the pool. The store's pool is its own, beside the platform's (OS_DATABASE_POOL_MAX, default 5), and both open connections to the same server when the store is in the platform database. A build of a source also holds one connection of its own (its builder lock) while it runs. Across every replica, keep

replicas × (OS_DATABASE_POOL_MAX + OS_KNOWLEDGE_POOL_MAX + builds running at once) + headroom ≤ max_connections

where the headroom covers migrations, admin sessions and superuser_reserved_connections. With max_connections = 200 and 20 kept as headroom, each replica may hold 180 / replicas connections. The default is a ceiling, not a count opened at boot: the pool opens a connection only when a search finds none idle, and closes idle ones again. Under load, a replica at the defaults reaches up to 26 (5 for the platform, 20 for the store, one build), so the store takes up to 20 × replicas: 60 with 3 replicas (78 with the platform pools and a build each). That fits up to 6 replicas (6 × 26 = 156 ≤ 180; 7 × 26 = 182 does not). A deployment that sets nothing used to stop at 4 store connections per replica and may now reach 20. With more replicas or a smaller server, lower OS_KNOWLEDGE_POOL_MAX (its ceiling is 84 with 2 replicas, 54 with 3, 39 with 4) or raise max_connections: a server out of connection slots refuses new connections (too_many_connections, class 53), and the searches that needed them are refused SERVICE_UNAVAILABLE. The default of 20 is measured: over 59,949 indexed passages with hybrid search, a pool of 4 left a third of the searches at 20 concurrent callers waiting past connectTimeoutMs, and a pool of 20 left none. A search holds a connection only while its statement runs; a search that finds every connection busy for connectTimeoutMs is refused SERVICE_UNAVAILABLE, never answered empty. A larger pool lets more searches wait in the database instead of in the pool: it does not make one search faster.

The time limit is set with SET LOCAL statement_timeout inside the search statement's own transaction, so it lasts exactly as long as that statement, touches no session setting and holds behind a transaction-mode pooler. (The store as a whole still needs a direct or session-mode connection for its builder lock; see Rebuilds.) Only the ranking statement is limited: the catalog reads around it are cheap, and writes and builds are not limited by it.

When a search fails

A search the database fails is refused with an ADR-0112 code, which the knowledge service hands to its caller in place of that source's hits: never an empty answer. The code is chosen by the error's SQLSTATE, never by the server's message (which lc_messages translates):

What failed Code
The statement ran past the time limit, or was cancelled (57014) TIMEOUT (504)
The database has no capacity: too_many_connections and the rest of class 53 SERVICE_UNAVAILABLE (503)
No connection: the pool's wait timed out, the connection ended, the server is shutting down or unreachable (class 08, 57P01–57P05, a socket error) SERVICE_UNAVAILABLE (503)
Any other database error DATABASE_ERROR (500)

The message is one sentence naming the source; the SQLSTATE, the driver's text and the setting to change are in the error's remedy, which the knowledge service logs for the operator.

An approximate index is an operator's step

The store creates no approximate index: every search is an exact scan, which is right for small and medium sources and works at any width. When a table outgrows it, add an index by hand:

CREATE INDEX ON os_knowledge.knowledge_vec_d1536 USING hnsw (embedding vector_cosine_ops);

pgvector's HNSW index takes at most 2,000 dimensions (vector type); a 3072-wide table stays on the exact scan.

Rebuilds

Every source's index is built under one index fingerprint (the embedding model and dimensions, the split, the content list — ADR-0161 K7). A write or a search under another fingerprint is refused KNOWLEDGE_REBUILD_REQUIRED (409) and never served from the stored vectors.

When the fingerprint changes, a complete reindex builds a new generation beside the active one; nothing has to be cleared by hand:

  • The reindex writes into the new generation, and so do the event-sync writes that arrive while it runs: they carry the new fingerprint. Nothing is written into the active generation under the new one.
  • A search of the source during the build is refused KNOWLEDGE_REBUILD_REQUIRED, saying the source is being rebuilt. It is never answered from the old generation.
  • When the walk and its purge are done, the new generation becomes the active one and the old one is retired, in one transaction. The old one's passages are then deleted in batches of 1,000 rows (deleteBatchSize on the adapter), and its generation row last. A deletion that stops part-way is finished by the source's next build; a retired generation is never searched.
  • One builder per source: a build holds a PostgreSQL advisory lock on the source, on a connection of its own, from its start to the switch. A second build from another process is refused LOCK_CONFLICT (409). The lock is freed when the build completes, when the process or its connection dies, or after 15 minutes without a call of the build itself (buildLockIdleMs; record events that arrive meanwhile do not count).
  • The lock needs a direct or session-mode connection. It is a PostgreSQL session advisory lock. Behind a connection pooler in transaction mode (PgBouncer's transaction pooling, or the pooled URL some hosted PostgreSQL services give you), the lock is not held by the store's session, so it can stay held with no build running, or fail to keep a second builder out. Give the store a direct URL or a session-mode one (the url option, else OS_DATABASE_URL). When the build ends and its session no longer holds the lock, the plugin logs a warning that says so.
  • A build that stops is resumed: the next build under the same fingerprint takes up the generation under construction with what it holds, and skips every document it already holds unchanged. A build under yet another fingerprint abandons it and deletes it.

A generation never takes over passage rows left without a generation row (a generation row deleted by hand, its passages not): they are deleted before any generation opens, so old vectors cannot be carried into a new index.

A passage whose text is unchanged is not embedded again on a reindex.

What it stores

Each row holds its passage's text, title and metadata as well as its vector: the text is as sensitive as the record it came from, and it is in every backup of the database.

Tests

pnpm test runs the unit cases everywhere. The contract suite and the acceptance cases run against a live PostgreSQL with pgvector when OS_TEST_POSTGRES_URL is set (CI: the Temporal Conformance job's pgvector/pgvector service), each in a schema of its own.

License

Apache-2.0. See LICENSING.md.