Review the prerequisites
Suitable for: Junior/mid-level AI application candidates with Python and backend fundamentals.
- Memory scopes and trusted authorization context
- The relevance, life cycle and visibility range of memory are three independent dimensions. Threads or namespaces provide organization, and real authorization is still determined by trusted identities and current resource relationships.
How does the mechanism work?
Step-by-step explanation
- After the user exits the project, how to deal with the context in the started task?
After static namespace separation, consider changes in the authorization lifecycle.
- Why might namespace prefix matching expand the read range?
The storage API's matching mechanism may expand candidates and must be separated from authorization.
- How to prioritize when organizational rules conflict with personal preferences?
Multiple authorized scopes can still have conflicting semantic priorities.
Implementation · Build it
Implement · SQL authorization and an independent ID reader
Objectives of this level: Run exact scope filtering with positive and negative controls, then implement an independently graded direct-record read.
Visual guide · Scope comes from trusted identity
Namespaces organize candidates; current authority decides access. Caches of mixed personal/project/organization bundles must include the trusted user boundary. Select the figure to open it at full size.
Start without a project or API key
This is a separate Python-standard-library experiment. Save the reference as memory_scope_lab.py in your own scratch directory and run it with Python 3. It creates a fresh in-memory SQLite database; all data disappears when the process ends. Importing/rerunning the file reconstructs the same fixture. It never reads the capstone ledger or calls a model.
SESSIONS is a fixed stand-in for already authenticated server sessions, not production credentials or a real login system. The gateway derives tenant/user from that fixture and rejects identity fields in the request. Logical time 100 is an internal test input; it must not be chosen by an untrusted client in production. Scores are fixed so the test isolates authorization rather than semantic relevance.
import json
import sqlite3
ROWS = [
("r1", "t1", "user", "alice", "prefer English", 1, 200, 1),
("r2", "t1", "user", "bob", "prefer Chinese", 99, 200, 1),
("r3", "t1", "project", "p1", "use PostgreSQL", 2, 200, 1),
("r4", "t1", "project", "p2", "private MongoDB design", 100, 200, 1),
("r5", "t2", "user", "alice", "t2 private preference", 999, 200, 1),
("r6", "t1", "org", "t1", "human approval required", 3, 200, 1),
("r7", "t1", "project", "p1", "expired decision", 1000, 100, 1),
("r8", "t1", "project", "p1", "withdrawn decision", 999, 200, 0),
("r9", "t2", "project", "p1", "t2 same project ID", 9998, 200, 1),
("r10", "t1-admin", "user", "alice", "prefix tenant secret", 10000, 200, 1),
]
# Fixed local authenticated-session fixture; this is not a real login system.
SESSIONS = {"demo-alice": ("t1", "alice"), "demo-bob": ("t1", "bob"),
"demo-t2-alice": ("t2", "alice")}
db = sqlite3.connect(":memory:")
db.row_factory = sqlite3.Row
db.executescript("""
CREATE TABLE memory(id TEXT PRIMARY KEY, tenant TEXT, scope TEXT, owner TEXT,
body TEXT, score INTEGER, expires INTEGER, active INTEGER);
CREATE TABLE membership(tenant TEXT, user TEXT, project TEXT, active INTEGER,
epoch INTEGER, PRIMARY KEY(tenant,user,project));
""")
db.executemany("INSERT INTO memory VALUES (?,?,?,?,?,?,?,?)", ROWS)
db.executemany("INSERT INTO membership VALUES (?,?,?,?,?)",
[("t1", "alice", "p1", 1, 1), ("t1", "bob", "p1", 1, 1),
("t1", "bob", "p2", 1, 1), ("t2", "alice", "p1", 1, 1)])
db.commit()
def context(token, request):
if token not in SESSIONS:
raise PermissionError("session_required")
if not isinstance(request, dict) or set(request) != {"project_id", "query"} or not all(isinstance(x, str) for x in request.values()):
raise ValueError("request_shape")
tenant, user = SESSIONS[token]
project = request["project_id"]
row = db.execute("SELECT active,epoch FROM membership WHERE tenant=? AND user=? AND project=?",
(tenant, user, project)).fetchone()
if row is None or not row["active"]:
raise PermissionError("project_membership_required")
return tenant, user, project, row["epoch"]
def select_authorized(tenant, user, project, at=100):
return [dict(r) for r in db.execute("""
SELECT * FROM memory WHERE tenant=? AND active=1 AND expires>?
AND ((scope='user' AND owner=?) OR (scope='project' AND owner=?)
OR (scope='org' AND owner=?)) ORDER BY score DESC,id
""", (tenant, at, user, project, tenant))]
def gateway(token, request, at=100):
tenant, user, project, _ = context(token, request)
return select_authorized(tenant, user, project, at)
def ids(rows):
return [r["id"] for r in rows]
request = {"project_id": "p1", "query": "database"}
assert ids(gateway("demo-alice", request)) == ["r6", "r3", "r1"]
assert ids(gateway("demo-bob", request)) == ["r2", "r6", "r3"]
assert ids(gateway("demo-t2-alice", request)) == ["r9", "r5"]
for token, req, expected in [
("demo-alice", {"project_id": "p2", "query": "database"}, "project_membership_required"),
("unknown", request, "session_required"),
("demo-alice", {**request, "tenant_id": "t2", "user_id": "bob"}, "request_shape")]:
try:
gateway(token, req)
except (PermissionError, ValueError) as exc:
assert str(exc) == expected
else:
raise AssertionError(expected)
assert not {"r2", "r4", "r5", "r7", "r8", "r9", "r10"} & set(ids(gateway("demo-alice", request)))
print(json.dumps({"alice": ids(gateway("demo-alice", request)),
"bob": ids(gateway("demo-bob", request)),
"t2_alice": ids(gateway("demo-t2-alice", request)),
"negative_controls": "passed"}, sort_keys=True))
Expected output and the mechanism
The output contains alice=["r6","r3","r1"], bob=["r2","r6","r3"], t2_alice=["r9","r5"] and negative_controls="passed". Exact SQL tenant equality excludes r10; membership excludes Alice/p2; personal owner filtering excludes Bob from Alice’s bundle; lifecycle predicates exclude r7/r8. The forged tenant/user request fails with request_shape before SQL selection. No model receives the excluded content.
Deliver your own code
Before consulting the reference, implement the gateway against these same rows and assertions. Then add a function the reference does not provide: fetch_one(token, request, memory_id, at=100). It must apply the same current authentication, membership and lifecycle rules; knowing an ID grants no permission. Return the authorized row or None for an absent/unauthorized record. Invalid session/project/request still uses the gateway’s existing errors.
Judge your code on these fixed cases: Alice/p1 reads r1 and r3; Alice/p1 receives None for r2, r4, r5, r7, r8, r9, r10 and nonexistent r404; Bob/p1 reads r2 but not r1; t2/Alice/p1 reads r9 but not r3; Alice/p2 raises project_membership_required. Include a forged identity request and an unknown session. A function returning None for everything fails the allowed cases.
Submit your implementation, a runnable assertion file and its output. Explain the trusted entry point and one limitation: this fixture has no real authentication provider, row-level database policies, write gateway, vector index, export API or concurrent revocation/send boundary. Passing it proves this small authorization contract, not a complete production security system.
code example
Filtering before top-k matters
If the ten global scores are truncated to top three before authorization, all three can be forbidden and allowed r1/r3/r6 disappear. Restrict the authorized candidate set first, then rank; safe empty output alone does not establish useful retrieval.
Acceptance task for this level
Implement your own gateway and fetch_one in a scratch module; provide an assertion file exercising all listed allowed/denied ID reads, forged identity, unknown session and unauthorized project. Submit code and outputs with the fixture’s limits.
Reading this browser’s record…
Hide the answer and check your understanding
A search is filtered correctly; can fetch_one simply SELECT by memory ID?
Expand reference derivation
No. A direct lookup is a separate entry point and must apply the same trusted tenant, eligible scope, current membership and lifecycle predicates. Its ID is only a locator. Returning private data by ID would bypass the search authorization contract.
Further explanations and practice
When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.
All linked explanations and exercises (1 )
Sources and verification scope
The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.