Sub topic 13
Scoping memory by user and session
This chapter assumes you have the MemoryStore from the long-term memory chapters: write a memory with an embedding, then return the top-k most similar ones. It also assumes you know the conversation buffer and build_prompt. Here you decide who is allowed to see each memory, and you enforce that in code.
Why scope matters
An agent that serves more than one person has a single store and many readers. Similarity search does not know about people. If Bob asks "What food do I like?", the nearest vector might be a memory Alice wrote. The model will then answer Bob using Alice's data.
Scoping is the rule that limits which memories a given request can read and write. It is a data-access problem, so treat it like one. Do not rely on the prompt ("only use facts about the current user"), because the model cannot unsee what you put in its context.
The scopes you will use
Most agents need three levels.
| Scope | Key | Lifetime | Example |
|---|---|---|---|
| Session | `user_id` + `session_id` | One conversation or task | "We are drafting a Lisbon itinerary" |
| User | `user_id` | Across all of that user's sessions | "Prefers vegetarian food" |
| Shared | none (or `org_id`) | Everyone in the group | "Refund policy is 30 days" |
Short-term memory (the buffer) is naturally session-scoped. Long-term memory is usually user-scoped. Some facts start in a session and later get promoted to user scope, for example when the user says "always do this from now on". Shared memory is read-only for most users. Only a trusted process, such as an admin job, should write to it.
This chapter implements the session and user levels. Shared memory is a third value of the same idea, with its own key and its own write rules.
Where the scope values come from
The scope keys must come from your application's authentication layer, never from the model. Consider an agent with a tool recall(user_id, query). A prompt injection in a web page could make the model call recall("bob", ...). The fix is to remove user_id from the tool's arguments and bind it when the tool is created.
def make_recall_tool(store, user_id, session_id):
"""Bind identity at construction time. The model only supplies the query."""
def recall(query):
return [m["text"] for m in store.search(user_id, query,
session_id=session_id)]
return recallThe model sees a tool called recall(query). It has no way to name another user.
A scoped store
The version below extends the earlier store with a session_id field. It also makes scope arguments mandatory, so a missing value fails loudly instead of matching everything.
import math
import time
import zlib
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b) if norm_a and norm_b else 0.0
def toy_embed(text, dims=512):
"""Hashed bag of words. A stand-in for a real embedding model."""
vec = [0.0] * dims
for word in text.lower().split():
vec[zlib.crc32(word.encode()) % dims] += 1.0
return vec
class ScopedMemoryStore:
def __init__(self, embed):
self.embed = embed
self.items = []
def write(self, user_id, text, session_id=None, kind="semantic"):
if not user_id:
raise ValueError("user_id is required")
self.items.append({
"user_id": user_id,
"session_id": session_id, # None means user-wide
"text": text,
"kind": kind,
"vec": self.embed(text),
"created": time.time(),
})
def _visible(self, user_id, session_id):
for m in self.items:
if m["user_id"] != user_id:
continue
if m["session_id"] is None or m["session_id"] == session_id:
yield m
def search(self, user_id, query, session_id=None, k=3, min_score=0.0):
if not user_id:
raise ValueError("user_id is required")
q = self.embed(query)
scored = [(cosine(q, m["vec"]), m)
for m in self._visible(user_id, session_id)]
scored = [(s, m) for s, m in scored if s > min_score]
scored.sort(key=lambda pair: pair[0], reverse=True)
return [m for _, m in scored[:k]]
store = ScopedMemoryStore(toy_embed)
store.write("alice", "Alice prefers vegetarian food")
store.write("bob", "Bob is allergic to peanuts and likes food spicy")
store.write("alice", "Draft itinerary for the Lisbon trip", session_id="s1")
hits = store.search("alice", "which food does the user prefer")
assert hits and all(m["user_id"] == "alice" for m in hits)
print([m["text"] for m in hits])
in_session = store.search("alice", "Lisbon trip itinerary", session_id="s1")
print([m["text"] for m in in_session])
other_session = store.search("alice", "Lisbon trip itinerary", session_id="s2")
assert all(m["session_id"] is None for m in other_session)
print([m["text"] for m in other_session])Three details carry the design:
- A memory with
session_id=Noneis visible in every session of that user. A memory with a session id is visible only in that session. - A search with
session_id=Nonesees only user-wide memories. searchraises ifuser_idis empty. Without that check, a bug that passesNonecould be written asm["user_id"] == user_idand match nothing, or as a lenient filter that matches everything.
Filter first, then rank
The order of operations matters. search filters by scope and then ranks. The tempting alternative is to rank the whole store, take the top k, and then drop memories that belong to someone else. That version has two failures.
- Starvation. If Bob's memories dominate the top 3, filtering for Alice leaves her with zero results, even though relevant memories of hers exist.
- Leaks through side channels. Scores, counts, or "no result" timing computed over the whole store can reveal that other users' memories exist.
In a real vector database, express the scope as a metadata filter on the query itself, not as code that runs on the returned rows. Most vector stores support this, for example a where clause or a filter argument. Check that your store applies the filter before the nearest-neighbor cutoff. Some approximate indexes apply it afterward and can return fewer than k results.
Session-scoped short-term memory
The conversation buffer needs the same discipline. Key it by user and session, not by a module-level list.
from collections import defaultdict
buffers = defaultdict(list) # (user_id, session_id) -> messages
def append_message(user_id, session_id, role, content):
buffers[(user_id, session_id)].append({"role": role, "content": content})
def get_history(user_id, session_id):
return list(buffers[(user_id, session_id)])A single global history list is a common bug in prototypes. It works with one tester and breaks the first time two people use the agent at once. Including user_id in the key, not only session_id, protects you if session ids ever collide or get guessed.
Promoting session memories to user scope
Session memories are cheap to keep and safe to discard. User-wide memories last longer and shape future behavior, so write them more carefully. A reasonable rule is that a fact is promoted only when one of these holds:
- The user states it explicitly as a lasting preference.
- The same fact appears in several sessions.
- A write step has classified it as semantic or procedural, not a one-off episode.
Promotion is a copy with session_id=None, followed by a deduplication check (covered in the maintenance chapter). Session memories can then expire when the session ends.
Common errors
- Trusting model-supplied identity. Bind
user_idoutside the model, as inmake_recall_tool. - Optional scope arguments. A default of
user_id=Nonesilently turns a scoped query into a global one in many implementations. Make the argument required. - Post-filtering. Filter before the top-k cutoff.
- Cached prompts shared across users. If you cache a built prompt or retrieval result, include
user_idandsession_idin the cache key. - Logs and traces. Debug logs that print retrieved memories copy private data into a store with weaker access control. Log memory ids, not text.
- Deleting by text match. A "forget this" request must delete within the requesting user's scope only. Otherwise one user can erase another's memory.
Choosing a granularity
Metadata filters on one shared index are cheap and simple, and they work well for thousands of users. Per-user namespaces cost more to manage but make cross-user leaks structurally harder, and they make "delete all of this user's data" a single operation. Pick the second when the data is sensitive or when you must prove deletion for privacy rules. The privacy chapter returns to this.
Exercise
In ScopedMemoryStore, a developer changes search so that it ranks all items, takes the top k, and then removes items where m["user_id"] != user_id. Name one concrete failure this causes and one way to fix it.
Show answer
With many users, the top k can all belong to other users, so after the filter the caller gets few or no results even if relevant memories of theirs exist. Scores and counts computed over the whole store may also leak information about other users. The fix is to filter by user_id (and session visibility) first, so only the caller's memories are candidates, and then rank and cut to k. In a vector database, pass the scope as a metadata filter applied before the nearest-neighbor cutoff.
Exercise
Why should user_id not be an argument that the model fills in when it calls a recall tool?
Show answer
The model's output can be influenced by user text or injected content, so it could request another user's memories. Bind user_id and session_id from the authenticated request when the tool is created, so the model can pass only the query.