Heuristic:ALwrity ALwrity Debounced Index Save
| Knowledge Sources | |
|---|---|
| Domains | Optimization, Performance, Semantic_Search |
| Last Updated | 2026-10-24 00:00 GMT |
Overview
Coalesce txtai index disk saves using a batch-size and debounce timer to reduce O(N) disk I/O from every task outcome to at most one save per batch or debounce interval.
Description
The `TaskMemoryService` records task outcomes (completed, dismissed, rejected) into a txtai embedding index for semantic deduplication. Naively saving the index to disk on every single upsert is O(N) disk I/O for N outcomes — expensive and unnecessary since the DB `TaskHistory` table is the source of truth and the txtai index is a derived cache that can be rebuilt.
The debounce mechanism coalesces upserts: the in-memory `embeddings.upsert()` happens immediately (fast), but the disk `embeddings.save()` is deferred. A save is triggered when either:
- The pending upsert count reaches `TASK_MEMORY_SAVE_BATCH_SIZE` (default 10), or
- The debounce timer `TASK_MEMORY_SAVE_DEBOUNCE_SEC` (default 5.0s) fires, whichever comes first.
If a burst of upserts arrives, the timer is rescheduled each time, so a burst results in a single save once the burst ends.
Usage
Apply this heuristic when:
- You are writing to a derived cache frequently and the source of truth is elsewhere (DB)
- You see high disk I/O from index saves during bursts of task outcomes
- You need to balance durability (data on disk) against throughput (don't save every write)
The Insight (Rule of Thumb)
- Action: Set `TASK_MEMORY_SAVE_BATCH_SIZE` and `TASK_MEMORY_SAVE_DEBOUNCE_SEC` environment variables.
- Value: `TASK_MEMORY_SAVE_BATCH_SIZE=10` (save after 10 upserts), `TASK_MEMORY_SAVE_DEBOUNCE_SEC=5.0` (save 5s after last upsert).
- Trade-off: Up to `BATCH_SIZE` upserts may be lost if the process crashes before a save fires. The DB `TaskHistory` is the source of truth and can rebuild the index.
- Compatibility: The debounce timer uses `asyncio.call_later`; set `DEBOUNCE_SEC=0` to disable debouncing and save immediately. If no event loop is running, falls back to synchronous immediate save.
Reasoning
The txtai `embeddings.save()` call writes the entire FAISS index to disk. For N task outcomes recorded in quick succession (e.g., a daily workflow batch), this means N full index writes. By coalescing, we reduce this to at most `ceil(N / BATCH_SIZE)` saves, or 1 save if the burst completes within a single debounce window.
The DB `TaskHistory` table stores every task outcome with a `vector_id`. If the in-memory index is lost (process crash before save), it can be fully rebuilt from the DB by re-indexing all `TaskHistory` rows. This makes the debounce safe: the worst case is a re-index on restart, not data loss.