Storage¶
Every store the vault uses is opened by a named backend and closed by whoever opened it. The protocols are importable from markdown_vault_mcp.interfaces, the value types from markdown_vault_mcp.types, the backends from their modules under markdown_vault_mcp.stores.
from markdown_vault_mcp.interfaces import StoreBackend, StoreLifecycle, SourceProbe
from markdown_vault_mcp.stores.registry import get_backend
from markdown_vault_mcp.stores.sqlite_keyword import SqliteKeywordBackend
Opening a store¶
A backend carries its own configuration; open() takes only the location and whether this process owns the files. An open that fails raises one of five StoreOpenError subclasses (see Exceptions); none of them means the store is empty.
StoreBackend
¶
Bases: Protocol[StoreT_co]
A named opener for one kind of store (#1766).
A backend carries its own configuration; :meth:open takes only what
varies per vault: where the store is and whether this process owns its
files. The registry in :mod:markdown_vault_mcp.stores.registry maps
(family, name) to a backend factory.
family
property
¶
Which kind of store this backend opens.
name
property
¶
The registry name a configuration value selects.
open(location, identity=None, *, owns_files=True)
¶
Open the store at location.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
location
|
Path | str | None
|
Where the store lives, in the backend's own terms; a
file-backed backend takes a path, |
required |
identity
|
object | None
|
The family's identity value, checked against what the
store holds; |
None
|
owns_files
|
bool
|
Whether this process owns the store's files. |
True
|
Returns:
| Type | Description |
|---|---|
StoreT_co
|
The open store. |
Raises:
| Type | Description |
|---|---|
StoreOpenError
|
One of its five subclasses, never an empty store. |
get_backend(family, name)
¶
Return the factory registered under (family, name).
Raises:
| Type | Description |
|---|---|
LookupError
|
If nothing is registered there; the message names the registered backends of that family. |
register_backend(family, name, factory)
¶
Register factory under (family, name).
Registering the same factory twice is fine (a module imported twice); a different one under a taken key is a programming error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
family
|
StoreFamily
|
The store family. |
required |
name
|
str
|
The configuration value that selects the backend. |
required |
factory
|
Callable[..., StoreBackend[Any]]
|
What the caller constructs the backend with. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the key holds a different factory already. |
backend_names(family)
¶
Return the registered names of family, sorted.
SqliteKeywordBackend(*, indexed_frontmatter_fields=None, searchable_frontmatter_fields=None, fts_weights=None)
¶
Open the keyword index SQLite serves, classifying what goes wrong.
The backend carries the index's configuration; :meth:open takes the
location and whether this process owns the file. None or
":memory:" opens an in-memory index, which is always this process's
own and therefore writable whatever owns_files says (#1758).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indexed_frontmatter_fields
|
list[str] | None
|
Frontmatter keys indexed for filtering. |
None
|
searchable_frontmatter_fields
|
list[str] | None
|
Frontmatter keys folded into search. |
None
|
fts_weights
|
dict[str, float] | None
|
Per-column BM25 weights. |
None
|
open(location, identity=None, *, owns_files=True)
¶
Open the index at location.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
location
|
Path | str | None
|
The SQLite file, or |
required |
identity
|
object | None
|
Must be |
None
|
owns_files
|
bool
|
|
True
|
Returns:
| Type | Description |
|---|---|
FTSIndex
|
The open :class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If identity is given. |
StoreBusyError
|
If another process owns the file. |
StoreUnavailableError
|
If the file cannot be opened or written, or its folder cannot be created. |
StoreCorruptError
|
If the file is not a SQLite database. |
StoreUnsupportedSchemaError
|
If its |
Vector stores¶
A vector store takes query vectors, not text: the caller embeds. Publication is conditional on the token the caller saw; ANY_TOKEN skips the comparison.
VectorReader
¶
Bases: Protocol
Read a vector store: nearest rows, per-document rows, tokens (#1767).
One call observes one committed state; a document is never half visible. The store holds no embedding provider: callers embed queries.
identity
property
¶
The embedding space of the rows the store holds.
generation
property
¶
Bumped each time :meth:VectorPublisher.publish_generation lands.
count
property
¶
The number of stored rows.
search(vector, *, limit=10, predicate=None, folder=None)
¶
Return the rows nearest vector, most similar first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector
|
Sequence[float]
|
The query embedding, of the store's dimension. |
required |
limit
|
int
|
Maximum number of rows; zero or less returns |
10
|
predicate
|
Callable[[dict[str, Any]], bool] | None
|
Keeps only the rows it accepts, applied before limit. |
None
|
folder
|
str | None
|
Keeps only rows in this folder or below it, applied before limit; a backend may push it down. |
None
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
Copies of the rows' metadata, each with a |
list[dict[str, Any]]
|
normalised dot product, |
similar_to_document(path, *, limit=10, predicate=None, folder=None)
¶
Return the rows nearest the mean of path's rows, excluding path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The document whose rows are averaged. |
required |
limit
|
int
|
Maximum number of rows; zero or less returns |
10
|
predicate
|
Callable[[dict[str, Any]], bool] | None
|
Keeps only the rows it accepts, applied before limit. |
None
|
folder
|
str | None
|
Keeps only rows in this folder or below it, applied before limit; a backend may push it down. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
As |
list[dict[str, Any]]
|
meth: |
rows_for(path)
¶
Return path's stored rows, vectors normalised, in storage order.
tokens()
¶
Return each stored document's token; None when unknown.
VectorPublisher
¶
Bases: Protocol
Publish to a vector store, conditionally on the stored token (#1767).
replace_document(document, *, expected_token)
¶
Replace every row of document.path with document.rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
document
|
DocumentRows
|
The document's new rows and the token they came from. |
required |
expected_token
|
ExpectedToken
|
The token the caller saw when it read the
source; |
required |
Returns:
| Type | Description |
|---|---|
PublicationOutcome
|
|
PublicationOutcome
|
from expected_token; nothing changes on a conflict. |
remove_document(path, *, expected_token)
¶
Remove every row and the token of path, with the same condition.
publish_generation(identity, documents)
¶
Replace the whole store with documents under identity, in one step.
A reader sees the previous generation until this returns; an interrupted publication leaves the previous generation in place. documents is re-iterable; it does not promise a length, indexing, or a meaningful truth value.
EmbeddingStore
¶
Bases: VectorReader, VectorPublisher, StoreLifecycle, Protocol
What a vector backend opens: read, publish and close (#1767).
VectorBackend
¶
Bases: StoreBackend[EmbeddingStore], Protocol
A backend that opens vector stores, including a fresh one (#1777).
open_fresh(location, identity)
¶
Open location as an empty store at identity, reading nothing there.
What the location holds stays in place until the fresh store's first persist replaces it, so a rebuild that never completes leaves the previous data for the next open. Used to rebuild a store that would not open (corrupt) or holds another identity.
EmbeddingIdentity(provider, model, variant, text_format, dimension)
dataclass
¶
The embedding space a vector store's rows belong to.
Two stores hold comparable vectors only when every field matches: the same provider, model and variant embed the same text format into the same number of dimensions.
Attributes:
| Name | Type | Description |
|---|---|---|
provider |
str
|
The provider's name ( |
model |
str
|
The model's name. |
variant |
str
|
How the provider embeds ( |
text_format |
str
|
The embedding-text format token
( |
dimension |
int
|
Floats per vector; |
of(provider, text_format)
classmethod
¶
Return the identity of provider embedding text_format text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
EmbeddingProvider
|
The embedding provider. |
required |
text_format
|
str
|
The embedding-text format token. |
required |
Returns:
| Type | Description |
|---|---|
EmbeddingIdentity
|
The identity a store holding this provider's vectors records. |
VectorRow(vector, metadata)
dataclass
¶
One stored chunk: its vector and the metadata returned with it.
Attributes:
| Name | Type | Description |
|---|---|---|
vector |
Sequence[float]
|
The embedding, as the provider returned it; the store normalises it. |
metadata |
dict[str, Any]
|
Every key the store hands back with a search result. |
DocumentRows(path, token, rows)
dataclass
¶
Every row of one document, with the source revision they came from.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The document's vault-relative path. |
token |
RevisionToken | None
|
The revision token of the source the rows were computed
from; |
rows |
Sequence[VectorRow]
|
The document's rows, possibly none. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a row's |
NumpySidecarBackend(*, legacy_only=False)
¶
Open a :class:NumpySidecarStore at a base path, or in memory.
Choose which files at a base path the stores this backend opens are.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
legacy_only
|
bool
|
Open the sidecar a release or an edge build left
( |
False
|
open(location, identity=None, *, owns_files=True)
¶
Open the store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
location
|
Path | str | None
|
The base path of the sidecar files, or |
required |
identity
|
object | None
|
The :class: |
None
|
owns_files
|
bool
|
|
True
|
Returns:
| Type | Description |
|---|---|
NumpySidecarStore
|
The open store. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If numpy is not installed. |
ValueError
|
If identity is not an |
StoreUnavailableError
|
If the files cannot be reached. |
StoreCorruptError
|
If they do not form a store. |
StoreUnsupportedSchemaError
|
If their format is newer. |
StoreIncompatibleError
|
If they hold another identity. |
hold_writer(location)
¶
Take a writer's share of location's lock without opening a store.
For a caller that closes one store and opens another on the same location, so the lock is not given up in between (#1505).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
location
|
Path | str
|
The store's base path; |
required |
Returns:
| Type | Description |
|---|---|
WriterLock
|
The share, to release once the new store is open. |
Raises:
| Type | Description |
|---|---|
StoreBusyError
|
If another process holds the lock. |
quarantine(location, *, clock=None)
¶
Rename this store's own files at location aside: it is corrupt (#1505).
{base}.v2.json and every {base}.v2.m{seq}.npy are renamed
to <name>.corrupt-<UTC time> under the writer lock; a released
sidecar ({base}.json, {base}.npy) and {base}.lock are
left.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
location
|
Path | str
|
The store's base path; |
required |
clock
|
Callable[[], datetime] | None
|
Supplies the time the suffix is stamped with. |
None
|
Returns:
| Type | Description |
|---|---|
list[Path]
|
The files' new paths; empty when there were none. |
Raises:
| Type | Description |
|---|---|
StoreBusyError
|
If another process holds the lock. |
StoreUnavailableError
|
If a file cannot be renamed; none is. |
open_fresh(location, identity)
¶
Open location as an empty store at identity, reading nothing there.
The next persist commits over whatever the location held, under a matrix name above every one already there.
Raises:
| Type | Description |
|---|---|
ImportError
|
If numpy is not installed. |
NumpySidecarStore(snapshot, *, base, read_only, seq, matrix_path, json_path=None, recorded_identity=_OWN_IDENTITY, writer_lock=None)
¶
Bases: ResidentStore
A vector store held in memory, optionally persisted beside a base path.
Construct through :class:NumpySidecarBackend.
recorded_identity
property
¶
The identity the opened files recorded, or None when they recorded none.
None for a bare-list sidecar, which opens under whatever identity
it is asked for, and for one whose index_metadata names no
positive dimension; a released sidecar's missing variant and text
format read as "" and v1, as :func:_check_identity reads
them. A store that wrote its own files reports its :attr:identity;
so does one that read none (no files, or in memory), which a donor
refuses as empty instead. A donor never matches a None (#1505).
replace_document(document, *, expected_token)
¶
Replace document.path's rows; see :class:~markdown_vault_mcp.interfaces.VectorPublisher.
Raises:
| Type | Description |
|---|---|
ReadOnlyError
|
If the store was opened read-only. |
ValueError
|
If a row is of another dimension or not finite. |
remove_document(path, *, expected_token)
¶
Remove path's rows and token, with the same condition.
Raises:
| Type | Description |
|---|---|
ReadOnlyError
|
If the store was opened read-only. |
publish_generation(identity, documents)
¶
Replace the store with documents under identity, durably.
Raises:
| Type | Description |
|---|---|
ReadOnlyError
|
If the store was opened read-only. |
ValueError
|
If a path appears twice, or a row is of another dimension or not finite. |
resources()
¶
Return the search mode and measured sizes (#1377): always resident.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the store is closed. |
OSError
|
If a stat of the store's files is refused. |
checkpoint()
¶
Persist pending changes; a no-op in memory, read-only or clean.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the store is closed. |
close()
¶
Persist pending changes and release the store. Idempotent.
The store is closed afterwards even if the final persist raises.
Lifecycle¶
StoreLifecycle
¶
Bases: Protocol
What every open store owes its owner (#1766).
Whoever opened a store closes it: the vault closes the stores its backends opened, a caller closes the store it passed in.
Sources and revisions¶
SourceProbe
¶
Bases: Protocol
The one question the indexing side asks a source about an identity.
probe(path)
¶
Return whether path is present (with its token), absent or unavailable.
SourceState(status, token=None)
dataclass
¶
The answer a :class:~markdown_vault_mcp.interfaces.SourceProbe gives.
Attributes:
| Name | Type | Description |
|---|---|---|
status |
SourceStatus
|
Whether the identity is present, absent, or could not be checked. |
token |
RevisionToken | None
|
The present revision's token; |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Exact keyword queries¶
An open FTSIndex can query the entire matching note population without
semantic retrieval or a top-k approximation. Its page size bounds output;
counts and aggregates always describe the full filtered population.
from markdown_vault_mcp.query_types import NoteGrouping, NoteQuery
request = NoteQuery(query="release", scope="body", folder="projects", limit=20)
page = index.query_documents(request)
count = index.count_documents_matching(request)
by_tag = index.aggregate_documents(request, NoteGrouping(by="tag", field="tags"))
Only configured indexed frontmatter fields support exact filters and tag
grouping; invalid fields raise InvalidRequestError, also a ValueError. Computed OKF filters require existing ranked search. Modification
bounds are RFC3339 instants with a timezone, inclusive modified_after and
exclusive modified_before. Metadata scope omits body sections. A lexical
query containing NUL is invalid; other malformed FTS expressions fall back to
literal terms within the same scope. See query types
for defaults and bounds. This library surface reads indexed data only. The three methods below form the
optional RunsExactQueries protocol, and FTSIndex has all three. A custom
keyword backend without them keeps working for search; the exact-query reader
methods raise InvalidRequestError on it.
The MCP tools and reader methods share these predicates; internal order and
pattern_mode switches are available only to typed library callers.
query_documents(spec)
¶
Read distinct notes and an exact total from one consistent read view.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
NoteQuery
|
Validated exhaustive population and page request. |
required |
Returns:
| Type | Description |
|---|---|
NoteQueryPage
|
Bounded typed page; metadata scope omits section content. |
count_documents_matching(spec)
¶
aggregate_documents(spec, grouping)
¶
Group all matching notes without limiting the input population.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
NoteQuery
|
Validated population; page/excerpt controls are ignored. |
required |
grouping
|
NoteGrouping
|
Bucket axis, indexed field and output limit. |
required |
Returns:
| Type | Description |
|---|---|
NoteAggregate
|
Exact total, missing count and bounded distinct-note buckets. |
Build-state listing¶
A build's final sweep needs each live note's path, title, hash and
modification time, not its frontmatter. A keyword index that has the
optional ListsNoteStates protocol returns exactly those four fields, and
FTSIndex does. A custom keyword backend without it keeps working: the build
reads the same fields through list_notes(), at the cost of loading every
note's frontmatter.
ListsNoteStates
¶
Bases: Protocol
A keyword index that lists live notes' build state alone (#1938); optional.
A build's final sweep and exclusion purge need each live note's path,
title, hash and modification time. An index without this reads them
through :meth:KeywordIndex.list_notes, frontmatter included.
list_note_states()
¶
Return path, title, content_hash and modified_at per live note.
Chunk traversal¶
IteratesChunks optionally yields the same grouped rows in the same order as
list_chunks(). Full embedding builds use it to release completed document
windows. The built-in FTS reader reads atomic whole-document pages in path order. Concurrent changes between pages may be observed or missed; convergence reconciles later edits. Custom indexes without it retain the eager list_chunks() fallback.
A custom index's non-scalar metadata stays resident through publication so its
objects retain their types and values; this applies to both reader paths.