Permission-Aware Retrieval & Freshness
Enforce user, role, group, owner, and admin access controls before ranking results, resolve latest document versions, filter out deleted or stale records against a deterministic freshness policy, and verify with pytest and GitHub Actions.
Enterprise assistants rarely search a single static corpus. Documents are updated, superseded, or revoked over time, and different employees, roles, and teams are allowed to see different records.
This module covers permission-aware retrieval and document freshness. You will enforce access controls before ranking results, filter out stale, future-dated, or deleted records against a freshness policy, reject duplicate document versions, and verify the implementation with pytest and GitHub Actions in the fde-02-4 repository.
Enterprise Scenario: Northwind Freight
Northwind’s operations, finance, and regional dispatch teams share a knowledge base of rate cards, carrier contracts, and incident notes. A dispatch coordinator should not retrieve restricted executive or HR memos, and an outdated tariff from last quarter or a record dated in the future should not override an active rate card or a deleted notice.
What You Will Build
- Access, freshness, and retrieval schemas: Define strict Pydantic v2 models for
AccessContext,FreshnessPolicy,DocumentRecord,RetrievalResult, andRetrievalResponse. - Pre-ranking authorization checks: Evaluate user ID, roles, groups, ownership, and admin status before scoring or returning documents.
- Version, tombstone, future-timestamp, and age freshness filtering: Reject duplicate
(doc_id, version)pairs, resolve the latest version perdoc_id, skip deleted/tombstoned or future-dated documents, and exclude stale documents exceedingmax_age_seconds. - Tested retrieval pipeline + CI: Implement
retrieve_authorized_fresh_docsinfde-02-4and verify withpytestand GitHub Actions.
1. Pre-Filtering ACLs and Freshness
- Why post-filtering after top-k retrieval is risky: If you retrieve top-k documents first and filter permissions afterward, unauthorized users can lose valid results from their top-k slot or leak metadata when restricted documents are inspected or scored. Enforcing ACLs before ranking keeps unauthorized content out of candidate sets early.
- Handling versions, tombstones, future timestamps, and staleness: Enterprise syncs frequently emit newer versions or soft-delete records. Rejecting duplicate
(doc_id, version)entries keeps version resolution unambiguous, and evaluating freshness usingas_of_epoch_s,max_age_seconds, andis_deletedprevents stale, future-dated, or revoked instructions from surfacing as current policy.
2. Step-by-Step Build Walkthrough
- Set up the
fde-02-4repository and virtual environment: Create the package layout insidefde-02-4(includingfde-02-4/.github/workflows), add.env.example,.gitignore,pyproject.toml, and.github/workflows/pytest.yml, and install in editable mode.mkdir -p fde-02-4/src/fde_02_4 fde-02-4/tests fde-02-4/.github/workflows cd fde-02-4 python3 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip python -m pip install -e ".[dev]" cp .env.example .env - Define strict schemas for access context, freshness policy, documents, and results: Create
src/fde_02_4/schemas.pywithextra="forbid",strict=True, non-blank string validation, and non-negative counters."""Strict Pydantic v2 schemas for ACLs, document freshness, and retrieval results.""" from __future__ import annotations import math from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator def _require_non_blank(value: str, field_name: str) -> str: if not value.strip(): raise ValueError(f"{field_name} must not be blank") return value def _require_clean_str_list(values: list[str], field_name: str) -> list[str]: cleaned: list[str] = [] for item in values: _require_non_blank(item, field_name) cleaned.append(item.strip()) return cleaned class AccessContext(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) user_id: str = Field(min_length=1) roles: list[str] = Field(default_factory=list) groups: list[str] = Field(default_factory=list) is_admin: bool = False @field_validator("user_id") @classmethod def _validate_user_id(cls, value: str) -> str: return _require_non_blank(value, "user_id") @field_validator("roles", "groups") @classmethod def _validate_acl_lists(cls, values: list[str], info) -> list[str]: return _require_clean_str_list(values, info.field_name) class FreshnessPolicy(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) as_of_epoch_s: int = Field(ge=0) max_age_seconds: int = Field(ge=1) allow_deleted: bool = False class DocumentRecord(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) doc_id: str = Field(min_length=1) version: int = Field(ge=1) title: str = Field(min_length=1) content: str = Field(min_length=1) owner_id: str = Field(min_length=1) allowed_users: list[str] = Field(default_factory=list) allowed_roles: list[str] = Field(default_factory=list) allowed_groups: list[str] = Field(default_factory=list) updated_at_epoch_s: int = Field(ge=0) is_deleted: bool = False @field_validator("doc_id", "title", "content", "owner_id") @classmethod def _validate_non_blank_fields(cls, value: str, info) -> str: return _require_non_blank(value, info.field_name) @field_validator("allowed_users", "allowed_roles", "allowed_groups") @classmethod def _validate_doc_acls(cls, values: list[str], info) -> list[str]: return _require_clean_str_list(values, info.field_name) class RetrievalResult(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) doc_id: str = Field(min_length=1) version: int = Field(ge=1) title: str = Field(min_length=1) content: str = Field(min_length=1) score: float age_seconds: int = Field(ge=0) updated_at_epoch_s: int = Field(ge=0) @field_validator("doc_id", "title", "content") @classmethod def _validate_non_blank_out(cls, value: str, info) -> str: return _require_non_blank(value, info.field_name) @field_validator("score") @classmethod def _validate_finite_score(cls, value: float) -> float: if not math.isfinite(value): raise ValueError("score must be finite") return value class RetrievalResponse(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) results: list[RetrievalResult] denied_count: int = Field(ge=0) stale_or_deleted_count: int = Field(ge=0) @model_validator(mode="after") def _validate_counts(self) -> "RetrievalResponse": if self.denied_count < 0 or self.stale_or_deleted_count < 0: raise ValueError("counts must be non-negative") return self - Implement permission-aware and freshness-aware retrieval: Create
src/fde_02_4/access_freshness.pyto check authorization, reject duplicate(doc_id, version)entries, select the latest version perdoc_id, skip deleted, future-dated, or stale records, and rank matching documents."""Permission-aware and freshness-aware document retrieval.""" from __future__ import annotations import math import re from fde_02_4.schemas import ( AccessContext, DocumentRecord, FreshnessPolicy, RetrievalResponse, RetrievalResult, _require_non_blank, ) def _tokens(text: str) -> set[str]: return set(re.findall(r"[a-z0-9_]+", text.lower())) def is_document_authorized(doc: DocumentRecord, ctx: AccessContext) -> bool: if ctx.is_admin: return True if doc.owner_id == ctx.user_id: return True if ctx.user_id in doc.allowed_users: return True if set(ctx.roles).intersection(doc.allowed_roles): return True if set(ctx.groups).intersection(doc.allowed_groups): return True return False def _latest_version_per_doc(docs: list[DocumentRecord]) -> dict[str, DocumentRecord]: seen_versions: set[tuple[str, int]] = set() latest: dict[str, DocumentRecord] = {} for doc in docs: key = (doc.doc_id, doc.version) if key in seen_versions: raise ValueError( f"Duplicate document version found for doc_id={doc.doc_id!r}, version={doc.version}" ) seen_versions.add(key) current = latest.get(doc.doc_id) if current is None or doc.version > current.version: latest[doc.doc_id] = doc return latest def retrieve_authorized_fresh_docs( query: str, documents: list[DocumentRecord], access_context: AccessContext, policy: FreshnessPolicy, top_k: int = 5, ) -> RetrievalResponse: _require_non_blank(query, "query") if top_k < 1: raise ValueError("top_k must be at least 1") latest_docs = _latest_version_per_doc(documents) q_toks = _tokens(query) if not q_toks or not latest_docs: return RetrievalResponse(results=[], denied_count=0, stale_or_deleted_count=0) denied_count = 0 stale_or_deleted_count = 0 scored: list[RetrievalResult] = [] for doc in latest_docs.values(): if not is_document_authorized(doc, access_context): denied_count += 1 continue if doc.is_deleted and not policy.allow_deleted: stale_or_deleted_count += 1 continue if doc.updated_at_epoch_s > policy.as_of_epoch_s: stale_or_deleted_count += 1 continue age_seconds = policy.as_of_epoch_s - doc.updated_at_epoch_s if age_seconds > policy.max_age_seconds: stale_or_deleted_count += 1 continue doc_toks = _tokens(f"{doc.title} {doc.content}") overlap = len(q_toks.intersection(doc_toks)) if overlap == 0: continue score = overlap / math.sqrt(len(doc_toks) if doc_toks else 1) scored.append( RetrievalResult( doc_id=doc.doc_id, version=doc.version, title=doc.title, content=doc.content, score=score, age_seconds=age_seconds, updated_at_epoch_s=doc.updated_at_epoch_s, ) ) scored.sort(key=lambda item: (-item.score, -item.version, item.doc_id)) return RetrievalResponse( results=scored[:top_k], denied_count=denied_count, stale_or_deleted_count=stale_or_deleted_count, ) - Run tests and push to GitHub: Verify unit tests pass with
pytestand pushfde-02-4with.github/workflows/pytest.yml.python -m pytest -v git status git add . git commit -m "Complete FDE module 02.4"
3. Common Pitfalls and Operational Hygiene
- Post-filtering after top-k retrieval: Always evaluate ACLs before ranking or returning candidate chunks so restricted records never displace authorized results or leak into downstream prompts.
- Serving stale, future-dated, or soft-deleted documents or duplicate versions: Reject duplicate
(doc_id, version)entries, trackversion,updated_at_epoch_s, andis_deleted, exclude records withupdated_at_epoch_s > as_of_epoch_s, and test against a fixedas_of_epoch_sin unit tests for deterministic behavior.
4. Completion Criteria
AccessContext,FreshnessPolicy,DocumentRecord,RetrievalResult, andRetrievalResponsevalidate inputs strictly.retrieve_authorized_fresh_docsenforces ACLs, rejects duplicate(doc_id, version)entries, skips deleted, future-dated, or stale documents underFreshnessPolicy, selects the latest version perdoc_id, and returns accurate skip counts.- All
pytesttests pass locally and in GitHub Actions, andfde-02-4is committed to GitHub.
Build this
In the fde-02-4 repository, implement strict Pydantic v2 models in src/fde_02_4/schemas.py (AccessContext, FreshnessPolicy, DocumentRecord, RetrievalResult, and RetrievalResponse) and retrieval logic in src/fde_02_4/access_freshness.py (is_document_authorized and retrieve_authorized_fresh_docs).
- Evaluate user ID, roles, groups, document ownership, and admin flags before scoring or returning documents.
- Reject duplicate
(doc_id, version)entries, select the highestversionperdoc_id, skip records whereis_deletedisTrueunlesspolicy.allow_deletedisTrue, exclude future-dated records whereupdated_at_epoch_s > as_of_epoch_s, and exclude stale records whereage_seconds > policy.max_age_secondsusingpolicy.as_of_epoch_s. - Return accurate
denied_countandstale_or_deleted_countmetrics alongside rankedresultsup totop_k. - Add unit tests in
tests/test_access_freshness.pycovering user/role/group/owner/admin authorization, denied record counts, duplicate(doc_id, version)rejection, latest-version selection, deleted/tombstoned documents, future-dated documents, stale documents, andtop_kranking, then runpython -m pytest -vand pushfde-02-4(including.github/workflows/pytest.yml) to GitHub.
Test your understanding
- Why is post-filtering retrieved chunks after top-k ranking risky for both security and answer quality?
- How do you handle document updates, soft deletes, and staleness without non-deterministic clock failures in tests?
- Why should a permission-aware retriever track
denied_countandstale_or_deleted_countwhen returning empty or partial results?
Reveal self-review answers (attempt the questions first)
- Pre-filter vs. post-filter: Post-filtering after top-k selection shrinks the visible result set for authorized users (hurting recall and ranking) and risks exposing metadata or inspecting restricted documents before filtering. Pre-filtering restricts candidates to authorized documents first.
- Updates, deletes, and staleness: Store
version,updated_at_epoch_s, andis_deletedon each document record, and compute age deterministically frompolicy.as_of_epoch_srather than calling live system time during unit tests. - Observability and debugging: Explicit
denied_countandstale_or_deleted_countcounters tell callers whether zero or fewer results came back because of missing permissions, soft-deleted records, or expired freshness windows instead of a broken search query.
Questions or notes on this module?