PDF 檢索架構如何在存取規則下平衡品質與延遲
PDF Retrieval Architecture with Access Rules (Balancing Quality Against Latency)
作者建議先按授權結果取得可讀文件清單,再只在清單內進行語義搜尋,並在檢索結果進入答案上下文前再次核對文件權限。文章比較預先篩選、全域搜尋後過濾及按存取邊界分設索引的取捨,指出搜尋品質和延遲都要按實際權限情況測試。範例實作在沒有可讀文件時不退回全域搜尋,並建議記錄各階段耗時、權限快照及引用文件 ID。
Bottom line: For internal engineering documentation, put access rules inside retrieval: derive an allowed document set before semantic search, retrieve only from that set, and verify authorization again before any PDF excerpt enters the answer context.
| Choice | Retrieval quality | Latency shape | Best fit |
|---|---|---|---|
| Pre-filter by allowed document IDs | Can miss good passages when the filter is too broad or poorly indexed | One bounded search path | Most B2B SaaS knowledge bases |
| Search globally, then discard forbidden hits | Good initial ranking, but authorized results may be pushed below the cutoff | Often needs deeper retrieval or a retry | Small, low-risk corpora with unusually sparse permissions |
| Separate index per access boundary | Clean candidate pools | Fast reads, slower and more complex updates | A few stable, non-overlapping groups |
My default is the first row. It keeps the security boundary close to the candidate-generation step without multiplying indexes. The catch is that filter selectivity becomes part of search quality, so it has to be tested like a ranking feature, not treated as plumbing.
For a solo SaaS operator, that distinction matters. A clever retrieval stack that demands weekly permission repairs steals the same hours that could ship customer-facing work. Outsource the undifferentiated parts, keep the authorization decision explicit, and spend engineering time on the corpus and evaluation set. Those are the parts unique to the product.
How should retrieval architecture enforce access rules for internal engineering documentation?
Start with the subject, resource, action, and current context. The subject might be a signed-in engineer plus team memberships. The resource is a PDF or a stable document identifier, not an embedding chunk. The action is usually read. Context can include tenant, environment, document status, and an access-policy version. This resembles attribute-based access control: a decision uses attributes of the subject, object, operation, and environment rather than trusting a role label alone.
Then split the request into two phases. The authorization phase returns the exact document IDs the caller may read. The retrieval phase ranks chunks only inside that allowed set. A final guard checks every selected chunk's parent document against the same authorization snapshot before context assembly. That last check isn't a substitute for pre-filtering. It is a narrow defense against stale metadata or a coding mistake between retrieval and prompt construction.
The unit of permission is important. If a PDF is readable as a whole, attach policy metadata to its document record and copy the immutable document ID onto every derived chunk. If permissions differ by page or section, the resource model must express that smaller unit before indexing. Don't bolt page-level policy onto document-level identifiers later; two chunks with the same parent and different visibility become impossible to reason about cleanly.
Keep the model input downstream of this boundary. Retrieval-augmented generation combines a model with retrieved external memory, which makes the selected passages part of the generation input. Once a forbidden passage reaches that input, asking the model not to reveal it is no longer an access-control design. The architecture should make unauthorized context unavailable, not merely undesirable.
This is also where tenant isolation belongs. A tenant constraint should be mandatory and non-overridable, while team or project rules further narrow the candidate set. Query text never supplies those constraints. The authenticated request context does.
The two numbers that drive the choice
Quality is the fraction of useful, authorized evidence that survives candidate generation. Latency is the full time from authorization lookup through context assembly, not just the vector query duration. Measure both at the permission shapes users actually have.
For quality, build a small evaluation set of real question forms paired with relevant document IDs and expected access outcomes. Include a question whose best semantic match is forbidden but whose second-best authorized match is useful. Include another where the caller can read only one document in a large folder. Also include a no-access case. Track whether an authorized relevant chunk appears in the first k results, whether any forbidden ID appears at any stage, and whether the final answer cites evidence that was actually retrieved. k = 20 is a reasonable experiment setting, not a universal target; tune it against your corpus rather than presenting it as a benchmark.
For latency, record authorization time, candidate-search time, reranking time, and context-assembly time separately. Percentiles matter more than an average because large team memberships and unusually permissive users create different filter sizes. I would start with a fixed service objective based on the product's interaction budget, then compare architectures under identical queries and permission snapshots. I'm not sure which cutoff will win for your PDFs. Tokenization, duplicate revisions, page layout, and group cardinality can move the result, and only a corpus-specific test resolves that.
Watch the empty and thin result sets. Post-filtering commonly spends its top ranks on documents the caller cannot read; after those hits are removed, the answer may have little evidence. Pulling more candidates can recover quality, but it adds work and makes latency depend on how much content is forbidden. Pre-filtering avoids that shape, although a very large allowed-ID expression may itself be expensive. There is no free branch.
Consider a hypothetical folder with 200 PDF revisions spread across product, security, and customer-specific projects. An engineer asks why a deployment approval was rejected. The closest passages may repeat the same approval language in ten customer runbooks, but this engineer can read only the product handbook and two project documents. A global top-5 search could return five excellent semantic matches and still leave zero eligible passages after filtering. Raising the request to top-50 might surface the handbook, yet it also makes every query scan and transfer more candidates, and there is no fixed depth that guarantees recovery as the folder grows. With pre-filtering, the ranking question becomes narrower and more honest: which passages are best among the documents this engineer may use? The evaluation record should retain the allowed-set size, relevant authorized document IDs, retrieved ranks, and stage timings for this case. Run the same question with a broad-access principal as well. If the narrow principal repeatedly loses the relevant handbook passage while the broad principal finds it, inspect filter execution and chunk metadata before tuning the language model; generation cannot repair evidence that retrieval removed.
Permissions first.
A small implementation boundary
The code below keeps policy evaluation out of the search adapter while making its output mandatory. The search engine receives an authorization snapshot and cannot issue an unscoped query through this interface. Names and values are illustrative; there is no vendor endpoint hiding behind them.
type Principal = {
tenantId: string;
userId: string;
teamIds: string[];
};
type AccessSnapshot = {
policyVersion: string;
allowedDocumentIds: ReadonlySet<string>;
};
type ChunkHit = {
documentId: string;
chunkId: string;
text: string;
score: number;
};
interface PolicyReader {
allowedDocuments(principal: Principal): Promise<AccessSnapshot>;
}
interface ScopedRetriever {
search(input: {
query: string;
tenantId: string;
allowedDocumentIds: readonly string[];
limit: number;
}): Promise<ChunkHit[]>;
}
async function retrieveAuthorizedContext(
principal: Principal,
query: string,
policy: PolicyReader,
retriever: ScopedRetriever,
): Promise<{ hits: ChunkHit[]; policyVersion: string }> {
const snapshot = await policy.allowedDocuments(principal);
if (snapshot.allowedDocumentIds.size === 0) {
return { hits: [], policyVersion: snapshot.policyVersion };
}
const hits = await retriever.search({
query,
tenantId: principal.tenantId,
allowedDocumentIds: [...snapshot.allowedDocumentIds],
limit: 20,
});
const verified = hits.filter((hit) =>
snapshot.allowedDocumentIds.has(hit.documentId),
);
return { hits: verified, policyVersion: snapshot.policyVersion };
}
One detail is deliberately boring: an empty permission set returns no context. It does not fall back to global search. Fail closed.
No exceptions.
In production, keep the policy version with the trace, along with hashed or otherwise appropriately protected subject identifiers, the filter cardinality, selected document IDs, timing by stage, and the final citation IDs. Avoid logging chunk text by default because logs become another copy of internal documentation. The trace should answer “why did this document become eligible?” without duplicating the document.
Indexing needs the same discipline. Give each PDF a stable ID, give each revision a separate version, and propagate the parent ID to chunks. Build the new revision, validate its metadata, then make it searchable. Permission changes need a defined freshness policy: either queries consult an authoritative policy store each time, or cached snapshots have explicit invalidation and bounded lifetime. Weekly shipping is easier when this contract is written down and tested instead of scattered across ingestion jobs.
Error handling should preserve the boundary too. Treat “no authorized evidence” as a normal result and let the answer layer say it lacks accessible support. Treat malformed identity context as a denied request. Don't silently broaden scope because a team list is missing. A useful answer can wait; an unauthorized answer cannot be recalled.
When the runner-up is the better design
Stick with a separate index per access boundary when there are only a few stable groups, documents never cross those groups, and duplicated ingestion is operationally acceptable. The query path stays simple, and each index contains only eligible material. It is not suitable when users belong to many overlapping projects or permissions change often; index proliferation and reindexing become product work rather than background infrastructure.
Global search followed by filtering can be acceptable for a tiny corpus where every user can read nearly everything and the remaining restrictions protect low-sensitivity material. Its downside is structural: ranking happens before eligibility is known. If that changes later, move the filter earlier rather than increasing the candidate count indefinitely.
Pre-filtering has limits as well. Huge allowed sets, highly dynamic attributes, or a search backend that cannot apply filters during candidate generation can make it a poor fit. In that case, use a retrieval layer capable of joining policy attributes during search, or partition on a stable hard boundary such as tenant and apply finer rules within it. The decision rule remains the same: unauthorized chunks must be excluded before answer context, while the chosen mechanism must preserve enough authorized candidates inside the latency budget.
Ship the simplest design that can prove those two properties. Re-run the evaluation set whenever chunking, embedding, reranking, or permission logic changes. Search quality and access behavior share a pipeline, so a change to either side can alter the final evidence even when the other side's code did not move.
References
- Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks: https://arxiv.org/abs/2005.11401
- NIST SP 800-162, Guide to Attribute Based Access Control: https://csrc.nist.gov/pubs/sp/800/162/upd2/final
- OWASP Authorization Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html
來源:DEV Community · dev.to