hindsight-api Python process memory grows unbounded in container (~1GB in <1 hour)
Description
The hindsight-api Python process memory grows continuously without releasing, reaching ~1GB RSS within less than 1 hour of uptime. On a Mac mini M4 (24GB RAM) running Docker Desktop, this eventually causes the container to consume all available Docker memory.
Environment
- Hindsight version: v0.5.0 (image
ghcr.io/vectorize-io/hindsight:latest, pulled 2026-04-12) - Host: Mac mini M4, 24GB RAM, macOS Darwin 25.3.0
- Docker Desktop: 7.65GB memory limit
- LLM:
ollama/gemma3:12bviaHINDSIGHT_API_LLM_BASE_URL=http://host.docker.internal:11434/v1 - Integrations: hindsight-openclaw (OpenClaw plugin) + hindsight-memory (Claude Code MCP plugin)
- Banks: ~10 banks, light usage (a few dozen retain/recall operations)
Observed behavior
# After ~50 minutes of uptime:
$ docker exec hindsight ps aux --sort=-rss | head -5
hindsig+ 9 1.8 13.0 8070056 1050224 ? Sl hindsight-api # ~1GB RSS
hindsig+ 90 0.0 0.4 319240 33144 ? Ss postgres # ~33MB (normal)
hindsig+171 0.0 0.8 5171836 71768 ? Sl next-server # ~70MB (normal)
$ docker stats --no-stream hindsight
MEM USAGE / LIMIT MEM %
945.8MiB / 7.653GiB 12.05%
Memory usage only goes up, never comes back down. No heavy workload — just idle with occasional retain/recall from OpenClaw TG bot conversations.
Expected behavior
Memory should stabilize after initial operations, or at least not grow without bound. There should be some form of memory management (cache eviction, periodic GC, configurable memory limits).
Current workaround
Set a hard container memory limit so the OOM killer restarts the container:
docker update --memory=2g --memory-swap=2g hindsight
Combined with --restart unless-stopped, this caps the leak and auto-recovers. But it's a band-aid — each restart loses in-flight operations (related to #991).
Questions
- Is there a known cause for the unbounded growth in
hindsight-api? (e.g., caching, connection pooling, embedding models loaded in memory) - Are there any environment variables or configuration options to limit memory usage? (I found
DB_POOL_MAX_SIZEbut nothing for the API process itself) - Would reducing
HINDSIGHT_API_DB_POOL_MAX_SIZEfrom the default 100 help?
Related
- #898 (OTel bank_id metric label memory leak — fixed in v0.5.0)
- #662 (entity_resolver pending_stats leak — fixed)
- #991 (stale claimed_at not reclaimed after worker crash)
can you upgrade to 0.5.1 and collect some logs if still happening? we added a bunch of diagnostic loggin in 0.5.1
Root-cause investigation on v0.4.20 — consolidation path has unbounded retrieval fan-out
Adding to this thread after spending a day reproducing, diagnosing, and tracing
the memory behaviour on v0.4.20. We believe the observed unbounded growth is
not a classical Python leak — it's unbounded retrieval fan-out inside the
consolidation pipeline that is not controlled by any of the documented
HINDSIGHT_API_CONSOLIDATION_* environment variables. Below is a file:line trace
plus an env-var coverage table that I hope is actionable for a fix.
Environment
hindsight-api+hindsight-api-slimboth pinned at v0.4.20 (pip-installed in a local venv; no upstream patches applied).- DB: PostgreSQL 16 + pgvector 0.8.2.
- Embeddings:
nomic-embed-textvia Ollama on a Mac on the LAN, exposed as OpenAI-compatible. - LLM:
glm-5.1via Ollama Cloud, accessed through a small local reverse proxy that injectsreasoning_effort: "none"into request bodies. - Reranker:
flashrank(CPU-only ONNX). - Host: Linux VM,
hindsight-apias a systemd user service. - Memory cap via systemd drop-in:
MemoryMax=13000M(13 GB hard cap). HINDSIGHT_API_LLM_MAX_CONCURRENT=1.
Banks (memory count distribution)
| bank | memories |
|---|---|
| Bank A | 1740 |
| Bank B | 785 |
| Bank C | 477 |
| Bank D | 283 |
| Bank E | 275 |
| Bank F | 218 |
| Bank G | 175 |
| Bank H | 139 |
| Bank I | 57 |
| Bank J | 53 |
| Bank K | 12 |
Total 4214 memories across 11 banks. The failure is reproducible only when the worker targets Bank A (1740 memories, ~1700 of which are already consolidated into observation-linked facts). Banks B-K consolidate cleanly.
Symptom
After a clean restart with 19 unconsolidated world-type memories in Bank A:
- Worker claims the
consolidationasync_operationrow. - Process RSS step-jumps +2 GB every ~60-90 s during batch processing.
- Hits
MemoryMax=13000Min roughly 4 minutes → OOM-killed by the cgroup. - systemd auto-restarts; the still-pending
consolidationtask is re-claimed on each restart → infinite OOM-restart loop until the task row is cancelled or the worker is prevented from claiming it. - Behaviour is identical on v0.4.20 and v0.5.4 (tested briefly via pip upgrade, then reverted due to schema drift).
Interestingly, total_unconsolidated never visibly decreases in
[CONSOLIDATION] log lines before the OOM, and the proxy only logs 2 LLM
calls in a full 5-minute window before the kill — so the overwhelming
majority of the process's time and memory is spent before the first LLM
call of the batch, i.e. in the recall / candidate-assembly phase.
What we tuned (didn't fix it)
| Env var | Default | We set | Observed effect |
|---|---|---|---|
HINDSIGHT_API_CONSOLIDATION_BATCH_SIZE |
50 | 10 | No measurable drop in peak RSS |
HINDSIGHT_API_CONSOLIDATION_LLM_BATCH_SIZE |
8 | 3 | No measurable drop in peak RSS |
HINDSIGHT_API_CONSOLIDATION_SOURCE_FACTS_MAX_TOKENS |
-1 (unlimited) | 4000 | No measurable drop in peak RSS |
HINDSIGHT_API_CONSOLIDATION_SOURCE_FACTS_MAX_TOKENS_PER_OBSERVATION |
256 | 256 (default) | n/a |
HINDSIGHT_API_LLM_MAX_CONCURRENT |
(default) | 1 | (serialises LLM calls, but the problem is before the LLM call) |
Trace of a consolidation batch
Following the code path from a claimed async_operation row through to LLM
invocation and DB write:
- Worker claims an
operation_type='consolidation'row — handled byworker/poller.py. engine/consolidation/consolidator.py:161run_consolidation_jobentry point.consolidator.py:217-227counts pending memories in the bank.consolidator.py:256-270fetchesCONSOLIDATION_BATCH_SIZE=10pending rows.consolidator.py:278-281groups by tag set.consolidator.py:284-287slices into LLM sub-batches ofLLM_BATCH_SIZE=3.consolidator.py:632_process_memory_batchentry point.consolidator.py:669-679fires 3 parallel_find_related_observationsviaasyncio.gather. Each call invokes:consolidator.py:1021→memory_engine.recall_async(...)without passingbudget=, so the defaultthinking_budget = MID = 300is always applied.memory_engine.py:2475_search_with_retries→engine/search/retrieval.py:533retrieve_all_fact_types_parallel.- For each of 3
fact_types (world,experience,observation):- Semantic arm:
retrieval.py:147computeshnsw_fetch = max(thinking_budget * 5, 100) = 1500rows. - BM25 arm: combined UNION-ALL query fetches rows with full
text+contextcolumns (retrieval.py:177-192). - Graph arm:
LinkExpansionRetriever.retrieve(link_expansion_retrieval.py:105) runsunnest(source_memory_ids)/array_agg/ full scan of rows whosesource_memory_ids && ca.source_ids(:400-435); outerLIMIT $2 = budget = 300bounds Python-side materialisation but the CTE materialises all intermediates in Postgres. - Optional temporal arm.
- Semantic arm:
- RRF merge → cross-encoder rerank up to
RERANKER_MAX_CANDIDATES = 300(memory_engine.py:2984-2992) → MMR → token filter. - Source-fact hydration:
memory_engine.py:3234-3242SELECT id, text, context, … FROM memory_units WHERE id = ANY(...)for every uniquesource_memory_idin the returned observations. The token-budget filter (SOURCE_FACTS_MAX_TOKENS) is applied post-fetch, so memory is only bounded bylen(source_ids_ordered), not by the env var. - LLM call (
consolidator.py:1120). - Embedding regeneration + DB writes (
consolidator.py:874,:1199). - Loop to next sub-batch.
Worst-case per-batch fan-out arithmetic
With defaults + our tuning:
- 3 parallel recalls per batch (
LLM_BATCH_SIZE=3) - ×
WORKER_CONSOLIDATION_MAX_SLOTS = 2concurrent consolidation jobs in the worker pool (default) - × 3 fact_types in
retrieve_all_fact_types_parallel - × 1500-row over-fetch per
hnsw_fetcharm (plus BM25 arm of similar size)
That's up to 27,000 rows materialised into Python per in-flight batch,
each carrying full text + context columns. For the 1740-memory Bank A
where text averages ~2 KB per row, the raw fetch alone is ~50 MB; typical
Python dataclass / dict overhead on retrieval result objects inflates this
5-10× in RSS. Plus the cross-encoder rerank input (up to 300 candidates ×
3 recalls × 2 slots = 1800 items held simultaneously), plus source-fact
hydration fetching all referenced memories before filtering.
This matches the observed +2 GB step-jumps per batch and the 4-minute trajectory to OOM at the 13 GB cap.
Env-var coverage gap
| Allocation site | Scales with | Covered by documented env? |
|---|---|---|
| Initial batch fetch | batch_size | ✅ CONSOLIDATION_BATCH_SIZE |
3 parallel _find_related_observations per batch |
llm_batch_size × worker slots | Partial (LLM_BATCH_SIZE caps fan-out; WORKER_CONSOLIDATION_MAX_SLOTS is undocumented but amplifies 2× by default) |
hnsw_fetch = thinking_budget × 5 per fact_type per recall |
thinking_budget (hardcoded default 300) |
❌ No env — would need patch to consolidator.py:1021 to pass budget=Budget.LOW |
| Cross-encoder rerank input list | RERANKER_MAX_CANDIDATES |
Partial — env exists but undocumented in README |
Graph-arm CTE in LinkExpansionRetriever._expand_observations |
bank size (CTE-side in Postgres) | ❌ No env |
| Source-fact hydration | count of unique source_memory_ids | Partial — SOURCE_FACTS_MAX_TOKENS only filters post-fetch |
Questions for the maintainer
- Is the hardcoded
thinking_budget = MID = 300in the consolidation recall path intentional? A patch toconsolidator.py:1021passingbudget=Budget.LOWwould cut thehnsw_fetchmultiplier from 1500 to roughly thebudget.valuelevel, which on our bank would turn ~27,000 per-batch rows into ~3,000 — a 9× reduction. Happy to open a PR if that direction is welcome. - Would it be reasonable to have source-fact hydration apply
SOURCE_FACTS_MAX_TOKENSas a streaming LIMIT against the hydration query (sort bycreated_at DESCor by reranker score, fetch until cumulative token budget is hit), rather than fetching all then filtering? - Is there any planned documentation of
HINDSIGHT_API_WORKER_CONSOLIDATION_MAX_SLOTS,HINDSIGHT_API_RERANKER_MAX_CANDIDATES, andHINDSIGHT_API_RECALL_CONNECTION_BUDGETin the README? Each of these materially affects the consolidation memory profile but isn't listed in the provider/tuning docs. - Does the
v0.5.1+diagnostic logging added in PR #1017 surface any of the above per-batch allocation counts? If so, we can enable it on a dev clone and share numbers.
Our workaround (current state)
We've disabled the consolidation worker by setting
HINDSIGHT_API_WORKER_CONSOLIDATION_MAX_SLOTS=0 — the poller then computes
consolidation_available = max(0, 0 - in_flight) = 0 and never claims
consolidation tasks. retain, search, recall all continue to work normally.
We also one-time updated existing pending consolidation rows to
completed_at = now() and flipped the stuck async_operation row to
status='failed' with an audit message so the queue stays clean. We'd love to
re-enable consolidation once there's a way to bound its memory — happy to help
validate a fix on our 1740-memory bank.
Thanks for maintaining this project.
Follow-up: why this surfaced now (LLM backend change as trigger)
Brief addendum to my earlier comment. An interesting data point on what changed to make this issue bite now, when the same code + same bank + same operator were fine for months.
Timing
- Before ~2 days ago: LLM backend was a locally-hosted model (dense 12B param), ~22 s per call, GPU-serialized on a single Mac.
- Recently switched: LLM backend to a cloud provider (OpenAI-compat API), 1-5 s per call warm, 3 concurrent slots available from the provider.
Nothing else was touched — same hindsight-api version (v0.4.20), same
embedding provider, same bank contents, same env vars, same postgres, same
host.
Hypothesis
With a slow, locally-GPU-serialized LLM, WORKER_CONSOLIDATION_MAX_SLOTS=2
(the default) didn't produce effective parallelism — both consolidation
slots claimed tasks but the LLM was the bottleneck. Memory allocated for the
recall phase of batch N could release before the LLM returned and batch N+1
started.
With a fast cloud LLM that serves multiple concurrent requests, both consolidation slots now run the retrieval / recall phase simultaneously. That's when the 18,000-27,000-row per-batch fan-out materialises in Python simultaneously across both slots instead of sequentially.
In other words: the consolidation pipeline's memory behaviour is implicitly assuming LLM latency as a serialising bottleneck. That assumption holds for small/slow/local LLMs. It breaks on fast cloud LLMs.
Testable
I haven't validated this on a dev instance. The shape is consistent with everything we observed — OOM window of ~4 minutes that started exactly when we cut over to the cloud LLM, on a bank that had been happy with the local model for weeks. If the maintainer's diagnostic logging from PR #1017 reports "concurrent consolidation batches in flight" or "peak concurrent recall pipelines," that would be the smoking gun.
Implication
Until the fan-out is bounded independent of LLM timing, anyone using a reasonably fast OpenAI-compat backend is going to run into this once a bank grows large enough. A doc note on the concurrency assumption might save the next person the 8-hour debugging day.
Thanks again.
Data point from v0.5.4-slim with split-path recall/consolidation rerank
Running v0.5.4-slim on a Linux VPS (12 GB RAM, 6 cores). Similar unbounded RSS growth confirmed, with a different angle that may help narrow the allocator.
Setup
- Image:
ghcr.io/vectorize-io/hindsight-api:0.5.4-slim - Split-path reranker via a small monkey-patch (
rerank_router_patch.py) that overridescreate_cross_encoder_from_envso:- Recall → Cohere provider pointed at Jina (
HINDSIGHT_API_RERANKER_PROVIDER=cohere,COHERE_BASE_URL=https://api.jina.ai/v1/rerank,MAX_CANDIDATES=75) - Consolidation →
onnx-customlocal CrossEncoder (CONSOLIDATION_RERANKER_PROVIDER=onnx-custom,RERANKER_ONNX_MICRO_BATCH=50,CONSOLIDATION_MAX_CANDIDATES=100)
- Recall → Cohere provider pointed at Jina (
- Routing confirmed in logs:
rerank_route: stage=recall path=coherevsstage=consolidation path=onnx-custom WORKER_CONSOLIDATION_MAX_SLOTS=1,CONSOLIDATION_BATCH_SIZE=50,CONSOLIDATION_LLM_BATCH_SIZE=5- DB: PostgreSQL 16 + pgvector
- LLM:
openrouter/mistral-small-latest
Observations
RSS trajectory from [WORKER_STATS] proc: rss_mb=... over ~2.5 h on a single bank (~4k memories):
| elapsed | slot state | rss_mb |
|---|---|---|
| fresh start | idle | ~900 |
| +45 s (consolidation starts) | consolidation=1/1 |
1013 |
| +75 s | consolidation=1/1 |
2435 |
| +105 s | consolidation=1/1 |
3602 |
| +2 h (mid-batch) | consolidation=1/1 |
4690 |
| +2 h (after op completed) | slots=0/10, consolidation=0/1, my_active: none |
still 4690 |
| restart → +1 h 20 min | idle, no consolidation yet | 999 |
Key observation: RSS does not fall back after the consolidation op finishes and all worker slots are idle. It stays pinned until the container is recreated. This is consistent with ONNXRuntime CPU arena allocator holding session memory across calls — SessionOptions.enable_cpu_mem_arena defaults to True and the arena is per-session, not freed on Session.__del__ reliably on glibc malloc.
The rerank calls themselves are visible and bounded per call:
rerank_route: stage=consolidation path=onnx-custom n=100 scored_in=25-67s
but each call appears to retain some allocation that the next call reuses and adds to, reaching a plateau around 4.5–5 GB on our bank size.
Why this is distinct from the fan-out analysis above
The v0.4.20 trace by @vikramwalia attributes the growth to per-batch retrieval fan-out (~27 k rows materialised per in-flight batch). That matches the step-jumps during active batches. But in our case memory does not release after the batch completes and worker returns to idle, which points to an allocator-retention problem on top of the per-batch fan-out — i.e. there are likely two layered causes:
- Per-batch fan-out (transient spikes during recall assembly) — your analysis
- ONNX session + Python allocator retention (permanent plateau after batches end) — this data point
Reproducer outside split-path
Any setup with HINDSIGHT_API_RERANKER_PROVIDER=onnx-custom doing repeated large rerank calls (MAX_CANDIDATES >= 100) should show the plateau effect. Split-path just makes it easier to see because recall traffic is offloaded to Jina, so the only thing growing ONNX allocations is consolidation.
Suggestions that might help upstream
- Explicit ONNX session lifecycle: release
InferenceSessionafter each consolidation batch (or after N batches), or expose an env likeHINDSIGHT_API_RERANKER_ONNX_RECREATE_EVERY_N_BATCHES. - Default
SessionOptions.enable_cpu_mem_arena=Falsewhenonnx-customruns on CPU in a batch worker context, at the cost of a small per-call allocation overhead. - Document
HINDSIGHT_API_WORKER_CONSOLIDATION_MAX_SLOTS,HINDSIGHT_API_RERANKER_MAX_CANDIDATES,HINDSIGHT_API_CONSOLIDATION_RERANKER_PROVIDER, and the (undocumented) feasibility of split-path, since this is the natural mitigation for the Jina 10 M-token free-tier ceiling once consolidation runs regularly. - A
periodic_gcormalloc_trimhook between consolidation ops would help glibc return heap to the OS.
Happy to test a patch branch against the same bank if useful — can produce before/after RSS curves on a reproducible workload.
1GB is normal on idle - see the hardware section here https://hindsight.vectorize.io/developer/installation#hardware in 0.6.1 we also fixed the memory usage during retain of large documents
feel free to reopen if after upgrading 0.6.1 you see weird mem usage spikes (0.6.1 will be released tomorrow/next few days)