MODULE 02.4 · PUBLISHED · ~1-2h

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, and RetrievalResponse.
  • 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 per doc_id, skip deleted/tombstoned or future-dated documents, and exclude stale documents exceeding max_age_seconds.
  • Tested retrieval pipeline + CI: Implement retrieve_authorized_fresh_docs in fde-02-4 and verify with pytest and 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 using as_of_epoch_s, max_age_seconds, and is_deleted prevents stale, future-dated, or revoked instructions from surfacing as current policy.

2. Step-by-Step Build Walkthrough

  1. Set up the fde-02-4 repository and virtual environment: Create the package layout inside fde-02-4 (including fde-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
  2. Define strict schemas for access context, freshness policy, documents, and results: Create src/fde_02_4/schemas.py with extra="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
  3. Implement permission-aware and freshness-aware retrieval: Create src/fde_02_4/access_freshness.py to check authorization, reject duplicate (doc_id, version) entries, select the latest version per doc_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,
        )
  4. Run tests and push to GitHub: Verify unit tests pass with pytest and push fde-02-4 with .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, track version, updated_at_epoch_s, and is_deleted, exclude records with updated_at_epoch_s > as_of_epoch_s, and test against a fixed as_of_epoch_s in unit tests for deterministic behavior.

4. Completion Criteria

  • AccessContext, FreshnessPolicy, DocumentRecord, RetrievalResult, and RetrievalResponse validate inputs strictly.
  • retrieve_authorized_fresh_docs enforces ACLs, rejects duplicate (doc_id, version) entries, skips deleted, future-dated, or stale documents under FreshnessPolicy, selects the latest version per doc_id, and returns accurate skip counts.
  • All pytest tests pass locally and in GitHub Actions, and fde-02-4 is committed to GitHub.
Practice assignment

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 highest version per doc_id, skip records where is_deleted is True unless policy.allow_deleted is True, exclude future-dated records where updated_at_epoch_s > as_of_epoch_s, and exclude stale records where age_seconds > policy.max_age_seconds using policy.as_of_epoch_s.
  • Return accurate denied_count and stale_or_deleted_count metrics alongside ranked results up to top_k.
  • Add unit tests in tests/test_access_freshness.py covering 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, and top_k ranking, then run python -m pytest -v and push fde-02-4 (including .github/workflows/pytest.yml) to GitHub.

View reference repository ↗

Knowledge check

Test your understanding

  1. Why is post-filtering retrieved chunks after top-k ranking risky for both security and answer quality?
  2. How do you handle document updates, soft deletes, and staleness without non-deterministic clock failures in tests?
  3. Why should a permission-aware retriever track denied_count and stale_or_deleted_count when returning empty or partial results?
Reveal self-review answers (attempt the questions first)
  1. 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.
  2. Updates, deletes, and staleness: Store version, updated_at_epoch_s, and is_deleted on each document record, and compute age deterministically from policy.as_of_epoch_s rather than calling live system time during unit tests.
  3. Observability and debugging: Explicit denied_count and stale_or_deleted_count counters 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.
Not completed
Discussion & field notes

Questions or notes on this module?

Leave a note or question

Comments are held in a moderation queue and appear once approved. Your email will not be published.