Inside FalkorDB

The Cypher queries Memspace depends on, the plans FalkorDB runs for them, and the things that bit us. Every query here is in the repo and runs against a sample graph with one command.

FalkorDB Browser · shared_memory_demo
FalkorDB Browser in light mode showing the sample Memspace graph: people, their memories, entities and a shared space.
The sample graph in FalkorDB Browser.

Memspace has no access table, no separate vector database and no job store. All three are the same FalkorDB graph, and this page shows how.

Every query is parameterized: user input is never pasted into Cypher. Line links point at commit 62ef358 of the main repo. Many of these are also runnable files in cypher/.

01One server, two graphs

One FalkorDB server holds two graphs, picked by name. Account profiles live in FALKORDB_GRAPH as User nodes keyed by Clerk ID. Everything else lives in FALKORDB_MEMORY_GRAPH. Profile details and memory content never share labels.

The memory graph has 15 labels, each with a range index and a unique constraint on id, created at startup. These are the ones that matter most:

The Memspace graph model A person authors memories, which have revisions and are about entities. People are members of spaces and memories are shared in spaces. Knowledge claims are supported by memories, based on revisions, and have subject and object knowledge entities. Publications are derived from claims and published in spaces. Search documents index claims and publications. Ontology jobs are supported by memories. Invitations are for spaces. AUTHORED HAS_REVISION SUPPORTED_BY MEMBER_OF SHARED_IN ABOUT SUPPORTED_BY BASED_ON SUBJECT · OBJECT DERIVED_FROM SUBJECT PUBLISHED_IN FOR_SPACE INDEXES INDEXES Person Memory Revision OntologyJob Space Entity KnowledgeClaim Invitation Publication KnowledgeEntity KnowledgeSearchDocument
  • (Person)-[:AUTHORED]->(Memory)-[:HAS_REVISION]->(Revision)
  • (Memory)-[:ABOUT]->(Entity)
  • (Person)-[:MEMBER_OF]->(Space)<-[:SHARED_IN]-(Memory)
  • (KnowledgeClaim)-[:SUPPORTED_BY]->(Memory), -[:BASED_ON]->(Revision)
  • (KnowledgeClaim)-[:SUBJECT|OBJECT]->(KnowledgeEntity)
  • (Publication)-[:DERIVED_FROM]->(KnowledgeClaim), -[:PUBLISHED_IN]->(Space)
  • (KnowledgeSearchDocument)-[:INDEXES]->(KnowledgeClaim|Publication)
  • (OntologyJob)-[:SUPPORTED_BY]->(Memory), (Invitation)-[:FOR_SPACE]->(Space)
The core of the memory graph. Also present: Change records for space activity, Connection, SharingRule, KnowledgeBatch and provisional OntologyPredicate nodes.

02Permissions are a query

You can read a memory if you wrote it, or if an active path connects you to it through a space you actively belong to. This clause is appended to every memory read and to every hop recall makes:

MATCH (m:Memory {id:$id})
OPTIONAL MATCH (m)-[:SHARED_IN {active:true}]->(:Space)
               <-[membership:MEMBER_OF {active:true}]-(:Person {id:$user})
WITH m, count(membership) AS memberships
WHERE m.deletedAt IS NULL AND (m.owner = $user OR memberships > 0)
RETURN m.id AS id, m.authorName AS author, m.text AS text

Here's the plan FalkorDB produces for it, from GRAPH.EXPLAIN on the sample graph. It starts from the id index and walks two edges toward the reader, so the work depends on one memory's connections rather than the size of the graph:

Project
    Filter
        Aggregate
            Apply
                Filter
                    Node By Index Scan | (m:Memory)
                Optional
                    Filter
                        Conditional Traverse | (_anon_1)<-(m:Memory)
                            Filter
                                Conditional Traverse | (_anon_2)-[membership:MEMBER_OF]->(_anon_1:Space)
                                    Argument

Revoking a member sets active:false on one MEMBER_OF edge, and retracting a share does the same on SHARED_IN. Nothing was copied to anyone, so there's nothing to clean up, and the very next read comes back empty. An old invitation link can't switch a revoked edge back on; that takes a new invitation.

03Recall: keywords, then one hop

Recall starts with memories you can read that match the words in your question, then hops one edge to bring back related memories, even ones that share no words with it. Every hop re-applies the permission check.

Hop through a shared entitysrc/memory.ts:254
MATCH (seed:Memory)-[:ABOUT]->(e:Entity)<-[:ABOUT]-(m:Memory)
WHERE seed.id IN $ids AND NOT m.id IN $ids
WITH DISTINCT m, e
OPTIONAL MATCH (m)-[:SHARED_IN {active:true}]->(:Space)
               <-[membership:MEMBER_OF {active:true}]-(:Person {id:$user})
WITH m, e, count(membership) AS memberships
WHERE m.deletedAt IS NULL AND (m.owner = $user OR memberships > 0)
RETURN DISTINCT m.id AS id, m.text AS text, e.name AS connectedThrough

A second hop runs the same way through SHARED_IN, pulling in what teammates shared next to your results. Each result carries the name of what connected it, so your assistant can say "connected through Loop" instead of guessing why it showed up.

In the sample graph, searching "launch" as Pranav returns the launch note, and the entity hop adds "Apollo budget is approved" and the pricing review, neither of which contains the word.

Structured facts are searched two ways at once, and both happen in FalkorDB. Each person's private facts, and each space's shared facts, get their own label of the form KS_<hash of scope and embedding model> with its own indexes:

CREATE FULLTEXT INDEX FOR (d:KS_3f7f782c…) ON (d.text)
CREATE VECTOR INDEX FOR (d:KS_3f7f782c…) ON (d.embedding)
  OPTIONS {dimension:768, similarityFunction:'cosine', M:16, efConstruction:200, efRuntime:100}

Splitting by scope means other people's vectors never take your nearest-neighbour slots, and switching embedding models starts a fresh index instead of mixing vectors. Embeddings are Gemini Embedding 2 at 768 dimensions. A fact whose text hasn't changed is never embedded twice.

Vector search, guarded by the same rulessrc/knowledge-search.ts:261
CALL db.idx.vector.queryNodes($label, 'embedding', 200, vecf32($vector)) YIELD node, score
MATCH (node)-[:INDEXES]->(c:KnowledgeClaim)-[:SUPPORTED_BY]->(m:Memory)
WHERE c.owner = $user AND c.sourceRevision = m.revision
  AND c.status IN ['active','disputed'] AND m.deletedAt IS NULL
  AND score <= 0.32
RETURN c.payload AS payload, c.status AS status, score AS distance
ORDER BY distance, c.id LIMIT 100

The full-text side uses db.idx.fulltext.queryNodes with the same guard. The two rankings are merged with reciprocal-rank fusion, where each fact scores the sum of 1 / (60 + rank) over the lists it appears in. Then one hop through the top facts' entities brings in neighbours. If fewer than 20 vector hits survive the guard, an exact vec.cosineDistance scan over that scope runs instead, so stale index entries can't crowd out good ones.

768

dimensions per vector, cosine, HNSW with M 16, efConstruction 200, efRuntime 100.

0.32

maximum cosine distance kept. It's a starting heuristic, not a calibrated threshold.

10 of 10

expected sources in the top five on our ten-question check, against 3 of 10 for plain text search. A small fixture, not a benchmark.

05Member linking, in the graph

When a fact is shared into a space, a person it mentions can resolve to a member of that space. The publication's SUBJECT edge then points at one KnowledgeEntity per member. Here's the sample graph in FalkorDB Browser: Pranav wrote "Afshal is leading the Apollo pricing review", Afshal wrote "Afshal is preparing the Apollo pricing deck", and both facts land on the same node.

FalkorDB Browser · table view
FalkorDB Browser table: two rows, one authored by Pranav Janakiraman and one by Afshal Gulam, with the same subjectNode id.
Two authors, one subjectNode.

Membership changes re-run the linking for the whole space. Each publication whose subject or object moved gets rewired in one query:

relinkSpace, abridgedsrc/knowledge.ts:644
MATCH (p:Publication {id:$id}) SET p.payload = $payload
WITH p OPTIONAL MATCH (p)-[r:SUBJECT|OBJECT]->() DELETE r
WITH DISTINCT p
MERGE (subject:KnowledgeEntity {id:$subjectId})
  ON CREATE SET subject.kind = $subjectType, subject.spaceId = $space
MERGE (p)-[:SUBJECT]->(subject)
// …and the same for OBJECT when the fact has one

06Writes that survive retries

Assistants retry. Networks drop. Two assistants sometimes correct the same note at once. Three patterns keep that safe.

Idempotent saves. A memory's ID is a hash of the user and the assistant's idempotency key. A retried remember finds the same node through MERGE. The same key with different content fails the stored request hash and gets a 409 instead of a silent overwrite.

remember, abridgedsrc/memory.ts:205
MERGE (p:Person {id:$user}) SET p.name = $name
MERGE (m:Memory {id:$id})
  ON CREATE SET m.owner = $user, m.text = $text, m.revision = 1, m.requestHash = $hash
WITH p, m WHERE m.deletedAt IS NULL AND m.requestHash = $hash
MERGE (p)-[:AUTHORED]->(m)
MERGE (r:Revision {id:$revisionId}) MERGE (m)-[:HAS_REVISION]->(r)
MERGE (job:OntologyJob {id:$revisionId})
  ON CREATE SET job.owner = $user, job.status = 'pending'
MERGE (job)-[:SUPPORTED_BY]->(m)

Compare-and-swap corrections. revise_memory only applies if the memory is still at the revision the caller read (WHERE m.revision = $expected). The slower assistant gets a 409 and re-reads. The same query rewires ABOUT edges, queues re-extraction and writes a Change into every space the note is shared in.

Exactly-once shares. Sharing and retracting go through a Change node with an applied flag, so a retried share or retraction takes effect once.

07The job queue is a graph too

Extraction jobs are OntologyJob nodes. A worker picks up to three due jobs every five seconds and claims each with a lease in the same query that checks it:

MATCH (m:Memory {id:$memory}) WHERE m.owner = $user AND m.deletedAt IS NULL AND m.revision = $revision
MERGE (j:OntologyJob {id:$id})
  ON CREATE SET j.owner = $user, j.revision = $revision, j.status = 'pending', j.attempts = 0, j.nextAt = 0
MERGE (j)-[:SUPPORTED_BY]->(m)
WITH j WHERE j.status = 'pending' AND (j.leaseUntil IS NULL OR j.leaseUntil < $now)
  AND j.nextAt <= $now AND j.attempts < $max
SET j.lease = $lease, j.leaseUntil = $until, j.attempts = j.attempts + 1
RETURN j.plan AS plan, j.attempts AS attempts

The lease lasts 120 seconds, so two workers can't process the same job. After the model answers, the lease and the memory's revision are checked again before anything is written. Jobs survive restarts because they're just nodes, and after five failed attempts a job is marked failed for its owner to retry.

08What bit us

score is a distance

On the FalkorDB build we pinned, db.idx.vector.queryNodes returns cosine distance in a column named score, so lower is closer. We alias it to distance right away so nobody reads it backwards.

"Variable s not found"

Space search started failing in the sandbox. After CALL db.idx.*.queryNodes, a newer FalkorDB rejected an inline map like (s:Space {id:$space}). The same filter in WHERE works, so all guards after an index call now filter there.

Row order isn't a promise

A newer image returned UNWIND plus MERGE rows in a different order. record_knowledge now returns claim IDs in input order instead of row order, so callers can still match claimIds[i] to claims[i].

Constraints finish later

Unique constraints are created with GRAPH.CONSTRAINT and become active asynchronously. Startup polls db.constraints() until each is OPERATIONAL. The duplicate-index error also changed wording between versions ("already indexed" became "already exists"), so we match both.

The Browser wants plain values

FalkorDB Browser rejects the CYPHER name=value prefix that the server accepts for parameters. Our graph demo prints a second copy of each query with the values written in, ready to paste.

What we'd love next

Filtering inside the vector index, so we wouldn't need a label per scope. And a choice of property for node captions in the Browser, which would make screenshots of real graphs much easier to read.

09Run it yourself

You need Docker and Node 24. This builds a sample graph through the product's own code (four people, one space, six memories, two claims), runs every query above, and prints the results, the GRAPH.EXPLAIN plan and a paste-ready copy for the Browser.

docker run -d --rm --name falkordb-demo -p 6379:6379 -p 3000:3000 falkordb/falkordb:latest
git clone https://github.com/pranavjana/shared-memory-mcp && cd shared-memory-mcp
npm ci && npm run graph:demo -- --keep
# open http://localhost:3000, connect to localhost:6379, pick shared_memory_demo

The same results are checked by test/graph-demo.integration.ts on every run of the graph tests, so the query files can't drift from what this page says. The complete list of queries, including the ones not shown here, is in docs/cypher.md.