Filter before top-k: a permission-aware retrieval lab

A small, runnable experiment shows why access checks and source freshness belong before context reaches a model.

Before you start

For developers and curious technical readers. Python basics help with the optional lab.

Evidence

Locally executed synthetic lab. Read the method and limits below.

On this page

A useful answer can still use the wrong source

Imagine a support assistant answering a refund question. It finds a document with a close match, quotes the policy and links to the source. The answer looks careful. But the document belongs to another customer account, or it is last month's policy, or the person asking no longer has permission to read it.

These are different failures from an irrelevant search result. Improving the model's writing would not correct the source boundary. A citation tells a reader where an answer came from; it does not establish that the application was entitled to use that source.

For a business reader, the decision is straightforward: ask what information the assistant may use before asking how confidently it answers. For a developer, there is an additional ordering question: do access and freshness checks happen before retrieval keeps its best candidates, or after?

This local exercise makes the ordering visible using fictional records and fixed ranking scores. It tests application logic before any context reaches a language model.

What the sources establish

Retrieval and generation deserve separate scrutiny. Google Research's discussion of sufficient context examines whether retrieved information is enough to support an answer. That research is useful context, but the exercise here asks an earlier question: which records may enter context at all?

Integration introduces its own access questions. The MCP security guidance discusses threats around authorization and connected tools. A connection mechanism does not define this fictional application's document policy. That policy remains explicit code in the exercise below.

Evaluation also needs a task-specific target. Hamel Husain's evaluation article describes constructing checks for an application's own behavior. Here the target is deliberately narrow: the prepared context must contain exactly the expected source IDs for a dozen authored cases. It does not grade a generated answer.

The rule to make testable

The fictional service has two tenants, Orchard and Harbor. A request carries an already established tenant and principal. Each document has a tenant, a list of permitted readers, a status, a source revision and a ranking score.

A document is eligible only when the request has an identity, the tenant matches, the principal is a permitted reader, the document is current and its revision matches the source manifest. Missing or malformed access metadata rejects the document. This is a teaching policy; it does not authenticate a real user or implement a production access-control system.

The contract at the context boundary is: every selected record is eligible under the current fixture state, and an eligible lower-ranked record is not lost simply because a forbidden record ranked above it. If a previously selected record changes, the guarded path stops and returns no context. A caller would need a separately designed retry or escalation path.

Three paths through the same records

The baseline ranks every document, takes the first result and prepares it as context. It deliberately omits access checks and state validation. It represents an incomplete application, not an acceptable default implementation.

The second path ranks everything, takes the first result, then removes an ineligible result. This protects the final context in several cases, but it can return nothing even when an eligible record was available just below the cutoff.

The guarded path filters to eligible records first, then ranks those records and keeps the first result. Both filtered paths recheck the selected source against a separate in-memory live-state fixture before preparing context.

# The ordering difference, simplified from the downloadable lab.
# k = 1 in every authored case.
postfilter = [d for d in rank(documents)[:1] if eligible(d, request, revisions)]
prefilter = rank([d for d in documents if eligible(d, request, revisions)])[:1]

Suppose a private document has score 0.99 and a permitted policy has score 0.80. Taking top-1 first discards the permitted policy before the access check happens. Filtering first keeps the permitted policy available for selection. These scores are authored inputs that isolate ordering; they are not measurements of semantic similarity.

In a real retrieval service, eligible candidate selection might use a database predicate, an index partition or another enforcement mechanism. The relevant question is what the retrieval engine actually does with those constraints. This Python list example cannot establish a vector database's behavior or an approximate index's recall.

Same records. Different order.

A conceptual view of one case in the Python lab. These fixed scores are fixture inputs; this browser view does not run a model or the full test suite.

Private recordScore 0.99 · Reader not permitted
Permitted policyScore 0.80 · Current revision
Context: permitted policy (score 0.80). The private record is excluded before top-1 is chosen.

Reproduce the exercise

Download the complete lab bundle, unzip it into a new directory and inspect lab.py and fixture.json. The code and synthetic data carry an MIT license. You need Python 3.10 or later. There are no third-party packages, credentials, model downloads or network calls.

Run the following from the extracted directory:

python3 lab.py

The script writes results.json beside itself. That file includes the Python version, fixture and code hashes, UTC execution time and a row for each case. The supplied raw result is also available as JSON. Re-running will naturally change the timestamp and may show a different Python/platform field; the expected context IDs should stay the same.

The fixture covers: a permitted current source; a higher-ranked private source; another tenant; retired content; an old revision; malformed reader metadata; no eligible source; access revoked after selection; an updated revision after selection; a deleted source; a missing principal; and deterministic ordering when two eligible scores tie.

Expected results are written into the fixture rather than generated by the same eligibility function. The script compares each path's context IDs with those expectations. Read the cases before relying on the totals: the checks were chosen to illustrate particular mistakes and do not represent a random sample of real workloads.

What actually happened

The local run completed all 12 cases. The deliberately incomplete baseline matched the expected context IDs in 2 cases. Ranking then filtering, with the same final state recheck as the guarded path, matched in 7 cases. Filtering before ranking, followed by the final state recheck, matched in all 12.

PathMatches to authored expectationsWhat the result means here
Rank only2 of 12The incomplete baseline often selected forbidden or outdated context.
Rank, take top-1, then filter and recheck7 of 12In five cases, an eligible lower-ranked source was lost before filtering.
Filter, rank, take top-1, then recheck12 of 12This code met this fixture's ordering and state expectations.

There were zero model calls and zero network calls. No cloud or API spend was incurred by the experiment. The run does not measure answer accuracy, model hallucination, production latency or retrieval quality. The twelve cases are not independent statistical samples, so percentages and claims of general reliability would overstate the evidence.

Why check again before preparing context?

Access and source state can change after selection. In three cases, the fixture changes the live document between retrieval and context preparation: it revokes the reader, replaces the revision, or deletes the source. The filtered paths compare the selected document with live state and return no context when the comparison fails.

That behavior is intentionally conservative. It does not find a replacement document, retry a model request or tell a user that an answer is safe. It simply prevents the old selection from becoming context in this in-memory demonstration.

There is still a race in the real-world design question. An in-memory check followed by a later action is not an atomic guarantee. A real system needs a defined relationship between authorization, version validation, prompt construction and the action that consumes the result. You may need transactional checks, a bounded snapshot, a versioned capability or an action-time validation rule appropriate to the system. Those mechanisms are proposed follow-up work; none was implemented or tested here.

What this lab leaves out

The request identity is supplied by the fixture. Real identity verification, token validation, tenant resolution and authorization infrastructure are absent. The manifest is trusted local input, not an adversarial or distributed source of truth. There is no embeddings provider, vector index, generation step, prompt injection defence or log-redaction mechanism.

The demonstration also does not prove that the text of a permitted current document is correct. Freshness is a revision relationship, not a guarantee of truth. A current document can contain a factual error, and two authorized documents can conflict. Those deserve different test cases and a rule for choosing authoritative information.

Because the baseline is deliberately defective, beating it is not a competitive claim. Because the guarded implementation and cases were authored together, passing them is not independent validation. A useful next review would ask another developer to add a counterexample without changing the policy code.

Turn the result into better questions

If you are evaluating an assistant for a business process, ask to see a denied-access example, a changed-policy example and the expected behavior when no authorized source remains. A polished answer is less informative than a trace showing how the system handled those boundaries.

If you are building the assistant, document the eligibility rule separately from the relevance score. Test a high-scoring forbidden record above an eligible one. Test the state transition after retrieval, not only the initial state. Keep logs useful for diagnosis without exposing the records that access checks rejected.

The next proposed experiment is a small isolated retrieval service that can demonstrate action-time version checks under concurrent updates. A later generation experiment would add a model and separately grade groundedness and abstention. Neither experiment has run. This first lab establishes a smaller, useful fact: filtering order and stale selections can be tested before a model is involved.

Sources and corrections

Published 8 November 2026. The checks cover the twelve authored cases in the downloadable fixture. Report an error through the corrections page.

Suggest a correction
Keep exploring

Understand the choices around a model.

All articles