Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
1fe5282
feat: add the adapter registry
rpenido Nov 5, 2026
195c577
feat: validate documents against the schema
rpenido Nov 5, 2026
7711ff6
feat: implement upsert and delete
rpenido Nov 5, 2026
dc83a13
fix: reject dotted document keys
rpenido Nov 5, 2026
c68b3fb
feat: implement check_write
rpenido Nov 16, 2026
ba7f1e6
fix: satisfy the test lint
rpenido Nov 24, 2026
5c0d986
refactor: label document errors at the boundary
rpenido Nov 24, 2026
96e2da7
test: cover the changed lines
rpenido Nov 24, 2026
d092882
fix: enforce the document id byte limit
rpenido Nov 25, 2026
8d7bab1
fix: validate object arrays nested in object arrays
rpenido Nov 25, 2026
afb5faa
fix: reject a non-sequence primary keys argument
rpenido Nov 25, 2026
e5494c4
test: cover primary key normalization through delete
rpenido Nov 25, 2026
1e4f2e0
test: drop redundant normalize filter tests
rpenido Nov 25, 2026
1d1bee9
test: drop the duplicate required field test
rpenido Nov 25, 2026
4b3b36c
test: reuse the adapter fake
rpenido Nov 25, 2026
9f98794
fix: enforce the integer field ranges
rpenido Dec 1, 2026
ec2d649
fix: accept a single object per array element
rpenido Dec 1, 2026
d626b66
feat: implement mint_credential
rpenido Nov 25, 2026
5a0ae04
test: fold the mint_credential validation cases
rpenido Nov 25, 2026
1a1b66e
feat: add the shared HTTP transport
rpenido Nov 24, 2026
a26a48c
feat: implement the Meilisearch adapter
rpenido Nov 24, 2026
02f0b82
test: cover the Meilisearch adapter paths
rpenido Nov 24, 2026
679b2c0
feat: mint Meilisearch tenant tokens
rpenido Nov 25, 2026
ece1508
feat: send JSON Lines through the shared transport
blarghmatey Dec 1, 2026
8f12c35
feat: implement the Typesense adapter
blarghmatey Dec 1, 2026
7631831
docs: record the Typesense limits in ADR 0002
blarghmatey Dec 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions docs/decisions/0002-schema-declarations-and-adapter-contract.rst
Original file line number Diff line number Diff line change
Expand Up @@ -173,9 +173,12 @@ absent.

The second is ``Adapter.validate_schema()``, which covers what the first cannot:
capabilities the neutral model allows but this particular adapter cannot
represent. Every adapter implements it. It is a no-op for Meilisearch and
Typesense, and the hook for an adapter with a narrower feature set, which raises
``UnsupportedSchema`` naming the parts it cannot represent.
represent. Every adapter implements it. It is a no-op for Meilisearch, and the
hook for an adapter with a narrower feature set, which raises
``UnsupportedSchema`` naming the parts it cannot represent. Typesense uses it for
two limits: it ranks ``query_by_weights`` into 16 levels, so a 17th searchable
field would lose its declared order, and its adapter reserves the names of the
hidden filter fields described with filters in "Consumers use a small API".

``register_use_case()`` does not call ``validate_schema()``; it validates the
registration object and its index ownership only, so the registry never reads
Expand Down Expand Up @@ -356,6 +359,14 @@ OR. Negation, ranges and field-to-field comparisons are out of scope until a
consumer needs one; adding it extends ``FilterTerm`` rather than the expression
shape.

Typesense's ``:=`` does not compare strings exactly: it compares tokenized
values, so case, punctuation and accents are ignored (``ab`` matches ``a-b``
and ``AB``). Its adapter writes a hidden ``<field>__exact`` companion holding
the SHA-256 digest of each value of a filterable string field, and renders
string filters against the digests. ``id`` is compared exactly and is filtered
directly. The Typesense adapter refuses a filter on a field that is neither
``id`` nor declared ``filterable``, which Meilisearch rejects at the engine.

``mint_credential`` takes a ``CredentialScope`` of tenant filters and a
positive ``expires_in`` lifetime as a ``timedelta``, and returns a
``SearchCredential``. It is derived locally (Meilisearch tenant tokens,
Expand All @@ -364,6 +375,10 @@ converts ``expires_in`` to the engine's absolute expiry (Typesense's Unix
timestamp, Meilisearch's expiry date). For Typesense the key embeds ``query_by``
and ``query_by_weights`` from the schema, and deliberately not ``sort_by``:
embedded parameters cannot be overridden, and the sort is a per-query choice.
A Typesense scoped key cannot name a collection, and one ``search_api_key``
serves every use case on a backend, so every document also carries a hidden
``__index`` digest of its logical index and every key filters on it. A key
minted for one index finds nothing in another.

``SearchCredential`` carries ``url``, ``index_name`` and ``api_key``. A bare key
is not enough for the browser: ``url`` is the backend's ``public_url``, a
Expand Down
95 changes: 86 additions & 9 deletions src/openedx_search/adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,22 @@ class exists so an engine contribution has one place to see the full surface.

from __future__ import annotations

import threading
from abc import ABC, abstractmethod
from collections.abc import Mapping, Sequence
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Any, TypeAlias

from .config import BackendConfig
from .config import BackendConfig, get_backend_config
from .registry import UseCaseRegistration
from .schema import FIELD_NAME_PATTERN, INDEX_NAME_PATTERN, IndexSchema

__all__ = [
"Adapter",
"AdapterError",
"AdapterFactory",
"AdapterNotRegistered",
"CredentialScope",
"Document",
"DocumentBatch",
Expand All @@ -37,6 +40,9 @@ class exists so an engine contribution has one place to see the full surface.
"UnsupportedSchema",
"WriteFailed",
"WriteReceipt",
"clear_adapter_registry",
"get_adapter",
"register_adapter",
]

Document: TypeAlias = Mapping[str, Any]
Expand Down Expand Up @@ -113,6 +119,31 @@ def __post_init__(self) -> None:
FilterExpression: TypeAlias = tuple[FilterGroup, ...]


def normalize_filter_expression(
filters: FilterExpression,
*,
raise_if_empty: bool = False,
) -> tuple[FilterGroup, ...]:
"""
Validate and freeze a sequence of ``FilterGroup`` values.

Raises ``ValueError`` for a string, a non-sequence or a non-group item, and
for an empty sequence when ``raise_if_empty`` is true.
"""
if isinstance(filters, (str, bytes)):
raise ValueError("filters must be a sequence of FilterGroup, not a string")
try:
groups = tuple(filters)
except TypeError as exc:
raise ValueError("filters must be a sequence of FilterGroup") from exc
if not groups and raise_if_empty:
raise ValueError("filters must not be empty")
for group in groups:
if not isinstance(group, FilterGroup):
raise ValueError("filters must contain FilterGroup instances")
return groups


@dataclass(frozen=True)
class CredentialScope:
"""Tenant filters for a scoped frontend credential."""
Expand All @@ -121,13 +152,7 @@ class CredentialScope:

def __post_init__(self) -> None:
"""Validate and freeze the filter groups."""
if isinstance(self.filters, (str, bytes)):
raise ValueError("filters must be a sequence of FilterGroup, not a string")
filters = tuple(self.filters)
for group in filters:
if not isinstance(group, FilterGroup):
raise ValueError("filters must contain FilterGroup instances")
object.__setattr__(self, "filters", filters)
object.__setattr__(self, "filters", normalize_filter_expression(self.filters))


@dataclass(frozen=True)
Expand Down Expand Up @@ -295,3 +320,55 @@ def search(self, query: Any) -> SearchResult:
@abstractmethod
def mint_credential(self, scope: CredentialScope, expires_in: timedelta) -> SearchCredential:
"""Mint a scoped, expiring credential and the endpoint to use it against."""


AdapterFactory: TypeAlias = Callable[[UseCaseRegistration, BackendConfig], Adapter]

_adapter_factories: dict[str, AdapterFactory] = {}
_adapter_lock = threading.RLock()


class AdapterNotRegistered(AdapterError):
"""No adapter is registered for the backend's engine."""


def register_adapter(engine: str, factory: AdapterFactory, *, replace: bool = False) -> None:
"""
Register the adapter factory for an engine.

Raises ``ValueError`` when the engine already has a factory, unless
``replace`` is true.
"""
if not isinstance(engine, str) or not engine:
raise ValueError("engine must be a non-empty string")
if not callable(factory):
raise ValueError("factory must be callable")
with _adapter_lock:
if engine in _adapter_factories and not replace:
raise ValueError(f"an adapter is already registered for engine {engine!r}")
_adapter_factories[engine] = factory


def get_adapter(
registration: UseCaseRegistration,
backend: BackendConfig | None = None,
) -> Adapter:
"""
Build the adapter for a registration and its resolved backend.

Raises ``AdapterNotRegistered`` when the backend's engine has no factory.
"""
backend = backend or get_backend_config(registration.use_case)
factory = _adapter_factories.get(backend.engine)
if factory is None:
raise AdapterNotRegistered(
f"no adapter is registered for engine {backend.engine!r}; "
"register one with register_adapter()"
)
return factory(registration, backend)


def clear_adapter_registry() -> None:
"""Remove every adapter factory. Intended for tests and process shutdown."""
with _adapter_lock:
_adapter_factories.clear()
67 changes: 45 additions & 22 deletions src/openedx_search/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@
Consumer-facing API for openedx-search.

ADR 0002, Decision 4: consumers use this module rather than talking to an
adapter. The functions resolve the registration and backend internally. The
registry helpers in ``openedx_search.registry`` are not part of this surface.

These functions are currently signatures and contracts only; the
implementations land with the engine adapters.
adapter. The functions resolve the registration, validate the input and delegate
to the adapter for the configured backend. The registry helpers in
``openedx_search.registry`` are not part of this surface.
"""

from __future__ import annotations
Expand All @@ -25,11 +23,16 @@
SearchCredential,
SearchResult,
WriteReceipt,
get_adapter,
normalize_filter_expression,
)
from .documents import DocumentError, validate_documents
from .registry import get_registration
from .schema import document_id_from_key, validate_document_id

__all__ = [
"CredentialScope",
"DocumentError",
"DocumentSource",
"RebuildInProgress",
"RebuildResult",
Expand Down Expand Up @@ -62,18 +65,20 @@ def upsert(use_case: str, documents: DocumentBatch) -> WriteReceipt:
"""
Submit one bounded batch of documents for upsert.

``documents`` is a sequence, not a one-shot iterator, because a same-version
reindex in progress submits the same batch to both the live index and the
target. The returned receipt covers the live index; the reindex confirms the
target's copy before it swaps.
``documents`` is a sequence, not a one-shot iterator. Every document is
validated against the registration's schema before it reaches the adapter,
so both engines accept and reject the same documents.

During a same-version reindex the batch is also submitted to the rebuild
target. A failure in either submission is raised to the caller. The caller
may retry with the same batch, since the operation is an upsert. A target
with a different schema version is a migration, whose writers are stopped;
submitting to it raises ``SchemaVersionMismatch``.
The rebuild target dual-write lands with the rebuild lifecycle. Until then
the batch is submitted to the live index only.
"""
raise NotImplementedError("upsert is implemented with the engine adapters") # pragma: no cover
registration = get_registration(use_case)
if isinstance(documents, (str, bytes)) or not isinstance(documents, Sequence):
raise ValueError("documents must be a sequence of mappings")
if not documents:
raise ValueError("documents must not be empty")
validate_documents(registration.schema, documents)
return get_adapter(registration).upsert(documents)


def _normalize_primary_keys(
Expand All @@ -84,6 +89,8 @@ def _normalize_primary_keys(
return None
if isinstance(primary_keys, str):
return (validate_document_id(primary_keys),)
if isinstance(primary_keys, (bytes, bytearray)) or not isinstance(primary_keys, Sequence):
raise ValueError("primary_keys must be a string or a sequence of strings")
keys = tuple(primary_keys)
if not keys:
raise ValueError("primary_keys must not be empty")
Expand All @@ -105,11 +112,19 @@ def delete(
filter expression used by search, never a raw engine string.

Exactly one of ``primary_keys`` and ``filter`` is required, and neither may
be empty, so a bare call cannot empty an index. During a same-version
reindex the delete is also submitted to the target; a target with a
different version raises ``SchemaVersionMismatch``.
be empty, so a bare call cannot empty an index. The rebuild target
dual-write lands with the rebuild lifecycle.
"""
raise NotImplementedError("delete is implemented with the engine adapters") # pragma: no cover
registration = get_registration(use_case)
keys = _normalize_primary_keys(primary_keys)
expression = (
None
if filter is None
else normalize_filter_expression(filter, raise_if_empty=True)
)
if (keys is None) == (expression is None):
raise ValueError("exactly one of primary_keys and filter is required")
return get_adapter(registration).delete(primary_keys=keys, filter=expression)


def check_write(use_case: str, receipt: WriteReceipt) -> WriteReceipt:
Expand All @@ -121,7 +136,10 @@ def check_write(use_case: str, receipt: WriteReceipt) -> WriteReceipt:
already-complete receipt without a request. The worker calls this until the
receipt is complete and raises when the engine reports a failed write.
"""
raise NotImplementedError("check_write is implemented with the engine adapters") # pragma: no cover
if not isinstance(receipt, WriteReceipt):
raise ValueError("receipt must be a WriteReceipt")
registration = get_registration(use_case)
return get_adapter(registration).check_write(receipt)


def rebuild(use_case: str, document_source: DocumentSource) -> RebuildResult:
Expand Down Expand Up @@ -174,7 +192,7 @@ def search(use_case: str, query: Any) -> SearchResult:
raise NotImplementedError("search is implemented with the engine adapters") # pragma: no cover


def mint_credential( # pylint: disable=unused-argument
def mint_credential(
use_case: str, scope: CredentialScope, expires_in: timedelta
) -> SearchCredential:
"""
Expand All @@ -191,6 +209,11 @@ def mint_credential( # pylint: disable=unused-argument
connection URL, and the index name belongs to the adapter, so the browser
needs all three rather than a bare key.
"""
if not isinstance(scope, CredentialScope):
raise ValueError("scope must be a CredentialScope")
if not isinstance(expires_in, timedelta):
raise ValueError("expires_in must be a timedelta")
if expires_in <= timedelta(0):
raise ValueError("expires_in must be positive")
raise NotImplementedError("mint_credential is implemented with the engine adapters") # pragma: no cover
registration = get_registration(use_case)
return get_adapter(registration).mint_credential(scope, expires_in)
12 changes: 12 additions & 0 deletions src/openedx_search/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,15 @@ class OpenEdxSearchConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "openedx_search"
verbose_name = "Open edX Search"

def ready(self) -> None:
"""Register the engine adapters the library ships."""
# Imported here so the app module stays free of engine code until the
# settings are loaded, and so a consumer cannot import an adapter by
# accident through this module.
# pylint: disable=import-outside-toplevel
from .meilisearch import register as register_meilisearch
from .typesense import register as register_typesense

register_meilisearch()
register_typesense()
Loading