Skip to content

API Reference parrot.knowledge.graphindex.persist_postgres

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.knowledge.graphindex.persist_postgres

View source

Postgres persistence backend for GraphIndex (FEAT-520 Module 2).

PostgresPersistence is the third GraphIndex backend, sitting next to ArangoPersistence (ArangoDB, persist_arango.py) and SQLitePersistence (persist_sqlite.py). Its public API mirrors ArangoPersistence exactly (duck-typed, same as the SQLite sibling) so GraphPublisher and the builder pipeline work unchanged.

Writes are bitemporal and append-only from day one (spec D1/D2): a correction to an existing node closes the current node_versions row's validity range and inserts a new row in the same transaction — content columns are NEVER UPDATEd. Reads in this module are current-time only (upper_inf(validity)); the temporal contract (as_of/history/ diff) is added by TASK-2767 in the same file.

Two schema fields on UniversalNode (parent_id, embedding_ref) have no dedicated column in the shared graphindex.* schema (spec §2 DDL — Module 1 intentionally keeps the identity/state tables lean). They round -trip through a private "_pg_extra" key nested inside the existing node_versions.domain_tags jsonb column instead of widening the schema outside this task's file scope. Likewise UniversalEdge has no evidence_ref field (spec U3 is a DB-level concept); the value is read from/written to edge.domain_tags["evidence_ref"], the exact extensibility seam the model's own docstring describes for domain-specific data (FEAT-392 precedent).

FEAT-520 Module 3 adds the graph commit protocol (apply_update/ get_commit/list_commits/revert_commit), mirroring ArangoPersistence/SQLitePersistence behaviorally (tests/knowledge/graphindex/test_persist_commit_protocol.py is the parity bar). Deviation from the ArangoDB sibling, worth calling out: on Postgres the pre-image capture, the commits/commit_items rows, and every mutation happen inside ONE conn.transaction() — a mid-apply crash rolls back everything, including the audit trail itself. Arango's "visible in audit trail even on partial failure" compromise does not apply here; the engine's transaction IS the atomicity guarantee, so no per-tenant asyncio.Lock is needed (matches sibling seq ordering via the commits.seq IDENTITY column). "Removal" (removed_nodes/ removed_edges) never physically deletes — it closes the validity range (tombstone-by-range), so history/temporal reads (TASK-2767) still see it; revert_commit restores a pre-image by inserting a FRESH version row (never re-opening a past range, which would violate the append-only/EXCLUDE invariant), the same close-and-insert discipline as every other write path in this module.

FEAT-520 Module 4 adds the temporal READ contract (as_of/history/ diff, spec D5) — Postgres-only in v1. SQLitePersistence and ArangoPersistence do NOT grow these methods; callers feature -detect via hasattr.

FEAT-520 Module 6 adds upsert_embeddings — in-schema embeddings keyed (version_id, model) (spec U4: PgVectorStore is explicitly NOT involved; zero parrot.stores.* imports). This gives TASK-2771's hybrid retrieval a KNN leg inside the same transaction snapshot as the graph and FTS legs.

FEAT-520 Module 7 adds hybrid_retrieve (spec D6/G5, deliberately named to avoid colliding with PgVectorStore.hybrid_search — spec C2): graph expansion (recursive CTE from seeds), pgvector KNN, and ts_rank_cd FTS run as CTEs of ONE SQL statement against the same as_of snapshot, fused with RRF (Σ w_leg/(60+rank_leg), _RRF_K=60 parity with pageindex/hybrid_search.py) in SQL. The graph leg's "rank" is derived from BFS depth order (closest-first), unifying all three legs under the same RRF formula rather than a separate depth-decay term. CTE order (graph→semantic: hood-restricted KNN when both seeds and query_embedding are given) follows TASK-2770's spike decision (artifacts/logs/feat-520-oq3-spike.md). Cross-encoder re-ranking runs in Python through the existing parrot.rerankers seam, copying HybridPageIndexSearch._apply_reranker's fallback semantics (failure or NaN score → fused order).

Alias AbstractReranker

Re-exported from parrot.rerankers.abstract.AbstractReranker.

Alias AssertionMeta

Re-exported from parrot.knowledge.graphindex.schema.AssertionMeta.

Alias CommitReceipt

Re-exported from parrot.knowledge.graphindex.schema.CommitReceipt.

Alias GraphUpdate

Re-exported from parrot.knowledge.graphindex.schema.GraphUpdate.

Class HybridCandidate

One fused candidate from hybrid_retrieve (pre- or post-rerank).

Fields:

Field Type Default Description
concept_id str
version_id int
title str
score float
signals dict[str, float]
body_ref Optional[str] None
evidence list[dict]

Class NodeVersionRow

One row of graphindex.node_versions, as returned by history()/as_of().

Fields:

Field Type Default Description
version_id int
concept_id str
valid_from datetime
valid_to Optional[datetime] None
tx_from datetime
title str
summary str ''
body Optional[str] None
body_ref Optional[str] None
provenance str 'extracted'
derived bool False

Class PostgresPersistence

Postgres-backed GraphIndex persistence over the shared graphindex.* schema.

Public API mirrors ArangoPersistence (persist_arango.py) — duck -typed, same as SQLitePersistence — plus the temporal (TASK-2767) and hybrid-retrieval (TASK-2771) extensions added later in this file.

Parameter Type Default Description
dsn Optional[str] None asyncpg-compatible DSN. Ignored when pool is supplied.
pool Optional[asyncpg.Pool] None An existing asyncpg pool to reuse instead of creating one. KNOWN LIMITATION (code-review finding): unlike a pool built by create_pg_pool, an externally-supplied pool does NOT get the pgvector codec registered automatically — callers passing pool= must register it themselves (pgvector.asyncpg. register_vector) on that pool's own init callback, or embedding reads/writes through this instance will fail.
schema str 'graphindex' The Postgres schema name housing the GraphIndex tables.

Method PostgresPersistence.close

Close the pool if this instance created it.

close() -> None

Method PostgresPersistence.persist_graph

Persist all nodes and edges for a tenant graph.

Corrections close the current version's validity range and insert a new row (spec D2); identical content is a no-op.

persist_graph(ctx: TenantContext, nodes: list[UniversalNode], edges: list[UniversalEdge]) -> dict[str, Any]

Parameter Type Default Description
ctx TenantContext Tenant context.
nodes list[UniversalNode] All graph nodes to persist.
edges list[UniversalEdge] All graph edges to persist.

Returns: dict[str, Any] — {"nodes_persisted": N, "edges_persisted": M}

Method PostgresPersistence.replace_document_slice

Atomically replace all nodes/edges for a single document.

Closes the current versions/edges scoped to document_uri and upserts the new slice, all in one transaction — a concurrent reader never observes a partial state. Canonical nodes (source_uri starting with odoo-model://) are never closed, even if their own URI is passed as document_uri.

Nodes present in the OLD slice but absent from the new nodes list are truly removed — any currently-open edge touching one of them is ALSO closed, regardless of that edge's own source_id stamp (an incoming edge from a different document into a node this slice just dropped would otherwise dangle: still "current" per its own validity range, but pointing at a concept_id with no current version — load_graph does not itself filter edges by endpoint currency).

replace_document_slice(ctx: TenantContext, document_uri: str, nodes: list[UniversalNode], edges: list[UniversalEdge]) -> dict[str, Any]

Parameter Type Default Description
ctx TenantContext Tenant context.
document_uri str URI of the document to replace.
nodes list[UniversalNode] Replacement nodes.
edges list[UniversalEdge] Replacement edges.

Returns: dict[str, Any] — {"nodes_replaced": N, "edges_replaced": M}

Method PostgresPersistence.file_hashes

Return every (source_uri, sha1) from {schema}.files, sorted by source_uri.

The v1 schema is not tenant-partitioned: files is keyed by source_uri alone, so ctx is accepted for contract parity and not used to filter.

file_hashes(ctx: TenantContext) -> list[tuple[str, str]]

Parameter Type Default Description
ctx TenantContext Tenant context (unused).

Returns: list[tuple[str, str]] — The sorted pairs.

Method PostgresPersistence.is_stale

Check whether a source file needs re-extraction.

is_stale(ctx: TenantContext, source_uri: str, mtime: float, sha1: str) -> bool

Parameter Type Default Description
ctx TenantContext Tenant context (unused — files are keyed by source_uri within the shared schema, parity with the SQLite sibling's per-tenant-file semantics).
source_uri str The file's source URI as stored in files.
mtime float Current filesystem modification time.
sha1 str SHA-1 hex digest of the current file content.

Returns: bool — True if the file should be re-extracted; False if the stored snapshot is still valid.

Method PostgresPersistence.load_graph

Load and rehydrate the CURRENT tenant graph as schema models.

Only rows with an open validity range (upper_inf(validity)) are returned — the current-time read path (spec D3). Rows with enum values unknown to this code version are skipped with a warning (forward-compat, sibling parity).

load_graph(ctx: TenantContext) -> tuple[list[UniversalNode], list[UniversalEdge]]

Parameter Type Default Description
ctx TenantContext Tenant context (unused — the schema is shared, not per-tenant partitioned in v1).

Returns: tuple[list[UniversalNode], list[UniversalEdge]] — (nodes, edges) lists of validated models.

Method PostgresPersistence.apply_update

Apply a :class:GraphUpdate in one audited transaction.

Captures the pre-image of every touched node/edge (including implicit incident edges of removed_nodes) into commit_items, records the commit row, then applies the writes: node/edge upserts reuse the TASK-2765 close-and-insert helpers; removals close the validity range rather than deleting (tombstone-by-range — history stays intact for TASK-2767's temporal reads). See the module docstring for the "one transaction" deviation from the ArangoDB sibling.

apply_update(ctx: TenantContext, update: GraphUpdate) -> CommitReceipt

Parameter Type Default Description
ctx TenantContext Tenant context.
update GraphUpdate The validated update batch to apply.

Returns: CommitReceipt — class:CommitReceipt describing the recorded commit.

Method PostgresPersistence.get_commit

Return a recorded commit with its decoded payload and items.

get_commit(ctx: TenantContext, commit_id: str) -> Optional[dict[str, Any]]

Parameter Type Default Description
ctx TenantContext Tenant context (unused — the schema is shared, not per-tenant partitioned in v1).
commit_id str The commit to fetch.

Returns: Optional[dict[str, Any]] — A dict with the commit row, decoded payload, and its items, or None when unknown.

Method PostgresPersistence.list_commits

List recorded commits, newest (highest seq) first.

list_commits(ctx: TenantContext, run_id: Optional[str] = None, agent_id: Optional[str] = None, limit: int = 50) -> list[dict[str, Any]]

Parameter Type Default Description
ctx TenantContext Tenant context (unused — see get_commit).
run_id Optional[str] None Optional filter on the producing run.
agent_id Optional[str] None Optional filter on the producing agent.
limit int 50 Maximum rows returned.

Returns: list[dict[str, Any]] — Commit summary rows (payload omitted) as dicts; [] when the schema has no commits yet.

Method PostgresPersistence.revert_commit

Restore the pre-images captured by a commit.

Refused when a LATER, non-reverted commit (higher seq) touched any of the same item keys — reverting would silently clobber the newer write.

revert_commit(ctx: TenantContext, commit_id: str) -> dict[str, Any]

Parameter Type Default Description
ctx TenantContext Tenant context.
commit_id str The commit to revert.

Returns: dict[str, Any] — {"status": "reverted", ...} on success or {"error": ...} on refusal/unknown commit.

Method PostgresPersistence.as_of

Return the graph snapshot valid at time t.

A caller can swap load_graph() for as_of(now()) transparently — both filter on the same validity predicate, just expressed differently (upper_inf(validity) vs. validity @> $t).

as_of(ctx: TenantContext, t: datetime) -> tuple[list[UniversalNode], list[UniversalEdge]]

Parameter Type Default Description
ctx TenantContext Tenant context (unused — see load_graph).
t datetime The point in time to snapshot (must be timezone-aware).

Returns: tuple[list[UniversalNode], list[UniversalEdge]] — (nodes, edges) valid at t.

Method PostgresPersistence.history

Return every version row of a concept, ordered oldest first.

history(ctx: TenantContext, concept_id: str) -> list[NodeVersionRow]

Parameter Type Default Description
ctx TenantContext Tenant context (unused — see load_graph).
concept_id str The concept to list version history for.

Returns: list[NodeVersionRow] — Ordered NodeVersionRow list (including closed ranges); [] for an unknown concept_id.

Method PostgresPersistence.diff

Return a structured diff of a concept between two points in time.

LLM-consumable: version rows and edge deltas, never raw-text comparison.

diff(ctx: TenantContext, concept_id: str, t1: datetime, t2: datetime) -> TemporalDiff

Parameter Type Default Description
ctx TenantContext Tenant context (unused — see load_graph).
concept_id str The concept to diff.
t1 datetime Start of the comparison window (timezone-aware).
t2 datetime End of the comparison window (timezone-aware).

Returns: TemporalDiff — class:TemporalDiff with version changes and incident edge deltas.

Method PostgresPersistence.upsert_embeddings

Batch-upsert embeddings for the CURRENT version of each concept.

The seam the graphindex embed stage (embed.py) writes through: (concept_id, vector) pairs, keyed in storage by (version_id, model) with concept_id denormalized (spec §3 Module 6). Concept ids with no current version are skipped (not an error — the embed stage may race a not-yet-persisted node; callers persist the graph first).

upsert_embeddings(ctx: TenantContext, items: list[tuple[str, list[float]]], *, model: str = '') -> int

Parameter Type Default Description
ctx TenantContext Tenant context (unused — see load_graph).
items list[tuple[str, list[float]]] (concept_id, vector) pairs.
model str '' Embedding model identifier.

Returns: int — Number of embedding rows actually written.

Raises:

  • ValueError — When any vector's length does not match GRAPHINDEX_EMBEDDING_DIM.

Method PostgresPersistence.hybrid_retrieve

One-pass hybrid retrieval: graph + KNN + FTS, RRF-fused in SQL.

All three legs are CTEs of ONE SQL statement (one fetch call) against the SAME as_of snapshot — no leg can see a version/edge the others can't. RRF fusion (Σ w_leg/(60+rank_leg), spec D6) happens in SQL; the graph leg's "rank" is its BFS depth order (closest-first) so all three legs share one fusion formula. CTE order follows TASK-2770's spike decision: when both seeds and query_embedding are given, the KNN leg is restricted to the graph hood (graph→semantic — the measured winner at depth <=3).

Re-ranking uses fts_terms as the query text (this call has no separate query_text param — the normative signature is spec §2's; when a reranker is supplied without fts_terms, reranking is skipped and the fused order is returned, documented here since the spec left the choice open).

hybrid_retrieve(ctx: TenantContext, *, query_embedding: Optional[list[float]] = None, fts_terms: Optional[str] = None, seeds: Optional[list[str]] = None, as_of: Optional[datetime] = None, weights: Optional[dict[str, float]] = None, limit: int = 20, reranker: Optional[AbstractReranker] = None, rerank_top_k: int = 10) -> list[HybridCandidate]

Parameter Type Default Description
ctx TenantContext Tenant context — its tenant_id doubles as the FTS regconfig namespace when fts_terms is given (this call has no per-row namespace to key off of, unlike the write paths).
query_embedding Optional[list[float]] None KNN leg query vector.
fts_terms Optional[str] None FTS leg query text (websearch_to_tsquery syntax) — also the re-ranking query text.
seeds Optional[list[str]] None Graph leg seed concept_ids.
as_of Optional[datetime] None Point in time for all three legs; None → now(). Must be timezone-aware.
weights Optional[dict[str, float]] None Per-leg RRF weight overrides ({"graph": ..., "knn": ..., "fts": ...}).
limit int 20 Maximum fused candidates returned.
reranker Optional[AbstractReranker] None Optional cross-encoder reranker.
rerank_top_k int 10 Maximum results after re-ranking.

Returns: list[HybridCandidate] — Fused (and optionally re-ranked) :class:HybridCandidate list.

Raises:

  • ValueError — When none of query_embedding/fts_terms/ seeds is given, or as_of is a naive datetime.

Alias SearchResult

Re-exported from parrot.models.stores.SearchResult.

Class TemporalDiff

Structured output of diff(concept_id, t1, t2) — LLM-consumable.

Never "compare these two texts": version_changes/edges_added/ edges_removed are structured rows, not prose.

Fields:

Field Type Default Description
concept_id str
t1 datetime
t2 datetime
version_changes list[dict]
edges_added list[dict]
edges_removed list[dict]

Alias TenantContext

Re-exported from parrot.knowledge.ontology.schema.TenantContext.

Alias UniversalEdge

Re-exported from parrot.knowledge.graphindex.schema.UniversalEdge.

Alias UniversalNode

Re-exported from parrot.knowledge.graphindex.schema.UniversalNode.

Alias create_pg_pool

Re-exported from parrot.knowledge.graphindex.pg_schema.create_pg_pool.

Alias ensure_schema

Re-exported from parrot.knowledge.graphindex.pg_schema.ensure_schema.

Attribute logger

Alias resolve_regconfig

Re-exported from parrot.knowledge.graphindex.pg_schema.resolve_regconfig.

Alias validate_embedding_dim

Re-exported from parrot.knowledge.graphindex.pg_schema.validate_embedding_dim.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally