Vectorstore Services

The service layer of vectorstores: their lifecycle, their documents, search, and maintenance.

VectorstoreService binds a VectorstoreMeta to its backend and embeddings model. The manifest broker, the REST API, the Celery tasks and the management commands all go through it.

Lifecycle

  • deploy(): check the api key, and queue the deploy task, which creates the database. A Pinecone index takes a minute or two to initialize, and a self-hosted Qdrant server needs a volume and a pod, so the task checks again every few seconds, with deployment_step(), records each condition, retries after errors, and fails the deploy after an error that retrying can’t fix, or too many checks. See smarter.apps.vectorstore.deployment.

  • reconcile(): Celery Beat runs it every few minutes. It checks deployed databases, creates a missing index or collection, records the status and statistics, and takes over a deploy whose task was lost.

  • undeploy(): stop serving. A self-hosted server’s volume, and so its data, is kept, and a managed index is left as it is.

  • destroy(): delete the database and its data, unless deletionProtection is enabled.

Documents are added with add_document(), which extracts and stores their text, and loaded by load_document(), normally in a Celery task.

Maintenance: maintain(), run hourly by Celery Beat, takes snapshots on the manifest’s schedule, prunes them to its retention, and retries documents whose task was lost.

class smarter.apps.vectorstore.service.VectorstoreService(vectorstore, backend=None, embeddings=None)[source]

Bases: object

The operations of one vectorstore.

Parameters:
  • vectorstore (VectorstoreMeta) – The vectorstore.

  • backend (SmarterVectorstoreBackend | None) – Its backend, e.g. one with an in-memory Qdrant client in tests. By default, get_backend().

  • embeddings (Embeddings | None) – Its embeddings model, e.g. a deterministic fake in tests. By default, get_embeddings(), created when first needed.

__init__(vectorstore, backend=None, embeddings=None)[source]
add_document(name, data=None, text=None, content_type=None, source=VectorstoreDocumentSource.UPLOAD, metadata=None)[source]

Extract and store a document’s text.

It is loaded by load_document().

Parameters:

data (bytes | None) – The file’s bytes, e.g. a PDF. Or text.

Return type:

tuple[VectorstoreDocument, bool]

Returns:

the document, and whether it is new. A document with the same text is not added again.

Raises:

VectorstoreExtractionError – if its text cannot be extracted.

add_documents(sources, metadata=None)[source]

Add documents, and queue the new ones to be loaded, if the vectorstore is ready.

A document whose text the vectorstore already has is a duplicate, and is not added again. The documents of a vectorstore that isn’t ready are loaded once its deploy is ready.

Parameters:
  • sources (Iterable[DocumentSource]) – The documents, e.g. from smarter.apps.vectorstore.sources.request_sources().

  • metadata (dict[str, Any] | None) – Stored with every chunk of every document.

Return type:

DocumentsAdded

Returns:

The documents added, the duplicates, and whether the new ones were queued.

Raises:

smarter.apps.vectorstore.extract.VectorstoreExtractionError – If a document’s text can’t be extracted.

advance_deployment(provision=False)[source]

Bring the database one step closer to ready, and record its conditions.

It creates the infrastructure, if provision, observes it, creates the index or collection once the infrastructure is ready, and checks that the index is ready. Nothing in it waits: what isn’t ready yet is recorded, and checked again by the next call.

Parameters:

provision (bool) – Create the infrastructure that Smarter runs, e.g. a self-hosted server.

Return type:

str

Returns:

The status: provisioning, or ready.

Raises:

Exception – Whatever the backend raises, e.g. a database that can’t be reached.

property backend: SmarterVectorstoreBackend

The vectorstore’s backend, created when it is first used.

check_again(reason)[source]

Schedule the deploy’s next check, or fail the deploy if it has made all of its checks.

Parameters:

reason (str) – What the deploy waits for, or its last error.

Return type:

int | None

Returns:

The seconds until the next check, or None if the deploy failed.

chunks(document)[source]

A document’s chunks, and their metadata: the document’s, and where the chunk came from.

Return type:

tuple[list[str], list[dict[str, Any]]]

delete()[source]

Destroy the vectorstore’s database, if it was deployed, then delete the vectorstore and its api key Secret.

The work of delete_vectorstore(), and of queue_delete() for a vectorstore that was never deployed.

Raises:
  • VectorstoreServiceError – If deletionProtection is enabled.

  • Exception – Whatever the backend raises when it destroys the database, which destroy() records as a failed status. The vectorstore is then kept.

Return type:

None

delete_document(document)[source]

Remove a document’s chunks from the database, then the document.

Return type:

None

deploy()[source]

Deploy the vectorstore: begin a deploy, and queue the deploy task, which creates the database.

It returns at once, provisioning. The task deploy_vectorstore() is queued once the current transaction commits, and checks the database until it is ready, or the deploy fails. Its progress is in deployment, which the manifest’s status shows.

Return type:

VectorstoreDeploymentState

Returns:

The new deploy’s state.

Raises:
  • VectorstoreServiceError – If the vectorstore is inactive.

  • VectorStoreBackendRejectedError – If the database refuses its api key.

property deployment: VectorstoreDeploymentState

The progress of the vectorstore’s last deploy, read when it is first used.

deployment_step(deployment_id)[source]

Make one check of a deploy, as the deploy task does, and say when to check again.

A deploy that another deploy replaced, or that was undeployed, does nothing. An error that retrying can’t fix, e.g. a refused api key, fails the deploy at once. Any other error is recorded, and checked again after a wait that doubles with each error in a row. The deploy fails after DEPLOY_MAX_ATTEMPTS checks.

Parameters:

deployment_id (str) – The id of the deploy that the task runs.

Return type:

int | None

Returns:

The seconds until the next check, or None if the deploy has ended.

destroy()[source]

Delete the database and all of its data.

Raises:

VectorstoreServiceError – if deletionProtection is enabled.

Return type:

None

property embeddings: Embeddings

The vectorstore’s embeddings model, created when it is first used.

ensure_api_key()[source]

The Secret with a self-hosted database’s API key, created with a random key the first time.

Return type:

Secret

fail_deployment(message)[source]

End the vectorstore’s deploy, failed.

Parameters:

message (str) – Why, for a person.

Return type:

None

find_document(reference)[source]

Find one of the vectorstore’s documents, by its id, or its name.

Parameters:

reference (str) – The document’s id, or its name, e.g. a file name or url.

Return type:

VectorstoreDocument

Returns:

The document.

Raises:

VectorstoreServiceError – If no document, or more than one, has that name.

finish_deployment()[source]

End the vectorstore’s deploy, if one is in progress, e.g. when it is undeployed.

Return type:

None

load_document(document)[source]

Split, embed and load a document’s chunks, replacing any that it had.

Return type:

int

Returns:

the number of chunks.

maintain(now=None)[source]

The scheduled maintenance of a ready database.

Refresh its status and statistics, take a snapshot if one is due, prune old snapshots, and return the documents whose task was lost, so that the caller can queue them again.

Return type:

dict[str, Any]

Returns:

what was done.

provision()[source]

Create the database’s infrastructure, without waiting for it, and record where it is reached.

Return type:

None

prune_snapshots(retention=None)[source]

Delete the oldest snapshots beyond the retention.

Failed snapshots are removed too.

Return type:

int

queue_delete()[source]

Delete the vectorstore: at once if it was never deployed, else by queuing delete_vectorstore().

The manifest broker’s delete and the console’s delete call it. A deployed vectorstore is kept, deleting, with the message VectorstoreQueuedMessage.DELETE, until the infrastructure worker has destroyed its database (delete()), so that a failure leaves it to delete again. One that was never deployed has no database, and is deleted now, with its api key Secret.

Return type:

bool

Returns:

True if it was deleted now, False if its deletion was queued.

Raises:

VectorstoreServiceError – If deletionProtection is enabled.

static queue_loads(documents)[source]

Queue the Celery task that loads each document.

Parameters:

documents (Iterable[VectorstoreDocument]) – The documents.

Return type:

int

Returns:

The number queued.

queue_pending_documents()[source]

Queue the documents that wait to be loaded, e.g. those added before the vectorstore was deployed.

Return type:

int

Returns:

The number queued.

queue_provision()[source]

Queue provision_vectorstore(), which applies a self-hosted server’s changed spec.

The manifest broker’s apply calls it when a deployed self-hosted vectorstore’s spec changes, e.g. its cpu or memory. The web server doesn’t write to the cluster (ADR-038, phase 3, issue #1080): the infrastructure worker does. The status is unchanged.

Return type:

None

queue_undeploy()[source]

End the deploy in progress, if any, and queue undeploy_vectorstore().

The manifest broker’s undeploy and the api’s undeploy view call it. The infrastructure worker stops serving (undeploy()), e.g. deletes a self-hosted server, keeping its volume.

Return type:

None

reconcile(take_over=True)[source]

Check a deployed database, record its status, conditions and statistics, and create a missing index.

Celery Beat runs it every few minutes, as a safety net. It leaves a deploy in progress to the deploy task, unless the deploy lost its task, and then it takes the deploy over. An error marks the vectorstore failed, until a later check succeeds. It never raises.

Parameters:

take_over (bool) – Whether it may take a stalled deploy over, which creates the database’s cluster resources. True for Beat’s check, which runs on the infrastructure worker. The api’s status view passes False: the app’s Kubernetes Role is read-only (ADR-038, phase 3), so it observes the deploy and leaves its provisioning to Beat’s next check.

Return type:

str

Returns:

the status.

record_error(error)[source]

Record an error of the vectorstore’s deploy, and the condition that it shows, if any.

Parameters:

error (Exception) – The error.

Return type:

None

refresh_stats()[source]

Read the database’s statistics, and save them, and the vector count, on the vectorstore.

Return type:

dict[str, Any]

Returns:

The statistics.

remove_document(document)[source]

Mark a document deleting, and queue the Celery task that removes it and its chunks.

Parameters:

document (VectorstoreDocument) – The document.

Return type:

VectorstoreDocument

Returns:

The document, deleting.

require_ready()[source]

Require that the vectorstore is ready and active.

Raises:

VectorstoreServiceError – If it is not.

Return type:

None

restore(snapshot)[source]

Replace the database’s data with a snapshot’s.

Documents are not changed: those loaded after the snapshot are no longer in the database.

Return type:

None

save_deployment()[source]

Save the progress of the vectorstore’s deploy.

Return type:

None

search(query, k=4, search_type='similarity', score_threshold=None, fetch_k=None, lambda_mult=None, metadata_filter=None)[source]

Find the chunks closest in meaning to a query.

See SmarterVectorstoreBackend.search().

Return type:

list[SearchResult]

set_status(status, message='')[source]

Record the vectorstore’s status, and send vectorstore_status_changed if it changed.

Parameters:
  • status (str) – The new status.

  • message (str) – Why, or an empty string.

Return type:

None

snapshot(scheduled=False)[source]

Take a Qdrant snapshot, or a Pinecone backup.

Return type:

VectorstoreSnapshot

snapshot_due(now=None)[source]

Whether a scheduled snapshot is due: snapshots are enabled, and none was taken within the interval.

Parameters:

now – The time, or None for now.

Return type:

bool

Returns:

True if one is due.

start_deployment()[source]

Begin a deploy: check what can be checked at once, and record a new deploy, provisioning.

It doesn’t create anything: deployment_step() does, in the deploy task. It checks that the vectorstore is active, and that its database accepts its api key, so that a refused key is an error now, rather than a deploy that fails minutes later. A database that can’t be reached isn’t an error yet: the deploy task tries again.

Return type:

VectorstoreDeploymentState

Returns:

The new deploy’s state.

Raises:
  • VectorstoreServiceError – If the vectorstore is inactive.

  • VectorStoreBackendRejectedError – If the database refuses its api key, which fails the deploy.

stuck_documents(now=None)[source]

Documents whose Celery task was lost: pending, loading or deleting for a while.

text_splitter()[source]

Return the text splitter of the spec’s chunkSize and chunkOverlap, or the defaults.

Return type:

RecursiveCharacterTextSplitter

undeploy()[source]

Stop serving.

A self-hosted server is deleted, but its volume and data are kept. The work of undeploy_vectorstore(), which queue_undeploy() queues.

Return type:

None

exception smarter.apps.vectorstore.service.VectorstoreServiceError(message='')[source]

Bases: SmarterException

A vectorstore operation is not possible, e.g. destroying a protected database.