From cf6618960869a31510d875ac3a152c6513738b05 Mon Sep 17 00:00:00 2001 From: phernandez Date: Tue, 29 Sep 2026 13:57:24 -0500 Subject: [PATCH] fix(core): replace an entity's search rows in one transaction SearchService.index_entity_data deleted the entity's search rows with a committed delete, then wrote the replacement rows (and on Postgres their FTS chunks) in a later transaction. A timeout while writing the replacement left an existing note with no search rows. Nothing rebuilds a missing projection: the orphan sweep only removes, and readiness counts files by checksum, so the note stayed unsearchable until edited or reindexed. delete_by_entity_id, index_item and bulk_index_items now accept an optional caller-owned session and leave the commit to scoped_session, and index_entity_data runs the delete and the replacement in one session. A failure rolls back to the previous projection, or to none on a first index. Fixes #1621 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BF4TkgAJpVrgwzrhemkdig Signed-off-by: phernandez --- CHANGELOG.md | 8 + .../repository/postgres_search_repository.py | 18 ++- .../repository/search_repository.py | 18 ++- .../repository/search_repository_base.py | 24 +-- .../repository/sqlite_search_repository.py | 12 +- src/basic_memory/services/search_service.py | 27 +++- .../services/test_search_refresh_atomicity.py | 146 ++++++++++++++++++ 7 files changed, 219 insertions(+), 34 deletions(-) create mode 100644 tests/services/test_search_refresh_atomicity.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 71c3811d7..942459e2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -271,6 +271,14 @@ ### Bug Fixes +- **#1621**: A failed search refresh no longer removes a note from search. Refreshing an + entity deleted its old search rows in one committed transaction and wrote the + replacement rows (and, on Postgres, their full-text chunks) in another, so a timeout + while writing the replacement left an existing note with no search rows, and nothing + rebuilt them until the note was edited or the project re-indexed. The delete and the + replacement now commit together: a failure keeps the previous rows, and a failed first + index leaves nothing partial behind to retry against. + - **#1598**: Under `BASIC_MEMORY_PROJECT_ROOT`, a project name whose permalink contains `/` (such as `Research/2026`) is refused, so every project under a shared root stays a single top-level directory. Cloud stores and purges projects by that top-level prefix, diff --git a/src/basic_memory/repository/postgres_search_repository.py b/src/basic_memory/repository/postgres_search_repository.py index b57b4eb01..b75e91a5b 100644 --- a/src/basic_memory/repository/postgres_search_repository.py +++ b/src/basic_memory/repository/postgres_search_repository.py @@ -134,7 +134,9 @@ async def init_search_index(self): await self._ensure_vector_tables() @override - async def index_item(self, search_index_row: SearchIndexRow) -> None: + async def index_item( + self, search_index_row: SearchIndexRow, session: AsyncSession | None = None + ) -> None: """Index or update a single item using UPSERT. Uses INSERT ... ON CONFLICT to handle race conditions during parallel @@ -144,9 +146,10 @@ async def index_item(self, search_index_row: SearchIndexRow) -> None: For rows with non-null permalinks, a conflict against the same kind is resolved by updating the existing row. For rows with null permalinks, no conflict occurs - on this partial index. + on this partial index. A caller-owned ``session`` keeps the write inside the + caller's transaction. """ - async with db.scoped_session(self.session_maker) as session: + async with db.scoped_session(self.session_maker, session) as session: # Serialize JSON for raw SQL insert_data = search_index_row.to_insert(serialize_json=True) insert_data["project_id"] = self.project_id @@ -195,7 +198,6 @@ async def index_item(self, search_index_row: SearchIndexRow) -> None: ) await self._replace_fts_chunks(session, [search_index_row]) logger.debug(f"indexed row {search_index_row}") - await session.commit() async def _replace_fts_chunks( self, @@ -491,7 +493,9 @@ def _timestamp_now_expr(self) -> str: # ------------------------------------------------------------------ @override - async def bulk_index_items(self, search_index_rows: List[SearchIndexRow]) -> None: + async def bulk_index_items( + self, search_index_rows: List[SearchIndexRow], session: AsyncSession | None = None + ) -> None: """Index multiple items in a single batch operation using UPSERT. Uses INSERT ... ON CONFLICT to handle race conditions during parallel @@ -505,12 +509,13 @@ async def bulk_index_items(self, search_index_rows: List[SearchIndexRow]) -> Non Args: search_index_rows: List of SearchIndexRow objects to index + session: Optional caller-owned session; the caller then owns the commit """ if not search_index_rows: return - async with db.scoped_session(self.session_maker) as session: + async with db.scoped_session(self.session_maker, session) as session: # When using text() raw SQL, always serialize JSON to string # Both SQLite (TEXT) and Postgres (JSONB) accept JSON strings in raw SQL # The database driver/column type will handle conversion @@ -563,4 +568,3 @@ async def bulk_index_items(self, search_index_rows: List[SearchIndexRow]) -> Non ) await self._replace_fts_chunks(session, search_index_rows) logger.debug(f"Bulk indexed {len(search_index_rows)} rows") - await session.commit() diff --git a/src/basic_memory/repository/search_repository.py b/src/basic_memory/repository/search_repository.py index ca4eb0c14..fb554a5f9 100644 --- a/src/basic_memory/repository/search_repository.py +++ b/src/basic_memory/repository/search_repository.py @@ -132,12 +132,16 @@ async def count( """Count indexed content matching the same filters as search.""" ... - async def index_item(self, search_index_row: SearchIndexRow) -> None: - """Index a single item.""" + async def index_item( + self, search_index_row: SearchIndexRow, session: AsyncSession | None = None + ) -> None: + """Index a single item, inside ``session``'s transaction when one is given.""" ... - async def bulk_index_items(self, search_index_rows: List[SearchIndexRow]) -> None: - """Index multiple items in a batch.""" + async def bulk_index_items( + self, search_index_rows: List[SearchIndexRow], session: AsyncSession | None = None + ) -> None: + """Index multiple items in a batch, inside ``session``'s transaction when given.""" ... async def get_entity_search_rows(self, entity_id: int) -> list[SearchIndexRow]: @@ -156,8 +160,10 @@ async def delete_project_search_rows(self) -> None: """Delete every full-text search row owned by this project.""" ... - async def delete_by_entity_id(self, entity_id: int) -> None: - """Delete items by entity ID.""" + async def delete_by_entity_id( + self, entity_id: int, session: AsyncSession | None = None + ) -> None: + """Delete items by entity ID, inside ``session``'s transaction when one is given.""" ... async def purge_stale_search_rows(self) -> int: diff --git a/src/basic_memory/repository/search_repository_base.py b/src/basic_memory/repository/search_repository_base.py index 8935b307d..87cf3c553 100644 --- a/src/basic_memory/repository/search_repository_base.py +++ b/src/basic_memory/repository/search_repository_base.py @@ -867,13 +867,16 @@ async def _finalize_prepared_vector_deletions( async def purge_stale_search_rows(self) -> int: return await purge_stale_search_index_rows(self.session_maker, self.project_id) - async def index_item(self, search_index_row: SearchIndexRow) -> None: + async def index_item( + self, search_index_row: SearchIndexRow, session: AsyncSession | None = None + ) -> None: """Index or update a single item. This implementation is shared across backends as it uses standard SQL INSERT. + A caller-owned ``session`` keeps the write inside the caller's transaction. """ - async with db.scoped_session(self.session_maker) as session: + async with db.scoped_session(self.session_maker, session) as session: # Replace only the row this address owns *for this kind*. Keying the # replacement on the permalink alone let a relation whose authored type # spells an observation's address evict that observation -- silently on @@ -918,9 +921,10 @@ async def index_item(self, search_index_row: SearchIndexRow) -> None: insert_data, ) logger.debug(f"indexed row {search_index_row}") - await session.commit() - async def bulk_index_items(self, search_index_rows: List[SearchIndexRow]) -> None: + async def bulk_index_items( + self, search_index_rows: List[SearchIndexRow], session: AsyncSession | None = None + ) -> None: """Index multiple items in a single batch operation. This implementation is shared across backends as it uses standard SQL INSERT. @@ -930,12 +934,13 @@ async def bulk_index_items(self, search_index_rows: List[SearchIndexRow]) -> Non Args: search_index_rows: List of SearchIndexRow objects to index + session: Optional caller-owned session; the caller then owns the commit """ if not search_index_rows: # pragma: no cover return # pragma: no cover - async with db.scoped_session(self.session_maker) as session: + async with db.scoped_session(self.session_maker, session) as session: # When using text() raw SQL, always serialize JSON to string # Both SQLite (TEXT) and Postgres (JSONB) accept JSON strings in raw SQL # The database driver/column type will handle conversion @@ -970,7 +975,6 @@ async def bulk_index_items(self, search_index_rows: List[SearchIndexRow]) -> Non insert_data_list, ) logger.debug(f"Bulk indexed {len(search_index_rows)} rows") - await session.commit() async def get_entity_search_rows(self, entity_id: int) -> list[SearchIndexRow]: """Return every search projection owned by one entity.""" @@ -1024,19 +1028,21 @@ async def get_entity_physical_chunk_keys(self, entity_id: int) -> set[str] | Non """ ... - async def delete_by_entity_id(self, entity_id: int) -> None: + async def delete_by_entity_id( + self, entity_id: int, session: AsyncSession | None = None + ) -> None: """Delete all search index entries for an entity. This implementation is shared across backends as it uses standard SQL DELETE. + A caller-owned ``session`` keeps the delete inside the caller's transaction. """ - async with db.scoped_session(self.session_maker) as session: + async with db.scoped_session(self.session_maker, session) as session: await session.execute( text( "DELETE FROM search_index WHERE entity_id = :entity_id AND project_id = :project_id" ), {"entity_id": entity_id, "project_id": self.project_id}, ) - await session.commit() async def delete_by_permalink(self, permalink: str, search_item_type: SearchItemType) -> None: """Delete the one search row an address owns for the given row kind. diff --git a/src/basic_memory/repository/sqlite_search_repository.py b/src/basic_memory/repository/sqlite_search_repository.py index 7f50b8df5..40920e91d 100644 --- a/src/basic_memory/repository/sqlite_search_repository.py +++ b/src/basic_memory/repository/sqlite_search_repository.py @@ -421,14 +421,18 @@ def _prepare_window_existing_rows_sql(self, placeholders: str) -> str: # ------------------------------------------------------------------ @override - async def index_item(self, search_index_row: SearchIndexRow) -> None: + async def index_item( + self, search_index_row: SearchIndexRow, session: AsyncSession | None = None + ) -> None: """Index a single row in FTS only. Vector chunks are derived asynchronously via sync_entity_vectors(). """ - await super().index_item(search_index_row) + await super().index_item(search_index_row, session) @override - async def bulk_index_items(self, search_index_rows: List[SearchIndexRow]) -> None: + async def bulk_index_items( + self, search_index_rows: List[SearchIndexRow], session: AsyncSession | None = None + ) -> None: """Index multiple rows in FTS only.""" - await super().bulk_index_items(search_index_rows) + await super().bulk_index_items(search_index_rows, session) diff --git a/src/basic_memory/services/search_service.py b/src/basic_memory/services/search_service.py index 874c0f94e..559f203fa 100644 --- a/src/basic_memory/services/search_service.py +++ b/src/basic_memory/services/search_service.py @@ -641,12 +641,19 @@ async def index_entity_data( # Outcome: storage errors remain visible before any search rows are deleted. replacement_content = await self.file_service.read_entity_content(entity) - await self.repository.delete_by_entity_id(entity_id=entity.id) - - if entity.is_markdown: - await self.index_entity_markdown(entity, replacement_content) - else: - await self.index_entity_file(entity) + # Trigger: every refresh replaces the entity's whole search projection. + # Why: the delete used to commit on its own, so a timeout while writing the + # replacement (Postgres FTS chunks under load, #1621) left an existing note + # with no search rows, and nothing rebuilds a projection that is missing + # rather than stale. + # Outcome: delete and replacement commit together; a failure rolls back to + # the previous projection, or to none on a first index, and stays retryable. + async with db.scoped_session(self.repository.session_maker) as session: + await self.repository.delete_by_entity_id(entity_id=entity.id, session=session) + if entity.is_markdown: + await self.index_entity_markdown(entity, replacement_content, session=session) + else: + await self.index_entity_file(entity, session=session) logger.debug( f"[BackgroundTask] Completed search index for entity_id={entity.id} " @@ -849,6 +856,7 @@ async def _clear_entity_vectors(self, entity_id: int) -> None: async def index_entity_file( self, entity: Entity, + session: AsyncSession | None = None, ) -> None: # Index entity file with no content await self.repository.index_item( @@ -865,19 +873,22 @@ async def index_entity_file( created_at=entity.created_at, updated_at=entity.updated_at, project_id=entity.project_id, - ) + ), + session, ) async def index_entity_markdown( self, entity: Entity, content: str | None = None, + session: AsyncSession | None = None, ) -> None: """Index an entity and all its observations and relations. Args: entity: The entity to index content: Optional pre-loaded content (avoids file read). If None, will read from file. + session: Optional caller-owned session; the caller then owns the commit. Indexing structure: 1. Entities @@ -1006,7 +1017,7 @@ async def index_entity_markdown( ) ) - await self.repository.bulk_index_items(rows_to_index) + await self.repository.bulk_index_items(rows_to_index, session) async def delete_by_permalink(self, permalink: str, search_item_type: SearchItemType): """Delete the search row one permalink owns for the given row kind.""" diff --git a/tests/services/test_search_refresh_atomicity.py b/tests/services/test_search_refresh_atomicity.py new file mode 100644 index 000000000..52b0e33f7 --- /dev/null +++ b/tests/services/test_search_refresh_atomicity.py @@ -0,0 +1,146 @@ +"""An entity's search refresh replaces its projection atomically (#1621). + +The refresh used to commit the delete of the old rows on its own, so a failure while +writing the replacement left an existing note with no search rows at all. +""" + +import pytest +from sqlalchemy import text + +from basic_memory import db +from basic_memory.models import Entity +from basic_memory.repository.postgres_search_repository import PostgresSearchRepository +from basic_memory.schemas.search import SearchQuery + + +class ReplacementFailed(RuntimeError): + """Stands in for the asyncpg timeout seen while writing replacement rows.""" + + +async def _reload(session_maker, entity_repository, entity: Entity) -> Entity: + async with db.scoped_session(session_maker) as session: + reloaded = await entity_repository.find_by_id(session, entity.id) + assert reloaded is not None + return reloaded + + +async def _projection(search_service, entity: Entity) -> list[tuple[str, int, str | None]]: + rows = await search_service.repository.get_entity_search_rows(entity.id) + return sorted((row.type, row.id, row.content_snippet) for row in rows) + + +async def _fts_chunk_count(session_maker, entity: Entity) -> int: + async with db.scoped_session(session_maker) as session: + result = await session.execute( + text( + "SELECT count(*) FROM search_index_fts_chunks c " + "JOIN search_index s ON s.id = c.search_index_id " + "AND s.type = c.search_index_type AND s.project_id = c.project_id " + "WHERE s.entity_id = :entity_id" + ), + {"entity_id": entity.id}, + ) + return int(result.scalar_one()) + + +def _fail_after_replacement_rows(monkeypatch, repository) -> None: + """Write the replacement rows for real, then fail before the transaction commits.""" + original = repository.bulk_index_items + + async def write_then_fail(search_index_rows, session=None): + await original(search_index_rows, session) + raise ReplacementFailed("replacement write timed out") + + monkeypatch.setattr(repository, "bulk_index_items", write_then_fail) + + +@pytest.mark.asyncio +async def test_failed_refresh_keeps_previous_projection( + monkeypatch, search_service, full_entity, entity_repository, session_maker +): + entity = await _reload(session_maker, entity_repository, full_entity) + await search_service.index_entity_data(entity, content="original searchable body") + before = await _projection(search_service, entity) + assert [kind for kind, _, _ in before].count("observation") == 2 + assert [kind for kind, _, _ in before].count("relation") == 2 + + _fail_after_replacement_rows(monkeypatch, search_service.repository) + with pytest.raises(ReplacementFailed): + await search_service.index_entity_data(entity, content="replacement body") + + assert await _projection(search_service, entity) == before + hits = await search_service.search(SearchQuery(text="original searchable")) + assert entity.id in {hit.entity_id for hit in hits} + + +@pytest.mark.asyncio +async def test_first_index_failure_leaves_no_partial_projection( + monkeypatch, search_service, full_entity, entity_repository, session_maker +): + entity = await _reload(session_maker, entity_repository, full_entity) + await search_service.repository.delete_by_entity_id(entity.id) + assert await _projection(search_service, entity) == [] + + _fail_after_replacement_rows(monkeypatch, search_service.repository) + with pytest.raises(ReplacementFailed): + await search_service.index_entity_data(entity, content="first body") + assert await _projection(search_service, entity) == [] + + monkeypatch.undo() + await search_service.index_entity_data(entity, content="first body") + assert len(await _projection(search_service, entity)) == 5 + + +@pytest.mark.asyncio +async def test_successful_refresh_replaces_rows_exactly_once( + search_service, full_entity, entity_repository, observation_repository, session_maker +): + entity = await _reload(session_maker, entity_repository, full_entity) + await search_service.index_entity_data(entity, content="original body") + + dropped = entity.observations[0] + async with db.scoped_session(session_maker) as session: + await observation_repository.delete(session, dropped.id) + entity = await _reload(session_maker, entity_repository, full_entity) + await search_service.index_entity_data(entity, content="replacement body") + + after = await _projection(search_service, entity) + assert ("observation", dropped.id) not in {(kind, row_id) for kind, row_id, _ in after} + assert sorted(kind for kind, _, _ in after) == [ + "entity", + "observation", + "relation", + "relation", + ] + assert [snippet for kind, _, snippet in after if kind == "entity"] == ["replacement body"] + + +@pytest.mark.asyncio +@pytest.mark.postgres +async def test_fts_chunk_failure_keeps_previous_rows_and_chunks( + monkeypatch, db_backend, search_service, full_entity, entity_repository, session_maker +): + if db_backend != "postgres": + pytest.skip("search_index_fts_chunks exists only on PostgreSQL") + repository = search_service.repository + assert isinstance(repository, PostgresSearchRepository) + + entity = await _reload(session_maker, entity_repository, full_entity) + await search_service.index_entity_data(entity, content="original chunked body") + before_rows = await _projection(search_service, entity) + before_chunks = await _fts_chunk_count(session_maker, entity) + assert before_chunks > 0 + + async def chunks_time_out(session, search_index_rows): + raise ReplacementFailed("canceling statement due to statement timeout") + + monkeypatch.setattr(repository, "_replace_fts_chunks", chunks_time_out) + with pytest.raises(ReplacementFailed): + await search_service.index_entity_data(entity, content="replacement body") + + assert await _projection(search_service, entity) == before_rows + assert await _fts_chunk_count(session_maker, entity) == before_chunks + + monkeypatch.undo() + await search_service.index_entity_data(entity, content="replacement body") + assert await _fts_chunk_count(session_maker, entity) == before_chunks