Course 5 of 6 in the Engineering Series, which builds one AI platform in Python for Larkfield Supply, a fictional company. In the lesson, E1 to E6 are the six courses; you can skip mentions of other lessons on a first read. Reading needs no setup. To run the code, you need the course repository (tag e5-m4-l2) and the earlier lessons.
You'll leave with OpenFGA in the stack with Larkfield's authorization model, tuples derived from the drive's sharing and the directory, a sync that writes and revokes, and the two calls the walls use, ListObjects and BatchCheck.
In one screen
- Use it on Monday: Filter by permissions before the search, check again just before the prompt, and make your permission sync delete as well as add.
- The picture: Who may see what is stored as relationships (Marcus is in finance, finance views the finance folder, the memo sits in it), derived from the drive's sharing by a sync that also deletes.
- The decision: ListObjects before the search, BatchCheck on every result after it. Post-filtering only when most people can read most of the corpus, and then over-fetch two to three times.
- You'll run:
uv run aip-knowledge sync, which now ends ontuples +48 -0, and+0 -0the second time. Before it,LocalAuthzshows Marcus may open 14 of the 15 documents.
Why this matters
Priya works in support. Marcus works in finance. Both ask the assistant the same thing: "How large a renewal discount can I give Brightwater Hotels?"
The right answer for Marcus is in a finance document: up to 18% for strategic-tier accounts. The right answer for Priya is in the support policy: renewal discounts go to Finance, and support never promises one first. If Priya's prompt ever contains the finance document, she gets the 18%, and she'll quote it to the customer. Nothing errors. The answer is even correct. It's just correct for the wrong person.
The idea
Lesson 4.1 set the rule: the model never sees a passage the asking person can't open. This lesson builds walls 1 and 2 with OpenFGA, an open-source authorization server. It follows Zanzibar, the design Google published for its own permissions, which stores who may see what as relationships rather than as rules in code.
Each relationship is a tuple of three parts: a user, a relation, an object. Here are three real ones from Larkfield's store, the ones that let Marcus read the pricing memo:
| User | Relation | Object | In plain English |
|---|---|---|---|
user:u-marcus |
member |
group:finance |
Marcus is in the finance group |
group:finance#member |
viewer |
folder:finance |
everyone who is a member of finance may view the finance folder |
folder:finance |
parent |
document:fin-pricing-authority |
the pricing memo sits in the finance folder, so it gets the folder's viewers |
group:finance#member reads as "the set of members of group finance". Without #member, the tuple would name the group itself as a viewer, and no person would ever match it. OpenFGA chains the three rows: Marcus is a member, members view the folder, the folder is the memo's parent. So Marcus may view the memo.
Lesson 4.1 numbered the walls by what they trust. A request meets them in a different order: 1, then 3, then 2. Wall 3 is the one that checks each row's access-control list (ACL), the sharing copied from the source:
| Wall | What it trusts | Where it runs in a request |
|---|---|---|
| 1 · ListObjects | OpenFGA's tuples, as of the last sync | first: the search only looks inside this list |
| 3 · row-level security | each row's ACL against the principals built for this request | inside the search, in Postgres (lesson 4.3) |
| 2 · BatchCheck | OpenFGA's tuples, asked again | last: just before the passages enter the prompt |
Wall 3 runs second but is numbered last, because it's the backstop that doesn't trust OpenFGA at all.
sync job: drive sharing + directory -> desired tuples -> OpenFGA (write missing, delete revoked)
request for one person (aip.identity.Principal, from E3's IdP):
wall 1 ListObjects(user:u-priya, viewer, document) -> the documents she may read
hybrid search inside that set only (Postgres; wall 3, row-level security, runs here from 4.3)
rerank, keep k
wall 2 BatchCheck(user:u-priya, final documents) -> drop anything no longer allowed
prompt: passages as data, question last
mirror tools: the same wall 1 for the view, the same BatchCheck on every grep and read result
Why both OpenFGA calls? The pre-filter keeps the search honest: ranking only ever sees permitted passages, so nothing starves and nothing restricted shapes the result. The final check is cheap, a handful of documents, and it catches what a pre-filter can't: rights that changed between the first call and the prompt.
Build it
Four steps: start OpenFGA, write the model, derive the tuples from the drive, and sync them, revocations included. Every output below is offline, no model called.
git checkout e5-m4-l2 && uv sync --all-extras
infra/compose/init/init-secrets.sh # adds OPENFGA_DB_PASSWORD; prints names, never values
(cd infra/compose && docker compose --profile authz up -d --wait --force-recreate postgres openfga)
Pinned at e5-m4-l2: OpenFGA v1.22.1 (openfga/openfga:v1.22.1, pinned by digest), httpx 0.28.1, Python 3.12, uv 0.11.21, Postgres 17 with pgvector 0.8.7 (pgvector/pgvector:0.8.7-pg17).
The tag adds no migration. config.py gains openfga_url (from AIP_OPENFGA_PORT, default 8080) and openfga_store (larkfield). The full list of changed files is in "Full code".
Step 1: OpenFGA in the stack
OpenFGA has been in the series compose file, pinned, since E3, under the authz profile. E5 gives it a datastore and a healthcheck. It keeps its tuples in Postgres, in a database of its own, and starts only after its own schema migration has run, so --wait in the setup above means ready. A restart loses nothing, and the port is reachable from your own machine only. The compose services, and why each of those matters, are in "Going deeper".
Step 2: the model
What to notice: the last line, which lets a document inherit its folder's viewers.
From src/aip/knowledge/authz_model/model.fga:
model
schema 1.1
type user
type group
relations
define member: [user, group#member]
type folder
relations
define viewer: [user, group#member]
type document
relations
define parent: [folder]
define viewer: [user, group#member] or viewer from parent
Four types. Groups can contain users and the members of other groups ([user, group#member]). Folders have viewers. A document's viewers are its own direct viewers or the viewers of its parent folder (viewer from parent). That last line keeps the tuple count small: share a folder once, and every document in it inherits. It's the third row of the table above at work.
The model mirrors how the drive expresses sharing, and that's deliberate. If your model has a concept the source doesn't have, someone has to invent the mapping, and an invented mapping is where wrong labels come from (lesson 4.1 calls this leak 3, wrong labels).
model.json next to it is the same model in the JSON the API takes, compiled by hand. An integration test checks that OpenFGA and the Python evaluator LocalAuthz agree for every person.
Step 3: tuples from the source
One function derives every tuple from the drive's sharing and the directory. What to notice: the else branch.
From src/aip/knowledge/authz.py:
def desired_tuples(snapshot) -> set[Tuple]:
"""What OpenFGA must hold for a connector snapshot: memberships, folder sharing, documents."""
out = {Tuple(f"user:{u}", "member", f"group:{g}") for u, gs in snapshot.directory.items() for g in gs}
for doc in snapshot.docs:
folder = doc.path.split("/")[0]
viewers = [f"{a}#member" if a.startswith("group:") else a for a in doc.meta.acl]
if doc.inherited: # the folder's sharing applies: link the document to its folder
out.add(Tuple(f"folder:{folder}", "parent", f"document:{doc.meta.doc_id}"))
out |= {Tuple(v, "viewer", f"folder:{folder}") for v in viewers}
else: # the document overrides its folder: direct viewers only
out |= {Tuple(v, "viewer", f"document:{doc.meta.doc_id}") for v in viewers}
return out
Three kinds of tuple, the three rows of the table: who is in which group (the directory), which folder each document sits in, and who may view each folder. Users are subjects from the identity provider (IdP), like user:u-priya, the same id the harness puts in ctx.subject. One id, everywhere.
The directory is the identity crawl from lesson 1.2: every employee is in everyone, and contractors (employment: contractor: Lee, and in the large corpus Hana) are not, as a domain-wide share works in a real drive. That one detail decides who reads the employee handbook.
The else branch is the override. The warehouse SLA (service level agreement) lives in pdf/, which everyone can open, but its own sharing says ops and finance only. So it gets direct viewer tuples and no parent link. If it kept the parent link, the union in the model would let everyone in through the folder. That's a one-line bug with a company-wide blast radius, and test_folder_and_override_sharing exists for it.
See Marcus's tuples, and the answer to ListObjects for him, with LocalAuthz, the Python evaluator of the same model (no server needed):
uv run python - <<'EOF'
from aip.config import get_settings
from aip.knowledge.authz import LocalAuthz, desired_tuples
from aip.knowledge.ingest import pull_local
tuples = desired_tuples(pull_local(get_settings().knowledge_dir))
for t in sorted(tuples, key=str):
if "marcus" in str(t) or "folder:finance" in str(t):
print(t.key())
print(sorted(LocalAuthz(tuples).list_documents("user:u-marcus")))
EOF
{'user': 'folder:finance', 'relation': 'parent', 'object': 'document:fin-margin-q3'}
{'user': 'folder:finance', 'relation': 'parent', 'object': 'document:fin-pricing-authority'}
{'user': 'group:finance#member', 'relation': 'viewer', 'object': 'folder:finance'}
{'user': 'user:u-marcus', 'relation': 'member', 'object': 'group:everyone'}
{'user': 'user:u-marcus', 'relation': 'member', 'object': 'group:finance'}
['con-brightwater', 'con-fenmore', 'fin-margin-q3', 'fin-pricing-authority', 'hr-handbook', 'pdf-price-list', 'pdf-rate-card', 'pdf-warehouse-sla', 'pol-expenses', 'pol-refunds', 'pol-refunds-2024', 'pol-retention', 'pol-security', 'pol-shipping']
Fourteen of the fifteen documents. The one missing is the compensation bands, shared with HR only. On the real server, the same question is one list-objects call: type document, relation viewer, user user:u-marcus.
Step 4: sync, including revocation
What to notice: sync computes two differences, what's missing and what's gone, and sends both.
From src/aip/knowledge/authz.py:
def sync(self, desired: set[Tuple]) -> tuple[int, int]:
"""Make the store hold exactly `desired`: write what is missing, delete what was revoked."""
current = self.read_all()
writes, deletes = sorted(desired - current, key=str), sorted(current - desired, key=str)
for i in range(0, max(len(writes), len(deletes)), 100): # API limit: 100 tuples per call
body = {}
if writes[i:i + 100]:
body["writes"] = {"tuple_keys": [t.key() for t in writes[i:i + 100]]}
if deletes[i:i + 100]:
body["deletes"] = {"tuple_keys": [t.key() for t in deletes[i:i + 100]]}
self._post("write", body)
return len(writes), len(deletes)
The delete half is the half people forget. A sync that only adds never revokes anything, and stale rights (leak 4 in lesson 4.1) become permanent.
The API takes at most 100 tuples per write, hence the batches. Before any of this, the client finds the larkfield store by name (_store), following OpenFGA's pages of stores, so a server that holds many never gets an empty duplicate; test_openfga_stores.py checks it against 120 stores.
Wall 2 is BatchCheck, in the same file. What to notice: an error ends in a deny.
From src/aip/knowledge/authz.py:
def batch_check(self, user: str, doc_ids: list[str]) -> dict[str, bool]:
"""The server refuses more than batch_max checks a request: send them in batches, one
after another. Fails closed: a batch that errors denies all of its documents, and says so."""
ids, verdict = sorted(set(doc_ids)), {}
for start in range(0, len(ids), self.batch_max):
batch = ids[start:start + self.batch_max]
checks = [{"tuple_key": {"user": user, "relation": "viewer", "object": f"document:{d}"},
"correlation_id": str(i)} for i, d in enumerate(batch)]
try:
result = self._post("batch-check", {"checks": checks})["result"]
except (httpx.HTTPError, KeyError, ValueError) as e:
log.error("BatchCheck failed for %s, %d documents denied: %s", user, len(batch), e)
result = {}
verdict |= {d: result.get(str(i), {}).get("allowed", False) for i, d in enumerate(batch)}
return verdict # a missing answer or a check error denies too
batch_check sends many checks in one request, each with a correlation_id so results come back keyed. The server caps how many checks one request may carry, so the checks go in batches and the answers are merged ("Going deeper" has the numbers). Every way to fail denies. A batch that errors denies all of its documents and logs why, and a missing answer or a check without allowed denies that document. A check that errors must never let a passage through.
Wall 1 is list_documents ("Full code"), the ListObjects call you saw answered above. ListObjects has server limits too. A cut list fails closed (fewer documents searched, none leaked) but costs recall, so the code logs a warning. "Going deeper" has the limits, and why Larkfield will meet them.
Try it 1: count one kind of tuple. Before you sync, look back at desired_tuples. The small corpus has 15 documents. How many parent tuples (folder links) will it write? Then sync, with the stack up:
uv run aip-knowledge sync
sync: 15 documents from the connector (ttlMs=900000); indexed=0 unchanged=15 pruned=0 chunks=0 tuples +48 -0
On a fresh database the first line says indexed=15. Run it again and you get tuples +0 -0.
Forty-eight tuples for 15 documents and eleven people: 23 memberships (each employee in everyone plus their own groups; Lee and Hana in contractors only), 14 folder links, 11 viewer tuples. The large corpus writes 884, almost all of them folder links:
uv run python -c "
from pathlib import Path
from aip.knowledge.ingest import pull_local
from aip.knowledge.authz import desired_tuples
print(len(desired_tuples(pull_local(Path('data/larkfield/knowledge-large')))))
"
884
Your turn (10 min)
Revocation, without a server. Write a few lines that take desired_tuples for the small corpus, remove one tuple, Marcus's membership of finance (Tuple("user:u-marcus", "member", "group:finance"), from aip.knowledge.authz), and ask LocalAuthz for his documents before and after. Before you run it, predict how many of his 14 documents he keeps, and name the ones he loses.
You now have OpenFGA holding exactly what the drive's sharing says, revocations included, and the two calls that read it. Part 2 puts ListObjects in front of the search and BatchCheck behind it, and asks the Brightwater question as two people.
Check yourself
- A sync job writes new tuples but never deletes. What leak does that create? Stale rights, forever: nobody ever loses access.
- During an OpenFGA outage, a teammate wants BatchCheck errors to fall back to the ListObjects answer, so people don't lose results. Do you merge it? No. A check that errors must deny: the fallback trusts the very list the final check exists to catch, stale or wrong. Here a missing
allowedmeans false, and the log line tells you how many documents were denied. - Try it 1. Fourteen, not fifteen: the warehouse SLA overrides its folder, so it gets direct viewers and no parent link. If you said fifteen, that's the one-line bug from Step 3.
- Your turn. He keeps 9 and loses 5: the margin review and the pricing memo, as you'd expect, but also both contracts (shared with legal, finance and support, and he's in none of the others) and the warehouse SLA (ops and finance). Revoking one group reaches further than the folder named after it.
from aip.config import get_settings
from aip.knowledge.authz import LocalAuthz, Tuple, desired_tuples
from aip.knowledge.ingest import pull_local
tuples = desired_tuples(pull_local(get_settings().knowledge_dir))
before = LocalAuthz(tuples).list_documents("user:u-marcus")
after = LocalAuthz(tuples - {Tuple("user:u-marcus", "member", "group:finance")}).list_documents("user:u-marcus")
print(len(before), len(after), sorted(before - after))
14 9 ['con-brightwater', 'con-fenmore', 'fin-margin-q3', 'fin-pricing-authority', 'pdf-warehouse-sla']
Run at tag e5-m4-l2 on 16 Nov 2026.
Part 2: the walls in a request
Why this matters
Part 1 filled OpenFGA with 48 tuples and gave you two calls. Neither protects anything until a request goes through it. Priya and Marcus still ask the same question about Brightwater's renewal discount, and only Marcus may see the 18%. This part wires ListObjects in front of the search and BatchCheck behind it, then asks as both of them, and as Lee.
Build it, continued
Step 5: the walls, in one class
What to notice: search is the request path in four lines, in the order of the walls table in part 1, and check_documents is public, because the mirror tools call it too.
From src/aip/knowledge/access.py:
def allowed(self, who: Principal) -> set[str]:
return self.authz.list_documents(fga_user(who))
def candidates(self, who: Principal, query: str, allowed: set[str], n: int) -> list[Passage]:
if self.store is not None:
return self.store.search(query, self.model.embed([query])[0], principals(who), allowed, k=n)
return self.index.search(query, k=n, allowed=allowed)
def search(self, who: Principal, query: str, k: int = 8, n: int = 30) -> list[Passage]:
allowed = self.allowed(who) # wall 1: pre-filter
found = self.candidates(who, query, allowed, n) # wall 3 inside Postgres (RLS)
if found and self.rerank is not None:
order = self.rerank(query, [f"{p.title}\n{p.section}\n{p.text}" for p in found], k)
found = [found[i] for i, _ in order]
return self.check(who, found[:k])
def check_documents(self, who: Principal, doc_ids: list[str]) -> set[str]:
"""Wall 2 for any result: the documents still viewable now (errors deny)."""
verdict = self.authz.batch_check(fga_user(who), list(doc_ids))
return {d for d in doc_ids if verdict.get(d, False)}
def check(self, who: Principal, passages: list[Passage]) -> list[Passage]:
still = self.check_documents(who, [p.doc_id for p in passages]) # wall 2
kept = [p for p in passages if p.doc_id in still]
if len(kept) < len(passages):
log.warning("batch_check dropped %d passages for %s", len(passages) - len(kept), who.subject)
return kept
The module's opening, its docstring and constructor, is in "Full code".
The person is E3's aip.identity.Principal: who the IdP says they are, now. fga_user turns their subject into the OpenFGA user. Their groups never come from a request body, where anyone could claim any group (leak 2 in lesson 4.1).
search walks the diagram. It pre-filters with ListObjects, asks for 30 candidates inside that set, reranks to k when rerank is on, and calls check last. Knowledge satisfies the same Searchable protocol as lesson 3.2's ByAcl, so the tools and the agent didn't change.
check logs a warning when it drops something. A drop means the pre-filter was stale or wrong, and you want that rate on a dashboard.
The store passes principals(who) down to Postgres. Nothing reads them yet. Lesson 4.3 turns them into wall 3.
Why not skip ListObjects and rely on the final check? That's post-filtering alone. Here it is by hand, for Priya and a finance-flavored query, on the in-memory index.
Try it 2: predict the survivors. The search takes the top 5 for "finance margin strategic tier discount CFO", then keeps only what Priya may read. How many of the 5 survive? Guess before you run it.
uv run python -c "
from aip.config import get_settings
from aip.knowledge.authz import LocalAuthz, desired_tuples
from aip.knowledge.ingest import pull_local
from aip.knowledge.model import OfflineModel
from aip.knowledge.pipeline import build_memory_index
s = get_settings()
snap = pull_local(s.knowledge_dir)
idx = build_memory_index(snap, OfflineModel(), s.knowledge_dir / '_parsed')
allowed = LocalAuthz(desired_tuples(snap)).list_documents('user:u-priya')
q = 'finance margin strategic tier discount CFO'
post = [p.doc_id for p in idx.search(q, k=5) if p.doc_id in allowed]
pre = [p.doc_id for p in idx.search(q, k=5, allowed=allowed)]
print('post-filter:', len(post), post)
print('pre-filter: ', len(pre), pre)
"
post-filter: 0 []
pre-filter: 5 ['pol-refunds', 'pol-security', 'pol-expenses', 'pol-refunds', 'pol-refunds']
Search everything and keep what she may read: zero of five survive. Search inside her set: five passages. OpenFGA's own guide says post-filtering "may return fewer than K after filtering" (OpenFGA, checked 12 Nov 2026).
Step 6: the answer, and the tools
The answer function from lesson 3.2 now gets its passages from Knowledge, and from nowhere else.
From src/aip/knowledge/answer.py:
def answer(knowledge: Searchable, who: Principal, question: str, k: int = 6) -> Answer:
passages = knowledge.search(who, question, k=k)
if not passages:
return Answer(NOT_FOUND, [])
if isinstance(knowledge.model, OfflineModel):
return Answer(extractive(question, passages), passages)
return Answer(knowledge.model.chat(messages(question, passages), alias="smart"), passages)
answer only ever gets passages through knowledge.search, so there's no other door into the prompt. Passages go first, as tagged data, and the question last (messages, in "Full code"). Offline, the answer is extractive: the best-matching sentences, each with its citation. Live, it goes to the smart alias. No passages means the abstention, never a guess.
The CLI wires both paths through the walls (knowledge and cmd_grep in cli.py, "Full code"). --memory swaps OpenFGA for LocalAuthz and Postgres for the in-memory index, so a laptop without Docker can follow along.
Either way, grep goes through KnowledgeTools, which builds the mirror view from knowledge.allowed (wall 1), checks every hit with check_documents (wall 2) and matches the file's ACL against the request's principals (wall 3).
Step 7: same question, two people
This is the moment the lesson opened on: Priya and Marcus ask about Brightwater's renewal discount, through all the walls.
for who in priya marcus; do echo "== $who"; uv run aip-knowledge ask --as $who "How large a renewal discount can I give Brightwater Hotels?"; done
== priya
Anything above that limit, and any discount on a contract renewal, goes to Finance through a discount request in the billing system. [pol-refunds §Goodwill credits and discounts by support, updated 2026-09-14] Support does not promise a renewal discount to a customer before Finance has approved it in writing. [pol-refunds §Goodwill credits and discounts by support, updated 2026-09-14]
== marcus
Finance may approve renewal discounts up to 18% for strategic-tier accounts until 31 December 2026, provided the account's gross margin stays above 22% after the discount. [fin-pricing-authority §Renewal discounts, updated 2026-10-01] The strategic tier for 2026 is Brightwater Hotels, Kestrel Logistics and Orchard Facilities Group. [fin-pricing-authority §Renewal discounts, updated 2026-10-01]
Two correct answers, each cited. Neither says "you don't have access to the finance policy": Priya gets the answer her documents give, and nothing hints a finance document exists (leaking that a document exists is leak 5 in lesson 4.1).
Live, on the large corpus, the same split holds: neither of Priya's citations is a finance document, and the 18% never reaches her. "Going deeper" has that run.
The grep tool from lesson 3.2, now from the command line:
uv run aip-knowledge grep --as priya "strategic-tier"
uv run aip-knowledge grep --as marcus "strategic-tier"
No matches.
larkfield-drive/finance/q3-2026-margin-review.md:26: Pass the freight surcharge through on new contracts from 1 November 2026. ... Keep strategic-tier discounts inside the 22% margin floor.
larkfield-drive/finance/q4-2026-pricing-authority.md:18: Finance may approve renewal discounts up to 18% for strategic-tier accounts until 31 December 2026, ... For all other accounts the Finance limit is 8%.
"No matches", the same words as for a string that exists nowhere.
Now the person the directory treats differently. Lee is a warehouse contractor. The handbook is shared with everyone, and contractors aren't in it. Try it 3: before you run it, decide what Lee should see. A refusal that names the handbook? A partial answer? Something else?
for who in priya lee; do echo "== $who"; uv run aip-knowledge ask --as $who "How many days of paid annual leave do I get?"; done
== priya
Full-time employees get 25 days of paid annual leave per calendar year, plus public holidays. [hr-handbook §Annual leave, updated 2026-07-01] Birth parents get 16 weeks of fully paid parental leave. [hr-handbook §Parental leave, updated 2026-07-01]
== lee
I could not find this in the documents you can access.
Priya gets "25 days", cited. Lee gets the abstention: no passage reached the prompt, so there was nothing to answer from and nothing to guess. That's what Larkfield's sharing says: the handbook is for employees. It's also the case most permission systems get wrong, because "everyone" quietly means "every account".
Step 8: the tests that matter
The tests pin what you've seen, plus one case you can't easily stage by hand: a revocation in the middle of a request.
uv run pytest -q tests/knowledge/test_permissions.py tests/knowledge/test_tools.py tests/knowledge/test_integration_authz.py
.............. [100%]
14 passed in 1.27s
Two carry the lesson beyond what you've seen. test_permissions.py::test_batch_check_catches_a_stale_prefilter revokes Marcus's finance membership between ListObjects and the final check, and the finance passages are dropped (test_tools.py does the same to grep and read).
test_integration_authz.py::test_revocation_reaches_openfga runs against the real server: remove Marcus's membership from the desired set, sync returns (0, 1) and he loses the document; put it back, (1, 0). Step 5's snippet and Step 7's contractor are tests too.
What breaks
The code prevents an override that keeps its parent link (test_folder_and_override_sharing), a check that errors into an allow, and a sync that never deletes. What it doesn't prevent:
- Revocation lag. Between a directory change and the next sync, ListObjects still says yes, and so does BatchCheck, because both read the same stale store. Wall 2 catches changes that land during a request, not changes that never reached OpenFGA. Control: a wall that reads identity from the request (wall 3, lesson 4.3, whose Step 6 states the lag per case; the mirror already has it).
- Groups the directory doesn't know. A folder shared with a group no one is in matches nobody in this model, which is the safe failure. The unsafe version is a mapping that turns unknown groups into "everyone". Control: alert on ACL groups the identity sync has never seen.
- Silent truncation. Past 1,000 readable documents, or 3 seconds, ListObjects returns a partial list. The code logs it; nothing stops it. Control: watch the warning, and move to StreamedListObjects or coarser filters (by folder) before you reach it.
Decide
My default: OpenFGA (or SpiceDB, with LookupResources and CheckBulkPermissions in the same roles), tuples derived from the source by the sync job, ListObjects as the pre-filter, BatchCheck on every result before the model sees it, search and mirror alike.
Pick post-filtering as the main mechanism only when most people can read most of the corpus, and then over-fetch two to three times, as OpenFGA's guide suggests. If your corpus is single-tenant and small, Postgres row-level security alone (lesson 4.3) is an acceptable first version.
Two people now get two correct answers from one index. Lesson 4.3 adds the wall that doesn't trust OpenFGA at all.
Check yourself
- A teammate wants to drop the final BatchCheck to halve the calls to OpenFGA, since the pre-filter already ran. What do you answer? Keep it. Rights can change during a request, and a filter can be wrong. The check costs one request on a handful of documents, and its drop log is how you'd learn the pre-filter is stale.
- Priya asks about something only finance documents cover. What should she see? The same "not found" she'd see for a question nobody's documents answer.
- Try it 2. None of the five. Searching everything ranks finance passages first for a finance-flavored query, and the filter then drops them all.
- Try it 3. The same abstention anyone gets for a question no document answers: no passage reached the prompt, so nothing hints that a handbook exists.
Transcript
Permission walls around retrieval, with OpenFGA. We filter before we search, and we check again right before anything reaches the prompt. All right, two people at Larkfield ask the assistant the same question. Priya is in support. Marcus is in finance. How large a renewal discount can I give Brightwater Hotels? The finance answer is eighteen percent. The support answer is: you don't decide that, finance does.
And if Priya's prompt ever contains the finance document, she gets eighteen percent, and she'll repeat it to the customer. So today we build the walls that stop that. So, OpenFGA is an open-source authorization server in the Zanzibar family, the design Google published for its own permission checks. Rights are tuples: this group's members view that folder. It's been in the series compose file since E3.
Here it gets a datastore: Postgres, in a database of its own, so a restart keeps every tuple. Two one-off steps run first, the database and OpenFGA's migrations. And keep in mind, the tuples are still derived state: the sync job rewrites them from the drive every time. Four types. Users, groups that can contain groups, folders with viewers, and documents.
A document's viewers are its own, or its folder's, and that one "or" keeps the tuple count small. Now, the model looks like the drive on purpose. If your model has a concept the source doesn't have, someone has to invent a mapping, and honestly, invented mappings are where wrong labels come from. Now, the sync job turns the drive's sharing into tuples.
Memberships from the directory, with users as the identity provider's subjects, the same id the harness uses. A link from each document to its folder. Viewers on the folder. And one special case: a document that overrides its folder gets direct viewers and no parent link. Why? Keep the parent link by mistake, and the union lets the whole company in through the folder.
Sync makes the store hold exactly what the source says. Write what's missing, delete what's gone. And the delete half is the one people forget, right? A sync that never deletes never revokes anyone. Below it, the two calls this lesson is about. ListObjects: which documents can this person view. BatchCheck: are these documents still allowed, in batches of fifty, the server's limit.
A check that errors counts as a no, and a batch that fails denies every document in it. Let's run it: forty-eight tuples for eleven people. So here's the request path. ListObjects first, and the search only runs inside that set. That's wall one. Postgres runs the search, and from the next lesson it applies wall three in there too. Then rerank.
Then, right before anything goes to the prompt, BatchCheck on the final documents. That's wall two. If it drops something, it logs it, because a drop means the pre-filter was stale or wrong, and you know, that's a rate you want on a dashboard. Now you might ask, why not search everything and check at the end? Well, the top results for a finance-flavored question are finance documents.
Search everything, keep what Priya may read: zero out of five. Search inside her set first: five. And the first version raises no error at all, it just answers worse, quietly. All right, now the question from the start. Priya gets the support policy, cited: renewal discounts go to finance. Marcus gets eighteen percent for strategic-tier accounts, cited to the finance document.
And look at Priya's answer: nothing in it tells her a finance document even exists. Now the grep tool from lesson three point two, on the command line. Priya gets no matches, the exact words she'd get for a string that exists nowhere. Marcus gets two finance lines. Same mirror, same pattern, and every hit checked again before it leaves. One more person.
Lee is a warehouse contractor. The handbook is shared with everyone, and in Larkfield's drive, everyone means employees. Priya asks how much leave she gets: twenty-five days, cited. Lee asks the same thing and gets the abstention. Nothing reached his prompt, so there was nothing to guess from. And by the way, that's the case most permission systems get wrong, because everyone quietly turns into every account.
So, the tests worth reading. The stale pre-filter: Marcus is revoked between the first call and the last, and the finance passages are gone. The same revocation on grep and read. The contractor. And against the real server: remove one membership, sync deletes one tuple, put it back, sync writes one. Now, both OpenFGA calls read the same store, though. So if the store is stale, both are wrong together.
That's why the next wall lives in Postgres. Next up, lesson four point three: row-level security. See you there.
Going deeper
Part 1
What this tag changes
Sixteen files: the authorization model, authz.py and access.py, the compose changes, and seven test files; git diff --stat=72 e5-m3-l2..e5-m4-l2 -- src data agents tests infra lists them (the output is in "Full code"). The decisions behind this part, in docs/decisions/: decision record 0505 (every output offline, through the offline model) and 0509 (contractors aren't in everyone, as a domain-wide share works in a real drive).
OpenFGA in the stack
What to notice: OpenFGA keeps its tuples in Postgres, in a database of its own, and starts only after its own schema migration has run.
From infra/compose/compose.yml:
openfga-migrate:
profiles: [authz]
image: &openfga openfga/openfga:v1.22.1@sha256:b852071314f1fda1194d341a6ebac0a4f619b3cd87a6626d2ccc7048af4ec671
command: migrate
depends_on: {openfga-db: {condition: service_completed_successfully}}
environment: &openfga-store
OPENFGA_DATASTORE_ENGINE: postgres
OPENFGA_DATASTORE_URI: postgres://openfga:${OPENFGA_DB_PASSWORD}@postgres:5432/openfga?sslmode=disable
openfga:
profiles: [authz]
image: *openfga
command: run
depends_on: {openfga-migrate: {condition: service_completed_successfully}}
environment:
<<: *openfga-store
OPENFGA_PLAYGROUND_ENABLED: "false"
OPENFGA_LOG_FORMAT: json
ports: ["127.0.0.1:${AIP_OPENFGA_PORT:-8080}:8080"]
healthcheck:
test: ["CMD", "/usr/local/bin/grpc_health_probe", "-addr=openfga:8081"]
interval: 5s
timeout: 3s
retries: 20
The series compose file has carried this service, pinned, since E3. E5 gives it a datastore and a healthcheck, so --wait means ready. A third service just above, openfga-db ("Full code"), creates OpenFGA's role and database on the platform's Postgres (idempotent, so a volume from an earlier course gets them too), openfga-migrate runs OpenFGA's own schema migrations, and the server starts after both.
A restart keeps the store, the model and every tuple; tests/knowledge/test_openfga_restart.py writes two tuples, restarts the container and checks that Marcus still sees fin-pricing-authority and Priya still doesn't (decision record 0503 in docs/decisions/). OpenFGA's default memory engine would lose every tuple on a restart, and every document would be refused until the next sync. The tuples are still derived state: aip-knowledge sync rewrites them from the drive's sharing every time, so the source of truth stays the drive. E6 runs the same engine on its one server (E6 lesson 4.1) and on managed Postgres in its cloud module (E6 lesson 4.2). The port binds to 127.0.0.1 only and the playground is off. An authorization server isn't something you expose to the office Wi-Fi.
The server's limits
BatchCheck: the server takes at most 50 checks a request by default, so the checks go in batches of batch_max (BATCH_CHECK_MAX = 50 at the top of authz.py) and the answers are merged; test_batch_check.py sends 120 and gets 50, 50, 20.
ListObjects: at most 1,000 objects and 3 seconds by default in v1.22.1 (openfga run --help, checked 12 Nov 2026). Larkfield's large corpus has 834 documents. Priya can open most of them. You'd hit the limit at the next acquisition, and the warning is how you'd find out.
Free, and worth your time
- Pang et al. (Google), "Zanzibar: Google's Consistent, Global Authorization System" (paper and talk, USENIX ATC 2019): the design OpenFGA follows. https://www.usenix.org/conference/atc19/presentation/pang
Part 2
The same question, live, on the large corpus
This run was on 14 November 2026 at tag e5-final, through Postgres and OpenFGA, with smart mapped to OpenAI gpt-6.1-sol behind the gateway, text-embedding-3-small embeddings and rerank off. The command was AIP_LIVE=1 AIP_KNOWLEDGE_DIR=data/larkfield/knowledge-large uv run aip-knowledge ask --as <who> "...":
== priya
**No renewal discount amount is specified in the provided passages.** Do not promise or hint at a discount until Finance has approved it in writing; ... [sup-macros-credits-and-discounts §Macro: Renewal discount request, updated 2026-09-15]
... Follow up with the account manager before quoting a discount. [ticket-t-20260612-0238 §Internal note, updated 2026-06-14]
== marcus
**Finance can approve a renewal discount of up to 18% for Brightwater Hotels until 31 December 2026, provided its gross margin after discount stays above 22%.** ... [fin-pricing-authority §Renewal discounts, updated 2026-10-01]
The **12% discount already assessed** is forecast to leave a 23.1% gross margin ... [fin-brightwater-renewal §Margin check, updated 2026-10-29]
...
Neither of Priya's citations is a finance document, and the 18% never reaches her. In the large corpus, a support macro and a ticket note answer her instead of the refunds policy.
Full code
Part 1
Where the excerpts in the lesson sit in their files, at tag e5-m4-l2:
src/aip/knowledge/authz_model/model.fga, whole filesrc/aip/knowledge/authz.py, lines 39-50, 95-106 and 119-133infra/compose/compose.yml, lines 215-238
The diff for this tag, git diff --stat=72 e5-m3-l2..e5-m4-l2 -- src data agents tests infra:
infra/compose/.env.example | 1 +
infra/compose/compose.yml | 36 ++++-
infra/compose/init/init-secrets.sh | 1 +
infra/compose/init/openfga-db.sh | 13 ++
src/aip/config.py | 2 +
src/aip/knowledge/access.py | 64 +++++++++
src/aip/knowledge/authz.py | 165 ++++++++++++++++++++++
src/aip/knowledge/authz_model/model.fga | 17 +++
src/aip/knowledge/authz_model/model.json | 23 +++
tests/knowledge/test_batch_check.py | 78 ++++++++++
tests/knowledge/test_integration_authz.py | 50 +++++++
tests/knowledge/test_openfga_restart.py | 44 ++++++
tests/knowledge/test_openfga_stores.py | 31 ++++
tests/knowledge/test_permissions.py | 72 ++++++++++
tests/knowledge/test_tools.py | 57 ++++++++
tests/unit/test_openfga_datastore.py | 31 ++++
16 files changed, 683 insertions(+), 2 deletions(-)
The three OpenFGA services, from infra/compose/compose.yml, lines 201-238:
# Used from E3 on (rights) and in E5 (permission-aware knowledge). Pinned now so the stack has one source of versions.
# E5 4.2: the tuples live in Postgres, in OpenFGA's own database (decision 0503): a restart loses nothing.
# Three steps on every `up`: the database (idempotent), `openfga migrate`, then the server.
openfga-db:
profiles: [authz]
image: pgvector/pgvector:0.8.7-pg17@sha256:7d0a41464797aeb9862dfdc0bbf1526b82cfd324cdd8036df19e3545f4a9ccb8
command: [sh, /init/openfga-db.sh]
depends_on: {postgres: {condition: service_healthy}}
environment:
PGHOST: postgres
PGPASSWORD: ${POSTGRES_PASSWORD}
OPENFGA_DB_PASSWORD: ${OPENFGA_DB_PASSWORD:?run init/init-secrets.sh}
volumes: ["./init/openfga-db.sh:/init/openfga-db.sh:ro"]
openfga-migrate:
profiles: [authz]
image: &openfga openfga/openfga:v1.22.1@sha256:b852071314f1fda1194d341a6ebac0a4f619b3cd87a6626d2ccc7048af4ec671
command: migrate
depends_on: {openfga-db: {condition: service_completed_successfully}}
environment: &openfga-store
OPENFGA_DATASTORE_ENGINE: postgres
OPENFGA_DATASTORE_URI: postgres://openfga:${OPENFGA_DB_PASSWORD}@postgres:5432/openfga?sslmode=disable
openfga:
profiles: [authz]
image: *openfga
command: run
depends_on: {openfga-migrate: {condition: service_completed_successfully}}
environment:
<<: *openfga-store
OPENFGA_PLAYGROUND_ENABLED: "false"
OPENFGA_LOG_FORMAT: json
ports: ["127.0.0.1:${AIP_OPENFGA_PORT:-8080}:8080"]
healthcheck:
test: ["CMD", "/usr/local/bin/grpc_health_probe", "-addr=openfga:8081"]
interval: 5s
timeout: 3s
retries: 20
sync, list_documents and batch_check, from src/aip/knowledge/authz.py, lines 95-133:
def sync(self, desired: set[Tuple]) -> tuple[int, int]:
"""Make the store hold exactly `desired`: write what is missing, delete what was revoked."""
current = self.read_all()
writes, deletes = sorted(desired - current, key=str), sorted(current - desired, key=str)
for i in range(0, max(len(writes), len(deletes)), 100): # API limit: 100 tuples per call
body = {}
if writes[i:i + 100]:
body["writes"] = {"tuple_keys": [t.key() for t in writes[i:i + 100]]}
if deletes[i:i + 100]:
body["deletes"] = {"tuple_keys": [t.key() for t in deletes[i:i + 100]]}
self._post("write", body)
return len(writes), len(deletes)
def list_documents(self, user: str) -> set[str]:
"""ListObjects returns up to 1000 objects within 3 s by default, then stops. A cut list fails
closed (fewer documents searched, none leaked) but costs recall, so we say so. Past about
1000 documents per person: raise the server limits or page with StreamedListObjects."""
start = time.monotonic()
r = self._post("list-objects", {"type": "document", "relation": "viewer", "user": user})
if len(r["objects"]) >= LIST_OBJECTS_MAX or time.monotonic() - start >= LIST_OBJECTS_DEADLINE:
log.warning("ListObjects for %s may be truncated (%d objects): search sees a partial list",
user, len(r["objects"]))
return {o.removeprefix("document:") for o in r["objects"]}
def batch_check(self, user: str, doc_ids: list[str]) -> dict[str, bool]:
"""The server refuses more than batch_max checks a request: send them in batches, one
after another. Fails closed: a batch that errors denies all of its documents, and says so."""
ids, verdict = sorted(set(doc_ids)), {}
for start in range(0, len(ids), self.batch_max):
batch = ids[start:start + self.batch_max]
checks = [{"tuple_key": {"user": user, "relation": "viewer", "object": f"document:{d}"},
"correlation_id": str(i)} for i, d in enumerate(batch)]
try:
result = self._post("batch-check", {"checks": checks})["result"]
except (httpx.HTTPError, KeyError, ValueError) as e:
log.error("BatchCheck failed for %s, %d documents denied: %s", user, len(batch), e)
result = {}
verdict |= {d: result.get(str(i), {}).get("allowed", False) for i, d in enumerate(batch)}
return verdict # a missing answer or a check error denies too
Part 2
Where the excerpts in the lesson sit in their files, at tag e5-m4-l2:
src/aip/knowledge/access.py, lines 38-64src/aip/knowledge/answer.py, lines 49-55
The whole access module, from src/aip/knowledge/access.py, lines 1-64:
"""Permission-aware search: pre-filter, search, rerank, re-check, then hand over.
Three walls, numbered as in lesson 4.1:
1. OpenFGA ListObjects gives the documents the user may view; search runs inside that set.
2. OpenFGA BatchCheck re-checks the final passages just before they enter the prompt,
which catches a stale pre-filter (for example access revoked a second ago).
3. Postgres RLS (pgstore.as_reader) hides rows whose ACL does not meet the principals of
this request, whatever the SQL asks for. It runs inside step 1's search, before wall 2;
it is numbered last because it is the backstop that does not trust OpenFGA at all.
The text mirror applies the same three walls to files (mirror.MirrorView, tools.KnowledgeTools).
The person is E3's aip.identity.Principal: who the IdP says they are, now.
"""
import logging
from aip.identity import Principal
from aip.knowledge.authz import Authz
from aip.knowledge.ingest import principals
from aip.knowledge.model import ModelClient, Reranker, reranker
from aip.knowledge.pgstore import PgStore
from aip.knowledge.retrieval import MemoryIndex, Passage
log = logging.getLogger("aip.knowledge")
AUTO = object() # rerank as configured (AIP_RERANK, decision 0508)
def fga_user(who: Principal) -> str:
return f"user:{who.subject}"
class Knowledge:
def __init__(self, authz: Authz, model: ModelClient, store: PgStore | None = None,
index: MemoryIndex | None = None, rerank: Reranker | None | object = AUTO):
assert (store is None) != (index is None), "one backend: Postgres or the in-memory index"
self.authz, self.model, self.store, self.index = authz, model, store, index
self.rerank = reranker(model) if rerank is AUTO else rerank
def allowed(self, who: Principal) -> set[str]:
return self.authz.list_documents(fga_user(who))
def candidates(self, who: Principal, query: str, allowed: set[str], n: int) -> list[Passage]:
if self.store is not None:
return self.store.search(query, self.model.embed([query])[0], principals(who), allowed, k=n)
return self.index.search(query, k=n, allowed=allowed)
def search(self, who: Principal, query: str, k: int = 8, n: int = 30) -> list[Passage]:
allowed = self.allowed(who) # wall 1: pre-filter
found = self.candidates(who, query, allowed, n) # wall 3 inside Postgres (RLS)
if found and self.rerank is not None:
order = self.rerank(query, [f"{p.title}\n{p.section}\n{p.text}" for p in found], k)
found = [found[i] for i, _ in order]
return self.check(who, found[:k])
def check_documents(self, who: Principal, doc_ids: list[str]) -> set[str]:
"""Wall 2 for any result: the documents still viewable now (errors deny)."""
verdict = self.authz.batch_check(fga_user(who), list(doc_ids))
return {d for d in doc_ids if verdict.get(d, False)}
def check(self, who: Principal, passages: list[Passage]) -> list[Passage]:
still = self.check_documents(who, [p.doc_id for p in passages]) # wall 2
kept = [p for p in passages if p.doc_id in still]
if len(kept) < len(passages):
log.warning("batch_check dropped %d passages for %s", len(passages) - len(kept), who.subject)
return kept
The answer module's prompt and the offline answer, from src/aip/knowledge/answer.py, lines 31-55:
def messages(question: str, passages: list[Passage]) -> list[dict]:
context = "\n\n".join(render(p) for p in passages)
return [{"role": "system", "content": SYSTEM},
{"role": "user", "content": f"<passages>\n{context}\n</passages>\n\nQuestion: {question}"}]
def extractive(question: str, passages: list[Passage], sentences: int = 2) -> str:
q = set(terms(question))
scored = []
for rank, p in enumerate(passages[:3]):
for s in re.split(r"(?<=[.!?])\s+|\n+", p.text):
overlap = len(q & set(terms(s)))
if overlap and not s.startswith("|"):
scored.append((overlap - 0.5 * rank, s.strip(), p))
best = sorted(scored, key=lambda x: -x[0])[:sentences]
return " ".join(f"{s} {p.citation()}" for _, s, p in best) or NOT_FOUND
def answer(knowledge: Searchable, who: Principal, question: str, k: int = 6) -> Answer:
passages = knowledge.search(who, question, k=k)
if not passages:
return Answer(NOT_FOUND, [])
if isinstance(knowledge.model, OfflineModel):
return Answer(extractive(question, passages), passages)
return Answer(knowledge.model.chat(messages(question, passages), alias="smart"), passages)
The CLI's wiring, from src/aip/knowledge/cli.py, lines 147-169:
def knowledge(memory: bool): # lesson 4.2: every search goes through the permission walls
from aip.knowledge.access import Knowledge
from aip.knowledge.authz import LocalAuthz, OpenFGA, desired_tuples
from aip.knowledge.model import default_model
s, model = get_settings(), default_model()
if memory:
from aip.knowledge.pipeline import build_memory_index
snap = snapshot()
return Knowledge(LocalAuthz(desired_tuples(snap)), model, index=build_memory_index(snap, model, parse_cache()))
from aip.knowledge.pgstore import PgStore
return Knowledge(OpenFGA(s.openfga_url, s.openfga_store), model, store=PgStore())
def cmd_grep(args) -> int: # lesson 3.2 (the mirror), behind the three walls from lesson 4.2
from aip.knowledge.mirror import Mirror
from aip.knowledge.tools import KnowledgeTools
tools = KnowledgeTools(knowledge(args.memory), Mirror(get_settings().mirror_dir))
print(tools.call("grep", {"pattern": args.pattern}, person(args.who)).content)
return 0
Sources
- OpenFGA, RAG authorization: pre-filter with ListObjects, post-filter with BatchCheck, over-fetch 2 to 3 times. https://openfga.dev/docs/modeling/agents/rag-authorization (checked 12 Nov 2026)
- OpenFGA HTTP API (stores, authorization models, write, list-objects, batch-check). https://openfga.dev/api/service (checked 12 Nov 2026)
- OpenFGA v1.22.1 server defaults (
--listObjects-max-results 1000,--listObjects-deadline 3s), fromopenfga run --helpin the pinned image, 12 Nov 2026. https://github.com/openfga/openfga/releases - AuthZed, SpiceDB with a vector store (when pre- or post-filtering fits). https://authzed.com/docs/spicedb/integrations/pinecone (checked 11 Nov 2026)
- Reference repository
ai-platform, branchseries, tage5-m4-l2:authz.py,access.py,answer.py,cli.py,model.fga,infra/compose/compose.yml,tests/knowledge/test_openfga_restart.py,tests/knowledge/test_batch_check.py, decision records 0503 and 0509; outputs run at the tag on 14 Nov 2026 (the compose block,authz.pyand the diff re-checked at the tag on 15 Nov 2026). - Reference repository
ai-platform, branchseries, tage5-m4-l2:authz.py,access.py,answer.py,cli.py,model.fga,infra/compose/compose.yml,tests/knowledge/test_openfga_restart.py,tests/knowledge/test_batch_check.py, decision records 0503, 0508 (rerank as configured) and 0509; outputs run at the tag on 14 Nov 2026 (the compose block,authz.pyand the diff re-checked at the tag on 15 Nov 2026).