fleet-memory/hindsight-api/hindsight_api/engine
Nicolò Boschi 43b3efc494
perf: replace window-function retrieval with UNION ALL + per-bank HNSW indexes (#541)
* perf: replace window-function retrieval with UNION ALL + per-bank HNSW indexes

The previous retrieve_semantic_bm25_combined() used ROW_NUMBER() OVER (PARTITION
BY fact_type ...) which forced a full sequential scan — pgvector cannot use HNSW
indexes when a window function partitions on the same column as the ORDER BY.

Changes:
- retrieval.py: rewrite to UNION ALL of per-fact_type subqueries; each arm has
  its own ORDER BY embedding <=> $1 LIMIT n, enabling partial HNSW index scans.
  Semantic arms over-fetch 5x (min 100) for HNSW approximation; trimmed in Python.
- memory_engine.py: set hnsw.ef_search=200 at pool init (persistent per-connection,
  no per-query SET/RESET overhead).
- bank_utils.py: add create_bank_hnsw_indexes / drop_bank_hnsw_indexes for
  per-(bank_id, fact_type) partial HNSW index lifecycle management.
- fact_storage.py / bank_utils.py: create per-bank indexes on fresh bank insert.
- memory_engine.py delete_bank: drop per-bank indexes via DELETE...RETURNING to
  avoid a separate round-trip.
- Migration a3b4c5d6e7f8: add interim fact_type-only partial indexes.
- Migration d5e6f7a8b9c0: add internal_id UUID UNIQUE to banks, replace
  fact_type-only indexes with per-(bank, fact_type) partial HNSW indexes, drop
  the global idx_memory_units_embedding that competed with them.

Why per-(bank, fact_type) not just per-fact_type:
The idx_memory_units_bank_id B-tree index always wins over fact_type-only partial
indexes when bank_id appears in the WHERE clause. Including bank_id in the partial
index predicate removes the B-tree from consideration and lets the planner choose
HNSW. The global HNSW index must also be dropped to avoid competing for the larger
fact_type partitions (world, observation).

* refactor: collapse two HNSW migrations into one

* refactor: generate bank internal_id in Python before insert

Instead of relying on DEFAULT gen_random_uuid() and RETURNING internal_id,
generate the UUID in application code before the INSERT. This means we
always know the value upfront and can call create_bank_hnsw_indexes
immediately without needing a DB round-trip to retrieve the assigned ID.

Also adds tests for HNSW index lifecycle and retrieve_semantic_bm25_combined.

* fix: correct migration and prevent global HNSW index recreation

Migration fixes:
- Add text() wrappers for raw SQL in d5e6f7a8b9c0 (SQLAlchemy 2.0 compat)
- Drop stale fact_type-only partial indexes (idx_mu_emb_world/observation/experience)
  that may exist from prior migrations on the same DB

migrations.py fix:
- Skip global HNSW index creation when per-bank partial HNSW indexes already
  exist on memory_units (idx_mu_emb_* pattern). Without this, the post-migration
  vector index check detects no %embedding% named index and recreates the global
  idx_memory_units_embedding, which defeats the per-bank index strategy.

Verified with EXPLAIN ANALYZE on 66K-row bank: all three fact_type arms use
their per-bank HNSW index scan (idx_mu_emb_worl/expr/obsv_<uid16>).

* fix: use correct embeddings.encode() in test
2026-03-11 12:09:50 +01:00
..
consolidation fix(consolidation): respect bank mission over ephemeral-state heuristic (#525) 2026-03-09 15:04:36 +01:00
directives feat: revisit mental models, directives and reflections (#179) 2026-01-22 17:13:16 +01:00
parsers Fix Iris parser httpx read timeout for file uploads (#524) 2026-03-09 11:22:44 +01:00
providers fix: normalize named tool_choice to required + filtered tools for OpenAI-compatible providers (#528) 2026-03-09 15:47:51 +01:00
reflect feat: entity labels — optional, free_values, multi_value, UI polish (#450) 2026-03-02 13:05:25 +01:00
retain perf: replace window-function retrieval with UNION ALL + per-bank HNSW indexes (#541) 2026-03-11 12:09:50 +01:00
search perf: replace window-function retrieval with UNION ALL + per-bank HNSW indexes (#541) 2026-03-11 12:09:50 +01:00
storage Fix GCS auth for Workload Identity Federation credentials (#518) 2026-03-07 08:59:51 +01:00
__init__.py feat: extensions (#54) 2025-12-22 11:05:23 +01:00
cross_encoder.py fix: zeroentropy rerank URL missing /v1 prefix and MCP retain async_processing param (#460) 2026-03-02 10:32:01 +01:00
db_budget.py fix: batch queries on recall (#149) 2026-01-13 13:20:22 +01:00
db_utils.py fix: strip null bytes from parsed file content before retain (#535) 2026-03-10 16:24:11 +01:00
embeddings.py fix: pass encoding_format="float" in LiteLLM embedding calls (#434) 2026-02-25 10:32:05 +01:00
entity_resolver.py fix(consolidation): respect bank mission over ephemeral-state heuristic (#525) 2026-03-09 15:04:36 +01:00
interface.py feat: add tags filtering and q description fix for list documents API (#468) 2026-03-02 17:03:16 +01:00
llm_interface.py feat: support Batch API for retain (openai/groq) (#365) 2026-02-16 13:31:50 +01:00
llm_wrapper.py fix(consolidation): respect bank mission over ephemeral-state heuristic (#525) 2026-03-09 15:04:36 +01:00
memory_engine.py perf: replace window-function retrieval with UNION ALL + per-bank HNSW indexes (#541) 2026-03-11 12:09:50 +01:00
operation_metadata.py fix: improve async batch retain with large payloads (#366) 2026-02-16 12:51:42 +01:00
query_analyzer.py fix(performance): improve recall and retain performance on large banks (#469) 2026-03-03 13:35:22 +01:00
response_models.py feat: include source facts in observation recall (#404) 2026-02-19 14:54:19 +01:00
task_backend.py fix: retain async fails if timestamp is set (#251) 2026-01-30 13:04:33 +01:00
utils.py feat: implement hierarchical configuration (system, tenant, bank) (#329) 2026-02-12 13:14:57 +01:00