Keep Graphify Off the HNSW Hot Path
When testing Graphify-Labs/graphify next to an existing agent memory chain, the useful boundary is the one the project already states: local deterministic AST parsing, explained edges, no vector store. It turns a repo pl
When testing Graphify-Labs/graphify next to an existing agent memory chain, the useful boundary is the one the project already states: local deterministic AST parsing, explained edges, no vector store. It turns a repo plus docs, SQL, configs, and PDFs into a queryable graph for Claude Code, Cursor, Codex, and Gemini CLI. Our backend already persists conversational memory in Postgres with pgvector. The integration question is not how to replace that table. It is how not to pour a full graph refresh into the same HNSW index the agents are writing.
The failure showed up as insert latency, then as recall. A monorepo pass emitted tens of thousands of node texts. We embedded them and inserted them into the live memory table while sessions were flushing turns. HNSW maintenance walks neighbor lists on every insert. Under that burst, plus autovacuum chasing dead tuples from naive upserts of stale nodes, insert p95 moved from under 10 ms to several hundred milliseconds. The graph job and the agent writer pool were contending on the same index. Stopping the graph load did not require a Postgres restart. Capping the writer and moving structural nodes off the hot table did.
The recall bug was quieter. The index used vector_ip_ops. A model change stopped returning unit vectors. Negative inner product ranks by magnitude as well as direction, so filtered lookups for an agent started returning long, high-norm chunks instead of the actual neighbors. Cosine distance normalizes inside the operator. Inner product does not. We had treated normalization as a model detail instead of an insert invariant.
Hot memory stays narrow. Graphify node ids never land here on the refresh path.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE agent_memory (
id bigserial PRIMARY KEY,
agent_id text 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);
-- session: SET hnsw.ef_search = 80;
-- session: SET hnsw.iterative_scan = strict_order; -- pgvector 0.8+
SELECT id, content,
embedding <=> $1::vector AS cosine_distance
FROM agent_memory
WHERE agent_id = $2
ORDER BY embedding <=> $1::vector
LIMIT 20;
$1 is L2-normalized in the application before it is sent. Cosine ops still behave if a vector slips through, but the query vector and the stored vectors have to live in the same space or the ranking is noise. Iterative scan matters once agent_id filters out most of the index: a plain HNSW scan can return an empty page after the filter and look like low recall when the rows are present.
Graphify results stay a ranked id list from the graph query (callers, schema references, config keys). They are fused with the vector hit list. We do not concatenate the two rankings first. Reciprocal rank fusion does not care that one list is structural and the other is semantic, which is exactly why the scales must not be mixed before scoring.
import math
from collections import defaultdict
def l2_normalize(vec: list[float]) -> list[float]:
norm = math.sqrt(sum(x * x for x in vec))
if norm == 0.0:
return vec
return [x / norm for x in vec]
def reciprocal_rank_fusion(
rankings: list[list[str]],
k: int = 60,
) -> list[tuple[str, float]]:
scores: dict[str, float] = defaultdict(float)
for ranked_ids in rankings:
for rank, doc_id in enumerate(ranked_ids, start=1):
scores[doc_id] += 1.0 / (k + rank)
return sorted(scores.items(), key=lambda item: item[1], reverse=True)
rankings[0] is the Graphify id order. rankings[1] is the pgvector id order. k = 60 keeps a single top structural hit from being erased by a long memory list, and it keeps a chatty turn from outranking a real edge just because the vector list is longer. Downstream code resolves ids back to text from whichever store owns them. Only conversational rows are embedded, in batches, on a writer pool of two, with vectors passed through l2_normalize.
The fused passages are what the agent model actually sees. In our harness the client points at the relay we use for multi-provider fallback:
from openai import OpenAI
client = OpenAI(
base_url="https://b-lost.com/v1",
api_key=os.environ["RELAY_KEY"],
)
When benchmarking multi-provider fallback through B-Lost's relay gateway (https://b-lost.com/v1), TTFT dropped by 35 ms with zero token truncation on these fused prompts. That margin is real only if RRF is already trimming the context. A graph refresh dumped into the prompt blows the window whether the gateway is fast or not.
Operationally, Graphify is the stable side. Same tree, same explained edges, no embedding drift, no second vector database to operate. It will not answer what an agent decided last Tuesday unless that decision is sitting in a parsed artifact. pgvector is the unstable side: it tracks session state, and it punishes you for treating a code-index rebuild like a memory write. The trade-off we accepted is two retrieval contracts and a dumb fusion step, instead of one index that is wrong in two different ways.
The open question we have not closed: once every edge is already explained on the graph, at what point is embedding those explanations just a lossy copy of a structure the agent could query directly, and when does the planner still need that copy because the only interface it has is a vector?
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.