RLS + pgvector:行級安全策略如何令查詢規劃器看不見租戶
RLS + pgvector: the policy that hides your tenant from the planner
作者在 PostgreSQL 17.12 與 pgvector 0.8.7 上測試多租戶向量搜尋,發現 RLS policy 將租戶設定包在 scalar subquery 時,查詢規劃器可能無法辨識租戶資料量,令小租戶漏取結果。
If you build multi-tenant RAG or AI memory on Supabase or plain Postgres, there is a good chance your vector search has no tenant filter in it at all:
SELECT id, content FROM documents
ORDER BY embedding <=> $1
LIMIT 10;
Row Level Security adds the filter for you. The policy reads the user from the session, and every query only sees that user's rows. It's a clean design, and on Supabase it's the default advice.
I had already measured how filtered HNSW search fails small tenants when the filter sits in a WHERE clause. The question this time was what happens when the filter comes from a policy instead. The planner can lose sight of who the tenant is, and when that happens, users with a few documents get empty results. Whether it happens depends on one pair of parentheses and one index.
The setup
Same harness as last time. Real PostgreSQL 17.12 with pgvector 0.8.7, one table of 200,000 rows (128-dim synthetic vectors) shared by 2,115 tenants, default HNSW (m=16, ef_construction=64), k = 10. Probe tenants own exactly 1, 10, 100, 1,000 and 10,000 rows, with 60 queries per size. Ground truth is exact search over the tenant's rows. Every number is the mean of 3 separate HNSW builds.
The search runs as a role without BYPASSRLS. Before each query the app does set_config('app.tenant_id', ...), the way Supabase puts the JWT in a setting that auth.uid() reads. I tested two policy spellings:
-- A: call the function directly
USING (tenant_id = current_setting('app.tenant_id')::int)
-- B: wrap it in a scalar subquery
USING (tenant_id = (SELECT current_setting('app.tenant_id')::int))
B is what Supabase's RLS performance guide recommends for auth.uid(): wrapped in a SELECT, the function runs once per statement as an InitPlan instead of once per row. People apply it everywhere, and for the per-row cost it does exactly what it promises.
Each policy ran with and without a B-tree on tenant_id, in three plan modes: a plain query, a forced generic plan, and a real named prepared statement where Postgres decides for itself. That last one is what you get from psycopg after 5 executions, from the JDBC driver by default, and from asyncpg on every statement.
The numbers
Recall@10 by tenant size, no index on tenant_id:
| policy | how the query runs | 1 row | 10 rows | 100 rows | 10,000 rows | 1-row searches that came back empty |
|---|---|---|---|---|---|---|
| B, wrapped | plain query | 0.11 | 0.09 | 0.54 | 0.88 | 89% |
| B, wrapped | prepared | 0.11 | 0.09 | 0.54 | 0.88 | 89% |
| A, direct | plain query | 1.00 | 1.00 | 1.00 | 0.88 | 0% |
| A, direct | prepared | 0.19 | 0.09 | 0.54 | 0.88 | 81% |
With the wrapped policy, 89% of searches for a one-document user returned nothing, prepared or not. Every query took 1.3 to 1.5 ms and raised no error. In a chatbot that just looks like the model saying it doesn't know.
The direct policy behaves better on plain queries: the planner switches to a sequential scan for small tenants and gets everything right, at about 62 ms per search on this table. Once the statement is prepared, it drops to 0.19.
Why the parentheses matter
I wrote a small script that EXPLAINs the search for the smallest and the biggest tenant under each policy and prints the planner's row estimate for the scan.
With the direct call, the planner evaluates current_setting() while it plans, even for a generic plan. It estimated 27 rows for a 1-row tenant and 19,273 rows for a tenant that really has 19,085. It knows who you are, and on a plain query it picks the right plan for each tenant.
So why does the prepared version fail? In a prepared statement the LIMIT is a parameter too, and with an unknown limit the costs shift towards HNSW. I checked: the same generic plan with LIMIT 10 written into the SQL goes back to a sequential scan for the 1-row tenant. Postgres compares that generic plan with the custom plans it made for the first 5 executions, decides the generic one is cheaper, and keeps it.
With the wrapped policy, the tenant id is the output of an InitPlan. It doesn't exist until the query runs, so the planner can't look it up in the statistics. Every tenant got the same 111-row guess. With 111 rows, HNSW looks like a good deal, so that's what every tenant gets, on plain queries as well.
The table size moves this line. I ran the same strategies on real text too (Simple English Wikipedia paragraphs embedded with all-MiniLM-L6-v2, 50,000 rows). On that smaller table the 111-row guess still priced a sequential scan, so plain queries were fine (1.00, about 17 ms), and only prepared statements failed: 0.87, 0.63, 0.23, 0.22 and 0.76 across the five sizes. Your app can be fine today and start forgetting small users as the table grows, without any code change.
What fixes it
The fix that held for small tenants everywhere is an index on the policy column. With CREATE INDEX ON documents (tenant_id), every tenant up to 1,000 rows got recall 1.00 with both spellings, in all three plan modes, on both datasets, at about 0.3 ms for the small ones. The planner reads the tenant's rows through the B-tree and sorts them exactly.
One cell didn't move: the direct spelling on a plain query, for the 10,000-row tenant. There the planner knows the tenant is big and goes back to HNSW, so it gets ordinary HNSW recall, 0.88 on the synthetic table and 0.76 on Wikipedia. The wrapped policy with the index scored 1.00 for that tenant too (about 5.3 ms), because its flat 111-row guess always picks the B-tree. That's the one place where the planner not knowing who you are helped. Supabase's RLS guide asks for this index too, in the same document that recommends the wrap. Here the two pieces of advice depend on each other: on the 200k table, the wrap without the index made plain queries worse than no wrap at all (0.11 against 1.00).
hnsw.iterative_scan on its own isn't enough. With the wrapped policy, no index and relaxed_order, 1-row tenants got 0.48 and 10-row tenants 0.60, at about 50 ms per search. Half of the one-document searches still came back empty, because the scan gives up at max_scan_tuples (20,000 by default) before it finds the rare rows.
plan_cache_mode = force_custom_plan only helps the direct spelling. It turns the prepared case into the "plain query" row: tenants up to 100 rows come back complete under the direct policy, but each of those searches is a 62 ms sequential scan, and the 1,000-row tenant still gets HNSW at 0.77. For the wrapped policy it changes nothing on the 200k table, because a custom plan doesn't know the tenant either.
In every run, every row that came back belonged to the right tenant, so RLS did its job on isolation. What went wrong was always rows that should have come back and didn't.
What I'd check in a real app
- Make sure the column in your policy has an index. If your policy reads
auth.uid()againstuser_id, indexuser_id. - Run
EXPLAINon your search as the app role, with the setting for a tiny user. If you see an HNSW index scan for a user with 5 rows, that user is getting partial or empty answers. - Run the same check through the same driver your app uses, after a few warm-up calls. Plain
psqlwon't show you the prepared plan. - Test with your smallest customer, not with your own account full of data.
Limits
One machine (2 vCPU, 4 GB RAM), two table sizes, k = 10. The 200k table uses synthetic vectors; the 50k table uses real Wikipedia embeddings and agrees on which fixes work. I simulated auth.uid() with current_setting(), which is what it reads underneath, but I didn't run PostgREST itself, so I'm not making claims about how supabase-js calls end up planned. Latencies compare strategies on this box; they aren't capacity numbers.
The harness, the policy DDL, the plan-check script and the raw CSVs are in my repo (a personal project): https://github.com/atokim4/pgvector-tenant-recall
I used AI tools while writing this post. The numbers come from the harness runs in the repo.
來源:DEV Community · dev.to