5/6
Industry Visibility & Career Brand · 6 min read

Designing Production RAG & Schema-Constrained Agents for Enterprise Compliance

Architect multi-tenant hybrid RAG, schema-constrained state machines, and blocking CI evaluation gates for SOC 2 and fintech audits, plus how to publish credible AI architecture writing.

Why This Matters at Engineering Leadership Scale

A weekend RAG prototype takes three hours and shines in a demo. Put that naive pipeline into an enterprise compliance or fintech platform under SOC 2, ISO 27001, or APRA CPS 234, and it fails fast: cosine-only search misses exact policy IDs and Jira keys, post-retrieval filtering risks tenant leaks, and unbounded agent loops execute unapproved writes or burn runaway token bills.

At Staff and Head of Engineering scale, AI architecture is about deterministic guardrails, verifiable retrieval precision, security isolation, and unit economics. Publishing real tenant-scoped SQL, Pydantic contracts, and CI eval thresholds establishes immediate platform authority.

Core Mental Model & Architecture

Enterprise compliance AI combines a 5-stage Hybrid RAG pipeline with a schema-constrained state machine wrapped in four runtime security layers.

LayerToy PrototypeProduction Compliance StandardRisk Eliminated
Chunking & Search500-token chunks, cosine onlyParent-child chunks (256/1024) + pgvector HNSW & BM25 (RRF) + Cross-encoder rerankMissed exact IDs, tickers, control codes
Tenant & ACL IsolationFilter results in app codeMandatory SQL pre-filter (WHERE tenant_id = $1 AND role = ANY($2))Cross-tenant leakage (IDOR)
Agent ControlUnbounded while(true) loopExplicit state machine, Pydantic schema, max_steps = 5, idempotency keysRunaway spend and invalid writes
Mutations & AuditAuto-run all tools; app logs3-tier tools (Read, Draft, HITL Mutation) + append-only audit trailUnapproved mutations; failed audits
Quality GateManual prompt spot-checks50-100 golden cases in CI blocking Faithfulness < 0.95 or p95 > +15%Silent prompt regressions

When publishing an architecture post, lead with blast-radius boundaries and hard numbers: chunk sizes, retrieval latency (+50 to 250ms), faithfulness bars (>0.95), and cost per 1,000 queries.

Step-by-Step Implementation Tutorial

Build a compliance-ready RAG and agent pipeline in four steps so Security and Risk approve during discovery instead of blocking GA.

  1. Build SQL-Enforced Hybrid Retrieval. Combine pgvector HNSW dense search with Postgres tsvector BM25 via Reciprocal Rank Fusion (RRF), enforcing tenant_id and acl_roles in every SQL WHERE clause before ranking, then cross-encoder rerank top 25 down to top 5.
  2. Scrub PII and Isolate Untrusted Text at Ingress. Before prompts leave your VPC to a Zero Data Retention (ZDR) endpoint, swap emails, account IDs, and keys for reversible placeholders ([PII_EMAIL_1]). Wrap untrusted external text (Jira comments, webhooks, PDFs) in <untrusted_document> XML tags to block indirect prompt injection.
  3. Constrain Agent Actions With Schemas and HITL Tiers. Enforce strict Pydantic/JSON Schema outputs with an explicit "insufficient_evidence" abstention path. Pause high-blast-radius mutations for Human-in-the-Loop (HITL) approval and log correlation_id, prompt_version, model_id, input_hash, and approver_id to an append-only audit store.
  4. Block Merges With Automated CI Evals. Run 50-100 curated golden cases (Recall@5, Faithfulness, p95 latency, cost/1k queries) on every prompt or chunking PR.

Drop these production SQL and Pydantic guardrail patterns directly into your service:

sql
-- Hybrid Dense (pgvector) + Sparse (BM25) RRF with Mandatory Tenant/ACL Pre-Filter
WITH dense AS (
  SELECT id, parent_content, ROW_NUMBER() OVER (ORDER BY embedding <=> $1::vector) AS r_d
  FROM compliance_chunks
  WHERE tenant_id = $2 AND acl_role = ANY($3::text[])
  ORDER BY embedding <=> $1::vector LIMIT 25
),
sparse AS (
  SELECT id, parent_content, ROW_NUMBER() OVER (ORDER BY ts_rank_cd(tsv, plainto_tsquery('english', $4)) DESC) AS r_s
  FROM compliance_chunks
  WHERE tenant_id = $2 AND acl_role = ANY($3::text[]) AND tsv @@ plainto_tsquery('english', $4)
  LIMIT 25
)
SELECT COALESCE(d.id, s.id) AS chunk_id, COALESCE(d.parent_content, s.parent_content) AS content,
       COALESCE(1.0 / (60 + d.r_d), 0.0) + COALESCE(1.0 / (60 + s.r_s), 0.0) AS rrf_score
FROM dense d FULL OUTER JOIN sparse s ON d.id = s.id
ORDER BY rrf_score DESC LIMIT 25;
python
from typing import Literal
from pydantic import BaseModel, Field

class Citation(BaseModel):
    chunk_id: str
    exact_quote: str = Field(..., max_length=240)

class ComplianceDecision(BaseModel):
    status: Literal["compliant", "gap_detected", "insufficient_evidence"]
    summary: str = Field(..., max_length=320)
    citations: list[Citation] = Field(default_factory=list)
    action: Literal["none", "create_draft_ticket", "escalate_hitl_approval"]
    idempotency_key: str = Field(..., min_length=16)

Worked Production Scenario: Before vs. After

A multi-tenant SOC 2 platform launched a vector-only RAG assistant across 12 beta customers to map Jira tickets and PRs to audit controls. It suffered 18.4% hallucinated mappings on exact control IDs (CC7.2), leaked an archived policy chunk after a role downgrade, and failed a bank security review for missing audit trails.

Rebuilding over six weeks with Postgres hybrid RRF, SQL ACL pre-filtering, cross-encoder reranking, Pydantic abstention contracts, per-tenant Redis TPM caps, and a 75-case CI eval gate transformed quality and cost:

MetricNaive BetaProduction GuardrailedNet Impact
Retrieval Recall@569%94%+25 pts accuracy
CI Eval Faithfulness0.810.97Above >0.95 bar
Unsupported Claims18.4%1.9% (clean abstention)-90% audit risk
p95 Latency / Cost per 1k4.8s / $38.501.9s / $14.20-60% latency, -63% cost

Common Failure Modes & Anti-Patterns

  1. Post-Retrieval Tenant Filtering. Filtering global top-10 vectors in Python risks leaks and returns empty results when another tenant dominates similarity scores. Fix: Enforce tenant_id and acl_role inside SQL.
  2. Tuning Prompts Without Regression Evals. Tweaking one edge case silently breaks 12% of existing queries. Fix: Gate every prompt and chunking PR behind a blocking golden CI eval suite.
  3. Publishing Box-and-Arrow AI Posts. Diagrams labeled "Agent Brain -> Tools" fail Staff Engineer scrutiny. Fix: Share real schema contracts, SQL tenant filters, prompt-injection delimiters, and unit economics.

How to Handle Pushback in the Room

Security & Risk Partner: "We cannot send customer compliance evidence to external LLM APIs under APRA CPS 234 and SOC 2."

Calm Response: "Agreed - zero raw PII and zero consumer endpoints. We enforce contractual Zero Data Retention enterprise endpoints via VPC PrivateLink, ingress PII redaction before prompts leave our network, and an append-only audit log capturing prompt version, input hash, and human approval. Let's run a 30-minute STRIDE check before coding."

Pushing Product Manager: "Can the agent auto-close passing controls so the UX feels magical?"

Calm Response: "Auto-closing controls is a one-way compliance risk - one false positive invalidates a SOC 2 audit. Let's auto-generate a cited draft with one-click human approval, cutting auditor effort 80% while keeping legal sign-off intact."

Key Takeaways & This Week's Action Rep

  • Prioritize retrieval over model swaps: Hybrid dense-plus-sparse RRF, parent-child chunking, and cross-encoder reranking drive reliability.
  • Isolate tenants in SQL and wrap untrusted text: Pre-filter tenant_id/ACLs at query time and isolate external inputs in XML tags.
  • Keep agents deterministic: Enforce Pydantic schemas, max_steps limits, idempotency keys, HITL gates, and immutable audit logs.
  • Use evals as CI gates and editorial proof: Blocking merges below 0.95 Faithfulness stabilizes production and grounds public writing.

This Week's Action Rep: Build a 20-question golden eval file for one active AI workflow (5 exact-ID lookups + 5 abstention cases), wire it into CI, and run a 30-minute STRIDE check covering tenant isolation and prompt injection.