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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
18 changes: 11 additions & 7 deletions src/basic_memory/repository/postgres_search_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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()
18 changes: 12 additions & 6 deletions src/basic_memory/repository/search_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand All @@ -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:
Expand Down
24 changes: 15 additions & 9 deletions src/basic_memory/repository/search_repository_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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.
Expand Down
12 changes: 8 additions & 4 deletions src/basic_memory/repository/sqlite_search_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
27 changes: 19 additions & 8 deletions src/basic_memory/services/search_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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} "
Expand Down Expand Up @@ -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(
Expand All @@ -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
Expand Down Expand Up @@ -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."""
Expand Down
Loading
Loading