DEV Community

kapilan-spec
kapilan-spec

Posted on

Permission-aware hybrid search: put the ACL inside both arms of the query

Where should you enforce permissions in hybrid search? Before ranking, and in both arms — vector and BM25. Post-filtering the top-k can return empty results or leak counts; filtering only one arm lets reciprocal rank fusion promote a restricted chunk.

Most RAG tutorials end at "embed, retrieve top-k, stuff into the prompt." The moment your corpus contains documents that not everyone may read (HR files, customer data, private incident notes) that recipe becomes a data-leak machine. And there's a particularly easy way to get it half-right: add a permission check, but in the wrong place.

Pre-filter vs post-filter: where the ACL check belongs

There are three places to enforce who-can-see-what:

  1. After generation (ask the model to redact). Not a control. The model has already seen the text.
  2. After retrieval (post-filter the top-k). Safe from leaking text, but broken for relevance: if the top 10 chunks are all ones the user can't read, they get nothing, even though permitted answers exist at rank 11. Counts and "I found 3 documents about X" messages can also leak existence.
  3. Before ranking (pre-filter). The candidate set only ever contains permitted chunks, so the top-k is the top-k of what this person may read.

Only option 3 is acceptable for sensitive data. With hybrid search there's a second trap.

Why both arms of hybrid search need the same permission filter

Hybrid retrieval runs a semantic (vector) search and a lexical (BM25) search, then fuses the rankings, commonly with reciprocal rank fusion (RRF). If you filter the vector arm but forget the keyword arm (or the other way round), the unfiltered arm can surface a restricted chunk, and fusion happily promotes it. A subtler leak: BM25 uses corpus statistics (document frequency, average length). Computing those over all documents means a user's scores depend on documents they can't see. Compute them over the visible set.

Here's a small, dependency-free implementation that makes the structure obvious: filter first, then run both arms over the same visible list, then fuse.

from __future__ import annotations
from dataclasses import dataclass
import math, re
from collections import Counter

@dataclass(frozen=True)
class Chunk:
    id: str
    text: str
    vec: tuple[float, ...]
    acl: frozenset[str]          # principals allowed to read; empty = nobody

def allowed(chunk: Chunk, principals: set[str]) -> bool:
    return bool(chunk.acl & principals)   # deny by default: empty acl matches nothing

def cosine(a, b):
    num = sum(x * y for x, y in zip(a, b))
    den = math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b))
    return num / den if den else 0.0

def tokens(s: str) -> list[str]:
    return re.findall(r"[a-z0-9_]+", s.lower())

def bm25_scores(query: str, docs: list[Chunk], k1=1.5, b=0.75):
    # IDF is computed over the VISIBLE docs only, so statistics don't leak either.
    n = len(docs)
    if n == 0:
        return {}
    toks = {d.id: tokens(d.text) for d in docs}
    avg = sum(len(t) for t in toks.values()) / n
    df = Counter(t for ts in toks.values() for t in set(ts))
    out = {}
    for d in docs:
        tf = Counter(toks[d.id])
        s = 0.0
        for q in set(tokens(query)):
            if tf[q] == 0:
                continue
            idf = math.log(1 + (n - df[q] + 0.5) / (df[q] + 0.5))
            s += idf * tf[q] * (k1 + 1) / (tf[q] + k1 * (1 - b + b * len(toks[d.id]) / avg))
        if s > 0:
            out[d.id] = s
    return out

def rrf(rankings: list[list[str]], k: int = 60) -> list[tuple[str, float]]:
    fused: dict[str, float] = {}
    for ranking in rankings:
        for rank, doc_id in enumerate(ranking, start=1):
            fused[doc_id] = fused.get(doc_id, 0.0) + 1.0 / (k + rank)
    return sorted(fused.items(), key=lambda kv: kv[1], reverse=True)

def search(query: str, qvec, corpus: list[Chunk], principals: set[str], top_k=5, arm_k=50):
    visible = [c for c in corpus if allowed(c, principals)]          # filter FIRST
    sem = sorted(visible, key=lambda c: cosine(qvec, c.vec), reverse=True)[:arm_k]
    kw_scores = bm25_scores(query, visible)
    kw = sorted(kw_scores, key=kw_scores.get, reverse=True)[:arm_k]
    fused = rrf([[c.id for c in sem], kw])
    return fused[:top_k]

if __name__ == "__main__":
    corpus = [
        Chunk("pub", "checkout api retries use backoff", (1, 0), frozenset({"domain:acme.com"})),
        Chunk("sec", "incident 4412: idempotency key reuse in checkout api", (1, .1), frozenset({"bob@acme.com"})),
        Chunk("orphan", "checkout api idempotency notes, no acl", (1, 0), frozenset()),
    ]
    alice = {"alice@acme.com", "domain:acme.com"}
    bob = {"bob@acme.com", "domain:acme.com"}
    for name, who in (("alice", alice), ("bob", bob)):
        ids = [i for i, _ in search("checkout api idempotency", (1, 0), corpus, who)]
        print(name, "sees:", ids)
        assert "orphan" not in ids and ("sec" in ids) == (who is bob)
Enter fullscreen mode Exit fullscreen mode

Run it and you get:

alice sees: ['pub']
bob sees: ['pub', 'sec']
Enter fullscreen mode Exit fullscreen mode

Three details worth copying:

  • Deny by default. bool(chunk.acl & principals) means an empty ACL matches nobody. The "no ACL = public" default is how orphaned documents leak.
  • Principals come from the session. principals should be built from your auth layer (user id, group ids, domain: style wildcards), never from request parameters the client or the model can set.
  • The negative test is the real test. The two asserts at the bottom are the idea: for every user, assert that nothing outside their ACL can appear. In a real suite, run it against both arms separately, not just the fused result.

The same permission-aware hybrid query in Postgres

In SQL, the equivalent is to put the predicate in each arm's WHERE, so the planner can use your indexes:

-- semantic arm
SELECT id FROM chunks
WHERE tenant_id = $1 AND acl && $2::text[]
ORDER BY embedding <=> $3::vector
LIMIT 50;

-- keyword arm
SELECT id FROM chunks, websearch_to_tsquery('english', $4) q
WHERE tenant_id = $1 AND acl && $2::text[] AND tsv @@ q
ORDER BY ts_rank_cd(tsv, q) DESC
LIMIT 50;
Enter fullscreen mode Exit fullscreen mode

Two gotchas. First, a highly selective filter makes approximate vector indexes return fewer rows than you asked for, because the index finds nearest neighbours then applies the filter; recent pgvector versions have iterative index scans for this (check the docs for your version), and partitioning by tenant helps. Second, a CTE referenced from both arms gets materialized in PostgreSQL 12+, which bypasses your indexes, so repeat the predicate or enforce it with a row-level-security policy. Look at EXPLAIN.

How to keep document ACLs in sync

The filter is only as good as the ACL data. Treat it as a synchronization problem:

  • Event-driven updates from the source system when someone is removed from a group.
  • Periodic reconciliation as a mandatory safety net, because event pipelines fail silently.
  • ACL changes should be cheap metadata updates, not re-embedding jobs. That's one reason to store them on the chunk or source rather than baking them into the vector.

Using a retrieval service for permission-aware RAG

If you'd rather not run this yourself, many services expose the same primitives. As an example, open-source HydraDB lets you attach an acl to each ingested source, and POST /query accepts the caller's principals, a hybrid/keyword switch, a semantic-vs-BM25 weight, and metadata filters:

curl -X POST 'https://api.hydradb.com/query' \
  -H "Authorization: Bearer $HYDRADB_API_KEY" \
  -H "API-Version: 2" \
  -H "Content-Type: application/json" \
  -d '{
    "database": "acme_corp",
    "collection": "company_docs",
    "query": "what changed in the Q3 refund policy?",
    "type": "knowledge",
    "query_by": "hybrid",
    "alpha": 0.8,
    "mode": "thinking",
    "acl": ["grace@acme.com"],
    "metadata_filters": { "department": {"equals": "legal"} }
  }'
Enter fullscreen mode Exit fullscreen mode

What the docs say about this, including the sharp edges:

  • A source's acl lists who may retrieve it (emails, domain: principals, group principals, __public__); a source with no acl is unrestricted, the opposite of the deny-by-default rule above, so set one at ingest.
  • The query's acl is who is asking. If you omit it, send [], or send ["*"], filtering is off and you get everything in scope. Derive it from your authenticated session.
  • alpha is the hybrid weight (1.0 pure semantic, 0.0 pure BM25; default 0.8). Metadata filters narrow results but don't replace acl.
  • Connectors for apps like Slack, Drive, and Confluence can carry the source app's permissions over on each sync, where the provider supports it.

Whichever route you choose, run the negative test from earlier against it: create two users, plant a private chunk, and assert that it never appears for the wrong one. Most permission bugs I've seen in RAG systems would have been caught by those ten lines.

FAQ: permission-aware hybrid search

What is permission-aware (ACL-aware) RAG?
Retrieval that only returns documents the current user is allowed to read. The access-control list lives on each source or chunk, the caller's principals come from your auth layer, and the filter runs before ranking so the top-k is the top-k of what that person may see.

Why is post-filtering the top-k a problem?
If the nearest neighbours are mostly documents the user can't read, they get an empty or thin answer even though permitted documents exist further down. Counts, facets, and "I found 3 documents about X" messages can also leak existence.

How do I apply ACLs in hybrid search (BM25 + vector)?
Use the same permission predicate in both arms, then fuse (for example with reciprocal rank fusion). Compute BM25 corpus statistics over the visible set only. A negative test — plant a private chunk, query as the wrong user, assert it never appears in either arm — catches most bugs.

Should an empty ACL mean public or private?
Deny by default: an empty ACL should mean nobody, not everybody. (If you use a managed service, check its default — some treat a missing ACL as unrestricted.)

Top comments (2)

Collapse
 
analista_83 profile image
Sammi De Blas •

Pre-filtering both arms is the only version that survives reciprocal rank fusion. Post-filtering the top-k also leaks existence, which is a real problem for HR or incident corpora. Did you measure the recall cost of the ACL predicate on the BM25 side, since the inverted index has to carry the permission field?

Collapse
 
sunnatulla_dev profile image
Sunnatulla •

The semantic arm can also come back empty only in production. On PG17 + pgvector 0.8.7, 100k chunks, 40 readable by one contractor: the plain query returns all 40. Through psycopg, from the 11th call the generic plan picks HNSW and returns 0. iterative_scan alone got 3 to 14; adding hnsw.max_scan_tuples = 200000 got all 40. Meanwhile RRF just serves that user keyword-only results.