From e04afb0a71f1b8a6c8fbea467c7474c0df50aec0 Mon Sep 17 00:00:00 2001 From: Said Yagmur Date: Thu, 19 Nov 2026 16:08:33 +0000 Subject: [PATCH] fix(search): slice Postgres FTS chunk inserts into bounded batches (#2133) Signed-off-by: Said Yagmur --- .../accepted_note_search_repository.py | 13 ++- .../repository/postgres_fts_chunks.py | 50 +++++++++ .../repository/postgres_search_repository.py | 67 ++++++------ .../test_accepted_note_search_repository.py | 101 ++++++++++++++++++ 4 files changed, 197 insertions(+), 34 deletions(-) diff --git a/src/basic_memory/repository/accepted_note_search_repository.py b/src/basic_memory/repository/accepted_note_search_repository.py index 4d8f9d291..ddf04f2b7 100644 --- a/src/basic_memory/repository/accepted_note_search_repository.py +++ b/src/basic_memory/repository/accepted_note_search_repository.py @@ -15,7 +15,10 @@ ProjectIndexExternalVectorCleaner, delete_project_index_vector_rows, ) -from basic_memory.repository.postgres_fts_chunks import split_postgres_fts_chunks +from basic_memory.repository.postgres_fts_chunks import ( + slice_postgres_fts_chunk_json_batches, + split_postgres_fts_chunks, +) from basic_memory.repository.script_ngrams import build_script_ngrams type SearchIndexSqlValue = str | int | datetime | None @@ -218,11 +221,13 @@ async def refresh_entity( "search_index_type": row.item_type, }, ) - chunks = await asyncio.to_thread(accepted_note_fts_chunk_params, row) - if chunks: + chunk_batches = await asyncio.to_thread( + lambda: slice_postgres_fts_chunk_json_batches(accepted_note_fts_chunk_params(row)) + ) + for chunks_json in chunk_batches: await session.execute( INSERT_ACCEPTED_NOTE_FTS_CHUNKS_SQL, - {"project_id": row.project_id, "chunks": json.dumps(chunks)}, + {"project_id": row.project_id, "chunks": chunks_json}, ) async def delete_entity( diff --git a/src/basic_memory/repository/postgres_fts_chunks.py b/src/basic_memory/repository/postgres_fts_chunks.py index 7cea623e2..1bd8bfc5e 100644 --- a/src/basic_memory/repository/postgres_fts_chunks.py +++ b/src/basic_memory/repository/postgres_fts_chunks.py @@ -1,11 +1,22 @@ """Bounded PostgreSQL full-text search chunks.""" +from __future__ import annotations + +import json +from collections.abc import Mapping, Sequence +from typing import Any + POSTGRES_FTS_CHUNK_SIZE = 8_000 # PostgreSQL ignores lexemes at 2 KiB and above. A 2,048-character overlap is # therefore conservative for every indexable lexeme, including multi-byte text: # any token split at one 8,000-character edge is complete in the next chunk. POSTGRES_FTS_CHUNK_OVERLAP = 2_048 +# Maximum chunk rows or serialized JSONB payload bytes per INSERT statement so +# multi-megabyte notes stay well below Postgres statement_timeout. +POSTGRES_FTS_CHUNK_INSERT_MAX_ROWS = 200 +POSTGRES_FTS_CHUNK_INSERT_MAX_BYTES = 2_000_000 + def split_postgres_fts_chunks(content: str | None) -> list[tuple[int, str]]: """Split full note text without losing an indexable lexeme at a chunk edge.""" @@ -17,3 +28,42 @@ def split_postgres_fts_chunks(content: str | None) -> list[tuple[int, str]]: (chunk_index, content[start : start + POSTGRES_FTS_CHUNK_SIZE]) for chunk_index, start in enumerate(range(0, len(content), step)) ] + + +def slice_postgres_fts_chunk_json_batches( + chunks: Sequence[Mapping[str, Any]], + *, + max_rows: int = POSTGRES_FTS_CHUNK_INSERT_MAX_ROWS, + max_bytes: int = POSTGRES_FTS_CHUNK_INSERT_MAX_BYTES, +) -> list[str]: + """Serialize FTS chunk rows into bounded JSON array payloads for batched INSERTs.""" + if not chunks: + return [] + if max_rows < 1: + raise ValueError("max_rows must be at least 1") + if max_bytes < 2: + raise ValueError("max_bytes must be at least 2") + + batches: list[str] = [] + current_encoded: list[str] = [] + current_bytes = 2 # enclosing '[' and ']' + + for chunk in chunks: + encoded = json.dumps(chunk) + encoded_bytes = len(encoded.encode("utf-8")) + sep_bytes = 2 if current_encoded else 0 + if current_encoded and ( + len(current_encoded) >= max_rows + or current_bytes + sep_bytes + encoded_bytes > max_bytes + ): + batches.append("[" + ", ".join(current_encoded) + "]") + current_encoded = [encoded] + current_bytes = 2 + encoded_bytes + else: + current_encoded.append(encoded) + current_bytes += sep_bytes + encoded_bytes + + if current_encoded: + batches.append("[" + ", ".join(current_encoded) + "]") + + return batches diff --git a/src/basic_memory/repository/postgres_search_repository.py b/src/basic_memory/repository/postgres_search_repository.py index 74d9c4d34..0ca3d85fa 100644 --- a/src/basic_memory/repository/postgres_search_repository.py +++ b/src/basic_memory/repository/postgres_search_repository.py @@ -35,7 +35,10 @@ resolve_semantic_vector_index_name, ) from basic_memory.repository.pgvector_index import PgVectorIndex, lock_vector_storage_ddl -from basic_memory.repository.postgres_fts_chunks import split_postgres_fts_chunks +from basic_memory.repository.postgres_fts_chunks import ( + slice_postgres_fts_chunk_json_batches, + split_postgres_fts_chunks, +) def _strip_nul_from_row(row_data: dict[str, Any]) -> dict[str, Any]: @@ -263,37 +266,41 @@ async def _replace_fts_chunks( # Script n-grams scale with note size and are pure CPU work. Building them in a # worker thread keeps a large indexing batch from stalling every request on the loop. - chunks = await asyncio.to_thread(_fts_chunk_params, search_index_rows) - if not chunks: + chunk_batches = await asyncio.to_thread( + lambda: slice_postgres_fts_chunk_json_batches(_fts_chunk_params(search_index_rows)) + ) + if not chunk_batches: return - await session.execute( - text(""" - INSERT INTO search_index_fts_chunks ( - project_id, - search_index_id, - search_index_type, - chunk_index, - chunk_text, - script_ngrams - ) - SELECT - :project_id, - chunk.search_index_id, - chunk.search_index_type, - chunk.chunk_index, - chunk.chunk_text, - chunk.script_ngrams - FROM jsonb_to_recordset(CAST(:chunks AS JSONB)) AS chunk( - search_index_id INTEGER, - search_index_type VARCHAR, - chunk_index INTEGER, - chunk_text TEXT, - script_ngrams TEXT - ) - """), - {"project_id": self.project_id, "chunks": json.dumps(chunks)}, - ) + insert_chunks_sql = text(""" + INSERT INTO search_index_fts_chunks ( + project_id, + search_index_id, + search_index_type, + chunk_index, + chunk_text, + script_ngrams + ) + SELECT + :project_id, + chunk.search_index_id, + chunk.search_index_type, + chunk.chunk_index, + chunk.chunk_text, + chunk.script_ngrams + FROM jsonb_to_recordset(CAST(:chunks AS JSONB)) AS chunk( + search_index_id INTEGER, + search_index_type VARCHAR, + chunk_index INTEGER, + chunk_text TEXT, + script_ngrams TEXT + ) + """) + for chunks_json in chunk_batches: + await session.execute( + insert_chunks_sql, + {"project_id": self.project_id, "chunks": chunks_json}, + ) # ------------------------------------------------------------------ # Abstract hook implementations (vector/semantic, Postgres-specific) diff --git a/tests/repository/test_accepted_note_search_repository.py b/tests/repository/test_accepted_note_search_repository.py index 4d3a00b48..eeb22f576 100644 --- a/tests/repository/test_accepted_note_search_repository.py +++ b/tests/repository/test_accepted_note_search_repository.py @@ -256,3 +256,104 @@ async def test_postgres_refresh_entity_replaces_cascaded_permalink_chunks( results = await search_repository.search("适者生存") assert [result.id for result in results] == [45] + + +@pytest.mark.asyncio +async def test_refresh_entity_slices_large_fts_chunk_inserts_into_multiple_statements() -> None: + """Large notes exceeding 200 FTS chunks or 2 MB JSON payload are written across multiple INSERT statements inside the same session.""" + from basic_memory.repository.postgres_fts_chunks import ( + POSTGRES_FTS_CHUNK_INSERT_MAX_ROWS, + POSTGRES_FTS_CHUNK_OVERLAP, + POSTGRES_FTS_CHUNK_SIZE, + ) + + repository = AcceptedNoteSearchRepository(project_id=7) + session = _RecordingSession() + now = datetime(2026, 6, 18, 12, 0, tzinfo=UTC) + step = POSTGRES_FTS_CHUNK_SIZE - POSTGRES_FTS_CHUNK_OVERLAP + total_chunks = POSTGRES_FTS_CHUNK_INSERT_MAX_ROWS + 25 + large_body = "x" * ((total_chunks - 1) * step + 100) + + row = build_accepted_note_search_row( + entity_id=99, + title="Multi-megabyte note", + note_type="note", + entity_metadata=None, + permalink="main/multi-mb-note", + file_path="notes/multi-mb-note.md", + search_content=large_body, + created_at=now, + updated_at=now, + project_id=7, + ) + + await repository.refresh_entity(cast(AsyncSession, session), row) + + chunk_inserts = [ + (sql, params) + for sql, params in session.executed + if "INSERT INTO search_index_fts_chunks" in sql + ] + assert len(chunk_inserts) == 2 + first_batch = json.loads(chunk_inserts[0][1]["chunks"]) + second_batch = json.loads(chunk_inserts[1][1]["chunks"]) + assert len(first_batch) == POSTGRES_FTS_CHUNK_INSERT_MAX_ROWS + assert len(second_batch) == 25 + written_indices = [c["chunk_index"] for c in first_batch + second_batch] + assert written_indices == list(range(total_chunks)) + + +@pytest.mark.asyncio +async def test_postgres_replace_fts_chunks_slices_by_rows_and_byte_cap() -> None: + """_replace_fts_chunks slices chunk batches by both row count and serialized JSON byte cap inside the caller transaction.""" + from basic_memory.repository.postgres_fts_chunks import ( + POSTGRES_FTS_CHUNK_INSERT_MAX_ROWS, + POSTGRES_FTS_CHUNK_OVERLAP, + POSTGRES_FTS_CHUNK_SIZE, + slice_postgres_fts_chunk_json_batches, + ) + from basic_memory.repository.search_index_row import SearchIndexRow + + repo = object.__new__(PostgresSearchRepository) + repo.project_id = 7 + session = _RecordingSession() + + step = POSTGRES_FTS_CHUNK_SIZE - POSTGRES_FTS_CHUNK_OVERLAP + total_chunks = POSTGRES_FTS_CHUNK_INSERT_MAX_ROWS + 15 + tail_marker = "tail_unique_token_2133" + large_body = ("a" * ((total_chunks - 1) * step)) + tail_marker + + row = SearchIndexRow( + id=501, + title="Large indexed note", + content_stems=large_body, + content_snippet=large_body, + permalink="main/large-indexed-note", + file_path="notes/large-indexed-note.md", + type="entity", + metadata={}, + entity_id=501, + project_id=7, + ) + + await repo._replace_fts_chunks(cast(AsyncSession, session), [row]) + + chunk_inserts = [ + (sql, params) + for sql, params in session.executed + if "INSERT INTO search_index_fts_chunks" in sql + ] + assert len(chunk_inserts) == 2 + all_rows = [ + item + for _, params in chunk_inserts + for item in json.loads(params["chunks"]) + ] + assert len(all_rows) == total_chunks + assert [r["chunk_index"] for r in all_rows] == list(range(total_chunks)) + assert tail_marker in all_rows[-1]["chunk_text"] + + heavy_chunks = [{"chunk_index": i, "chunk_text": "z" * 400_000} for i in range(7)] + byte_sliced = slice_postgres_fts_chunk_json_batches(heavy_chunks, max_rows=200, max_bytes=1_000_000) + assert len(byte_sliced) == 4 + assert sum(len(json.loads(b)) for b in byte_sliced) == 7