HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 34“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
Enterprise RAG: Permissions, Tenancy and Data Isolation
Northwind Academy and Contoso Learning are both tenants on TechLearningPro.
Course progress0%
Focus
24 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
AI-Powered Full Stack Development · Lesson 34 · RAG, Search and Knowledge Systems
Lesson Overview
Northwind Academy and Contoso Learning are both tenants on TechLearningPro. A Northwind learner asked for "the rubric for the module assessment." Contoso had uploaded a private hiring rubric that used the same phrase. The vector query ranked Contoso's chunk first. The application filtered "afterward" in a helper that the prompt path forgot to call. The model quoted Contoso's rubric, and the citation rendered a title the Northwind learner could not open in the product. That is a data incident. Similarity is not entitlement.
A second bug was quieter. The request body included tenantId. One route trusted it. A third bug logged the top five chunk bodies, including instructor notes, into the info stream "to debug relevance." The access check on the HTTP response was fine. The log pipeline was a second store with no tenant boundary.
This lesson puts authorization in the retrieval predicate, built from the server session. The browser does not choose the tenant. A missing tenant fails closed. Platform catalog content is an explicit extra tenant id, platform, and only for public_catalog chunks when the tenant's license says to include it. Instructor notes, enrolled-course material, and private uploads are different visibilities. Memory from Lesson 32 and graph hops from Lesson 33 must use the same scope. A chunk that fails chunkVisible never enters the prompt, the citation list, or the info log.
Planning assumptions:
The lab corpus is an array of ChunkRecord with a precomputed score. Production computes distance in PostgreSQL after the same predicate. The score field exists so the test can prove a high-scoring foreign chunk still loses.
Row Level Security is a backstop for tenant_id. The application predicate also encodes visibility, enrollment, and owner. Keep them in lockstep with a test you can run without a database and a database test when Postgres is up.
Illustrative policy names match PostgreSQL's current_setting('app.tenant_id', true). If the setting is missing, the comparison matches no rows.
No real customer documents, connection strings, or credentials appear in fixtures. Tenant ids in tests are northwind, contoso, and platform.
Lesson 30's citation checker can only cite ids this filter returned. If you skip this lesson's predicate, that checker has nothing trustworthy to enforce.
Learning Objectives
By the end of this lesson you will be able to:
Explain why a global nearest-neighbor search followed by an application filter is the wrong primary control.
Build an AccessScope from the server session, ignoring any tenant id in the body.
Map a scope to visibilities: public catalog, enrolled course, instructor, and private upload.
Include the platform catalog only as an explicit licensed tenant, and only for public_catalog.
Implement chunkVisible so a tenant admin still cannot read another tenant.
Retrieve by filtering first and ranking second, and return an empty list when the scope has no tenant id.
Stamp new chunks with the session tenant and owner, ignoring a tenant id on the draft.
Keep eligible citation ids equal to the filtered result set.
Describe a Postgres predicate and a Row Level Security backstop that fails closed when the session variable is unset.
State why post-filtering a small global candidate list can both leak and return too few authorized hits.
Apply the same scope to conversation reads and graph walks.
Keep private chunk text out of info logs. Log ids and counts.
Separate an audited support impersonation grant from a missing predicate.
Test a foreign chunk with a higher score, a forged body tenant, instructor visibility, and a private upload owned by someone else.
Hand Lesson 35 a ScopedRetriever the orchestrator calls before ModelPort.
Lesson 32's owner check on conversations and Lesson 33's tenant check on edges. This lesson is the corpus half of the same rule.
You will not connect to a production database. The unit tests use an in-memory corpus.
What is Enterprise RAG: Permissions, Tenancy and Data Isolation?
Tenancy means each customer's rows carry a tenant_id and queries are limited to the tenants that session may touch. Data isolation means a request for tenant A cannot read tenant B's chunks, conversations, edges, or traces, even when B's text is the nearest match. Permissions inside a tenant mean a learner, an instructor, and the owner of a private upload do not all see the same visibilities.
In a RAG system the dangerous step is retrieval, because the model will treat whatever text you place in the prompt as material it may quote. A filter after generation is too late. A filter after you have already written chunk text to a log is too late for that log. The purpose of this lesson is to make the authorized set the only set the rest of the pipeline can see.
Search engines and vector indexes do what you ask. If you ask for the nearest chunks in the whole table, you get them. Enterprise products at banks, hospitals, and learning platforms learned this with ordinary databases first: a missing WHERE account_id = $session is broken object-level authorization. Embeddings did not repeal that bug. They made it easier to miss, because the query that looks "smart" is the one that sorts by distance with a limit and no predicate.
public_catalog, enrolled, instructor, or private_upload
Platform tenant
Shared TechLearningPro catalog, id platform
Predicate
The boolean a chunk must pass before ranking
Eligible citations
Chunk ids in the filtered result
RLS
Database policy that repeats the tenant boundary
Impersonation
A separate audited grant, not a null filter
Fail closed
No tenant id yields no rows
Why Do We Need It?
text
Nearest neighbors across the whole corpus
|
v
Another tenant's private chunk ranks first
|
v
The prompt quotes it, or a log stores it
|
v
Filter from the session, then rank
|
v
Only visible chunks can be cited
Benefits:
A high similarity score cannot outrank an authorization failure, because unauthorized rows are not candidates.
Learners, instructors, and upload owners see different visibilities inside one tenant.
The platform catalog is shared on purpose, under a license flag, not because a query forgot a predicate.
Tests document the incident as a regression: Contoso's higher score stays out of Northwind's result.
Memory, graph expansion, and traces have a single scope type to accept.
Real World Example
Priya's session at Northwind includes tenantId: "northwind", role: "learner", enrollment in the RAG course, and includePlatformCatalog: true. She can retrieve public_catalog chunks from platform, enrolled chunks for courses she is in, and her own private_upload notes. She cannot retrieve Contoso rows, Northwind instructor notes, or another learner's upload. An instructor session adds instructor visibility for staffCourseIds. A tenant admin can read visibilities inside Northwind for support, and that read is audit-logged. The admin scope still has tenantId: "northwind". There is no scope whose tenant id is "all."
Microsoft 365-style copilots answer from documents the signed-in user can open. Google-style enterprise search does the same with drive permissions. A bank's assistant can talk about the caller's accounts. A hospital assistant that retrieved another patient's note would be a reportable event, not a bad eval score. Amazon-style marketplace search does not mix one seller's private operational notes into another seller's help bot. Netflix-style content catalogs separate global title metadata from a subscriber's private history. TechLearningPro's split is the platform catalog versus the tenant's uploads and instructor material. The mechanism is the same: identity in the session, predicate in the query, quotes only from rows that survived.
Internal Working
The route authenticates and loads enrollments and the license flag from PostgreSQL. It constructs AccessScope. If tenantId or userId is empty, it returns 401 and does not retrieve.
The route ignores body.tenantId, body.role, and any sentence in the user text that names a tenant. scopeFromSession returns the session scope unchanged. The user text is only a query string.
chunkVisible(scope, chunk) applies the rules in the deep dive. rankVisible filters the corpus with that function and then sorts by score descending, then by chunkId for stability, and slices to limit.
The production SQL has the same predicate in WHERE, then ORDER BY distance, then LIMIT. The application function is the specification. The SQL must match it.
The result's ids are the eligible citation set. The answer checker drops any other id.
stampChunk writes tenantId and ownerUserId from the scope. A draft that carries tenantId: "contoso" still stores northwind when the session is Northwind. Visibility private_upload is the default for an upload. Instructor notes can be stamped only when role is instructor or admin.
Graph expansion from Lesson 33 is invoked with scope.tenantId and, when licensed, a second walk on platform that may only contribute chunks chunkVisible accepts. The union is filtered again at hydrate time.
Conversation get from Lesson 32 uses the same tenantId and userId. A trace row stores those ids and the chunk ids, not the chunk text.
If the database role used by the app sets app.tenant_id and app.include_platform with SET LOCAL, RLS can reject a query that forgot the tenant predicate. Visibility and enrollment still belong in the SQL the app sends, unless you also encode them in RLS and test both.
Support impersonation is a different middleware: a staff grant, a reason code, an expiry, and an audit row written before the read. It builds a scope for the target user. It does not disable chunkVisible.
WHERE tenant and visibility and enrollment and owner
|
v
ORDER BY distance LIMIT k
|
v
Eligible chunk ids
|
+--> prompt passages
+--> citation allow-list
+--> trace ids
|
x Foreign chunk text stops here
The browser is outside the trust boundary for authorization fields. The model is outside the trust boundary for the decision. Both receive only what the predicate allowed.
Deep Dive
The predicate
A chunk is visible when all of the following hold.
The tenant clause:
chunk.tenantId === scope.tenantId, or
scope.includePlatformCatalog is true and chunk.tenantId === "platform" and chunk.visibility === "public_catalog".
The visibility clause, inside that tenant match:
public_catalog is visible to every role that passed the tenant clause.
enrolled is visible when scope.enrolledCourseIds contains chunk.courseId. Admins of the same tenant may read it. Instructors may read it when the course is in staffCourseIds or enrolledCourseIds.
instructor is visible to instructor and admin when the course is in staffCourseIds. Learners never pass this arm. Admins pass for courses in the tenant because the admin arm is explicit in code, not implied by a missing check.
private_upload is visible only when chunk.ownerUserId === scope.userId. Tenant admins do not automatically read another person's private upload. Support uses impersonation as that user, which is audited, or a separate legal hold tool that this lesson does not stub into the learner route.
Empty tenantId fails the function. Unknown visibility values fail the function. A null courseId fails enrolled and instructor.
Why filter-then-rank
If you take the global top 10 by distance and then drop other tenants, two failures follow. First, those 10 texts may already be in a log, a trace, or a prompt you built in the same function by habit. Second, all 10 might belong to other tenants or to instructor notes, so the learner gets an empty answer while authorized chunks sat at rank 11. The query has to demand authorized rows until it fills k or runs out of authorized rows. In PostgreSQL that is a WHERE clause before LIMIT.
Vector indexes and filters interact. Some planner choices can make a filtered query slower or, with an older index scan, approximate in ways you must verify. The product rule stays: correctness is the predicate. Performance options you evaluate with the pgvector version you actually run include a selective btree on tenant_id, partial indexes, partitioning by tenant, and iterative index scans when that version documents them. Record the version in the module comment when you tune. Do not remove the predicate because a plan was inconvenient.
Platform catalog
platform is a tenant with a name, not a missing tenant. Northwind's license sets includePlatformCatalog. Contoso's contract might set it false for a private-only deployment. The flag is loaded from the tenant row on the server. The browser cannot flip it. Platform chunks with visibility other than public_catalog stay hidden even when the flag is true. That keeps draft instructor material in the platform tenant off learner prompts.
Writes
Ingestion uses the uploading user's scope. stampChunk overwrites tenant and owner from the scope. A worker that processes an upload queue receives the tenant on the job payload, copied at enqueue time from the scope, not from a file the user edited. The worker's database role can insert for that tenant. A job without a tenant is dead-lettered, not processed as "all tenants."
RLS backstop
sql
ALTERTABLE chunks ENABLEROWLEVEL SECURITY;
ALTERTABLE chunks FORCEROWLEVEL SECURITY;
CREATE POLICY chunks_tenant ON chunks
USING(
tenant_id = current_setting('app.tenant_id',true)
OR(
tenant_id ='platform'
AND current_setting('app.include_platform',true)='on'
AND visibility ='public_catalog'
)
);
current_setting(..., true) returns null when the setting is absent, and the equality fails, so a connection that forgot SET LOCAL sees no rows. The application still sends the visibility predicate. RLS as written here does not understand enrollments. Say that in the runbook so nobody assumes the policy is the whole authorization model. A database contract test can assert that a session set to northwind cannot SELECT a Contoso row even if the SQL string omits tenant_id.
-- visibility predicate still in the application SQL
COMMIT;
set_config with the third argument true is local to the transaction. Pool checkouts must not leak the setting to the next request. Use a transaction per request or reset the setting. A pooled connection that keeps Northwind's setting and then serves Contoso is the bug RLS was supposed to prevent, inverted.
Citations, logs, and traces
eligibleCitationIds is results.map(chunk => chunk.chunkId). The model may return extra ids. The checker intersects. Titles shown in the UI come from the same result objects.
Info logs: tenantId, userId, resultCount, chunkIds. Not text, not the private title if the title itself is sensitive. The lab logs ids only. Evaluation samples that need text use the retention path from Lesson 31, still stored under the tenant, not the shared debug log.
Prompt text is not a parameter
rankVisible accepts scope, corpus, and limit. It does not accept the user utterance. That signature is the design. A test can pass a query string that says to use another tenant and show that the function cannot see that string. The retriever that embeds the utterance uses the embedding for order among rows the predicate already allows. The embedding function does not return rows.
Impersonation
A support engineer helping Priya uses a grant row: actor id, target user id, tenant id, reason, expiry. Middleware loads Priya's real enrollments and builds her scope. The audit log records the actor. The learner route used by Priya's browser has no grant parameter. A body field named impersonateUserId is ignored there.
Code Examples
Place the package in packages/knowledge/src/access/. Routes call scopeFromSession and rankVisible. Ingestion calls stampChunk.
Private uploads compare ownerUserId to the session user. A tenant admin who needs to read one for support uses the audited impersonation grant and builds that user's scope. A legal-hold tool, if you add one later, is a different function with its own audit reason. It does not change chunkVisible to return true for every admin.
The corpus strings are synthetic labels. They are not customer data.
Architecture Diagram
text
Browser
| user text, conversation id
| body.tenantId is ignored
v
Session -> AccessScope
|
+--> unauthorized
|
v
rankVisible / SQL WHERE
|
+--> chunks the session may read, ordered by score, limited
|
v
eligibleCitationIds
|
+--> ModelPort messages (Lesson 23), passages only
+--> citation intersection (Lesson 30)
+--> trace chunk ids (Lesson 31)
Database session:
text
BEGIN
set_config app.tenant_id from scope.tenantId, local
set_config app.include_platform from the license flag, local
SELECT ... WHERE <visibility predicate> ORDER BY distance LIMIT k
COMMIT
Real-Time Enterprise Example
TechLearningPro's ask route builds Priya's scope once and passes it to memory, to rankVisible, and to graph hydration. The SQL the route's repository runs includes both the tenant arm and the visibility arm. RLS is enabled and forced on chunks, conversations, graph_edges, and ask_traces. A quarterly test runs a query that omits tenant_id on purpose in a transaction set to Northwind and expects zero Contoso rows. That test is a safety check in a private CI database with synthetic tenants. It is not a tool you point at a customer.
The incident in the overview is now a unit test: contoso-rubric scores 0.99 and is absent, and its text is absent from the log line. Instructor notes score 0.95 and are absent for Priya. An instructor fixture with staffCourseIds: ["course-rag"] would receive nw-instructor. Add that fixture when you extend the suite. Keep Priya's test red if her result ever contains that id.
Challenge: a private-only tenant and a model outage. Set includePlatformCatalog false in that tenant's row. rankVisible then drops platform-pgvector even if it is the only high-quality public chunk. The assistant says it has no source, which is the honest outcome under the contract. You do not flip the flag because retrieval looked thin. During a model outage you still do not widen the predicate to "find something to say." Lesson 35 returns the authorized passages or a refusal. It does not search a second tenant.
Pooled connections: integration coverage opens two transactions, sets different app.tenant_id values, and asserts each sees only its tenant. A connection returned to the pool is checked out inside a new transaction so SET LOCAL cannot leak.
Performance Optimization
The predicate should be selective. tenant_id equality cuts the corpus to one customer plus, when licensed, the platform public set. That is the difference between a global scan and a tenant scan. Measure plans with EXPLAIN on realistic volumes. If the vector index ignores the filter and then discards rows, look at the pgvector version's filtered-search guidance, partial indexes per large tenant, or partitioning. Put the measurement in the runbook. The learner-facing decision remains filter-then-limit.
rankVisible on an in-memory array is for tests and small corpora. Production must not load every tenant's chunks into the Node process to filter them. The database applies the predicate. Loading the world into RAM would both spend memory and recreate the leak in the client.
Cache authorized results only with a key that includes tenant id, user id, role, enrollment hash, license flag, and the query. A cache keyed by the query string alone is a cross-user bug. Prefer no cache until the key is reviewed. Authorization bugs in caches last longer than bugs in the SQL you can read on one screen.
Do not embed unauthorized text "just to rank it." The embedder on the ask path embeds the query, not the foreign corpus. Corpus embeddings were computed at ingest inside the owner's tenant.
Security
Authentication. Missing user or tenant yields unauthorized before any retrieval.
Authorization.chunkVisible is the document decision. Role and enrollment come from the session, not the body.
Object-level access. Chunk ids, conversation ids, and node ids are locators. Each read applies the scope again at hydrate time, so a graph id cannot smuggle text.
Tenant isolation. Other tenants are not candidates. Platform is opt-in and public-catalog only. Admins are scoped to their tenant. Private uploads stay with the owner.
Injection. User text is not an argument to the predicate. A sentence that names another tenant does not change AccessScope.
Logging. Info logs carry ids and counts. Chunk bodies stay in the database.
Writes.stampChunk overwrites tenant and owner from the session. Learners cannot stamp instructor or public catalog rows.
Database. RLS is forced. Session variables are transaction-local. The app role is not a superuser that bypasses RLS.
Impersonation. A grant with actor, target, reason, and expiry. The learner route ignores impersonation fields.
OWASP API risks that match are broken object level authorization and broken function level authorization (a learner stamping instructor visibility). The controls are the session scope, chunkVisible, stampChunk, and tests that use a higher score on the forbidden row.
Common Mistakes
Global top-k, then filter in the application. Symptom: a foreign rubric is quoted, or the learner gets no hits while authorized chunks existed. Cause: LIMIT ran before the predicate. Fix: predicate, then order, then limit, in SQL.
Trusting body.tenantId. Symptom: the client selects the tenant. Cause: the scope was parsed from JSON. Fix: scopeFromSession ignores the body.
Treating platform rows as "no tenant." Symptom: draft platform notes appear, or a private deployment searches the public catalog against contract. Fix: explicit includePlatformCatalog and public_catalog only.
Admin means all tenants. Symptom: a Northwind admin retrieves Contoso. Cause: the admin arm skipped tenantOk. Fix: admins stay inside scope.tenantId.
Admin means all private uploads. Symptom: staff browse learner notes from the learner route. Cause: private visibility was treated as tenant-wide. Fix: owner match, and a separate audited tool if support must look.
Logging the chunk text you just filtered. Symptom: instructor notes land in the log vendor. Cause: a debug dump. Fix: log ids. Review the logger in tests.
Hydrating graph ids without chunkVisible. Symptom: a platform walk returns an id the learner cannot open, and the prompt includes it anyway. Cause: the expander's ids were trusted. Fix: filter again at hydrate.
RLS without FORCE, or a superuser app role. Symptom: the policy never runs. Cause: the owner role bypasses RLS. Fix: force RLS and use a non-owner login.
SET instead of transaction-local config on a pool. Symptom: the next request inherits the previous tenant. Cause: session state on a shared connection. Fix: set_config local to the transaction, one transaction per request.
Cache key is the query string. Symptom: Priya receives Alex's private upload because he asked the same question. Fix: include the scope identity in the key, or skip the cache.
Citation list built from the model output. Symptom: a cited id the user cannot open. Cause: eligible ids were not the filtered set. Fix: intersect with eligibleCitationIds.
Widening the filter when the model is down. Symptom: an outage "fix" searches all tenants to keep a demo alive. Cause: a fallback corpus. Fix: return an authorized empty result or the passages you already filtered.
Best Practices
Derive AccessScope from the session after authentication.
Ignore tenant, role, and impersonation fields on the learner body.
Fail closed when tenant id or user id is empty.
Filter in the query, then rank, then limit.
Keep chunkVisible as the specification tests import.
Match that specification in SQL.
Force RLS as a tenant backstop, and document that it is not the enrollment model by itself.
Set tenant configuration for the transaction only, and test pool reuse.
Treat platform as a real tenant id gated by a license flag.
Restrict platform hits to public_catalog.
Require enrollment or staff assignment for course material.
Keep private uploads on ownerUserId.
Stamp writes from the scope, not from the draft's tenant field.
Reject learner attempts to publish instructor or catalog visibility.
Hydrate graph and memory-related chunk ids through the same visibility function.
Make eligible citation ids exactly the filtered ids.
Log ids and counts at info level.
Store eval samples that contain text under the tenant's retention rules.
Use a granted impersonation flow with an audit row for support.
Include a forbidden high-score chunk in the automated test.
Do not load all tenants' text into the app process to filter it.
Revisit index strategy when you change pgvector versions, without dropping the predicate.
Pass the same scope into Lesson 32's store and Lesson 33's reader.
Interview Questions & Answers
Beginner
Why is similarity not permission?
The index answers "what text is close to this query?" The session answers "what may this person read?" A private document in another tenant can be the closest text. If it is a candidate, the model can quote it. The predicate removes it before ranking and before the prompt.
Who sets the tenant id?
The server session, after authentication, from your user directory. A field in the JSON body is ignored. The platform catalog is added only when the tenant record says the license includes it.
What should a learner receive if the only close chunk is an instructor note?
The authorized hits that remain, or an empty authorized set and a refusal. They should not receive the note because it scored well, and the product should not search another tenant to fill the gap.
Intermediate
What goes wrong with global top-k followed by a filter?
Forbidden text can enter logs or prompts if any step forgets the later filter, and the limit can fill up with forbidden rows so authorized rows never surface. Put the predicate in the same query as the limit.
How do private uploads differ from tenant admin access?
A private upload is visible to its ownerUserId. A tenant admin can read enrolled and instructor material inside that tenant under the rules in chunkVisible. The admin does not automatically read private uploads. Support impersonation is a audited grant that acts as the owner.
What is the citation allow-list?
The chunk ids rankVisible returned. The model may emit other ids. The checker keeps the intersection. The UI titles come from the filtered records, so a title is not rendered for an id the user cannot open.
Senior
How do you test isolation without production data?
Build a synthetic corpus where the forbidden chunk has the highest score and contains a distinctive string. Assert the string is absent from results and from the info log. Add cases for an empty tenant, a body tenant id, instructor visibility, and another user's upload. Add a database test that sets app.tenant_id and expects a cross-tenant select to return zero rows.
How should graph hits and chat memory use this scope?
Memory reads already require tenant and user. Graph walks take a tenant id and return chunk ids, not text. Hydration calls chunkVisible again. A platform walk cannot contribute an instructor chunk to a learner. One scope object is passed through the orchestrator so a new store cannot invent a wider default.
Architect
How do you split RLS and application predicates?
RLS on tenant_id and the licensed platform public catalog is the backstop that still returns nothing when a query forgets the tenant. Enrollment, instructor courses, and upload ownership live in the application SQL and in chunkVisible, with tests. You may fold them into RLS later, but then the database test must cover each visibility. State the split in the runbook so an operator does not assume the short policy is the full product rule.
What do you change for a tenant that forbids the public catalog and forbids a fallback model vendor? includePlatformCatalog is false, so platform rows drop out. The vendor allow-list from Lesson 23 is a different field on the tenant policy. Neither outage nor a thin result sets the license flag to true or adds a vendor. The assistant returns an authorized refusal or authorized passages with no generated paragraph.
Knowledge Check
1. What problem does this capability solve?
It stops the knowledge assistant from retrieving, quoting, logging, or citing another tenant's data or a document the signed-in user cannot open, even when that document is the nearest match.
2. What alternatives exist, and when would you choose each?
A single-tenant prototype on one laptop can still call chunkVisible so the habit exists. Session predicates plus RLS fit TechLearningPro. Filter-after-limit fits no production ask path. A support impersonation grant fits a staff tool with an audit row. A superuser search across tenants fits a separate locked-down investigation process, not the learner route.
3. Which data, identity, and trust boundaries matter?
The session holds tenant, user, role, enrollments, staff courses, and the license flag. The body does not. The database enforces a tenant backstop. The model sees only filtered passages. Logs at info level see ids. Private uploads stay bound to the owner. The browser and the model are both untrusted for authorization decisions.
4. What can fail, and how should the system respond?
An empty tenant yields no rows and an unauthorized scope. A foreign chunk is not a candidate. A pooled session variable must not leak between requests. A graph id that fails hydration is dropped. A model citation outside the eligible set is dropped. An outage does not widen the predicate.
5. How would you test quality, security, performance, and cost?
Unit tests cover the high-scoring foreign chunk, instructor notes, private uploads, body tenant ids, empty tenants, write stamping, and log redaction. A database test covers RLS and pool isolation. Performance work uses EXPLAIN on the filtered query. Cost stays bounded because you do not embed foreign corpora on the ask path and you do not call the model with unauthorized text.
Practical Exercise
Implement packages/knowledge/src/access/ and run the tests. Add an instructor scope whose staffCourseIds include course-rag, and assert that scope receives nw-instructor while Priya's result still does not. Write two sentences on why the instructor result must still exclude contoso-rubric.
Deliverable and Rubric
Submit the scope diagram, the access package, the test output, the RLS sketch with the enrollment gap called out, and a note on what the info log contains.
Area
Weight
Conceptual accuracy and architecture
20%
Working implementation and code quality
25%
Security, privacy, and responsible AI
20%
Testing, reliability, and observability
20%
Documentation and decision rationale
15%
Key Takeaways
Authorization is a retrieval predicate, not a cleanup step after the model.
The session builds AccessScope. The body does not.
Filter, then rank, then limit.
An empty tenant returns nothing.
Platform content is an explicit licensed tenant and public visibility only.
Learners, instructors, admins, and upload owners follow different visibility arms.
Tenant admins do not cross tenants and do not inherit private uploads.
Writes take tenant and owner from the scope.
Eligible citations are the filtered ids.
Graph and memory hydration use the same visibility function.
Info logs carry ids, not private bodies.
RLS is a tenant backstop. Enrollment still lives in the application predicate.
Transaction-local settings prevent pool leaks.
Impersonation is an audited grant.
A higher score on a forbidden chunk belongs in the test suite.
Outages do not widen the corpus.
Summary
Lesson 34 is the boundary that makes the rest of Module 3 deployable. TechLearningPro ranks chunks only after chunkVisible accepts them, stamps writes from the session, and treats the platform catalog as a licensed tenant rather than as the absence of a filter. Memory, graph ids, citations, and traces all consume that scope. The capstone can call a model only with what this predicate returns.
Next Lesson Preview
Production Knowledge Assistant Capstone wires the module into one ask path: scope, memory, standalone query, filtered retrieval, a short graph walk, citation checks, and ModelPort. You will test the refusal when nothing is visible, the timeout that shows sources without a paragraph, and the double-submit that must not bill the model twice.