Persistent Memory Beside Agent Skills: HNSW, Filters, and Rank Fusion
The page landed at 03:12. Insert p99 on the memory table had jumped from tens of milliseconds to several seconds, and a PDF skill was citing rows written under a spreadsheet skill. The plans were fine. The lock queue and the geometry were not.
Agent Skills in the public anthropics/skills repository are a procedural layer I integrate from the outside. I do not maintain that repository. A skill is a folder of SKILL.md: YAML frontmatter, instructions, sometimes scripts. The runtime matches the description and loads the body only when the task fits. The folder is stateless. Recall while a skill runs has to live outside the markdown.
I keep skills as the policy and tool surface, and PostgreSQL with pgvector as the semantic memory chain. The skill decides how to act. The memory table decides which prior context is still relevant. Embeddings, locks, and rank math do not belong in SKILL.md.
What actually broke under concurrency
Two failures showed up once we left the single-connection notebook.
Insert latency came first. One HNSW index was fine at low QPS. Around forty concurrent writers, p99 insert time moved from the tens of milliseconds into multiple seconds. Each insert searches for neighbors and rewires graph edges, and that maintenance serialized under load. Autovacuum made it worse: reads that should have been independent queued behind index work. Loading a few thousand rows from one session will never show you this.
Recall came second, and the first diagnosis was wrong. One endpoint returned unit vectors, another raw magnitudes. We blamed cosine for a high-norm bias. True cosine, pgvector's <=>, is invariant to positive scale. The drop tracked raw dot product and negative inner product (<#>), which both reward magnitude.
The fix was separation, not a larger index. Recent writes land in a staging heap with btree filters only. A single merger L2-normalizes, batch-inserts into the HNSW table, and deletes the staged rows. Readers hit the indexed table for durable memory and, for the hot session, union a small exact scan of staging.
Guard the merger with one session advisory lock. A second merger, or a retry after a crash between insert and delete, double-inserts because the only key is a bigserial. Commit both writes together and add a natural unique key before retries are safe. Union on that key under READ COMMITTED.
hnsw.ef_search is a session GUC: reset it on pool return. Do not hold a connection across the embedding call, or you exhaust max_connections while Postgres is idle. Back off on 502 and 503. Do not immediately retry 429. A vector(1536) is about 6 KB before graph bloat, so one merger batches the maintenance the writers used to do inline.
Schema and filtered HNSW search
Embedding width here is 1536. Cosine distance is <=> with vector_cosine_ops. Scope columns stay on a btree index so the planner can cut the set before the graph walk.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE agent_memory (
id bigserial PRIMARY KEY,
agent_id text NOT NULL,
skill_name text NOT NULL,
session_id uuid NOT NULL,
content text NOT NULL,
embedding vector(1536) NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX agent_memory_hnsw
ON agent_memory
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
CREATE INDEX agent_memory_scope
ON agent_memory (agent_id, skill_name, created_at DESC);
hnsw.ef_search defaults to 40, which is often too tight once a filter is applied. Raise it per session instead of rebuilding.
SET hnsw.ef_search = 100;
SELECT id, skill_name, content,
(embedding <=> $1::vector) AS cosine_distance
FROM agent_memory
WHERE agent_id = $2
AND skill_name = $3
AND created_at > now() - interval '30 days'
ORDER BY embedding <=> $1::vector
LIMIT 20;
skill_name is the bridge back to a skill package. When the runtime activates a skill, that name goes into the filter so a PDF skill does not pull rows written under a spreadsheet skill. Session scope stays on the row, not in the skill file. Vectors must be unit length before INSERT. The check belongs next to the write, not in a trigger that surprises the merger. Reject a zero vector there: cosine is undefined on it.
A selective filter can starve HNSW: neighbors come back, then WHERE drops them. A few hundred rows for one skill are cheaper as an exact sort. Higher ef_search only burns CPU and work_mem.
Hybrid rank fusion
Vector search misses exact identifiers: ticket ids, paths, error strings. A lexical list catches those. Reciprocal rank fusion merges the two orders without a fragile linear weight. Both lists must be best-first. k=60 is the usual start; raise it if one list is much longer and starts to dominate.
import math
from typing import Iterable
def l2_normalize(vec: list[float]) -> list[float]:
norm = math.sqrt(sum(x * x for x in vec))
if norm == 0.0:
raise ValueError("zero vector")
return [x / norm for x in vec]
def reciprocal_rank_fusion(
ranked_lists: Iterable[list[dict]],
k: int = 60,
top_n: int = 10,
) -> list[dict]:
scores: dict[str, float] = {}
payloads: dict[str, dict] = {}
for ranked in ranked_lists:
for rank, item in enumerate(ranked, start=1):
key = str(item["id"])
scores[key] = scores.get(key, 0.0) + 1.0 / (k + rank)
payloads[key] = item
ordered = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
return [
{**payloads[i], "rrf_score": score}
for i, score in ordered[:top_n]
]
Fusion reconciles ranks. It does not repair geometry. Do not feed it mixed normalized and raw embeddings and expect recall back. Dedupe ids inside each list, or a repeat inflates the score. A missing id is a broken contract.
When a session outgrows the skill context budget, condensation uses the same client as our multi-provider fallback tests. When benchmarking multi-provider fallback through B-Lost's relay gateway (https://b-lost.com/v1), the summarizer sets that base URL, then the condensed paragraph goes through l2_normalize before the merge job. Skill instructions stay untouched. Only the memory row changes. Keep that call's timeout inside the checkout budget.
The staleness you have to accept
Staging plus one writer adds seconds of staleness for brand-new memories. That is acceptable for long-term recall. A skill that must see the tool result it just wrote should exact-scan staging by session_id instead of waiting on HNSW. m=16 and ef_construction=64 are a recall versus build compromise. If labeled recall is still short after unit vectors and one operator, raise ef_search before you rebuild.
Skills from anthropics/skills remain the right place for procedure and the wrong place for index locks and distance math. Keep SKILL.md declarative, keep the vectors in Postgres, and treat normalization plus insert isolation as part of the memory contract.
The hard call is not m or ef_construction. It is which writes may arrive a few seconds late, and which tool results the same turn must read before the skill answers. Miss that and you either stall on graph maintenance or return a line from a row that has not committed.
How do you decide which memories are allowed to lag the skill that just wrote them?
Top comments (0)