FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Access-Aware Retrieval

Enforce tenant and document authorization before evidence enters ranking or model context.

Freshness: current•15 min read•Retrieval and Knowledge Systems

Key Learning Outcomes

  • ✓Explain the operating model behind Access-Aware Retrieval.
  • ✓Evaluate trade-offs and failure modes for Access-Aware Retrieval.
  • ✓Apply Access-Aware Retrieval to a production decision.
Full Technical Reference Document

Mental model

Retrieval authorization is a mandatory query-time Zero-Trust boundary ensuring restricted tenant, group, or document records never enter dense rerankers, semantic response caches, model prompts, or intermediate reasoning traces—preventing cross-tenant disclosure and indirect prompt injection before generation ever begins.

Verified JWT / identity claims
Pre-filter HNSW & BM25 indexes
Iterative filtered graph traversal
Authoritative live ACL assertion
Scoped cache & cited prompt
Conceptual teaching model synthesized from:Zero Trust Architecturepgvector Documentation

Learning outcomes

  • Enforce deterministic identity and group membership predicates directly inside vector and lexical index scans rather than post-generation filters.
  • Prevent recall collapse under selective HNSW graph filters using iterative index scanning or tenant-partitioned physical indexes.
  • Isolate response caches, ranking metadata, and prompt context strictly along cryptographic identity and permission-epoch boundaries.

Theory

Treating authorization as a prompt instruction ("Only reveal documents Alice is permitted to read") or a post-generation regex over cited IDs creates guaranteed confidentiality breaches. Even if a post-generation filter deletes a forbidden footnote before rendering UI text, facts synthesized from that confidential document remain baked inside the generated prose, and timing or citation-count side channels reveal protected workspace existence cleanly. Enforcement therefore spans three deterministic layers:

Security Control BoundaryImplementation PatternResidual Risk PreventedLatency & Index Impact
Pre-Filter Index QueryBind server-verified JWT tenant_id & acl_groups inside SQL WHERE / vector metadata filterUnauthorized vectors never score or leave index storageSelective ACLs in naive HNSW shrink top-k candidate pool unless iterative scan runs
Tenant-Partitioned Indexes / TablesPhysical Postgres table partitions (PARTITION BY LIST (tenant_id)) or dedicated HNSW per tenantEliminates cross-tenant graph edge leaks & noisy-neighbor recall dropHigh small-tenant catalog count raises index handle memory
Scoped Semantic Cache KeyHash sha256(normalized_query, tenant_id, sorted_acl_groups, index_epoch)Prevents User A's executive memo answer from hitting User B's cacheLower cache hit ratio for highly granular per-user ACL combinations

When selective HNSW pre-filtering matches only 1% of rows globally, naive efSearch = 40 graph walks visit 40 globally nearest neighbors, discard all unauthorized items post-visit, and return zero results even when authorized documents exist! Enabling hnsw.iterative_scan = relaxed_order (PostgreSQL pgvector >= 0.8), partitioning indexes by tenant, or combining filtered BM25 lexical search with iterative vector fallback preserves both recall and zero-leak confidentiality cleanly.

sql
-- Authoritative PostgreSQL + pgvector access-aware hybrid retrieval query
BEGIN;
SET LOCAL hnsw.iterative_scan = relaxed_order;
​
WITH authorized_candidates AS (
SELECT
c.chunk_id,
c.doc_id,
c.acl_epoch,
c.content,
(c.embedding <=> :query_vec) AS cosine_dist
FROM document_chunks c
WHERE c.tenant_id = :verified_tenant_id
AND c.deleted_at IS NULL
AND c.acl_groups && :verified_user_groups::text[] -- Pre-filter BEFORE rerank or LLM
ORDER BY c.embedding <=> :query_vec
LIMIT 25
)
SELECT chunk_id, doc_id, content, cosine_dist
FROM authorized_candidates
ORDER BY cosine_dist ASC
LIMIT 8;
COMMIT;

Trade-offs

Pre-filtering vector scans over a shared global HNSW table is simple to provision across thousands of dynamic SMB tenants and handles fine-grained document-level RBAC rules cleanly, yet requires iterative index scans (hnsw.iterative_scan) and carefully sized indexes when selective user roles match tiny corpus fractions. Physical per-tenant index partitioning (tenant_id partitioned collections or schemas) guarantees hard noisy-neighbor isolation, maximum filtered Recall@K, and instant offboarding drops, at the expense of higher cluster metadata overhead when tens of thousands of inactive tenants exist. Pairing database pre-filtering with a fast authoritative ACL-epoch re-check right before packing prompts closes the propagation gap between HR role revocations and asynchronous index syncs.

Failure modes and misconceptions

  • Filtering After Model Generation: Stripping restricted citations only after LLM synthesis leaks sensitive numbers, names, and paraphrases right inside the visible completion text.
  • Trusting Client-Supplied tenant_id Fields: Accepting user_id or org_id directly from HTTP body JSON instead of verified session tokens or mTLS claims enables trivial horizontal privilege escalation.
  • Global Unscoped Semantic Caches: Keying caches purely by embedding similarity serves confidential board slides retrieved for an admin directly to unprivileged contractors asking an identical prompt.
  • HNSW Pre-Filter Starvation: Applying selective WHERE acl_groups && ... predicates over small static LIMIT 40 ANN scans returns 0 matches silently unless iterative scanning or per-tenant partitions are active.

Decision scenario

A multi-tenant B2B enterprise search product stores engineering specs, M&A diligence memos, and HR policies inside one shared vector cluster. After enabling role filters on top of naive ANN search, sales reps see 0 results on valid product queries while caching briefly leaked a private layoff FAQ summary across tenants. Architect tenant partitioning/iterative pre-filtering, JWT claim derivation, and ACL-hashed cache keys cleanly.

Reflect before revealing the guide

Why is stripping restricted document citations after LLM generation fundamentally insufficient for multi-tenant RAG authorization?

Prerequisites & Related Concepts (5)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-401RAG Engineer

Build evidence-carrying retrieval systems from ingestion and provenance through search reranking grounded generation and evaluation.

21 concepts~25h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next