feat: consolidate memory during idle time instead of at session end
Follow-up to #41 (the shutdown stall). The stall has two halves: when consolidation runs, and what it costs. This is about the first half.
Current behaviour
agent_end only buffers messages; the LLM call happens in session_before_switch and session_shutdown, both awaited. So extraction is paid at the exact moment the user wants to leave, against a prompt of up to 30 conversation pairs (~45 KB), through a spawned pi --print child (1.75 s of boot before the first token).
Proposal: consolidate while the conversation is idle
pi exposes the idle moment directly, so this needs no new machinery:
agent_settled— "Fired after an agent run has fully settled and no automatic retry, compaction, or queued continuation will run" (AgentSettledEvent,agent-session.js:_emitAgentSettled). It isawaited, so the handler must fire-and-forget, not resolve work inside it.ctx.isIdle()/ctx.hasPendingMessages()— cheap guards so a queued turn is never consolidated mid-flight.ctx.modelRegistry.complete(model, { messages }, { maxTokens, signal })— provider-neutral one-shot call from the extension process (model-registry.d.ts, used byexamples/extensions/custom-compaction.ts). Optional: it removes the child process entirely; keepingpi.execneeds a much smaller diff.
Shape
let pushingUserMessages = 0; // monotonic — pendingUserMessages.shift() makes indices lie
let consolidatedThrough = 0; // value of pushingUserMessages at the last successful run
let inFlight = false;
let lastRunAt = 0;
const COOLDOWN_MS = 5 * 60_000;
pi.on("agent_settled", () => {
const fresh = pushingUserMessages - consolidatedThrough;
if (inFlight || fresh < 3 || Date.now() - lastRunAt < COOLDOWN_MS) return;
if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
inFlight = true;
lastRunAt = Date.now();
const through = pushingUserMessages;
void consolidateSession()
.then(() => { consolidatedThrough = Math.max(consolidatedThrough, through); })
.catch(() => {})
.finally(() => { inFlight = false; });
});
session_shutdown then has one job — close the store — plus an optional best-effort tail: consolidate only if pushingUserMessages - consolidatedThrough > 0 and cap the wait (e.g. 1.5 s), so quitting is bounded no matter how slow the provider is.
Things worth deciding
- Cooldown vs. tail loss. One call per idle window with a 5-minute cooldown is ~a handful of calls in a long session. Quitting within the cooldown after the last turn leaves that tail unconsolidated (it is still in the session file, and a resumed session re-seeds
pendingUserMessagesatsession_start, so it is not lost forever — just later). - Prompt size.
buildConsolidationPromptcaps at 30 pairs × (1000 + 500) chars. During a long idle-time session that window starts at the oldest buffered pair, so a background run re-reads stale turns and misses the recent ones. Sending the newest pairs (or only turns sinceconsolidatedThrough) would make idle runs both cheaper and better. store.close()race. If a background run finishes aftersession_shutdownclosed the store,applyExtractedthrows. Needs aclosedflag (or the store left open until the in-flight promise settles).- Visibility. A silent background LLM call should be inspectable — a
ctx.ui.setStatusduring the run, or at least a line inmemory_stats.
Happy to prototype any of this behind a setting (memory.consolidation: "session-end" | "idle" | "manual") if that helps — the measurements in #41 come from a machine with a slow fsync, but the shutdown delay is a fixed ~1.7 s child boot plus provider latency on any disk.
I prototyped this on a local fork (not a PR — it is a behavioural change and you may want it shaped differently). Everything below is measured on Node 26 / pi 1.3.0, on a machine where one fsync costs ~77 ms. The branch is heliar-k/pi-memory@local/perf; happy to send it as a PR if the direction is right.
What it does
agent_settled queue the tail (one commit) → drain it detached
before_switch queue the tail, return
shutdown queue the tail, hand an interrupted job back, return (no close)
pending_consolidation is an outbox keyed per session. A job is claimed per row and deleted in the same transaction that writes its facts, so delivery is at-least-once: a kill mid-run retries it (stale claim after 10 min, or immediately because shutdown releases the claim).
Numbers
| before | after | |
|---|---|---|
| quit with ≥3 messages pending | awaited a child: 3.9 s measured (12 s with a 12 s stand-in child) | 0 children spawned at exit |
| quit during a 12 s drain | would have waited 12 s | 112 ms, job handed back |
pi -p answer → process exit |
3.4 s | 0.3 s |
| consolidation as a function of token spend | one run per session end | one run per 3 new user messages, while idle |
Five things that real-binary testing changed in the design
- Every resumed session re-seeds its history, so the first version queued the whole conversation again on every run — the queue grew one duplicate job per run and each one re-consolidated the same tail. Jobs are now keyed per session and replace the queued tail only when it carries more messages.
- Applying facts and deleting the job must be one transaction. Split, a quit in between left a job whose facts were already written and it was re-consolidated next time. (
withLockhad to become re-entrant, since the write helpers take it themselves.) ctx.sessionIdis empty in 1.3.0 — usesessionManager.getSessionId().pi -pnever exits promptly while the embedding backfill fromsession_starthas a request in flight: pending I/O holds the event loop, measured at ~3 s of tail latency. The backfill now runs intui/rpconly;getEmbedder()still runs everywhere so a broken provider is still reported (#30).store.close()checkpoints the WAL, fsync-bound: 140 ms – 1.5 s on the exit path, for data already durable in the WAL. Dropped the close at shutdown; the next open recovers without checkpointing.- A print/json run exits as the turn ends, so draining there started the child at exit and helped nobody. Draining is
tui/rpconly; other modes leave the tail queued for the next interactive session.
Knock-on effect worth knowing
Consolidation no longer has to be cheap, because nobody waits for it. The first thing that buys is consolidationModel: a stronger model is now affordable, which is exactly Letta's argument for a separate sleep-time agent. That's a settings change, not code.