Skip to content

API Reference parrot.knowledge.pageindex.embedding_store

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

parrot.knowledge.pageindex.embedding_store

View source

Two-tier content-addressed embedding store for PageIndex trees.

Each PageIndex node's embedding is identified by a content-addressed SHA-1 key derived from the model identifier, node title, and node summary. This design survives reindex_node_ids mutations that rewrite all node_ids on every tree mutation.

Storage layout::

<storage_dir>/
    <tree_name>/
        embeddings/
            global/           <- content-addressed .npy sidecar files
                <sha1_hex>.npy
            <tree_name>.matrix.npy     <- per-tree (N, d) matrix
            <tree_name>.node_order.json <- node_id ordering for the matrix

The global tier caches individual node embeddings keyed by content hash. The per-tree tier materializes a contiguous (N, d) float32 numpy array for fast BLAS matmul — rebuilt via build_tree_matrix(), loaded (memory-mapped) via load_tree_matrix(), deleted via invalidate_tree().

An in-memory LRU cache fronts the global tier to avoid repeated disk I/O for hot nodes across multiple search calls.

Alias JSONTreeStore

Re-exported from parrot.knowledge.pageindex.store.JSONTreeStore.

Class NodeEmbeddingStore

Two-tier content-addressed embedding cache for PageIndex trees.

Per-tree tier: materialized (N, d) contiguous numpy matrix, rebuilt on build_tree_matrix(); mmap for fast matmul.

The store is model-agnostic — the caller supplies an embed_fn to build_tree_matrix(). This keeps model loading in the toolkit and the store as a pure caching / persistence layer.

Parameter Type Default Description
storage_dir str | Path Directory for sidecar .npy files. Created on first write if it does not exist.
model_id str Embedding model identifier used in the content key. Changing this effectively invalidates all existing entries (new hash, no collision with old).
dimension int Embedding vector dimension. Used to validate loaded vectors and batches before they enter the cache.
cache_size int 512 Maximum number of content-key → vector entries held in the in-memory LRU cache.

Method NodeEmbeddingStore.content_key

Compute the SHA-1 content-addressed cache key.

The digest is unchanged from the three-argument form when extra is empty.

The "\x00" separator prevents collisions between prefix-equal strings: ("ab", "c") and ("a", "bc") hash to different values.

content_key(model_id: str, title: str, summary: str, extra: str = '') -> str

Parameter Type Default Description
model_id str Embedding model identifier.
title str Node title text.
summary str Node summary text.
extra str '' Additional text that participates in the key when present.

Returns: str — 40-character lowercase hex SHA-1 digest.

Method NodeEmbeddingStore.prune_tree_matrices

Remove generation matrix files not represented by keep.

prune_tree_matrices(tree_name: str, keep: set[int]) -> int

Parameter Type Default Description
tree_name str Name of the tree whose generated matrix files to prune.
keep set[int] Generation identifiers whose files must remain.

Returns: int — Number of matrix and order files removed.

Method NodeEmbeddingStore.get_or_embed

Return the cached embedding vector for a node, or None if missing.

Checks the in-memory LRU cache first, then the global .npy sidecar. Does NOT call the embed function — use build_tree_matrix for batch embedding.

get_or_embed(tree_name: str, node_id: str, title: str, summary: str) -> Optional[np.ndarray]

Parameter Type Default Description
tree_name str Name of the tree this node belongs to.
node_id str Node identifier (used only for logging).
title str Node title text.
summary str Node summary text.

Returns: Optional[np.ndarray] — 1-D float32 numpy array if cached; None otherwise.

Method NodeEmbeddingStore.build_tree_matrix

Build (or rebuild) the per-tree (N, d) embedding matrix.

Only nodes whose content key is absent from the global cache are sent to embed_fn — unchanged nodes incur zero embed cost. The resulting matrix is saved as a contiguous C-order float32 .npy file alongside a node_order JSON sidecar.

build_tree_matrix(tree_name: str, nodes: list[dict], embed_fn: Callable[[list[str]], np.ndarray], *, generation_id: int = 0) -> tuple[np.ndarray, list[str]]

Parameter Type Default Description
tree_name str Name of the tree to embed.
nodes list[dict] List of node dicts, each with at least "node_id", "title", and one of "summary" / "prefix_summary".
embed_fn Callable[[list[str]], np.ndarray] Callable accepting a list of text strings and returning an (n, d) float32 numpy array.
generation_id int 0

Returns: tuple[np.ndarray, list[str]] — Tuple of (matrix, node_id_order) where matrix[i] is the embedding for node_id_order[i].

Raises:

  • ValueError — When nodes is empty.

Method NodeEmbeddingStore.load_tree_matrix

Load the materialized per-tree matrix (memory-mapped read-only).

load_tree_matrix(tree_name: str, *, generation_id: int = 0) -> Optional[tuple[np.ndarray, list[str]]]

Parameter Type Default Description
tree_name str Name of the tree whose matrix to load.
generation_id int 0

Returns: Optional[tuple[np.ndarray, list[str]]] — Tuple of (matrix, node_id_order) if the matrix exists, or None if it has not yet been built or was invalidated.

Method NodeEmbeddingStore.invalidate_tree

Delete the per-tree matrix without touching global-tier entries.

After invalidation, the next build_tree_matrix call will reassemble the matrix (re-embedding only truly changed nodes; unchanged nodes will hit the global tier cache).

invalidate_tree(tree_name: str) -> None

Parameter Type Default Description
tree_name str Name of the tree to invalidate.

Alias key_item_text

Re-exported from parrot.knowledge.pageindex.hybrid_search.key_item_text.

Attribute logger

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