Filter Timing: Putting Timeliness and Tenancy Inside Tax-RAG Recall
Filter Timing: Putting Timeliness and Tenancy Inside Tax-RAG Recall
Let me start with the conclusion: in a domain like tax, where the same question yields different answers depending on when you ask and who you are, treating timeliness and tenant identity as post-retrieval filters is not enough. Once the candidate pool is filled with expired documents or another tenant's documents, no amount of re-ranking can rescue it—because top_k truncates first and returns after.
This article records three trade-offs, and one thing I deliberately did not turn into a hard gate.
Repository: https://github.com/erishen/tax-agent-platform
Why This Domain Has Two Extra Dimensions
Open this project's corpus directory and both dimensions are right there:
data/corpus/
├── vat-2022.md # software services at 13%, expiry_date: 2023-12-31
├── vat-2024.md # software services at 6%, effective_date: 2024-01-01
├── small-scale.md
├── cit-2024.md
├── iit-2024.md
├── rnd-deduction.md
├── stamp-duty.md
├── vat-credit-refund.md
└── acme-us/ # tenant-private corpus
└── us-federal-cit-2024.md
First fact: vat-2022.md and vat-2024.md sit in the library at the same time. The former says software services were previously subject to a 13% VAT rate and that the rule has been superseded by the 2024 regulations, with expiry_date: 2023-12-31 in its metadata; the latter says software services are subject to 6% VAT effective from January 2024. If both make it into the candidate pool, the model can perfectly well pick the 13% one—and it will look just as "evidence-backed," because it really is citing a genuine document from the library.
Second fact: acme-us/ is a tenant's private corpus, and the eight Chinese-language regulations in the shared root must not appear in its retrieval results.
Neither dimension is a ranking problem. Both are filtering problems—and which layer the filtering happens in determines whether it does anything at all.
Timeliness: Expired Documents Should Never Enter the Candidate Pool
In this project every corpus file is Markdown with a frontmatter header (the corpus files are written in Chinese; the sample below shows the English gloss only):
---
doc_id: vat-2024
title: VAT Regulations 2024
effective_date: 2024-01-01
source: State Taxation Administration
---
Once loaded into a TaxDocument, "is this still in force" is a pure function:
@dataclass
class TaxDocument:
doc_id: str
title: str
content: str
effective_date: date | None = None
expiry_date: date | None = None
source: str = ""
def is_active(self, on: date | None = None) -> bool:
check_date = on or date.today()
if self.effective_date and check_date < self.effective_date:
return False
return not (self.expiry_date and check_date > self.expiry_date)
What matters is not this function but where it is called—not after sorting, but as a continue before any candidate result is constructed:
for doc_id, chunks in self._chunks.items():
doc = self._docs[doc_id]
# Filter by timeliness
if active_only and not doc.is_active():
continue
for chunk, vec in zip(chunks, self._embeddings.get(doc_id, [])):
cos = cosine(query_vec, vec)
...
The reason is that the last line of coarse_recall is return results[:top_k]. Once an expired document takes one of the top_k slots, the valid documents behind it get no chance whatsoever to be rescued by the later re-ranking stage—re-ranking can only operate on candidates that survived truncation. Hoisting the continue to the front costs one date comparison per document and keeps the candidate set clean at the source.
There is also a deliberately lenient convention: both effective_date and expiry_date may be empty, and is_active() returns True when neither is set. That is not laziness but the reality of the corpus—plenty of currently-in-force documents never declare an expiry date, and if a missing field were read as "expired," the whole library would empty out on the spot.
Alongside it sits _parse_date, a convergence function. Dates in frontmatter are hand-written, so they may be empty strings or may have been written as None or null:
def _parse_date(value: str | None) -> date | None:
"""Parse an ISO ``YYYY-MM-DD`` date, tolerating empty / null markers."""
if not value:
return None
value = value.strip()
if value in ("None", "null", ""):
return None
try:
return date.fromisoformat(value)
except ValueError:
logger.warning("Bad date in corpus frontmatter: %r", value)
return None
A parse failure only logs a warning, never raises, and returns None (equivalent to "no timeliness constraint declared"). It is an extension of the same trade-off: one broken corpus file should not take down the whole knowledge base.
Tenancy: Identity Reverse-Looked-Up from the Key, Corpora Isolated by Directory
I did two things for tenant isolation, and the first matters more than the second—identity must not be client-declared.
A caller submits a key via X-API-Key, and the tenant identity is reverse-looked-up from that key:
@staticmethod
def _tenant_for_key(api_key: str) -> str | None:
"""Reverse-lookup the tenant that owns this key (authoritative identity)."""
mapping = settings.tenant_api_keys or {}
for tenant_id, key in mapping.items():
if key and key == api_key:
return tenant_id
return None
The accompanying policy lives in the middleware, and the comment is blunt: the tenant is derived from the key, and a client-declared X-Tenant-ID is intentionally ignored so a caller cannot become someone else by forging a header; if the key matches no tenant, the response is a flat 401 (fail-closed rather than falling back to a default tenant). This matters more than any isolation at the retrieval layer—no matter how clean retrieval is, forgeable identity means there is no isolation at all.
The second piece selects the corpus directory based on that identity:
def _resolve_corpus_dir(tenant_id: str | None) -> Path:
"""Return the corpus directory for a tenant (data isolation)."""
if tenant_id:
tenant_dir = CORPUS_DIR / tenant_id
if tenant_dir.is_dir() and any(tenant_dir.glob("*.md")):
return tenant_dir
return CORPUS_DIR
The rule: if the tenant has its own non-empty directory, load that; otherwise fall back to the shared root. So acme-us gets the US federal corporate income tax file, and the eight Chinese-language regulations in the shared root are invisible to it.
There is an implicit precondition that is easy to miss: load_documents_from_corpus uses a non-recursive glob("*.md"), so data/corpus/acme-us/ never gets swept into the shared-root pipeline. The source comment calls this out explicitly—if someone ever switches it to a recursive traversal, tenant isolation silently stops working while every test may still pass.
Retrieval Layering: Three Numbers and One Deduplication Pass
RAGPipeline.query is the entry point for the whole retrieval chain, and its structure is simpler than I first assumed:
def query(self, question: str, top_k: int = 5, active_only: bool = True):
# Embed the question once, then run cosine recall against chunk vectors.
qvec = _l2_normalize(self.embedder.embed([question])[0])
# Stage 1: Dense-vector coarse recall
candidates = self.store.coarse_recall(
qvec,
query_text=question,
top_k=50,
active_only=active_only,
mode=self.rag_mode,
)
if not candidates:
return []
# Stage 2: Re-rank (over-fetch, then collapse duplicates per doc)
ranked = self.reranker.rerank(question, candidates, top_k=max(top_k, 1) * 4)
best: dict[str, RetrievalResult] = {}
for r in ranked:
if r.doc_id not in best or r.score > best[r.doc_id].score:
best[r.doc_id] = r
deduped = sorted(best.values(), key=lambda r: r.score, reverse=True)
return deduped[:top_k]
Three numbers: recall at top_k=50 → re-rank over-sampled to top_k * 4 → return top_k (default 5). The division of labor: wide recall leaves room for re-ranking to work; re-ranking over-samples first, then collapses by doc_id (keeping only the highest-scoring chunk per document), and only then truncates to top_k.
Why is that deduplication layer necessary? Because the chunking strategy follows Markdown structure:
def chunk_by_semantic(text: str, max_chunk_size: int = 512, overlap_sentences: int = 1):
"""Semantic chunking: split by Markdown headings / paragraphs, then by size."""
sections = re.split(r"(?=#{1,3}\s)", text)
...
It splits on headings, and further by sentence (with a one-sentence overlap) when a section runs long. A single regulation becomes many chunks, but what the user wants to see is "this regulation," not "chunk number 7 carved out of this regulation." Collapsing at the doc_id level therefore saves context and keeps both the API and the frontend display clean.
One more configuration deserves an explanation—the mode parameter of coarse_recall, whose default lives in config:
# RAG retrieval mode: "vector" (dense only) | "hybrid" (vector + lexical blend).
# Default is "hybrid": this corpus is Chinese-heavy and the local embedding
# model (nomic-embed-text) is stronger on English, so blending a lexical
# overlap score hardens Chinese recall without losing semantic matching.
rag_mode: str = "hybrid"
Under hybrid, the score blends two paths:
if mode == "hybrid" and query_terms:
chunk_terms = tokenize(chunk.content)
overlap = len(query_terms & chunk_terms)
overlap_score = overlap / max(len(query_terms), 1)
score = 0.7 * cos + 0.3 * overlap_score
That is 0.7 * cosine + 0.3 * lexical overlap ratio. The reason for adding that second path has nothing to do with tax; it is engineering reality: the corpus is mostly Chinese, while the local embedding model is stronger on English, so pure vector recall misses on Chinese terminology. The lexical overlap score is a crude signal, but at the recall stage that is enough—its job is to bring candidates up, not to make the final semantic judgment.
Evidence Verification: A Guardrail, Not a Gate
I want to be precise about this point, because I have seen a lot of articles in this genre get it backwards.
The system does have evidence verification, but its real structure is a primary path plus a fallback:
The primary path lives in EvaluatorAgent. It hands each acceptance criterion, together with independently retrieved evidence, to the LLM and gets back a per-criterion verdict through structured output:
# Derive a robust overall verdict from per-criterion results
verdicts = {c.verdict.upper() for c in eval_data.criteria}
if "CONTRADICTED" in verdicts:
overall = Verdict.FAIL.value
elif not verdicts or verdicts == {"SUPPORTED"}:
overall = Verdict.PASS.value
else:
overall = Verdict.PARTIAL.value
If any single criterion is judged CONTRADICTED, the overall result is FAIL; only an all-SUPPORTED set is PASS; everything else is PARTIAL.
The fallback path fires only when the LLM call raises (the original source comment here is in Chinese: "unify LLM-boundary degradation to the heuristic check"):
except Exception as e: # noqa: BLE001 - unify LLM-boundary degradation to the heuristic check
logger.warning("[%s] LLM audit failed, falling back to heuristic: %s", self.name, e)
overall, verifications = self._heuristic_verify(criteria, independent_evidence)
And the predicate underneath _heuristic_verify is implemented like this:
def _criterion_supported_by_evidence(criterion: str, evidence: list[str]) -> bool:
"""Crude heuristic: does any 2-char substring of the criterion appear in evidence?
Used only as a fallback when no LLM is configured. Good enough to flag
whether independently retrieved evidence is at least topically related.
"""
if len(criterion) < 2:
return True
for frag in evidence:
for i in range(len(criterion) - 1):
if criterion[i : i + 2] in frag:
return True
return False
In other words: any two-character substring of the criterion, appearing anywhere in any piece of evidence, counts as "supported." Its own docstring is honest about it—"crude heuristic," "good enough to flag whether evidence is at least topically related." All it can judge is whether the topics touch.
That is why I position it as a guardrail rather than a correctness gate:
- It can catch blunt problems like "the conclusion has nothing to do with the retrieved material";
- It gives a deterministic degradation path when the LLM is unavailable, instead of taking down the whole pipeline;
- But it has no ability to notice that "this paragraph cites a document number that does not exist." A two-character overlap cannot hit a fabricated identifier.
Treating it as a hard gate is dangerous: using an extremely weak signal to reject or wave through an answer is more likely to mislead than not having that check at all. Which is exactly why the primary path has to be an LLM structured audit—weak signals may only degrade; strong judgments require strong capability.
Downstream there is one more workflow-level safety net: a verdict other than FAIL routes to next_on_success, FAIL routes to next_on_failure, each branch retries locally up to max_retries (default 3), and PARTIAL is recorded as an issue:
if overall != Verdict.PASS.value:
unsupported = [v for v in verifications if v["verdict"] != "SUPPORTED"]
issues.append(
f"{overall}: {len(unsupported)} criterion(s) not fully supported by independent evidence"
)
What This Article Has Not Verified
Having written all of the above, there are several things I have to state plainly, or the article would be implying conclusions it does not actually support:
- There is no benchmark data. The repository contains no latency or accuracy measurement script and no controlled comparison. So this article contains no quantitative claims—any "how much faster" or "how much more accurate" statement would require measurement scaffolding that does not exist here.
- The second retrieval stage is a mock. The
ReRankerdocstring itself says production should use a cross-encoder (cross-encoder/ms-marco-MiniLM-L-6-v2); the current implementation merely weights by how recently a document took effect:boost = max(0, 1.0 - days_old / 365.0) * 0.3. So the semantic capability in "two-stage retrieval" comes from the first-stage recall plus the second stage's structure (over-sampling,doc_idcollapsing), not from that scoring function. - The vector store is in-memory. The
SemanticVectorStoredocstring states plainly that production would use pgvector / Milvus / Qdrant, whereas this is "embeddings computed once atadd_documenttime, stored L2-normalized in memory, retrieved with a single cosine pass." This structure hits a ceiling once the corpus grows. - Timeliness only works at document granularity. One file has one
effective_date/expiry_datepair and cannot express "a particular clause was amended on a particular date"—yet real policy amendments are frequently clause-level. - Tenant isolation is directory-level, not database-level RLS. It holds through a key mapping plus a directory convention, with no enforcement at the database layer.
Applicable Boundaries
What kind of scenario justifies pushing these two dimensions into the recall stage:
First, answers must be traceable to a specific document. If a user asks "where is that from" and you cannot answer, this structure means nothing to you.
Second, the corpus itself carries a time attribute, and contradictory versions genuinely coexisted historically. vat-2022 and vat-2024 sitting in the same library is the archetypal shape of this scenario; if your knowledge base has never contained "a document that was superseded but is still being cited," timeliness filtering is a switch idling in the off position.
Third, a wrong answer must cost far more than no answer. In tax, compliance, and healthcare, delivering a rigorous-looking wrong conclusion is far worse than stating plainly "I have no basis for this."
Conversely, a few categories where this does not fit: general knowledge Q&A (the answer comes from the model itself, with no external evidence source), high-frequency data interpretation (no static corpus to appeal to), and subjective judgment tasks (no single source text can falsify a conclusion).
One last precondition is the easiest to overlook: the metadata quality of your corpus is the ceiling of this whole system. is_active() depends entirely on whether effective_date / expiry_date were written correctly in frontmatter, and tenant isolation depends entirely on whether the key mapping is configured correctly. Get either wrong and a clean retrieval layer is worthless—and it will not raise an error; it will quietly return a wrong answer that looks thoroughly well-sourced.
Why does timeliness filtering belong in the recall stage rather than filtering out expired documents after retrieval?
Because the last step of coarse_recall is return results[:top_k]—truncation happens before the return. Once an expired document occupies a top_k slot, the valid documents behind it never reach the re-ranking stage, and re-ranking can only operate on the candidates that survived. Only by placing if active_only and not doc.is_active(): continue before results are constructed does the candidate pool stay clean at the source.
How is tenant identity determined? Can a client declare its own?
No. Tenant identity is reverse-looked-up from the X-API-Key by _tenant_for_key; a client-declared X-Tenant-ID is intentionally ignored, otherwise any caller could impersonate another tenant by changing a header. When the key matches no tenant the response is a flat 401 (fail-closed), not a fallback to a default tenant.
By what rule are corpora isolated?
_resolve_corpus_dir(tenant_id) loads data/corpus/<tenant_id>/ when that directory exists and is non-empty, otherwise falling back to the shared root data/corpus. Separately, load_documents_from_corpus uses a non-recursive glob("*.md"), so tenant subdirectories are never swept into the shared-root pipeline—switch it to a recursive traversal and the isolation silently breaks.
Can _heuristic_verify guarantee a correct conclusion?
No, it is only a guardrail. It calls _criterion_supported_by_evidence per criterion, and that predicate's bar is "any two-character substring of the criterion appears in any piece of evidence." That is enough to judge whether topics touch, and it cannot detect problems like "a document number that does not exist." Its real role is the deterministic degradation path when the LLM structured audit raises, not a correctness gate.
Then who guarantees correctness?
The primary path is EvaluatorAgent's LLM structured audit—each acceptance criterion plus independently retrieved evidence goes to the model, which returns a per-criterion verdict; CONTRADICTED on any criterion fails the whole thing, only all-SUPPORTED passes, everything else is PARTIAL. A FAIL routes to next_on_failure at the workflow layer and retries up to max_retries times.
Is multi-tenant corpus isolation database-level RLS?
No. It is directory-level isolation: it holds through the data/corpus/<tenant_id>/ directory convention plus the API-key-to-tenant mapping, with no database-enforced constraint. The RLS filter mentioned in the README is the target shape for a SQL-backed store; the current in-memory implementation corresponds to this directory-based isolation in _resolve_corpus_dir.
Enjoy this article?
erishen/tax-agent-platform
Comments (0)