Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 4 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ dependencies = [
"fastembed>=0.7.4",
"sqlite-vec>=0.1.6",
"openai>=1.100.2",
"logfire>=4.19.0",
# The fastapi extra lets read-cache tests instrument the app as production does.
"logfire[fastapi]>=4.19.0",
"psutil>=5.9.0",
# uvloop's C event loop has no self._ready.popleft() codepath, so the
# asyncpg engine-dispose race ("IndexError: pop from an empty deque") that
Expand Down Expand Up @@ -136,7 +137,8 @@ select = ["E4", "E7", "E9", "F"]

[dependency-groups]
dev = [
"logfire>=4.19.0",
# The fastapi extra lets read-cache tests instrument the app as production does.
"logfire[fastapi]>=4.19.0",
"gevent>=24.11.1",
"icecream>=2.1.3",
"pytest>=8.3.4",
Expand Down
8 changes: 5 additions & 3 deletions src/basic_memory/api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,11 @@ async def lifespan(app: FastAPI): # pragma: no cover
)


# fastapi-redis-sdk's hit handler and response capture. Registered before the
# workspace middleware so capture runs inside it; cached routes opt in with
# ``cached_read`` dependencies, and every other response passes straight through.
# fastapi-redis-sdk's response capture. Registered before the workspace middleware
# so capture runs inside it; cached routes opt in with ``cached_read`` dependencies,
# and every other response passes straight through. The SDK's hit handler is
# registered too but never reached: ``ReadCacheRoute`` returns hits instead of
# raising them through the app.
add_redis_caching(app)
# fastapi-redis-sdk reads this module constant on every capture and defaults it
# to 10 MiB. The package re-exports a function named ``cache``, which shadows the
Expand Down
9 changes: 7 additions & 2 deletions src/basic_memory/api/v2/routers/directory_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,12 @@

from basic_memory.read_cache import ReadCacheOperation
from basic_memory.read_cache.policy import READ_CACHE_TTL_SECONDS
from basic_memory.read_cache.routes import cached_read, content_group, project_group
from basic_memory.read_cache.routes import (
ReadCacheRoute,
cached_read,
content_group,
project_group,
)
from basic_memory.deps import DirectoryServiceV2ExternalDep
from basic_memory.schemas.directory import (
DEFAULT_DIRECTORY_PAGE_SIZE,
Expand All @@ -23,7 +28,7 @@
DirectorySortOrder,
)

router = APIRouter(prefix="/directory", tags=["directory-v2"])
router = APIRouter(prefix="/directory", tags=["directory-v2"], route_class=ReadCacheRoute)


@router.get(
Expand Down
3 changes: 2 additions & 1 deletion src/basic_memory/api/v2/routers/knowledge_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
from basic_memory.read_cache import ReadCacheOperation, invalidate_cache
from basic_memory.read_cache.policy import READ_CACHE_TTL_SECONDS
from basic_memory.read_cache.routes import (
ReadCacheRoute,
cached_read,
note_group,
project_group,
Expand Down Expand Up @@ -117,7 +118,7 @@
validate_project_path,
)

router = APIRouter(prefix="/knowledge", tags=["knowledge-v2"])
router = APIRouter(prefix="/knowledge", tags=["knowledge-v2"], route_class=ReadCacheRoute)


def _schedule_post_write_followups(
Expand Down
4 changes: 2 additions & 2 deletions src/basic_memory/api/v2/routers/memory_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from basic_memory import db
from basic_memory.read_cache import ReadCacheOperation
from basic_memory.read_cache.policy import RECENT_ACTIVITY_READ_CACHE_TTL_SECONDS
from basic_memory.read_cache.routes import cached_read, content_group
from basic_memory.read_cache.routes import ReadCacheRoute, cached_read, content_group
from basic_memory.deps import (
ContextServiceV2ExternalDep,
EntityRepositoryV2ExternalDep,
Expand All @@ -35,7 +35,7 @@
from basic_memory.api.v2.utils import to_graph_context

# Note: No prefix here - it's added during registration as /v2/{project_id}/memory
router = APIRouter(tags=["memory"])
router = APIRouter(tags=["memory"], route_class=ReadCacheRoute)


@router.get(
Expand Down
4 changes: 2 additions & 2 deletions src/basic_memory/api/v2/routers/search_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
)
from basic_memory.read_cache import ReadCacheOperation
from basic_memory.read_cache.policy import SEARCH_READ_CACHE_TTL_SECONDS
from basic_memory.read_cache.routes import cached_read, content_group
from basic_memory.read_cache.routes import ReadCacheRoute, cached_read, content_group
from basic_memory.deps import (
EntityServiceV2ExternalDep,
MemoryTimeIndexRepositoryV2ExternalDep,
Expand All @@ -33,7 +33,7 @@
from basic_memory.services.search_guidance import unspaced_script_query_hint

# App registration mounts this router at /v2/projects/{project_id}.
router = APIRouter(tags=["search"])
router = APIRouter(tags=["search"], route_class=ReadCacheRoute)


async def _search_with_exact_count(
Expand Down
176 changes: 118 additions & 58 deletions src/basic_memory/read_cache/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,25 @@
- QUERY support, which the SDK's ``cache()`` bypasses (it caches GET only)
- a no-op when the host has no cache configured

Attach with ``dependencies=[cached_read(...)]``. Route-level dependencies resolve
before the endpoint's own parameters, so a hit returns before any dependency that
opens a database connection.
Attach with ``dependencies=[cached_read(...)]`` on a router built with
``route_class=ReadCacheRoute``. The route class serves the read before FastAPI solves
any dependency, so a hit returns before anything opens a database connection.

The SDK signals a hit by raising ``CacheHitException`` from its dependency. Raised
inside FastAPI's dependency solving, FastAPI instrumentation records it on the
request span as an exception, once per hit. ``ReadCacheRoute`` runs the SDK step
itself and catches the hit before the instrumented route code runs, so a hit is
returned as a response and never raised through the app.
"""

import json
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Mapping
from collections.abc import AsyncGenerator, Awaitable, Callable, Coroutine, Iterator, Mapping
from dataclasses import dataclass
from functools import lru_cache
from typing import Any, override

import logfire
from fastapi import Depends, Request
from fastapi import Depends, Request, Response
from fastapi.dependencies.models import Dependant
from fastapi.routing import APIRoute
from pydantic import TypeAdapter
Expand All @@ -42,6 +48,7 @@
from basic_memory.workspace_context import current_workspace_permalink_context

_PENDING_STATE = "redis_cache_pending"
_SERVED_STATE = "basic_memory_read_cache_served"


@dataclass(frozen=True, slots=True)
Expand All @@ -58,6 +65,8 @@ class ReadCacheScope:

type ReadCacheScopeResolver = Callable[[Request], Awaitable[ReadCacheScope | None]]
type GroupForRequest = Callable[[Request], ReadCacheGroup]
type RouteHandler = Callable[[Request], Coroutine[Any, Any, Response]]
type SdkCacheDependency = Callable[..., AsyncGenerator[None]]


async def _resolve_scope(request: Request) -> ReadCacheScope | None:
Expand Down Expand Up @@ -110,90 +119,140 @@ def method(self) -> str:
return "GET"


def cached_read(
operation: ReadCacheOperation,
*,
group: GroupForRequest,
ttl_seconds: int,
hit_headers: Mapping[str, str] | None = None,
) -> Any:
"""A route dependency that serves and fills the read cache for ``operation``.
@dataclass(frozen=True, slots=True, eq=False)
class _ReadThrough:
"""One route's read cache, served by ``ReadCacheRoute`` around the endpoint.

``hit_headers`` are response headers the route always sets. A hit returns before
the route runs, and fastapi-redis-sdk 0.8.1 does not replay stored headers, so
they are added to every cached response here.
``eq=False`` keeps identity hashing: FastAPI caches dependencies by their
callable, and ``hit_headers`` is a dict.
"""

async def key_builder(request: Request, eviction_group: str = "", prefix: str = "") -> str:
target: _CachedTarget = request.state.basic_memory_read_cache_target
versions = await target.scope.cache.versions(target.project_id, target.group)
key = entry_key(
prefix=target.scope.cache.prefix,
namespace=target.scope.cache.namespace,
project_id=target.project_id,
operation=operation.value,
versions=versions.token,
request_digest=read_cache_request_digest(target.scope.user_key, target.identity),
)
# A miss stores under this key, and invalidation can delete it only if it
# was recorded under the versions it embeds.
request.state.basic_memory_read_cache_entry = _LookedUpEntry(versions=versions, key=key)
return key

sdk_dependency = cache(ttl=ttl_seconds, key_builder=key_builder, cache_prefix="")

async def dependency(request: Request) -> AsyncIterator[None]:
target = await _cached_target(request, group)
operation: ReadCacheOperation
group: GroupForRequest
ttl_seconds: int
hit_headers: Mapping[str, str]
sdk_dependency: SdkCacheDependency

async def __call__(self, request: Request) -> None:
"""Fail fast when the route was built without ``ReadCacheRoute``.

Without the route class nothing would serve or fill the cache, and the
route would silently run uncached.
"""
if not getattr(request.state, _SERVED_STATE, False):
raise TypeError("cached_read routes need a router with route_class=ReadCacheRoute")

async def serve(self, request: Request, endpoint: RouteHandler) -> Response:
"""Answer from the cache, or run the endpoint and let the SDK store its response."""
setattr(request.state, _SERVED_STATE, True)
target = await _cached_target(request, self.group)
if target is None:
yield
return
return await endpoint(request)

request.state.basic_memory_read_cache_target = target
sdk_request = (
_AsGet(request.scope, request.receive) if request.method == "QUERY" else request
)
steps = sdk_dependency(sdk_request, target.scope.cache.client)
cache_hit: CacheHitException | None = None
steps = self.sdk_dependency(sdk_request, target.scope.cache.client)
with logfire.span(
"read_cache.read_through",
operation=operation.value,
operation=self.operation.value,
) as span:
span.set_attributes(
{
"cache.operation": operation.value,
"cache.operation": self.operation.value,
"cache.group": group_kind(target.group),
"cache.configured_ttl_seconds": ttl_seconds,
"cache.configured_ttl_seconds": self.ttl_seconds,
}
)
try:
# Raises the SDK's CacheHitException on a hit; its handler turns
# it into the cached response before the endpoint runs.
await anext(steps)
except CacheHitException as hit:
# The SDK raises on a hit. It is caught here, before FastAPI solves
# dependencies, so instrumentation never records a hit as an error.
span.set_attribute("cache.lookup.outcome", "hit")
hit.response.headers.update(hit_headers or {})
cache_hit = hit
hit.response.headers.update(self.hit_headers)
return hit.response
except ReadCacheUnavailable:
# Version lookup failed: Redis is down, so the database answers
# and nothing is stored under a version we could not read.
span.set_attribute("cache.lookup.outcome", "unavailable")
skip_read_cache_store(request)
target = None
else:
await _track_pending_entry(request, target, ttl_seconds, span)
# The hit is control flow, not a failure. Raise it after the span has
# closed so Logfire does not record every cache hit as an error.
if cache_hit is not None:
raise cache_hit
if target is None:
yield
return
await _track_pending_entry(request, target, ttl_seconds=self.ttl_seconds, span=span)
try:
yield
return await endpoint(request)
finally:
await steps.aclose()

return Depends(dependency)

class ReadCacheRoute(APIRoute):
"""An API route that serves its ``cached_read`` before solving dependencies.

Routes without a ``cached_read`` dependency get FastAPI's handler unchanged.
"""

@override
def get_route_handler(self) -> RouteHandler:
endpoint = super().get_route_handler()
read_through = next(
(
depends.dependency
for depends in self.dependencies
if isinstance(depends.dependency, _ReadThrough)
),
None,
)
if read_through is None:
return endpoint

async def handler(request: Request) -> Response:
return await read_through.serve(request, endpoint)

return handler


def cached_read(
operation: ReadCacheOperation,
*,
group: GroupForRequest,
ttl_seconds: int,
hit_headers: Mapping[str, str] | None = None,
) -> Any:
"""A route dependency that marks the route's reads as cached under ``operation``.

The router must use ``route_class=ReadCacheRoute``, which does the serving.

``hit_headers`` are response headers the route always sets. A hit returns before
the route runs, and fastapi-redis-sdk 0.8.1 does not replay stored headers, so
they are added to every cached response here.
"""

async def key_builder(request: Request, eviction_group: str = "", prefix: str = "") -> str:
target: _CachedTarget = request.state.basic_memory_read_cache_target
versions = await target.scope.cache.versions(target.project_id, target.group)
key = entry_key(
prefix=target.scope.cache.prefix,
namespace=target.scope.cache.namespace,
project_id=target.project_id,
operation=operation.value,
versions=versions.token,
request_digest=read_cache_request_digest(target.scope.user_key, target.identity),
)
# A miss stores under this key, and invalidation can delete it only if it
# was recorded under the versions it embeds.
request.state.basic_memory_read_cache_entry = _LookedUpEntry(versions=versions, key=key)
return key

return Depends(
_ReadThrough(
operation=operation,
group=group,
ttl_seconds=ttl_seconds,
hit_headers=dict(hit_headers or {}),
sdk_dependency=cache(ttl=ttl_seconds, key_builder=key_builder, cache_prefix=""),
)
)


async def _track_pending_entry(
Expand Down Expand Up @@ -362,6 +421,7 @@ def project_group(request: Request) -> ReadCacheGroup:


__all__ = [
"ReadCacheRoute",
"ReadCacheScope",
"ReadCacheScopeResolver",
"cached_read",
Expand Down
Loading
Loading