Retrieval/embedding infra: adding a Node Type's own pgvector store
How a Node Type gets a working Postgres/pgvector-backed embedding store (engine/embedding.py,
engine/embedding_config.py, engine/embedding_store.py) — the mechanism the Playbook
sits on top of.
1. Declare the embedding Configuration Schema fragment
Same pattern as inference (docs/operations/changing-the-inference-model.md): embed
EMBEDDING_CONFIG_SCHEMA under the Node Type's own config_schema.properties.embedding
(engine/embedding_config.py). A Node Type doing both chat-based synthesis and retrieval declares
inference and embedding side by side — they're independent fragments, not a shared one, since
they compose to different pydantic models.
"embedding": {
"endpoint": "http://ollama.example.local:11434",
"model": "nomic-embed-text",
"dimensions": 768
}
dimensions is required and has no default — it's this model's real output width, not a guess.
Get it from a live probe rather than assuming:
curl -s http://<ollama-host>:11434/api/embed -d '{"model": "nomic-embed-text", "input": ["probe"]}' \
| python3 -c "import json,sys; print(len(json.load(sys.stdin)['embeddings'][0]))"
endpoint/timeout_seconds/max_attempts/retry_backoff_seconds are all Shared Configuration
Fragment candidates (docs/operations/sharing-configuration-fragments.md) — every node instance on
the same Ollama endpoint should share the same tuning, the same reasoning inference already uses.
model and dimensions almost never belong in a shared fragment: they're what make one Node Type's
table what it is.
max_input_chars (positive whole number, default 6000) is the longest single input a caller that
composes free-form text should send; the client itself never truncates. It belongs with the backend, not
the Node Type: set it under the model's own measured refusal point (the reference Ollama
nomic-embed-text refused about 10.8 KB and accepted 9.3 KB), lower for a smaller-context model. See
docs/operations/shift-handoff-live-license-gating.md for the one caller that reads it today.
2. Build the profile and the store
from engine.embedding_config import build_embedding_profile
from engine.embedding_store import EmbeddingStore
profile = build_embedding_profile(document["config"]["embedding"])
store = EmbeddingStore(node_type.identity.name, profile.dimensions, embedding_model=profile.model)
store.ensure_schema() # idempotent - safe to call on every startup
ensure_schema() creates embeddings_<sanitized node type name>_<hash> (e.g. embeddings_mes_a1b2c3d4e5; the
store's table_name property gives the real name) with an
HNSW index on embedding vector_cosine_ops, if it doesn't already exist. On a table made by an
earlier version it adds the active column (every existing row stays, active) and never touches the
vector column — see "The embedding profile record" below if the model or its dimensions change.
A Node with a document_intake section builds all of this itself, and fills the table through the
ingestion stage (retrieval-ingestion-pipeline.md); the code below is for a script or a test that
works with a store directly.
3. Embed and store chunks
from engine.embedding import EmbeddingClient
from engine.embedding_store import NewChunk
with EmbeddingClient(profile) as client:
vectors = client.embed([chunk.text for chunk in chunks])
store.replace_document(
source_document_id,
[
NewChunk(f"{source_document_id}:{chunk.sequence}", chunk.text, vector, chunk.metadata)
for chunk, vector in zip(chunks, vectors, strict=True)
],
source_revised_at=source_revised_at,
document_type=document_type,
)
replace_document makes the chunks the whole of the document. It upserts them by chunk_id and removes any the document had before and no longer has, in one transaction.
- Re-ingesting the same revision replaces rather than duplicates.
- A shorter revision leaves no stale tail.
- A failure part-way leaves the earlier chunks exactly as they were.
- The document keeps its
activestate (for deactivating and activating a document, seeretrieval-ingestion-pipeline.md). - An empty list of chunks is refused, because it would delete the document.
upsert writes a single chunk and removes nothing. It is for a test or a one-off, not for a document.
Required fields. source_document_id, source_revised_at and document_type are required, not optional extras folded into metadata. A chunker always knows which source document and revision a chunk came from and what type of document it is. These three fields give a row a stable identity and a revision ordering (see "Why every row carries..." below).
embedded_context. A chunk's metadata may carry the context that was put before its text when it was embedded, under embedded_context. It is stored, but a search never returns it.
4. Retrieve by similarity
query_vector = client.embed([question])[0]
hits = store.similarity_search(query_vector, top_k=5, min_similarity=0.5)
Only active chunks are searched. include_inactive=True searches the chunks of deactivated documents
as well, for an analysis of everything that was on file.
similarity is cosine similarity (1 - cosine distance), not raw distance — higher means more
relevant. min_similarity here is a plain filter; deciding what to do about a thin or empty result
(broaden and retry, or flag incomplete) is Retrieval Quality Gate's job,
not this store's.
5. Scope an instruction's applicability (product, Mfg Order, unit, date)
"SOP" understates the real domain: a work instruction can be shared across every product, scoped to
one product, scoped further to a single Mfg Order, or effective only for a unit-number range and/or
a date range — sometimes several of these at once. Applicability carries that scope on every row;
ApplicabilityContext is the real-world scope a query is actually being asked in:
from engine.embedding_store import Applicability
store.upsert(
chunk.id,
chunk.text,
vector,
source_document_id=source_document_id,
source_revised_at=source_revised_at,
document_type=document_type,
applicability=Applicability(product_id="widget-a", effective_unit_from=4500),
metadata=chunk.metadata,
)
Every Applicability field defaults to None — unconstrained on that axis. Omit applicability
entirely (or pass Applicability()) for the common case: a generic instruction shared across every
product, order, unit, and date.
from engine.embedding_store import ApplicabilityContext
hits = store.similarity_search(
query_vector,
top_k=5,
min_similarity=0.5,
context=ApplicabilityContext(product_id="widget-a", unit_number=4812),
)
context pre-filters candidates before similarity ranking runs, not after — a chunk that fails
applicability is never even a candidate for "most similar," so it can't crowd out a correctly-scoped
chunk in a top_k-limited result. Passing no context at all skips applicability filtering
entirely, the same as passing an empty context.
Fails closed, not open. If a chunk constrains an axis (say, mfg_order_id) and the query's
context doesn't supply a value for it, that chunk is excluded — never assumed to match. A
wrong-context work instruction is a real correctness risk on a shop floor, not a relevance nicety a
slightly-broader match can paper over.
Why one physical table per Node Type, not one shared table with a node_type column
engine/activity_log.py uses a single shared table filtered by a node_type column for its own
per-node data — deliberately not the shape used here. A pgvector column's width (vector(n)) is
fixed at table-creation time, and two Node Types are free to configure different embedding models
with different output dimensions (one Node Type on nomic-embed-text at 768 dimensions,
another on a different model at some other width) — one shared column literally couldn't
hold both. Table-per-Node-Type is a consequence of that, not an access-control layer bolted on.
Why every row carries a stable document identity and revision marker
The Appliance principle (no shared database, each Node self-contained) plus the
Inter-Node Reasoning Boundary (only structured facts cross node boundaries, never content) mean
two Node Types needing the same source document each hold an independently-ingested local copy —
live cross-node retrieval is ruled out, not just impractical. Each Node holds its own copy, which
costs some duplicated compute, and independent copies can drift when a
source document is revised. Giving every row source_document_id and source_revised_at as explicit
columns gives a stable identity to key off and a revision ordering to compare, so a copy's
revision can be told apart from another copy's.
source_revised_at is the revision marker rather than a content hash: a revision's effectivity date
supersedes a prior one, and a timestamp directly
supports that ordering — a hash only tells you whether content changed, not which copy is newer.
The embedding profile record, and rebuilding a store
Vectors from different models are not comparable, and a model swap that keeps the same
dimensions passes every width check while making every similarity score meaningless. A store given
its embedding_model therefore records the model and dimensions it was first filled under (a row in
embedding_store_profile, written in the same transaction that creates the table) and compares them
on every start:
- A Node configured with another model, or the same model at other
dimensions, starts, logs why, and then refuses to ingest or retrieve against that store with anEmbeddingProfileMismatchErrorbefore anything is written. - A table whose vector width differs from the configured
dimensionsis refused the same way, even when no model was recorded. - A store that already holds chunks but has no record (made before the record existed) takes the current configuration as its record, with a warning, since the model that made them cannot be known.
To move to another embedding model or width, rebuild into a fresh table from the source documents:
- Stop the Node.
- Drop the store's table:
EmbeddingStore(node_type_name, dimensions).drop_schema()drops it and its recorded profile together (DROP TABLE embeddings_<name>_<hash>and deleting the table's row fromembedding_store_profiledoes the same by hand). - Change the
embeddingsection of the configuration. - Start the Node and have every provider deliver its documents again. The ingestion stage creates the table at the new width and records the new profile; the configuration history keeps the old profile's version, so the change is on the record.
Re-embedding a whole corpus is never a side effect of a configuration edit; the store is derived data and the source documents are the record.
What is on which configuration version
Every chunk is stamped with the version of its document type's configuration (metadata.config_version and metadata.config_fingerprint).
Reporting. engine.document_report.version_report(store, catalogue) lists, per type and version:
- how many documents and chunks there are;
- how many documents are active;
- which version is in force now.
It reports counts only, never text. Chunks written without a stamp (made before stamping, or by a script) appear as version None.
Bringing documents up to date. A configuration change re-embeds nothing. To bring a type's older documents up to date, select them with stale_document_batches(store, "sop", below_version=2, batch_size=50).
- It yields the documents of the type made under a version below the bound, in bounded batches, and can be resumed from the last id handled.
- Pass
catalogue=to leave out documents already on the type's current configuration. A type that went back to an earlier configuration has that version in force again, and a version bound alone would select its up-to-date documents. - The Node does not keep source documents, so each one has to be offered again by whatever delivers it, flagged
overwrite. It is then chunked and stored under the version now in force.
Pitfalls
- A model's output dimension is fixed at table-creation time.
ensure_schema()never alters the vector column of an existing table. A differentdimensionsvalue is detected and refused (see "The embedding profile record" above) and needs the rebuild described there. EmbeddingClient.embedraises, it doesn't report a partial outcome. UnlikeInferenceClient.call(chat), an embedding call is deterministic — a failure that survives plain retries means something is actually wrong (endpoint down, wrong model name, dimension drift), not worth papering over with an escalating-sampling retry loop that wouldn't help anyway. A 4xx answer (other than 408, 425 and 429) is not retried at all - the backend refused that exact input and will refuse it again - and its error carries the status code only, never the body.- Table names are derived from the Node Type's own name, not passed through as literal SQL.
engine/embedding_store.py's_table_namesanitizes andpsycopg.sql.Identifierquotes it — don't bypassEmbeddingStoreto hand-write a query againstembeddings_<name>directly, since the sanitization rules (lowercased, non-alphanumeric collapsed to_) aren't guaranteed stable API to depend on from outside this module. effective_unit_from/effective_unit_toare a sequential effectivity number, not necessarily a literal serial number. Real unit serials aren't always numerically orderable; if a site's own units genuinely aren't, map them to a separate sequential effectivity count before callingupsertrather than passing a non-numeric serial through directly.- Omitting
contextonsimilarity_searchisn't the safe default for a real applicability-scoped Node Type — it disables the filter entirely, not "filters permissively." Any caller retrieving on behalf of a real operator/question should always pass acontext, even a mostly-empty one (ApplicabilityContext()still enforces date effectivity via itsas_ofdefault); leaving it out is for callers that genuinely have no applicability model at all (most current tests).
Release: v0.11.0