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
57 changes: 40 additions & 17 deletions hindsight-api-slim/hindsight_api/engine/memories/pg/reads.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,14 @@
acquires a connection of its own.

**Cursor semantics.** ``scan_memories``'s ``page_token`` is opaque to callers, and
for Postgres it is simply a *numeric offset rendered as a decimal string* against
the scan's fixed ``ORDER BY created_at, id``. An empty token means "start at the
beginning", and an empty token comes back once the walk is exhausted (i.e. the
final short page). An offset cursor is a position rather than a snapshot — exactly
the guarantee :class:`~hindsight_api.engine.memories.base.ScanPage` documents:
here it is a *keyset* — ``<created_at iso>|<id>`` of the last row returned — against
the scan's fixed ``ORDER BY created_at, id``. Each page seeks past that row instead
of counting rows from the start, so a full walk is linear rather than quadratic, and
a row deleted behind the cursor no longer shifts the next page onto a row it skips.
An empty token means "start at the beginning", and an empty token comes back once
the walk is exhausted (i.e. the final short page). A keyset cursor is still a
position rather than a snapshot — exactly the guarantee
:class:`~hindsight_api.engine.memories.base.ScanPage` documents:
rows written or deleted mid-walk can shift later pages, so a scan is
eventually-complete browsing rather than a consistent iterator. ``skip`` is applied
*on top of* the decoded cursor, so a caller that pages with both should pass
Expand Down Expand Up @@ -52,8 +55,8 @@
created_at, updated_at, source_memory_ids, consolidated_at, observation_scopes
"""

# The scan's order. Fixed (created_at, id) like the export loader's, because an
# offset cursor is only meaningful against a total order.
# The scan's order. Fixed (created_at, id) like the export loader's, because a
# keyset cursor is only meaningful against a total order.
_SCAN_ORDER = "ORDER BY created_at, id"


Expand Down Expand Up @@ -133,15 +136,27 @@ def _stored_from_row(row: Any) -> StoredMemory:
)


def _decode_page_token(page_token: str) -> int:
"""Decode the offset cursor. Empty, malformed or negative all mean "start"."""
@dataclass(frozen=True)
class _ScanCursor:
"""The last row a scan page returned: where the next page starts after."""

created_at: datetime
unit_id: uuid.UUID


def _encode_page_token(created_at: datetime, unit_id: uuid.UUID | str) -> str:
return f"{created_at.isoformat()}|{unit_id}"


def _decode_page_token(page_token: str) -> _ScanCursor | None:
"""Decode the keyset cursor. Empty or malformed both mean "start"."""
if not page_token:
return 0
return None
try:
offset = int(page_token)
except (TypeError, ValueError):
return 0
return offset if offset > 0 else 0
created_at, unit_id = page_token.split("|", 1)
return _ScanCursor(created_at=datetime.fromisoformat(created_at), unit_id=uuid.UUID(unit_id))
except ValueError:
return None


async def get_memories(
Expand Down Expand Up @@ -211,7 +226,7 @@ async def scan_memories(
) -> ScanPage:
"""Page through stored memories. A full walk — for browsing and export only.

See the module docstring for the ``page_token`` (offset) cursor semantics.
See the module docstring for the ``page_token`` (keyset) cursor semantics.
"""
if limit is None or limit <= 0:
return ScanPage()
Expand Down Expand Up @@ -248,7 +263,15 @@ async def scan_memories(
group_params = built.params
params.extend(group_params)

offset = _decode_page_token(page_token) + max(int(skip or 0), 0)
# Seek past the last row returned. Spelled out rather than as a row comparison
# `(created_at, id) > (...)` because Oracle runs this same statement and has none.
cursor = _decode_page_token(page_token)
if cursor is not None:
params.extend([cursor.created_at, cursor.unit_id])
at, uid = len(params) - 1, len(params)
where.append(f"(created_at > ${at} OR (created_at = ${at} AND id > ${uid}))")

offset = max(int(skip or 0), 0)
params.append(limit)
limit_idx = len(params)
params.append(offset)
Expand All @@ -274,7 +297,7 @@ async def scan_memories(
memory.semantic_edges = edges.get(memory.unit_id, [])

# A short page means the walk is exhausted, so the cursor goes empty.
next_token = str(offset + len(rows)) if len(rows) == limit else ""
next_token = _encode_page_token(rows[-1]["created_at"], rows[-1]["id"]) if len(rows) == limit else ""
return ScanPage(memories=memories, next_page_token=next_token)


Expand Down
81 changes: 81 additions & 0 deletions hindsight-api-slim/tests/test_scan_memories_keyset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"""The Postgres memory scan pages by keyset, not by offset (#7116).

An offset cursor counts rows from the start on every page: a full walk re-sorts
``offset + limit`` rows per page (quadratic, and deep pages spill to temp files),
and a row deleted behind the cursor shifts the next page so it skips a live row.
"""

import uuid
from collections.abc import Awaitable, Callable
from datetime import datetime, timezone

import pytest

from hindsight_api import RequestContext
from hindsight_api.engine.memories.pg import reads
from hindsight_api.engine.schema import fq_store_table

pytestmark = [pytest.mark.asyncio, pytest.mark.memory_backend_incompatible]


async def _seed(conn, bank_id: str, n: int) -> list[str]:
"""``n`` memories sharing one created_at, so only ``id`` orders them.

Raw SQL on purpose: this tests the Postgres scan itself, so the rows are seeded as
bare rows (no embeddings, entities or links) with a created_at tie, the case the
cursor's ``id`` tiebreak must get right."""
same_instant = datetime(2026, 1, 1, tzinfo=timezone.utc)
ids = sorted(uuid.uuid4() for _ in range(n))
for i, unit_id in enumerate(ids):
await conn.execute(
"INSERT INTO memory_units (id, bank_id, text, fact_type, created_at) VALUES ($1, $2, $3, 'world', $4)",
unit_id,
bank_id,
f"fact {i}",
same_instant,
)
return [str(i) for i in ids]


async def _walk(
conn, bank_id: str, *, limit: int, between_pages: Callable[[list[str]], Awaitable[None]] | None = None
) -> list[str]:
seen: list[str] = []
token = ""
while True:
page = await reads.scan_memories(
conn=conn, fq_table=fq_store_table, bank_id=bank_id, limit=limit, page_token=token
)
seen.extend(m.unit_id for m in page.memories)
token = page.next_page_token
if not token:
return seen
if between_pages is not None:
await between_pages(seen)


async def test_full_walk_returns_every_row_once_in_order(memory):
bank_id = f"scan_keyset_{uuid.uuid4().hex[:8]}"
await memory.ensure_bank_profile(bank_id, request_context=RequestContext())
async with memory._pool.acquire() as conn:
ids = await _seed(conn, bank_id, 7)
assert await _walk(conn, bank_id, limit=3) == ids


async def test_row_deleted_behind_the_cursor_does_not_skip_a_live_row(memory):
bank_id = f"scan_keyset_{uuid.uuid4().hex[:8]}"
await memory.ensure_bank_profile(bank_id, request_context=RequestContext())
async with memory._pool.acquire() as conn:
ids = await _seed(conn, bank_id, 6)
deleted: set[str] = set()

async def delete_first_seen(seen: list[str]) -> None:
if not deleted:
deleted.add(seen[0])
# Raw SQL: the race under test is one row vanishing between two pages of a walk,
# and only the row itself must go — not the cleanup a full memory delete runs.
await conn.execute("DELETE FROM memory_units WHERE id = $1", uuid.UUID(seen[0]))

seen = await _walk(conn, bank_id, limit=2, between_pages=delete_first_seen)
# Every row that was alive when the walk passed it is there, exactly once.
assert seen == ids