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, withdeployment_step(), records each condition, retries after errors, and fails the deploy after an error that retrying can’t fix, or too many checks. Seesmarter.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, unlessdeletionProtectionis 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:
objectThe 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.
- 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:
- 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:
- 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.
- 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.
- chunks(document)[source]
A document’s chunks, and their metadata: the document’s, and where the chunk came from.
- 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 ofqueue_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:
- delete_document(document)[source]
Remove a document’s chunks from the database, then the document.
- Return type:
- 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 indeployment, which the manifest’s status shows.- Return type:
- 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_ATTEMPTSchecks.
- destroy()[source]
Delete the database and all of its data.
- Raises:
VectorstoreServiceError – if deletionProtection is enabled.
- Return type:
- 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:
- 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:
- 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:
- load_document(document)[source]
Split, embed and load a document’s chunks, replacing any that it had.
- Return type:
- 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.
- provision()[source]
Create the database’s infrastructure, without waiting for it, and record where it is reached.
- Return type:
- prune_snapshots(retention=None)[source]
Delete the oldest snapshots beyond the retention.
Failed snapshots are removed too.
- Return type:
- queue_delete()[source]
Delete the vectorstore: at once if it was never deployed, else by queuing
delete_vectorstore().The manifest broker’s
deleteand the console’s delete call it. A deployed vectorstore is kept, deleting, with the messageVectorstoreQueuedMessage.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:
- 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:
- 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:
- Returns:
The number queued.
- queue_provision()[source]
Queue
provision_vectorstore(), which applies a self-hosted server’s changed spec.The manifest broker’s
applycalls 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:
- queue_undeploy()[source]
End the deploy in progress, if any, and queue
undeploy_vectorstore().The manifest broker’s
undeployand 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:
- 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:
- Returns:
the status.
- record_error(error)[source]
Record an error of the vectorstore’s deploy, and the condition that it shows, if any.
- refresh_stats()[source]
Read the database’s statistics, and save them, and the vector count, on the vectorstore.
- 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:
- Returns:
The document, deleting.
- require_ready()[source]
Require that the vectorstore is ready and active.
- Raises:
VectorstoreServiceError – If it is not.
- Return type:
- 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:
- 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.
- 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:
- 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:
- 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
chunkSizeandchunkOverlap, 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(), whichqueue_undeploy()queues.- Return type: