Implux Field GuideAGENTIC AI · FORWARD DEPLOYED ENGINEERING

A practical reference for designing agents, delivering software, and proving outcomes.

THE PRACTITIONER'S REFERENCE
Questions · Patterns · Practice

Runnable coding lab / Python standard library

Tenant-safe retrieval

Enforce tenant and principal access before any retrieved text is returned to a model. The exercise is deliberately small: focus on the invariant and tests, then explain what production hardening it would need.

No external packagesSolution and unittest cases includedCopy, run, then extend

The exercise

Implement authorization filtering before ranking retrieved records. Prove with tests that cross-tenant and unauthorized documents never enter the model context.

  1. Before looking at the solution

    Write down the invariant the code must preserve and one failure case that could violate it.

  2. Run the reference implementation

    Download the single-file lab and run python tenant-safe-retrieval.py. It uses Python's built-in unittest and needs no network or API key.

  3. Read each test as a requirement

    Identify what the test proves, what it does not prove, and which production boundary remains trusted.

  4. Modify one condition

    Add a test for cancellation, concurrent requests, revocation, or a corrupted evaluation case. Explain how the design changes.

Download runnable lab and tests ↗

Reference solution

Show the complete solution and tests
def retrieve_for(principal: dict, documents: list[dict], query: str) -> list[dict]:
    tenant = principal["tenant_id"]
    roles = set(principal.get("roles", []))
    allowed = [d for d in documents if d["tenant_id"] == tenant and set(d["required_roles"]).issubset(roles)]
    terms = set(query.lower().split())
    return sorted(allowed, key=lambda d: len(terms & set(d["text"].lower().split())), reverse=True)

if __name__ == "__main__":
    import unittest
    class RetrievalTests(unittest.TestCase):
        def setUp(self):
            self.docs = [
                {"id":"a", "tenant_id":"acme", "required_roles":[], "text":"refund policy"},
                {"id":"b", "tenant_id":"other", "required_roles":[], "text":"refund policy"},
                {"id":"c", "tenant_id":"acme", "required_roles":["finance"], "text":"refund limits"},
            ]
        def test_isolates_tenant(self):
            got = retrieve_for({"tenant_id":"acme"}, self.docs, "refund policy")
            self.assertEqual({d["id"] for d in got}, {"a"})
        def test_enforces_roles(self):
            got = retrieve_for({"tenant_id":"acme", "roles":["finance"]}, self.docs, "refund")
            self.assertEqual({d["id"] for d in got}, {"a", "c"})
        def test_ranks_matching_terms(self):
            got = retrieve_for({"tenant_id":"acme", "roles":["finance"]}, self.docs, "refund policy")
            self.assertEqual(got[0]["id"], "a")
    unittest.main()

The mental model

Authorization is a prerequisite to retrieval, not a ranking preference. The model should only receive records already authorized for the authenticated principal.

Limits and production extensions

The example uses trusted principal data and simple term overlap. Production authorization must use authoritative policy, account for revocation and cache invalidation, and avoid exposing denied records in logs or debug output.

Explain it in an interview

01InvariantWhat must always remain true?
02BoundaryWhich decision belongs in trusted code?
03FailureWhat happens when the result is unknown?
04EvidenceWhich test demonstrates the property?
05ProductionWhat concurrency, persistence, or policy layer is missing?
A concise implementation answer names both the working code path and the assumptions the toy example leaves behind.

Follow-up prompts

  • What race or failure does this example still permit?
  • How would you make the result observable without logging secrets?
  • Which property belongs in a unit test, integration test, or production alert?