12.4 PII, Privacy and Data Leakage

ProductionLesson 4 of 1017,015 words8 parts
Module 12 · 0 of 10 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

Every prompt you send to a model is a data transfer. The question is not whether data leaves your systems — it does, on every call — but which data, to whom, under which terms, and what copies of it survive afterwards. This lesson is the privacy engineering companion to the rest of Module 12: where personal and sensitive data leaks in an LLM system, how to classify it, how to detect it, how to protect it before it moves, and what the law expects you to build. It is defensive by design: the goal is to keep your users' data yours.

What you'll learn

  • Every place sensitive data can leak in an LLM system: provider-side copies, your own logs and caches, derived copies in vector stores and eval sets, cross-tenant paths, and model output
  • A working taxonomy of sensitive data — direct identifiers, quasi-identifiers, sensitive categories, credentials and confidential business data — plus data classification levels and a provider policy matrix
  • How to detect PII and secrets: checksum validators (Luhn, IBAN, national IDs), regex detectors, NER (Presidio, spaCy, GLiNER), LLM-based detection and secret scanners — and how to measure a detector's precision and recall honestly
  • The protection toolkit: minimise, redact, mask, tokenise and pseudonymise with a reversible vault, synthetic substitution, local models, regional endpoints, contract controls (ZDR, BAAs), encryption, retention and the right to erasure
  • Output-side controls: scanning model output, system-prompt leakage, tenant/memory/cache isolation and safe error messages
  • What memorisation and extraction attacks mean for the data you put in prompts and fine-tuning sets
  • Privacy law at engineering level — GDPR, CCPA/CPRA, HIPAA, PCI DSS, India's DPDP Act and more — as awareness, not legal advice
  • Privacy-preserving evaluation and debugging: scrubbed traces, synthetic replacements and consent for production data in evals

What you don't need

  • Legal expertise. Part 7 teaches the engineering shape of privacy obligations; your legal team owns the actual compliance call.
  • API keys. Every code sample in this lesson is pure Python standard library — no model calls, no services, no keys. The Presidio and spaCy sections are optional deeper dives.
  • Module 07 or 08 internals. RAG and agent mechanics are covered there; this lesson links to the exact sections where data-handling decisions live.

Setup

The core code needs only Python 3.11+ and the standard library:

bash
uv init guardrails --bare --python 3.13 && cd guardrails   # the module's running project; skip if you already made it
# or: pip install nothing — pii.py uses only the standard library

The lesson builds one file, pii.py, presented in parts across Parts 3–5 and consolidated at the end. For the optional NER section (3.4), install Presidio and its spaCy model:

bash
uv add presidio-analyzer presidio-anonymizer
uv run python -m spacy download en_core_web_lg
# or: pip install presidio-analyzer presidio-anonymizer && python -m spacy download en_core_web_lg

The samples were checked against the two Presidio packages (the analyser and presidio-anonymizer) at 2.2.366 as of November 2026, and a plain install gives you the newest release. Recognizer names and the spaCy model Presidio expects can change between releases, so if the analyser raises about a missing model or entity, check the release notes for the version you installed.

No .env file or provider keys are needed for anything in this lesson.


What you must be able to do after this lesson#

  • List the places where sensitive data leaks in an LLM system
  • Classify data as direct identifiers, quasi-identifiers, sensitive categories or credentials
  • Detect PII and secrets with validators such as Luhn, regex and NER
  • Choose between redaction, masking and reversible tokenisation
  • Scan model output and isolate tenants, caches and memory to stop leaks
  • Explain what a deletion pipeline must reach

Why this matters for an AI engineer#

Privacy failures in LLM systems are rarely dramatic hacks. They are mundane engineering oversights: a prompt logged with a user's email, a vector store shared across tenants, an eval dataset built from production chats, a screenshot of a support ticket posted to a vendor's consumer chat app. Each one is a data breach waiting for an audit.

You'll hear... You'll understand it after...
"The provider says they don't train on API data, so we're fine." 1.2 Provider-side copies
"It's just a vector — you can't read text back from it." 1.4 Derived copies
"Redact the PII before we send it." 3 Detection, 4 Protection
"The model refused to leak the system prompt, so it's safe." 5.2 System-prompt leakage
"We need real user chats to build a good eval set." Part 8: Privacy-preserving evaluation
"Delete my data" must work across how many stores? 4.8 Retention and erasure
"Is pseudonymised data still personal data?" 2.1–2.2, 4.3
"Can we fine-tune on our support tickets?" Part 6: Memorisation
"Which detector should we use — regex, Presidio, or an LLM?" 3.7 Evaluating detectors

Part 1: Where data leaks in an LLM system#

1.1 The LLM data-flow and its leak points#

A classical web application has a clear trust boundary: your database is inside, the internet is outside, and every read/write crosses a gate you control. An LLM application blurs that boundary because the model itself is a third party (or at least a separate trust domain), and because data keeps being copied into places nobody thinks of as "storage": prompts inside log lines, retrieved chunks inside traces, embeddings inside vector indexes, conversation history inside provider-side state.

Here is the same docs_qa-style support assistant from earlier modules, drawn as a data-flow with every place sensitive data can escape or persist:

flowchart TB
    subgraph user_side ["User side"]
        U["End user<br/>(types PII into the chat)"]
    end

    subgraph app ["Your application (trust boundary)"]
        API["API layer<br/>auth, rate limits"]
        PIPE["Pipeline<br/>retrieve -> prompt -> model -> answer"]
        LOG["Logs & traces<br/>(PII-safe by default?)"]
        CACHE["Caches<br/>(response + semantic)"]
        MEM["Memory store<br/>(user facts)"]
        VS[("Vector store<br/>chunks + embeddings")]
        EVAL["Eval sets<br/>(built from prod?)"]
        FT["Fine-tuning sets<br/>(built from prod?)"]
    end

    subgraph outside ["Outside your boundary"]
        LLM["LLM provider<br/>(OpenAI / Anthropic / Gemini / OpenRouter)"]
        EMB["Embedding provider"]
        OBS["Observability vendor<br/>(traces, replays, screenshots)"]
        SUP["Support/analytics tools<br/>(session replay, chat widgets)"]
    end

    U -->|"question + history"| API
    API --> PIPE
    MEM -.->|"recalled facts"| PIPE
    VS -->|"retrieved chunks"| PIPE
    PIPE -->|"full prompt"| LLM
    PIPE -->|"chunk text"| EMB
    PIPE -->|"answer + citations"| API
    API -->|"answer"| U
    PIPE -.->|"spans, prompts?, outputs?"| LOG
    PIPE -.->|"answers keyed by scope?"| CACHE
    PIPE -.->|"OTLP spans"| OBS
    API -.->|"session events"| SUP
    U -.->|"uploads: images, PDFs, audio"| API
    LOG -.->|"exported?"| EVAL
    EVAL -.->|"curated?"| FT

Every dotted arrow is a leak path. Solid arrows are the intended data flow — but note that the solid arrows to LLM, EMB and OBS already carry whatever PII was in the question, the retrieved chunks, or the recalled memory. The leak paths worth memorising:

# Leak path What escapes Covered in
1 Prompt to LLM provider Question text, retrieved chunks, memory facts, few-shot examples, tool outputs 1.2, 4
2 Chunk text to embedding provider Every ingested document 1.2
3 Traces/spans to observability vendor Prompts and outputs if content capture is on 1.3, 11A.1
4 Session replay / support widgets Screen content, chat text, form fields 5.5
5 Vector store Chunk text + embeddings of everything you indexed 1.4
6 Caches Answers and prompts keyed without permission scope 5.3
7 Memory store Facts the agent chose to remember about users 5.3
8 Eval sets & fine-tuning sets Production queries, answers, documents Part 8, Part 6
9 Error messages, stack traces, analytics events Request payloads echoed back 5.4
10 Model output itself PII the model echoes, system-prompt contents, other tenants' data Part 5

1.2 Provider-side copies: what the API does with your data#

When your code calls an LLM API, the provider receives the full prompt — instructions, history, retrieved documents, tool definitions — and returns the completion. What the provider does with that data is a contractual question, not a technical one, and the answer differs per provider, per product, and per tier. Lesson 02.9, Part 9 owns the question list and the provider snapshot; lesson 07.11, 2.6 verified the details for RAG workloads. The engineering-relevant summary, as of November 2026 (re-verify on the official pages before relying on it — these policies change):

Provider Training on API data Retention highlights Zero-data-retention option
OpenAI Not used to train or improve models unless you explicitly opt in Abuse-monitoring logs retained up to 30 days; some features store data (stored responses, files, vector stores, batches) ZDR and Modified Abuse Monitoring, both subject to prior approval; several endpoints are not ZDR-eligible (Files, Batches, the Conversations/threads/agents endpoints, vector stores, fine-tuning, Evals)
Anthropic "Retained data is never used for model training without your express permission" Prompts and outputs not retained by default, except Covered Models (30-day retention required); trust-and-safety-flagged content may be kept up to 2 years; classifier scores 7 years; feedback (thumbs) up to 5 years and may be used for training ZDR by arrangement with sales, per organization; not available for Covered Models or some features; HIPAA readiness with a signed BAA, self-serve in the Claude Console for most orgs
Google (Gemini API) Unpaid tier: content IS used to improve products and human reviewers may read it. Paid tier: not used. Paid: prompts/responses logged for a limited period for policy-violation detection; Grounding with Google Search stores prompts/context/output 30 days (cannot disable) Through Gemini Enterprise Agent Platform / Vertex AI enterprise controls; paid API is close to ZDR but grounding tools still retain
OpenRouter OpenRouter itself doesn't store prompts/responses by default; routing to providers that train is opt-out in account settings Metadata (tokens, latency) logged; optional I/O logging retains ≥3 months; CSAM screening applies in-flight even to ZDR traffic Per-endpoint data-policy tiers (ZDR / Safety Retention / Retention-and-Training) selectable in routing
Self-hosted open weights Your choice Your choice Your choice

Three consequences for privacy engineering:

  1. "No training" ≠ "no retention". Even where providers promise not to train, abuse-monitoring logs, safety classifiers, stored conversation state, files, caches and batch inputs create copies with their own clocks. Your erasure story must include their retention windows — you can't delete a provider's logs; you can only pick providers whose windows fit your obligations (4.8).
  2. The free tier is a different product. Gemini's unpaid quota explicitly feeds product improvement and human review. Development and throwaway workloads only — never production user data.
  3. ZDR is a contract, not a flag. Every provider gates it behind approval, a different product (Vertex AI), or an enterprise plan. If your compliance posture requires it, it's a procurement conversation that starts months before launch.

1.3 Your own copies: logs, traces, caches, memory#

The provider isn't the only place data accumulates — your own observability and state layers are copy machines:

  • Traces and spans. Lesson 11A.1 covers what to capture; the privacy rule is that content (prompt text, completion text, retrieved chunks, tool arguments) is off by default and, when enabled for debugging, goes only to an access-controlled store with short retention and redaction applied at write time, not read time. Lesson 08A.14, 3.5 states it for agents: "Redact at write time, not at read time." Lesson 03.10, 4.5 implements the same discipline for request logs — content logging is opt-in, sampled, scrubbed and truncated.
  • Semantic and response caches. A cached answer is a stored copy of model output, and a cached embedding is a stored copy of the input text in vector form (1.4). Cache keys must carry the permission scope so one user's answer can't be served to another (5.3; lesson 07.11, 2.3.2).
  • Conversation stores. Server-side state (store=true on OpenAI, Anthropic message threads, Gemini interactions) keeps prompts and outputs provider-side until deleted — 03.2, Part 10 covers what each API retains and how to delete it.
  • Memory. Whatever an agent decides to "remember" about a user is a durable copy of personal data. Lesson 08B.2 owns memory design; its write policy already excludes secrets and unneeded PII, and its multi-tenant namespacing is the isolation mechanism this lesson relies on (5.3).
  • Error trackers and support tools. Exception payloads, request bodies attached to Sentry-style events, and session-replay widgets capture whatever was on screen — including form fields with card numbers or health details. Treat them as data stores with their own retention and access rules.

1.4 Derived copies: vectors, eval sets, fine-tuning data#

The most under-appreciated leak paths are the derived copies — artefacts built from user data that nobody thinks of as containing user data:

  • Embeddings and vector stores. A vector is not an anonymised summary. Morris et al. (EMNLP 2023, arXiv:2310.06816) showed text can be reconstructed from its embedding with surprising accuracy — about 92% of short inputs recovered exactly, including names from clinical notes. Lesson 02.3, 10.7 owns this topic; the operational rules are: treat vectors like the text they encode — same access control, encryption, retention and deletion. Deleting a document means deleting its vectors, including in backups and caches.
  • Evaluation datasets. The fastest way to build a good eval set is to sample production traffic — which means copying real user queries, answers and documents into test fixtures. Lesson 10A.2 (building eval datasets) and Module 10A own eval methodology; Part 8 of this lesson owns the privacy rules for doing it.
  • Fine-tuning data. Fine-tuning on production conversations bakes user data into model weights — the strongest possible copy, one you cannot selectively delete afterwards. Part 6 covers why this is the riskiest copy of all.
  • Synthetic data derived from real data. Synthetic examples generated from real records inherit their privacy properties: "treat anything derived from real rows as real until proven otherwise" (10A.2).
  • Analytics and aggregations. "Just counts" can still leak: a count of one is an identity; a histogram of rare diseases in a small town is a patient list. Aggregation is a privacy technique only above a threshold — see 4.5.

1.5 Cross-tenant and cross-user leakage#

Multi-tenant LLM systems fail privacy in a specific way: tenant A's data appears in tenant B's answers. The mechanisms are always the same few:

  • ACL filters that aren't applied. Retrieval filters are code, not prompts — if the tenant filter is missing, post-filtered, or bypassable, the model happily quotes another tenant's contract. Lesson 06.6 owns the ACL-filtering pattern; lesson 07.11, 2.3 applies it to RAG; lesson 12.6 covers the agent/tool side.
  • Shared caches. A semantic cache keyed on question similarity but not on permission scope serves one user's personalised answer to another. The fix is structural: the scope is part of the key, computed server-side (5.3).
  • Shared memory. An agent memory store without per-user namespacing lets one user's "remembered" facts surface in another's session. Lesson 08B.2, Part 5 owns the namespace model.
  • Batch and provider-side state. Provider-side conversation IDs, vector stores and file storage are scoped per API key/project — a shared project across tenants collapses the boundary at the provider too.
  • Debug and support access. The engineer who can read traces can read every user's prompts. Trace access is data access (5.3).

1.6 The leak-path inventory#

Before designing protections, write the inventory for your system. For each row, ask: what data class flows here, who can read it, how long is it kept, and how is it deleted? The OWASP Top 10 for LLM Applications names this risk class LLM02 Sensitive Information Disclosure (the ID is the same in the 2025 and 2026 editions) — covering PII, financial details, health records, confidential business data, credentials and legal documents exposed through model output — and two related items whose IDs changed in the 2026 edition: system-prompt leakage, now LLM08:2026 Hidden Context Exposure (it was LLM07:2025 System Prompt Leakage), and LLM09:2026 Vector and Embedding Weaknesses (it was LLM08:2025) (OWASP GenAI Security Project, 2026 edition, see 12.1, 3.1; checked November 2026). Lesson 12.1 owns the full threat model; this table is the privacy slice of it:

Surface Data at risk Primary controls (this lesson)
Outbound prompts Everything in context Minimise, vault-tokenise, provider selection Part 4
Provider retention Prompt/output copies Contract controls, ZDR, residency 4.6
Logs, traces, error trackers Content if captured PII-safe logging, write-time redaction 1.3, 5.1
Vector store + caches Chunks, embeddings, answers Treat vectors as sensitive; scope keys 1.4, 5.3
Memory User facts Write policy, namespacing, user-visible deletion 5.3
Eval/fine-tuning sets Production data Scrubbed fixtures, consent, synthetic data Part 8, Part 6
Model output Echoed PII, other tenants' data, system prompt Output scanning, least-context design Part 5
Media uploads EXIF/GPS, faces, voices, documents Strip metadata, redact, consent 5.5

Part 2: What counts as sensitive#

2.1 Personal data, PII and the taxonomy#

Personal data is the legal term — GDPR's "any information relating to an identified or identifiable natural person" is the broadest common definition. PII (personally identifiable information) is the engineering term: data that can identify a person, alone or combined with other data you hold. For building systems, the useful split is how the data identifies:

Class Examples Identifies alone?
Direct identifiers Email, phone, full name + context, government ID (passport, national ID, SSN), bank account, card number, username, precise location (home address, live GPS), biometric template, credentials/secrets Yes
Quasi-identifiers Age, postcode/district, job title, purchase history, device ID, IP address, "the only person in the team who..." Only combined
Sensitive categories Health data, racial/ethnic origin, political/religious beliefs, sexual orientation, trade-union membership, genetic/biometric data, children's data Yes — and regulated hardest
Credentials & secrets API keys, passwords, tokens, private keys, session cookies Yes — and usable, so worse than PII
Confidential business data Unreleased prices, M&A plans, source code under NDA, customer lists, security findings Maybe — but commercially sensitive

Two distinctions matter for engineering:

  • PII vs secrets. A leaked email is a privacy incident; a leaked API key is a security incident that also happens to be personal data. They travel together through the same pipelines but need different detectors and different responses (3.3; key management is lesson 12.7's).
  • Sensitive categories are not just "more PII". Health, biometric, children's and similar data carry stricter legal regimes (GDPR special categories, HIPAA, COPPA-class rules, BIPA-class biometric laws) and often can't be sent to a third-party model at all, redacted or not (Part 7).

2.2 Quasi-identifiers and why "not PII" doesn't mean safe#

A quasi-identifier is data that doesn't identify anyone alone but narrows the field enough to re-identify when combined — the classic example is {ZIP code, birth date, sex}, which Latanya Sweeney showed could uniquely identify ~87% of the US population in the 1990 census (Sweeney, 2000, "Simple Demographics Often Identify People Uniquely"). LLM systems are quasi-identifier machines:

  • "The support ticket from the customer in the Lisbon office who joined in March" is anonymous until you join it against your CRM.
  • An embedding of a clinical note contains quasi-identifiers even when names are stripped — inversion attacks recover the content, and content is identifying.
  • Agent memory accumulates quasi-identifiers over time: preferences, project names, schedules, "usually asks about invoices over €5k". Each fact is harmless; the profile is a person.
  • Aggregated analytics leak through small cells: "3 users in sector X reported issue Y" can be one user.

2.3 Credentials and secrets#

API keys, passwords, tokens and private keys pasted into prompts, documents, tickets or code snippets are the highest-severity leak class because they are directly usable. They appear constantly in real corpora — a support ticket containing a .env paste, a README with a hard-coded key, a stack trace echoing an Authorization header. Lesson 03.10's redact.py already covers the credential shapes for logs; this lesson's detector adds the same coverage to prompts, documents and model output (3.2, 3.3). The rules:

  • Secrets never enter prompts or retrieved context. If a document contains a key, the document needs redaction before embedding, not after.
  • Secrets never appear in logs or traces — not even "partially", not even in error messages (5.4).
  • Detection is necessary but not sufficient — the durable fix is secret management and least-privilege keys (lesson 12.7), because a scanner will always miss some format.

2.4 Regulated data classes#

Some data classes trigger specific legal regimes regardless of how careful you are. Awareness level — your compliance team owns the detail:

Class Examples Regime (awareness)
Health data / PHI Symptoms, diagnoses, prescriptions, mental-health content HIPAA (US) requires a BAA with the provider; GDPR treats it as special category; many providers offer HIPAA-eligible endpoints only under enterprise terms (4.6)
Payment card data PAN, CVV, expiry PCI DSS scope; never send card numbers to a model — mask to last-4 at most
Children's data Anything about under-18s (varies: under-13 in US COPPA, under-16 in some EU states) COPPA-class consent and parental controls; EU AI Act prohibits certain uses outright; design for the strictest regime (09.10, 5.1)
Biometric data Face embeddings, voiceprints, fingerprints GDPR special category; US state laws (BIPA in Illinois); voice cloning needs documented consent (09.10, 5.1–5.5)
Government IDs Passport, national ID, SSN, driver's licence High-value identity theft material; strict handling + breach notification duties
Precise location GPS coordinates, home addresses GDPR personal data; often special-category-adjacent when combined with other data

2.5 Confidential business data#

Not personal data, but leaking it is still a breach of trust: unreleased product plans, pricing, M&A information, source code under NDA, security findings, customer lists. The controls are the same family — minimise what enters prompts, control who can read traces, classify documents at ingestion (05.5 tags confidentiality/acl metadata) — but the detection problem is harder: "is this sentence confidential?" has no regex. That's a classification problem for your ingestion pipeline and your access-control metadata, not for a PII detector.

2.6 Data classification and the provider policy matrix#

The output of classification is a policy: for each data class, which destinations are allowed. Write it as a matrix and enforce it in code at the egress point — this is the "data classification levels and what may be sent to which provider" decision the plan asks for:

Data class Public LLM API (paid tier) LLM API (free/consumer tier) Self-hosted model Third-party observability
Public docs, synthetic data ✅ ✅ ✅ ✅
Internal business data (non-PII) ✅ per DPA ⚠️ check terms ✅ ⚠️ redacted traces only
PII (emails, names, IDs) ⚠️ minimise/vault first ❌ ✅ ❌ raw; ✅ counts/hashed IDs
Sensitive categories (health, biometrics, children's) ❌ unless BAA/ZDR + lawful basis ❌ ✅ preferred ❌
Credentials/secrets ❌ never ❌ never ❌ never ❌ never
Regulated data (PHI, PCI PAN) ❌ unless HIPAA-eligible endpoint + BAA ❌ ✅ ❌

Part 3: Detecting PII and secrets#

You can't protect what you can't find, so detection comes first — and it's where most privacy engineering actually happens. The toolbox has five layers, each catching what the others miss:

Method Catches Misses Cost Determinism
Validators + checksums Emails, cards (Luhn), IBANs, national IDs with real format proof Everything without a checksum ~free Exact
Regex/pattern detectors Structured shapes: phones, SSNs, key formats, labelled fields Names, addresses, context-dependent PII ~free Exact
NER (Presidio, spaCy, GLiNER) Names, locations, organisations, dates — the unstructured 80% Domain-specific entities, heavy setup Medium Mostly
LLM-based detection Semantic PII ("my son Tyler", "the Acme deal") Can hallucinate spans, costs tokens, sends the data to a detector High Probabilistic
Secret scanners API keys, tokens, passwords in text/git Novel formats, split secrets ~free Exact

The lesson's code builds the first two layers plus the evaluation harness; 3.4 covers NER and 3.5 covers the LLM option. Everything lives in one file, pii.py, built up across this part and Part 4 — standard library only, fully deterministic, safe to run with no keys.

3.1 Validators and checksums: prove it, don't just match it#

A regex can match the shape of a credit-card number; a checksum validator proves it's probably real. The difference matters: 4111 1111 1111 1111 and 1234 5678 9012 3456 have identical shapes, but only the first survives the Luhn check. Validators turn false positives into near-certainties for free.

This is the first part of pii.py:

python
# pii.py — lesson 12.4. Part A: validators.
# "Is this candidate string actually a valid X?" — checksum and format
# checks that turn a regex shape-match into a near-certain match.
# Standard library only; deterministic.

from __future__ import annotations

import re


def luhn_ok(digits: str) -> bool:
    """Luhn check digit (ISO/IEC 7812) used by payment card numbers."""
    total = 0
    for i, ch in enumerate(reversed(digits)):
        if not ch.isdecimal():      # also accepts non-ASCII digits, e.g. full-width 4242
            return False
        d = int(ch)
        if i % 2 == 1:
            d *= 2
            if d > 9:
                d -= 9
        total += d
    return total % 10 == 0


def card_digits_ok(candidate: str) -> bool:
    digits = re.sub(r"\D", "", candidate)
    return 12 <= len(digits) <= 19 and luhn_ok(digits)


def iban_ok(candidate: str) -> bool:
    """ISO 13616 IBAN check: rearrange, convert letters to digits, mod-97 == 1."""
    iban = re.sub(r"\s+", "", candidate).upper()
    if not re.fullmatch(r"[A-Z]{2}\d{2}[A-Z0-9]{11,30}", iban, re.ASCII):
        return False
    rearranged = iban[4:] + iban[:4]
    digits = "".join(str(int(c, 36)) if c.isalpha() else c for c in rearranged)
    remainder = 0
    for ch in digits:
        remainder = (remainder * 10 + (ord(ch) - 48)) % 97
    return remainder == 1


EMAIL_SHAPE = re.compile(
    r"^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}@"
    r"(?:[A-Za-z0-9-]{1,63}\.)+[A-Za-z]{2,63}$"
)


def email_ok(candidate: str) -> bool:
    return bool(EMAIL_SHAPE.match(candidate.strip()))


def ssn_us_ok(candidate: str) -> bool:
    """US SSN: format plus the published invalid ranges (no public checksum)."""
    m = re.fullmatch(r"(\d{3})-(\d{2})-(\d{4})", candidate.strip())
    if not m:
        return False
    area, group, serial = (int(g) for g in m.groups())
    return not (area == 0 or area == 666 or area >= 900 or group == 0 or serial == 0)


# Verhoeff dihedral-group tables — the checksum behind India's Aadhaar
# and several other national ID schemes.
_D5P = [
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
    [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
    [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
    [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
    [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
    [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
    [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
    [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
]
_D5N = [
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],
    [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
    [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],
    [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],
    [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
    [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],
    [7, 0, 4, 6, 9, 1, 3, 2, 5, 8],
]


def _verhoeff_checksum(digits: str) -> int:
    c = 0
    for i, ch in enumerate(reversed(digits)):
        c = _D5P[_D5N[i % 8][c]][int(ch)]   # int() handles any Unicode decimal digit
    return c


def verhoeff_check_digit(base: str) -> int:
    """Compute the Verhoeff check digit for a base digit string."""
    return next(d for d in range(10) if _verhoeff_checksum(base + str(d)) == 0)


def aadhaar_ok(candidate: str) -> bool:
    """12-digit Aadhaar-shaped number passing the Verhoeff checksum."""
    digits = re.sub(r"\D", "", candidate)
    return len(digits) == 12 and _verhoeff_checksum(digits) == 0

Three checksum families appear here, and they're worth recognising because national ID schemes reuse them:

  • Luhn (payment cards, some national IDs): double every second digit from the right, sum, mod 10. 4242 4242 4242 4242 passes; 1234 5678 9012 3456 doesn't.
  • IBAN mod-97 (ISO 13616): rearrange the country code and check digits to the end, expand letters to numbers, and the whole thing must be divisible by 97 leaving remainder 1. GB29 NWBK 6016 1331 9268 19 is the canonical valid example.
  • Verhoeff (India's Aadhaar, and several other schemes): a dihedral-group checksum — each digit transforms the running value through position-dependent permutations. It's why Aadhaar can catch a single mistyped digit.

3.2 Pattern detectors: spans, not substitutions#

Validators answer "is this candidate real?"; detectors answer "where in this text is sensitive data?" The design choice that matters: detectors return spans (type + offsets), never the matched text. A Finding is safe to log; the text it points into is not.

python
# pii.py — Part B: span detectors and secret scan. (Parts A–D are sections of one file: paste them into pii.py in order, A first.)

from dataclasses import dataclass
from typing import Callable


@dataclass(frozen=True)
class Finding:
    """A detected span. Carries type + offsets + score — never the matched
    text, so a list of findings is safe to log and inspect."""
    entity_type: str
    start: int
    end: int
    score: float = 1.0

    def describe(self) -> str:
        return f"{self.entity_type}[{self.start}:{self.end}] score={self.score:.2f}"


def _phone_digits_ok(candidate: str) -> bool:
    # Only a digit-count check (E.164 allows 8-15) — the shape below is
    # permissive, so precision comes from the eval fixture, not this gate.
    n = sum(c.isdigit() for c in candidate)
    return 8 <= n <= 15


PHONE_SHAPE = re.compile(
    r"(?<![\w.:/+-])(?:\+\d{1,3}[ .-]?(?:\(\d{1,5}\)[ .-]?)?\d{2,5}(?:[ .-]?\d{2,5}){1,3}"
    r"|\(?\d{3,5}\)?[ -]\d{3,4}[ -]\d{3,5}(?:[ -]\d{1,4})?)(?![\w-])"
)
# Deliberately stricter than card_digits_ok (which accepts 12-19 digits):
# the shape requires >=13 digits so order IDs don't flood the candidates.
CARD_SHAPE = re.compile(r"(?<!\d)(?:\d[ \u00a0.-]?){12,18}\d(?!\d)")
# Bounded and anchored (local part <= 64 characters, domain <= 253): an unbounded
# "[...]+@" retried from every position is quadratic on a long "a.a.a.a..." run.
EMAIL_FIND = re.compile(
    r"(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,}\b")
# IGNORECASE: iban_ok() uppercases its input, and real text contains
# lowercase/mixed-case IBANs the validator would happily accept.
IBAN_FIND = re.compile(
    r"\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]{4}){2,7}(?:[ ]?[A-Z0-9]{1,3})?\b",
    re.IGNORECASE,
)
SSN_FIND = re.compile(r"\b\d{3}-\d{2}-\d{4}\b")
AADHAAR_FIND = re.compile(r"\b\d{4}[ -]?\d{4}[ -]?\d{4}\b")

# (entity_type, pattern, validator-or-None, score)
_DETECTORS: list[tuple[str, re.Pattern[str], Callable[[str], bool] | None, float]] = [
    ("EMAIL", EMAIL_FIND, email_ok, 0.95),
    ("IBAN", IBAN_FIND, iban_ok, 0.95),
    ("CREDIT_CARD", CARD_SHAPE, card_digits_ok, 0.90),
    ("SSN_US", SSN_FIND, ssn_us_ok, 0.90),
    ("AADHAAR", AADHAAR_FIND, aadhaar_ok, 0.90),
    ("PHONE", PHONE_SHAPE, _phone_digits_ok, 0.80),
]


def _overlaps(a: Finding, b: Finding) -> bool:
    return a.start < b.end and b.start < a.end


def _resolve_overlaps(candidates: list[Finding]) -> list[Finding]:
    """Sort by start offset (then score, then length) and keep the first
    claimant of each overlapping range. Score decides only between claims
    that start at the same character; a card-shaped run inside a longer
    IBAN loses to the IBAN because the IBAN starts first."""
    candidates.sort(key=lambda f: (f.start, -f.score, -(f.end - f.start)))
    kept: list[Finding] = []
    for f in candidates:
        if not any(_overlaps(f, k) for k in kept):
            kept.append(f)
    return sorted(kept, key=lambda f: f.start)


def _detect_candidates(text: str) -> list[Finding]:
    """Raw regex + validator candidates, before overlap resolution."""
    candidates: list[Finding] = []
    for entity, pattern, validator, score in _DETECTORS:
        for m in pattern.finditer(text):
            if validator is None or validator(m.group()):
                candidates.append(Finding(entity, m.start(), m.end(), score))
    return candidates


def detect_pii(text: str) -> list[Finding]:
    """Return non-overlapping PII findings (regex + validators only).
    For the NER layer, merge analyzer spans via detect_with_analyzer."""
    return _resolve_overlaps(_detect_candidates(text))


# Secret shapes — labels only, never the matched value.
SECRET_PATTERNS: list[tuple[str, re.Pattern[str]]] = [
    ("JWT", re.compile(r"(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}")),
    ("API_KEY", re.compile(
        r"(?<![A-Za-z0-9_-])(?:"
        r"sk-(?:ant-|or-v1-|or-|proj-)?[A-Za-z0-9_-]{16,}"
        r"|AIza[0-9A-Za-z_-]{30,}"
        r"|ya29\.[A-Za-z0-9_-]{20,}"
        r"|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}"
        r"|xai-[A-Za-z0-9]{20,}"
        r"|gsk_[A-Za-z0-9]{20,}"
        r"|hf_[A-Za-z0-9]{20,}"
        r"|(?:AKIA|ASIA)[0-9A-Z]{16}"
        r"|(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}"     # Stripe
        r"|xox[abeoprs]-[A-Za-z0-9-]{10,}"               # Slack
        r")")),
    ("PRIVATE_KEY", re.compile(r"-----BEGIN (?:[A-Z]+ )*PRIVATE KEY(?: BLOCK)?-----")),
    ("BEARER", re.compile(r"(?i)\bbearer\s+[A-Za-z0-9._\-]{12,}")),
    ("SECRET_KV", re.compile(
        # Matches DB_PASSWORD=..., aws_secret_access_key: ... and "token": "..." alike.
        r"""(?i)(?<![a-z0-9])(password|passwd|pwd|passphrase|secret|api[_-]?key|access[_-]?token|token)(?:[_-][a-z0-9]+)*(["']?\s*[:=]\s*["']?)(?!<redacted>|\[[A-Z_]+\])([^\s"',;&]{4,})""")),
    # Scheme length is capped and may not start inside a longer run of scheme
    # characters: "\b[a-z][a-z0-9+.-]*://" retried from every letter of a long
    # "a.a.a.a..." run is quadratic (12 s on 100 kB).
    ("URL_CREDENTIALS", re.compile(
        r"(?i)(?<![a-z0-9+.-])[a-z][a-z0-9+.-]{0,31}://[^\s/:@]+:[^\s/@]+@")),
    # "Authorization: Basic <base64>" and other schemes, not just Bearer.
    ("AUTH_HEADER", re.compile(
        r"""(?i)\bauthorization["']?\s*[:=]\s*["']?[a-z]+\s+[^\s"',;]{8,}""")),
    ("WEBHOOK_URL", re.compile(r"https://hooks\.slack\.com/services/T[A-Z0-9]{6,}/B[A-Z0-9]{6,}/[A-Za-z0-9]{16,}")),
]


def scan_secrets(text: str) -> list[str]:
    """Which credential shapes appear in `text`? Labels only — safe to log."""
    return sorted({label for label, pat in SECRET_PATTERNS if pat.search(text)})

Run it against realistic text and you get real output (excerpted from the __main__ demo in pii.py, pure stdlib):

text
$ python3 pii.py
TEXT: Contact jane.doe@example.com or call +1 (415) 555-0132 about invoice INV-9.
  findings: ['EMAIL[8:28] score=0.95', 'PHONE[37:54] score=0.80']
  secrets : []
  scrubbed: Contact [EMAIL] or call [PHONE] about invoice INV-9.

TEXT: Card 4242 4242 4242 4242 on file; IBAN GB29 NWBK 6016 1331 9268 19.
  findings: ['CREDIT_CARD[5:24] score=0.90', 'IBAN[39:66] score=0.95']
  secrets : []
  scrubbed: Card [CREDIT_CARD] on file; IBAN [IBAN].

TEXT: Reach me at jane dot doe at example dot com — names need NER, not regex.
  findings: []
  secrets : []
  scrubbed: Reach me at jane dot doe at example dot com — names need NER, not regex.

TEXT: My key is sk-ant-api03-EXAMPLEEXAMPLEEXAMPLE12 and order 12345678901.
  findings: []
  secrets : ['API_KEY']
  scrubbed: My key is [API_KEY] and order 12345678901.

VAULT raw : Jane Doe (jane.doe@example.com) asked about order 88213; card on file ends 4242.
VAULT safe: Jane Doe ([PII_EMAIL_58e08c8a0d]) asked about order 88213; card on file ends 4242.
VAULT back: ('Jane Doe (jane.doe@example.com) asked about order 88213; card on file ends 4242.', 1)
aadhaar example: 234567890129 valid: True

Three things to notice:

  1. The card and the IBAN are both found. They are separate spans, so both survive. Had the IBAN's trailing digit groups also matched the card shape, the overlap resolver would still keep the IBAN: it keeps the earliest-starting claim of each overlapping range (the higher-scoring, longer claim wins a tie), and the IBAN starts first.
  2. The obfuscated email is missed. jane dot doe at example dot com has no @ — no regex will find it. That's the honest limit of pattern detection, and the argument for NER or a second pass.
  3. The API key is found but the order number isn't — 12345678901 is 11 digits, below the card minimum and not phone-shaped (no separators). Validators are doing exactly their job: rejecting lookalikes.

3.3 Secret scanners: keys in prompts, logs and repos#

Credentials are the one PII-adjacent class where a miss is catastrophic, so they get their own scanner. scan_secrets covers the shapes that actually show up in LLM pipelines — provider keys (sk-, sk-ant-, sk-or-, AIza, xai-, gsk_, hf_), AWS IDs (AKIA/ASIA), GitHub, Stripe and Slack tokens, JWTs, PEM -----BEGIN ... PRIVATE KEY----- headers, Bearer headers, scheme://user:password@host connection strings, Slack incoming-webhook URLs and password=/api_key=-style key-value pairs (including DB_PASSWORD= and aws_secret_access_key:) — and returns labels only, safe to log and alert on. What it misses, said plainly: a password that is not labelled (my password is hunter2), a credential split by invisible characters or spelt out in words, and a value in a format nobody has written a pattern for; scrub_text folds full-width and zero-width tricks before it looks, scan_secrets does not, so run the scrubber over text before you log it. Its file-oriented sibling in 12.7, Part 9 recognises the same shapes (plus PyPI and npm tokens and an entropy pass for opaque literals) but returns line and column findings with a redacted excerpt instead of labels, so the two agree on the credential shapes that matter most; the labelled-assignment rules differ in detail (this one also redacts Authorization: headers with any scheme and pwd=/passphrase= pairs, and treats any labelled value as a secret, while 12.7 judges the value's entropy), so pick one for a given pipeline and do not mix their output.

For scanning whole repositories, files and git history, use the dedicated tools rather than rolling your own — they're maintained against new formats:

Tool Licence (as of Nov 2026) What it's for
gitleaks MIT Scan git repos, dirs, stdin for secrets; pre-commit hook and CI action. Author notes it's feature-complete and moving focus to Betterleaks
trufflehog AGPL-3.0 (since v3.0) Find and verify leaked credentials — it can log in to check if a found secret is live. AGPL matters if you embed it
detect-secrets (Yelp) Apache-2.0 Baseline approach: scan once, prevent new secrets in diffs, audit what exists

3.4 NER-based detection: Presidio, spaCy and GLiNER#

Regex and checksums own the structured identifiers — anything with a format and a checksum. The harder 80% is unstructured: names, addresses, organisations, dates, the "Jane Doe" that has no @. That's named-entity recognition (NER) territory, and the standard open-source stack is:

  • Microsoft Presidio — the de-facto framework. Presidio Analyzer (MIT, current 2.2.366 as of November 2026, Python ≥3.11) runs pattern recognizers and spaCy NER and optional transformers/GLiNER backends, then fuses them with context words ("my email is…", "call me at…") to raise confidence. Presidio Anonymizer handles the redaction/tokenisation side. The repo moved to the data-privacy-stack org (github.com/data-privacy-stack/presidio).

  • spaCy — the underlying NER engine (en_core_web_lg etc., spaCy 3.8.x, MIT). Presidio wraps it; you can also call it directly for PERSON, GPE, ORG, DATE labels.

  • GLiNER — a newer zero-shot NER model (gliner on PyPI, 0.2.30, Apache-2.0, October 2026) that takes arbitrary label names at inference time — "patient_name", "invoice_id", "diagnosis" — without retraining. It's the interesting option when your PII taxonomy doesn't match standard NER labels.

  • OpenAI Privacy Filter — an open-weight PII detector OpenAI released in April 2026 under Apache 2.0 (model card). It is a small token-classification model (about 1.5B total parameters, 50M active) that labels eight categories (account number, private address, email, person, phone, URL, date and secret) in one forward pass, with a 128,000-token context, and it is built for on-premises, high-throughput sanitisation; you can fine-tune it when your label policy differs. Its own model card calls it "a redaction and data minimization aid, not an anonymization, compliance, or a safety guarantee", warns of weaker results on non-English text, non-Latin scripts and unusual domains, and says uncommon names may be missed while benign strings may be over-redacted. Treat it as one more detector to run on your fixture (3.7), next to Presidio and GLiNER; its static label set means no custom entity types without fine-tuning.

  • GLiNER2-PII — a small PII model from Fastino Labs built on GLiNER2 (Hugging Face fastino/gliner2-privacy-filter-PII-multi, Apache-2.0, created May 2026; the model card gives 205M parameters, 42 entity types and 7 languages). Its card reports the highest span-level F1 (0.477) on the SPY benchmark among four compared systems, but precision is only 0.35 to 0.37, the model card itself calls it evaluated on a single benchmark, and the result is self-reported, so measure it yourself before choosing.

  • Managed services. The cloud guardrail services of 12.5, 5.2 (Bedrock Guardrails, Google Model Armor and similar) include sensitive-information filters; use them when you already run on that cloud, and note that they send text to that provider.

The Presidio workflow is recognizers → analysis → (optional) context enhancement → operator decision. You plug in custom recognizers for your domain's identifiers (employee IDs, ticket refs, internal project codenames), which is where it beats raw spaCy.

The lesson's code defines a Presidio-style analyser interface so the rest of pii.py doesn't care which implementation is underneath — FakePresidioAnalyzer for tests, PresidioAnalyzer as a lazy-import adapter over the real package:

python
# pii.py — Part D: analyzer interface + output scrub + evaluation.
# (PiiVault sits between these in the file; shown in Part 4.)

from dataclasses import dataclass, field
from typing import Protocol


@dataclass(frozen=True)
class Span:
    entity_type: str
    start: int
    end: int
    score: float = 1.0


class Analyzer(Protocol):
    def analyze(self, text: str, language: str = "en") -> list[Span]: ...


class FakePresidioAnalyzer:
    """Stand-in for presidio_analyzer.AnalyzerEngine in tests and keyless
    development. Returns canned spans; never sees the real package."""

    def __init__(self, canned: dict[str, list[Span]] | None = None):
        self._canned = canned or {}

    def analyze(self, text: str, language: str = "en") -> list[Span]:
        return list(self._canned.get(text, []))


class PresidioAnalyzer:
    """Adapter over the real Presidio AnalyzerEngine (lazy import).

    Install: uv add presidio-analyzer presidio-anonymizer
    then `python -m spacy download en_core_web_lg` for the NER backend.
    """

    def __init__(self, entities: list[str] | None = None):
        try:
            from presidio_analyzer import AnalyzerEngine
        except ImportError as exc:
            raise RuntimeError(
                "presidio-analyzer not installed: "
                'uv add presidio-analyzer presidio-anonymizer'
            ) from exc
        self._engine = AnalyzerEngine()
        self._entities = entities

    def analyze(self, text: str, language: str = "en") -> list[Span]:
        kwargs = {"text": text, "language": language}
        if self._entities:
            kwargs["entities"] = self._entities
        return [
            Span(r.entity_type, r.start, r.end, r.score)
            for r in self._engine.analyze(**kwargs)
        ]


# Presidio's entity names mapped onto this file's Finding vocabulary.
# Presidio returns EMAIL_ADDRESS, PHONE_NUMBER, CREDIT_CARD, IBAN_CODE,
# US_SSN, PERSON, ... — unmapped names pass through unchanged.
PRESIDIO_TO_FINDING = {
    "EMAIL_ADDRESS": "EMAIL",
    "PHONE_NUMBER": "PHONE",
    "CREDIT_CARD": "CREDIT_CARD",
    "IBAN_CODE": "IBAN",
    "US_SSN": "SSN_US",
}


def _analyzer_candidates(
    analyzer: Analyzer,
    text: str,
    entity_map: dict[str, str] | None = None,
) -> list[Finding]:
    """Analyzer spans -> Finding candidates, with entity names mapped."""
    mapping = entity_map or PRESIDIO_TO_FINDING
    return [
        Finding(mapping.get(s.entity_type, s.entity_type), s.start, s.end, s.score)
        for s in analyzer.analyze(text)
    ]


def detect_with_analyzer(text: str, analyzer: Analyzer) -> list[Finding]:
    """detect_pii plus NER spans, merged and de-overlapped in one pass —
    claims that start at the same character go to the higher score,
    otherwise the earlier start wins."""
    return _resolve_overlaps(
        _detect_candidates(text) + _analyzer_candidates(analyzer, text)
    )

The integration step is detect_with_analyzer: it runs the analyser over the text, maps Presidio's entity names onto the Finding vocabulary (EMAIL_ADDRESS → EMAIL, PHONE_NUMBER → PHONE, IBAN_CODE → IBAN, US_SSN → SSN_US; names with no mapping — PERSON, LOCATION, ORG — pass through under their own type), converts the Spans to Finding candidates, and merges them with the regex candidates before overlap resolution. That last detail is what makes the merge honest: a regex EMAIL at score 0.95 and a Presidio EMAIL_ADDRESS over the same characters aren't two findings — they're one contested range (same start offset), and the higher score wins; where two claims overlap but start at different offsets, the earlier start wins and the score is only a tie-breaker. FakePresidioAnalyzer lets you exercise the whole path with no package installed; the __main__ demo does exactly that:

python
# pii.py — __main__ demo for the analyzer merge.
ner_only = "Reach me at jane dot doe at example dot com — names need NER, not regex."
fake = FakePresidioAnalyzer(canned={
    ner_only: [Span("PERSON", 12, 16, 0.72)],      # "jane"
})
print("NER-only :", [f.describe() for f in detect_with_analyzer(ner_only, fake)])

merged = "Jane Doe can be reached at jane.doe@example.com or +1 (415) 555-0132."
fake2 = FakePresidioAnalyzer(canned={
    merged: [
        Span("PERSON", 0, 8, 0.85),                # "Jane Doe"
        Span("EMAIL_ADDRESS", 27, 47, 0.85),       # Presidio name -> EMAIL
        Span("PHONE_NUMBER", 51, 68, 0.70),        # Presidio name -> PHONE
    ]
})
print("NER merge:", [f.describe() for f in detect_with_analyzer(merged, fake2)])
text
NER-only : ['PERSON[12:16] score=0.72']
NER merge: ['PERSON[0:8] score=0.85', 'EMAIL[27:47] score=0.95', 'PHONE[51:68] score=0.80']

Two things to read in that output: the first line is the whole point of the NER layer — the obfuscated address that no regex can see produces a PERSON finding anyway. The second shows the merge working: PERSON passes through unmapped, the two Presidio spans map to EMAIL/PHONE, and because the regex candidates score higher (0.95, 0.80) they win the contested ranges — one finding per span, not duplicates.

3.5 LLM-based detection: powerful, leaky and expensive#

The third detection layer is the model itself: "does this text contain PII? Return spans." It catches what patterns can't — "my son Tyler", "the Acme renewal", "she's the one in the Lisbon office" — because it understands context, not just shape.

Three problems keep it from being the default:

  1. It sends the data to a detector. Running PII detection through an LLM means the unredacted text goes to that model's provider — you've created the leak you're trying to prevent. LLM detection only works after the data is already cleared to leave, or on a self-hosted model, or via the vault pattern (4.3) where the detector sees tokens, not values.
  2. It hallucinates spans. Models return character offsets unreliably — they'll flag "roughly here" or invent boundaries. You need a second pass to snap spans to real text, and even then recall on exact boundaries is poor.
  3. It costs tokens and latency. Detection runs on every document, prompt and trace — the volume makes per-call LLM detection expensive at scale.

3.6 What detection still misses#

Every detector has a blind spot; the honest engineering move is to know yours:

  • Names without context. "Tyler", "Acme", "the Lisbon office" — no pattern, and NER needs the capitalisation or surrounding cues. Only an LLM or a domain dictionary catches these.
  • Obfuscation. jane dot doe at example dot com, leetspeak, zero-width characters, base64 blobs, split-across-lines values. Normalisation before detection catches some; determined obfuscation beats everything short of an LLM.
  • Multimodal PII. Faces in images, voices in audio, signatures on PDFs, EXIF/GPS in photos — text detectors see none of it (5.5, 09.10).
  • Quasi-identifiers. {age, postcode, job title} passes every detector and still re-identifies (2.2). Detection finds fields; it can't judge combinations.
  • Already-tokenised or encrypted data. If upstream encryption or tokenisation worked, the detector sees ciphertext — which is correct, but means your detector can't audit what you can't read.

The rule: detection is a filter, not a guarantee. Design assuming it misses things — which is why Part 4 treats detection as the first layer of defence, not the only one, and why the vault and minimisation patterns matter more than any detector's recall.

3.7 Evaluating detectors: precision, recall and the fixture#

"Does the detector work?" is a measurable question, and the answer is almost always worse than intuition. You evaluate a detector the same way you evaluate a classifier: a labelled fixture — texts with known PII spans — scored for precision (of what it flagged, how much was real?) and recall (of the real PII, how much did it catch?).

python
# pii.py — Part D: detector evaluation.

@dataclass(frozen=True)
class Expected:
    entity_type: str
    start: int
    end: int


@dataclass
class DetectorReport:
    per_type: dict[str, dict[str, float]] = field(default_factory=dict)
    totals: dict[str, int] = field(default_factory=lambda: {"tp": 0, "fp": 0, "fn": 0})

    def add_counts(self, entity: str, tp: int, fp: int, fn: int) -> None:
        row = self.per_type.setdefault(entity, {"tp": 0, "fp": 0, "fn": 0})
        row["tp"] += tp; row["fp"] += fp; row["fn"] += fn
        self.totals["tp"] += tp; self.totals["fp"] += fp; self.totals["fn"] += fn


def _iou(a_start: int, a_end: int, b_start: int, b_end: int) -> float:
    inter = max(0, min(a_end, b_end) - max(a_start, b_start))
    union = max(a_end, b_end) - min(a_start, b_start)
    return inter / union if union else 0.0


def _match(findings: list[Finding], expected: list[Expected]) -> tuple[int, int, int]:
    """Greedy one-to-one matching by (entity_type, overlap). Returns tp, fp, fn.

    A finding matches an expected span of the same entity_type when their
    IoU is >= 0.5 or when one span contains the other — detectors routinely
    return tighter spans than a human label, and strict IoU would deflate recall.
    """
    pairs = []
    for i, f in enumerate(findings):
        for j, e in enumerate(expected):
            if f.entity_type != e.entity_type:
                continue
            iou = _iou(f.start, f.end, e.start, e.end)
            contained = (f.start >= e.start and f.end <= e.end) or (
                e.start >= f.start and e.end <= f.end
            )
            if iou >= 0.5 or contained:
                pairs.append((f.start, -iou, i, j))
    pairs.sort()
    used_f, used_e, tp = set(), set(), 0
    for _, _, i, j in pairs:
        if i not in used_f and j not in used_e:
            used_f.add(i); used_e.add(j); tp += 1
    return tp, len(findings) - tp, len(expected) - tp


def evaluate_detector(fixture: list[tuple[str, list[Expected]]]) -> DetectorReport:
    report = DetectorReport()
    for text, expected in fixture:
        findings = detect_pii(text)
        per_entity: dict[str, list[Finding]] = {}
        for f in findings:
            per_entity.setdefault(f.entity_type, []).append(f)
        per_expected: dict[str, list[Expected]] = {}
        for e in expected:
            per_expected.setdefault(e.entity_type, []).append(e)
        for entity in set(per_entity) | set(per_expected):
            tp, fp, fn = _match(per_entity.get(entity, []), per_expected.get(entity, []))
            report.add_counts(entity, tp, fp, fn)
    for row in report.per_type.values():
        p = row["tp"] / (row["tp"] + row["fp"]) if row["tp"] + row["fp"] else 0.0
        r = row["tp"] / (row["tp"] + row["fn"]) if row["tp"] + row["fn"] else 0.0
        row["precision"] = round(p, 3)
        row["recall"] = round(r, 3)
        row["f1"] = round(2 * p * r / (p + r), 3) if p + r else 0.0
    return report

The fixture is the part that takes real work — you hand-label spans in realistic text, including the hard cases: obfuscated emails, tracking numbers that look like cards, names that aren't PII in context, phone numbers that are actually order IDs. Expected offsets are plain character positions, so the practical way to author them is to run detect_pii on the text, check each span by eye, and freeze the positions — or compute them with text.index(...). Matching counts a hit when two same-type spans have IoU ≥ 0.5 or one contains the other, so a detector that returns a tighter span than your label still scores as a match. Build the fixture from your actual data distribution, not synthetic examples; lesson 10A.2 (building eval datasets) owns the methodology, and Part 8 covers keeping the fixture itself private.

This is the fixture from pii.py's __main__ — four texts covering a clean hit, a card+IBAN pair, an obfuscated email and a Luhn-valid tracking number:

python
# pii.py — __main__: the labelled fixture and the eval driver.
fixture = [
    # (text, [Expected(entity_type, start, end), ...])
    ("Contact jane.doe@example.com or call +1 (415) 555-0132 about invoice INV-9.",
     [Expected("EMAIL", 8, 28), Expected("PHONE", 37, 54)]),
    ("Card 4242 4242 4242 4242 on file; IBAN GB29 NWBK 6016 1331 9268 19.",
     [Expected("CREDIT_CARD", 5, 24), Expected("IBAN", 39, 66)]),
    ("Reach me at jane dot doe at example dot com — names need NER, not regex.",
     [Expected("EMAIL", 12, 43)]),
    ("Your tracking number is 6604876475933; delivery Friday.", []),
]

report = evaluate_detector(fixture)
print("EVAL:")
for entity, row in sorted(report.per_type.items()):
    print(f"{entity:12} precision={row['precision']:.3f} "
          f"recall={row['recall']:.3f} f1={row['f1']:.3f}  "
          f"({row['tp']} TP, {row['fp']} FP, {row['fn']} FN)")

Real output from python3 pii.py:

text
EVAL:
  CREDIT_CARD  precision=0.500 recall=1.000 f1=0.667  (1 TP, 1 FP, 0 FN)
  EMAIL        precision=1.000 recall=0.500 f1=0.667  (1 TP, 0 FP, 1 FN)
  IBAN         precision=1.000 recall=1.000 f1=1.000  (1 TP, 0 FP, 0 FN)
  PHONE        precision=1.000 recall=1.000 f1=1.000  (1 TP, 0 FP, 0 FN)

Read that table honestly: the card detector has 50% precision because a 13-digit tracking number (6604876475933) happened to pass Luhn — the fourth fixture text expects nothing, so the finding counts as a false positive. That's not a bug — it's the detector working as designed, and the eval is what tells you the design cost. The fix isn't "make it perfect" (impossible); it's "know the number and set the threshold" — for a high-stakes path (redacting before a third-party API), you'd add the tracking-number context or tighten the pattern; for a low-stakes log scrub, 50% precision on cards might be acceptable because a false positive just redacts a harmless number. Meanwhile email recall is 50% — the detector caught the plain address and missed jane dot doe at example dot com, which is exactly the gap 3.4's NER layer exists to fill.


Part 4: Protecting data before it moves#

Detection tells you where the PII is; protection decides what happens to it. The techniques form a spectrum from "remove it entirely" (safest, least useful) to "leave it as-is" (most useful, most dangerous) — and the right point depends on whether the model needs the value or just needs to know it exists.

4.1 Minimise first: the cheapest protection is not collecting#

Every protection downstream is harder than the upstream decision to not send the data at all. Data minimisation — collect and transmit only what the task requires — is the first and most effective control:

  • Field selection. If the model needs "does this ticket mention a refund?", send the ticket text — not the customer's email, account ID and order history "just in case". Build the prompt from the fields the task needs, not the whole record.
  • Prompt construction. The system prompt, retrieved chunks and tool outputs are all egress. Audit what actually goes into messages[] — often it's the whole user profile when three fields would do.
  • Document ingestion. At indexing time, decide which fields become searchable chunks. An HR document's salary band doesn't need to be in the vector store just because the document is.
  • Log and trace design. The same instinct: capture metadata (lengths, hashes, entity counts) not content (1.3).

4.2 Redact and mask: remove the value, keep the shape#

Redaction replaces sensitive spans with a placeholder — [EMAIL], [PHONE], [CARD] — destroying the value while preserving that something was there. Masking keeps part of the value visible (last-4 of a card, first letter of a name) for utility. Both are lossy: the model can't use the actual email, but it knows an email was mentioned.

Use redaction when:

  • The model only needs to know PII exists ("the customer provided an email") not use it.
  • You're scrubbing logs, traces, eval fixtures or support dashboards (5.1).
  • You're stripping PII before sending to a third-party detector or analytics tool.

Use masking when:

  • The last-4 of a card or the domain of an email is enough for the task ("verify the card ending in 4242").
  • You need to preserve some signal for debugging or matching without exposing the full value.

pii.py's scrub_text (shown in 5.1) is the redaction implementation — it replaces detected spans with [TYPE] markers. The limitation is the same as detection: it catches what the detectors catch, so names and obfuscated values slip through (3.6).

4.3 Tokenise and pseudonymise: the PII vault#

Redaction destroys the value; pseudonymisation preserves it in reversible form. The pattern: swap each detected PII value for a stable opaque token before the text leaves your boundary, keep the token→value map in a vault you control, send the tokenised text to the model, and restore the values in the response at a controlled boundary.

This is the PiiVault — the heart of pii.py:

python
# pii.py — Part C: the PII vault (reversible pseudonymisation).

import hashlib
import unicodedata

_TOKEN_RE = re.compile(r"\[PII_[A-Z0-9_]+_[0-9a-f]{10}\]")   # shape of a vault token


class PiiVault:
    """Tokenise detected PII into stable surrogate tokens and restore them.

    Tokens are deterministic (entity + value hash + optional salt), so the
    same email always maps to the same token — preserving the co-reference
    the model needs ("email the same person twice") without revealing who.
    Determinism also means tokens are linkable across documents *within the
    same salt*: use a per-vault salt when isolation matters.
    """

    def __init__(self, salt: str = ""):
        self._salt = salt
        self._store: dict[str, str] = {}

    def _token_for(self, entity: str, value: str) -> str:
        digest = hashlib.sha256(
            f"{self._salt}\x00{entity}\x00{value}".encode("utf-8")
        ).hexdigest()[:10]
        token = f"[PII_{entity}_{digest}]"
        self._store[token] = value
        return token

    def tokenize(self, text: str) -> str:
        """Replace every detected PII span with its stable token."""
        findings = detect_pii(text)
        out, cursor = [], 0
        for f in findings:
            out.append(text[cursor:f.start])
            value = text[f.start:f.end]
            out.append(self._token_for(f.entity_type, value))
            cursor = f.end
        out.append(text[cursor:])
        return "".join(out)

    def restore(self, text: str) -> tuple[str, int]:
        """Swap known tokens back to their values. Returns (text, n_restored).
        Unknown tokens are left untouched — they may be model-invented."""
        restored = 0

        def swap(m: re.Match[str]) -> str:
            nonlocal restored
            value = self._store.get(m.group(0))
            if value is None:
                return m.group(0)
            restored += 1
            return value

        # One pass over the text: a restored value that happens to contain
        # token-shaped text is not itself restored again.
        return _TOKEN_RE.sub(swap, text), restored

    def __len__(self) -> int:
        return len(self._store)

The round-trip, from the real pii.py run:

text
VAULT raw : Jane Doe (jane.doe@example.com) asked about order 88213; card on file ends 4242.
VAULT safe: Jane Doe ([PII_EMAIL_58e08c8a0d]) asked about order 88213; card on file ends 4242.
VAULT back: ('Jane Doe (jane.doe@example.com) asked about order 88213; card on file ends 4242.', 1)

The model sees [PII_EMAIL_58e08c8a0d] — enough to know "an email was provided" and to keep the reference consistent across the conversation — but never jane.doe@example.com. The vault holds the map; restore happens after the model responds, at your boundary.

sequenceDiagram
    participant U as User / doc
    participant V as PiiVault (yours)
    participant D as Detector (pii.py)
    participant M as LLM provider
    participant R as Restore boundary

    U->>D: raw text (contains PII)
    D->>V: findings (spans only)
    V->>V: tokenize → stable tokens
    V->>M: prompt with [PII_EMAIL_x] tokens
    Note over M: provider sees tokens, not values
    M-->>R: response (may echo tokens)
    R->>V: restore()
    V-->>U: response with real values

Why this beats plain redaction for LLM workloads:

  • The model keeps working. "Email jane.doe@example.com her order status" becomes "Email [PII_EMAIL_x] her order status" — the model still knows to perform the email action, it just can't read the address. Redaction ([EMAIL]) loses the co-reference; tokenisation keeps it.
  • Consistency across turns. The same email always maps to the same token (deterministic hash), so multi-turn conversations stay coherent — "send it to the same address" resolves correctly.
  • The provider never sees the value. The whole point: the sensitive data stays inside your boundary; only opaque tokens cross to the model.

The catch — and it's important:

4.4 Synthetic substitution#

Where tokenisation preserves the real value reversibly, synthetic substitution replaces it with a generated value — a fake name, a synthetic email, a made-up card number — that's structurally valid but belongs to nobody. The model sees maria.garcia@example.com instead of the real address; the vault isn't needed because there's nothing to restore.

Use synthetic substitution when:

  • The task needs a plausible value, not the real one (testing, demos, eval fixtures).
  • You want zero re-identification risk — there's no vault to breach.
  • You're generating training/eval data that must look real but can't contain real people (10A.2 owns synthetic data generation).

The trade-off: the model can't perform actions on the synthetic value (can't actually email maria.garcia@example.com), and you lose the ability to restore. It's for contexts where the value's form matters but its identity doesn't.

4.5 Privacy-preserving analytics: k-anonymity and differential privacy#

Not all privacy problems are "hide the PII in the prompt." Some are "publish statistics without revealing individuals." Two formal frameworks matter at awareness level:

  • k-anonymity (Sweeney, 2002): a dataset is k-anonymous if every combination of quasi-identifier values is shared by at least k records — so no individual stands out. "3 users in sector X" fails; "≥20 users across sectors" passes. It's the intuition behind "small cells suppress."
  • Differential privacy (Dwork, 2006): a stronger guarantee — the output of a query changes only negligibly whether or not any single person's data is included, by adding calibrated noise. It's what lets you publish "average salary by department" without exposing any one salary. 10A.2, 16.3 covers it in one paragraph; the glossary has the term.

For LLM systems, these matter when you:

  • Build analytics dashboards over user data (suppress small cells, add noise).
  • Fine-tune on aggregated or derived data (DP-SGD is the formal version — research-grade, not yet standard practice).
  • Publish eval results or usage metrics that could reveal individual behaviour.

4.6 Architectural controls: local models, regional endpoints, contracts#

Sometimes the answer isn't "protect the data going out" but "don't send it out." Four architectural levers:

  • Self-hosted / on-prem models. Open-weight models run inside your boundary — no provider sees the prompt at all. The trade-off is you now own the security, the updates and the breach response (lesson 11C.6 covers local deployment). For the most sensitive data classes (health, biometrics, children's), this is often the only compliant option.
  • Regional endpoints and data residency. Some providers let you pin processing to a region (EU, US) so data doesn't leave a jurisdiction. Gemini's regional endpoints, Azure OpenAI's regional deployment, and Bedrock's region pinning are examples. This satisfies transfer requirements but not retention or training ones — it's one control, not the whole policy.
  • Contract controls: ZDR, no-training, BAAs, DPAs. The provider-side levers from 1.2: zero-data-retention arrangements, no-training DPAs, Business Associate Agreements for HIPAA-covered data, and Data Processing Agreements that make the provider your processor (bound by your instructions) rather than an independent controller. These are procurement conversations, not code — but they determine what your code is allowed to send.
  • Confidential computing (the fourth lever). When even a contractual guarantee isn't enough — the data can't be exposed to the provider's operators either — the strongest hosted option is confidential inference: the model runs inside a trusted execution environment (a TEE — secure enclave or confidential GPU) where data stays encrypted in use, not just at rest and in transit, and remote attestation lets you verify which code and model are running before you send anything. Cloud providers and specialist vendors offer TEE-backed inference tiers; the residual risks are real — side-channel attacks on enclaves are an active research area, attestation adds integration complexity, model selection is limited to what the enclave supports, and cost is typically higher than standard endpoints. It sits between self-hosting and standard hosted APIs on the isolation spectrum: more capability than local models (you get frontier models), less trust required than a plain API contract. Awareness level — verify current offerings and attestation docs before designing around it; 12.7 covers the supply-chain side of trusting vendor hardware.

4.7 Encryption, access control and audit#

The vault, the vector store, the trace backend, the eval fixtures — all the places sensitive data accumulates need the same three controls:

  • Encryption at rest and in transit. TLS for anything crossing a network boundary; encryption at rest for stores. This protects against infrastructure breach (stolen disk, intercepted traffic) but not against application breach (SQL injection, leaked API key) — it's the floor, not the ceiling.
  • Access control. Who can read the vault? Who can query the vector store? Who can export the eval fixtures? Scope access like you'd scope database access — least privilege, role-based, audited. The engineer who can read traces can read every user's prompts; that's a data-access decision, not a debugging convenience.
  • Audit logging. Log who accessed what sensitive data, when, and why — not the data itself. "Alice exported 1,200 eval fixtures at 14:32" is auditable; the fixtures themselves shouldn't be in the audit log. This is what makes a breach investigable and a DSAR request answerable (7.6).

4.8 Retention limits and the right to erasure#

"Delete my data" is a feature request that touches every copy point from 1.1. The engineering requirements:

  • Retention schedules per store. Traces: 30–90 days. Caches: hours to days. Vector stores: as long as the source doc is live. Conversation stores: until deleted or provider expiry. Fine-tuning data: effectively forever (it's in the weights). Write the schedule down; enforce it with TTLs and lifecycle rules.
  • Deletion propagation. A user's erasure request must reach every store: the primary DB, the vector index, the cache, the trace backend, the eval fixtures, the memory store, and the provider-side copies (conversation IDs, files, vector stores) — each with its own delete API. Lesson 05.9 owns the ingestion-side deletion pipeline; lesson 07.11, 3.3 covers vector-store deletion; lesson 11C.4, 3.3 owns the operations-side runbook for deleting a user across every store an LLM system writes to.
  • Backups are the hard part. Deleted data persists in backups until they rotate. Your erasure story must include backup expiry windows — "we delete on request, backups purge within 30 days" is an honest answer; "we delete immediately" without a backup story is not.
  • Provider-side retention. You can't delete the provider's abuse-monitoring logs — but you can pick providers whose retention windows fit your obligations (1.2). ZDR arrangements exist precisely for this.

4.9 Decision table: technique × data class#

Technique Direct identifiers (email, ID) Quasi-identifiers Sensitive categories Secrets Confidential business
Minimise (don't send) ✅ best ✅ best ✅ best ✅ best ✅ best
Redact/mask ✅ good ⚠️ partial ⚠️ may not be enough ⚠️ detection-dependent ⚠️ semantic, hard
Tokenise/vault ✅ good (reversible) ⚠️ linkable ⚠️ still personal data ❌ wrong tool ⚠️ linkable
Synthetic substitution ✅ good (no restore) ✅ good ⚠️ may break utility ❌ wrong tool ✅ good
Local/self-hosted ✅ best for sensitive ✅ ✅ best ✅ ✅
Contract controls (ZDR/BAA) ✅ provider-side ✅ ✅ required for regulated n/a ✅

The pattern: minimise > tokenise > redact > synthetic > send raw, with local models and contract controls as the architectural alternatives when minimisation isn't enough. Secrets are the exception — they need prevention (secret management), not pseudonymisation.


Part 5: Output-side leakage controls#

Everything so far protects data going in. But the model's output is a leak path too — it can echo PII it saw, reveal other tenants' data, expose the system prompt, or leak secrets it encountered in context. Output-side controls are the last line of defence.

5.1 Scanning model output before display and logging#

The model's response goes to three places: the user (display), your logs/traces (storage), and downstream systems (actions). Each needs a different control:

  • Before display to the user: scan for PII that shouldn't be shown (other users' data, secrets the model hallucinated) and for secrets that leaked into context.
  • Before logging/storing: scrub PII and secrets — the same scrub_text discipline as input, applied to output.
  • Before downstream actions: a tool call that includes PII in its arguments needs the same scrutiny as a prompt.

pii.py's scrub_text is the implementation — it redacts detected PII spans to [TYPE] and secret shapes to [SECRET_LABEL]:

python
# pii.py — Part D: output scrubbing (the last function in the file).

def scrub_text(text: str) -> str:
    """Replace detected PII spans with [TYPE] markers and secret shapes
    with [SECRET_LABEL]. Span-based, so multi-word values are handled whole.

    The text is folded first (NFKC, so a full-width @ or digit becomes a plain
    one, and invisible format characters such as zero-width spaces are dropped),
    so the scrubbed output is the folded text, not byte-for-byte the input.

    Best-effort: removes what the detectors catch — names, addresses and
    obfuscated values still slip through (see 3.6)."""
    text = unicodedata.normalize("NFKC", text)
    text = "".join(ch for ch in text if unicodedata.category(ch) != "Cf")
    # Secrets first: in postgres://user:pw@db.example.com the email detector
    # would otherwise claim "pw@db.example.com" and the credential pattern
    # (which needs the "@") would never see it.
    scrubbed = text
    for label, pat in SECRET_PATTERNS:
        scrubbed = pat.sub(f"[{label}]", scrubbed)
    findings = detect_pii(scrubbed)
    out, cursor = [], 0
    for f in findings:
        out.append(scrubbed[cursor:f.start])
        out.append(f"[{f.entity_type}]")
        cursor = f.end
    out.append(scrubbed[cursor:])
    return "".join(out)

Real output from the pii.py run:

text
scrubbed: Contact [EMAIL] or call [PHONE] about invoice INV-9.
scrubbed: Card [CREDIT_CARD] on file; IBAN [IBAN].
scrubbed: My key is [API_KEY] and order 12345678901.

5.2 System-prompt and context leakage#

The system prompt is not secret. OWASP names it explicitly: LLM08:2026 Hidden Context Exposure (called LLM07:2025 System Prompt Leakage in the previous edition), and the research is unambiguous: models can be induced to reveal their instructions through direct asks, roleplay, encoding tricks, or injection (lesson 12.2 owns the attack mechanics; lesson 12.3 covers model-level defences). The privacy implication is sharper than "the prompt is embarrassing":

  • The system prompt contains your data model. "You are a support agent for Acme Corp; escalate billing issues to tier-2; never discuss competitor pricing" reveals your org structure, escalation paths and policies.
  • It can contain real data. Few-shot examples, tenant-specific instructions, or dynamically-injected context can put actual customer data in the system prompt — which then leaks when the prompt does.
  • Indirect leakage. Even without the prompt text, the model's behaviour reveals it: consistent refusals on certain topics, citation patterns, formatting quirks all fingerprint the instructions.

The engineering rules:

  1. Assume the system prompt leaks. Design as if every user will eventually see it — don't put secrets, PII, or security-through-obscurity controls in it.
  2. Keep sensitive context out of the prompt. Customer data belongs in the user turn or retrieved context, scoped and access-controlled — not baked into instructions.
  3. Use canary tokens. Plant a unique string in the system prompt ("CANARY-7f3a2b") and alert if it appears in outputs or logs — detects leakage without exposing the prompt. Lesson 12.2 covers canary design.
  4. Separate instructions from data. The system prompt says how to behave; retrieved documents and user input are data to process, clearly delimited (lesson 12.2's delimiting patterns).

5.3 Tenant isolation, memory scoping and cache scoping#

The cross-tenant failures from 1.5 all come down to scope: every store that holds user data must be partitioned by tenant/user, and every lookup must carry the scope as a server-computed key, not a client-supplied filter.

  • ACL filtering in retrieval. The tenant filter is code, applied before the model sees results — not a prompt instruction the model might ignore. Lesson 06.6 owns the pattern; lesson 07.11, 2.3 applies it to RAG. Test it: a tenant-isolation test suite that verifies tenant A's queries never return tenant B's chunks.
  • Memory namespacing. Agent memory must be keyed by user/tenant — memory[user_id][fact], not a shared store. Lesson 08B.2, Part 5 owns the namespace model; a memory write from user A must never surface in user B's session.
  • Cache scoping. Semantic and response caches must include the permission scope in the key — hash(question + tenant_id + acl_version), computed server-side. A cache hit for user A's personalised answer must never serve user B. Lesson 07.11, 2.3.2 covers the key design; lesson 11B.3 covers caching generally.
  • Provider-side state. Conversation IDs, vector stores and file storage are scoped per API key/project — a shared project across tenants collapses the boundary at the provider too. Use separate projects/keys per tenant where the provider supports it.

5.4 Error messages and stack traces#

Errors are an underrated leak path. A stack trace, an API error response, or a debug message can echo the request payload — including PII — back to the user or into logs:

  • Don't echo request bodies in errors. 400: invalid input {"email": "jane@...", "ssn": "..."} leaks what the user sent. Return 400: invalid email format — the field name, not the value.
  • Scrub stack traces. Framework error pages and exception handlers can include local variables, request headers (including Authorization), and query parameters. Strip or redact before returning to the client.
  • Log errors scrubbed. The error tracker (Sentry-style) gets the scrubbed version — scrub_text on the message and any attached context — not the raw exception with payload.
  • Provider errors. API error responses from OpenAI/Anthropic/etc. can echo parts of the request. Log the status and error type, not the full response body, unless it's been scrubbed.

5.5 Media PII: EXIF, screenshots and recordings#

Text detectors don't see images, audio or video — but those carry PII too:

  • EXIF/GPS metadata. Photos carry location, device and timestamp in EXIF — strip it on ingest, before storage or sending (09.1's EXIF-stripping code is the reference; do it before you store, not after).
  • Screenshots and session replay. Support tools, error trackers and analytics widgets capture what's on screen — including form fields with card numbers, health details, or other users' data in a shared screen. Treat session replay as a data store with its own retention and access rules; mask input fields by default.
  • Recordings and voice. Call recordings, voice messages and video contain biometric data (voiceprints) and whatever was said — including PII read aloud. Lesson 09.4, 13.1 covers consent and retention for recorded speech; lesson 09.7, 14.1 covers consent for live voice sessions; lesson 09.10 covers the cross-modal privacy frame.
  • Documents in images/PDFs. A scanned ID, an invoice photo, a signed contract — the PII is in the pixels, not the text layer. OCR-then-detect is the pipeline; redaction must happen on the image (blur boxes) not just the extracted text.

5.6 The leak-path checklist#

Before shipping, walk every row of the 1.6 inventory and confirm the control is in place:

  • Outbound prompts: minimised, vault-tokenised or cleared for the provider tier
  • Provider retention: contract controls (ZDR/no-training/BAA) match the data class
  • Logs/traces: content off by default; write-time redaction; short retention; access-controlled
  • Vector store: encrypted, access-controlled, deletion propagates to vectors
  • Caches/memory: scope in the key; namespaced per user/tenant
  • Eval/fine-tuning sets: scrubbed or synthetic; consent for production data
  • Model output: scanned for PII/secrets before display and logging
  • System prompt: no secrets or PII; canary tokens planted; assumes leakage
  • Error messages: no request payloads echoed; stack traces scrubbed
  • Media: EXIF stripped; recordings consented; screenshots masked
  • Cross-tenant: isolation tests pass on every retrieval/memory/cache path
  • Erasure: deletion reaches every store including provider-side and backups

Part 6: Memorisation and extraction#

Deep-dive

The most dangerous copy of user data isn't in your logs or vector store — it's in the model's weights. A fine-tuned model doesn't just see your data during training; it absorbs it, and can regurgitate it later to anyone who asks the right way. This is the privacy failure that can't be patched after the fact.

6.1 Memorisation vs hallucination#

Lesson 02.10, 2.8 covers the phenomenon: LLMs generalise, but they also memorise some training data — especially text that appeared many times or is unusually distinctive. Hallucination is producing text that isn't in the training data; memorisation is producing text that is, word for word. The privacy problem is the second one.

What gets memorised, in rough order of risk:

  • Duplicated boilerplate — privacy policies, terms of service, legal disclaimers that appear thousands of times.
  • Distinctive sequences — a rare name+address+phone combination, a unique code snippet, a specific error message.
  • PII that appeared in training data — names, emails, phone numbers, API keys that were scraped into the corpus (Carlini et al. extracted verbatim training examples including personal contact details from GPT-2 in 2021).
  • Fine-tuning data — your own data, memorised into your model, extractable by your users.

6.2 Extraction attacks: getting the data back out#

Memorisation becomes a breach when an attacker can extract the memorised data efficiently. The research lineage:

  • Carlini et al. 2021 ("Extracting Training Data from Large Language Models", USENIX Security 2021, arXiv:2012.07805): showed that querying GPT-2 could recover hundreds of verbatim training sequences — including PII, IRC conversations, code and UUIDs — even from data appearing in just one document. Larger models memorised more.
  • Nasr et al. 2023 ("Scalable Extraction of Training Data from (Production) Language Models", arXiv:2311.17035, ICLR 2025): scaled this to gigabytes of extraction from open models (Pythia, GPT-Neo), semi-open (LLaMA, Falcon) and even ChatGPT — using a "divergence attack" that made the aligned model emit training data at ~150× the normal rate. Key finding: alignment doesn't eliminate memorisation.

The implication for your fine-tuning pipeline:

6.3 Embedding inversion and membership inference#

Two related attacks apply to your retrieval layer, not just the model:

  • Embedding inversion — Morris et al. (EMNLP 2023, arXiv:2310.06816) showed text can be reconstructed from its embedding with surprising accuracy: ~92% of short inputs recovered exactly, including names from clinical notes. Your vector store is a compressed copy of your documents — treat it as such (1.4, 02.3, 10.7).
  • Membership inference — given a model or a vector store, can an attacker determine whether a specific person's data was in the training/indexed set? "Is Jane Doe's medical record in this corpus?" is itself a privacy leak even if the content isn't extracted. Research-grade attacks exist; the defence is minimising what's embedded and access-controlling the store.

6.4 What this means for your data#

The practical rules:

  1. Assume anything you fine-tune on can be extracted. Design the training set as if it will be published — because extraction attacks are real and improving.
  2. Prefer RAG over fine-tuning for user data. Retrieval keeps data in a deletable store; fine-tuning bakes it into weights. Lesson 13A.8 covers the prompting/RAG/fine-tuning decision; privacy is a strong argument for RAG.
  3. Use canary memorisation tests. Plant unique synthetic PII ("Canary User, canary@example.com, SSN 000-00-0000") in your fine-tuning data and probe the trained model to see if it regurgitates — a practical extraction test you can run yourself.
  4. Provider filters help but don't save you. Gemini's RECITATION stop reason and similar provider-side filters catch some verbatim reproduction, but they're tuned for copyrighted text, not your specific PII (02.10, 2.8).
  5. The vector store is part of the threat model. Embedding inversion means your index is as sensitive as the source documents — same encryption, access control, retention and deletion (1.4).

Deep-dive

This part is engineering awareness, verified against official sources as of November 2026 — not legal advice. Privacy law is jurisdiction-specific, fact-specific and changes; your legal team owns the compliance call. What follows is the shape of the obligations so you know what to build and what questions to ask.

7.1 The shape of the problem#

Privacy law isn't one rulebook — it's a patchwork of overlapping regimes that attach to what data you have, where your users are, and what you do with it. For an LLM system, three questions determine which rules apply:

  1. What data? Personal data? Special categories (health, biometrics, children's)? Regulated data (PHI, PCI)? Each triggers different rules.
  2. Where? EU/UK users → GDPR. California → CCPA/CPRA. India → DPDP. US health → HIPAA. The same codebase can be under five regimes at once.
  3. What do you do? Collect, store, send to a provider, train on, delete on request — each action has its own obligations (lawful basis, minimisation, retention, erasure, breach notification).

The engineer's job isn't to know every statute — it's to build the mechanisms the statutes require (consent records, deletion pipelines, data maps, audit trails) and to know which questions to escalate.

7.2 GDPR (EU/UK)#

The broadest and most influential regime. Key obligations that land on engineering:

  • Lawful basis — every processing activity needs one (consent, contract, legitimate interest, etc.). For LLM features, "legitimate interest" is common but requires a balancing test; consent is cleaner but harder to evidence.
  • Data minimisation & purpose limitation — collect only what the purpose needs, use it only for that purpose. Sending a whole user profile to a model "just in case" violates both.
  • Right to erasure ("right to be forgotten") — delete personal data on request, across all copies including backups and derived data. The deletion-propagation problem from 4.8 is a GDPR requirement, not a nice-to-have.
  • Right of access / data portability — export a user's data in a usable format. You need a DSAR (Data Subject Access Request) export pipeline.
  • Data Protection Impact Assessment (DPIA) — required for high-risk processing (systematic monitoring, special categories, large-scale profiling). Your LLM system likely needs one; the engineering inputs are the data map, the retention schedule, and the threat model.
  • Automated decision-making — where model output produces a decision with legal or similarly significant effect on a person (credit, hiring, insurance, moderation at scale), GDPR Art. 22-style rules apply: you must be able to explain the logic involved, offer a route to human review and intervention, and let the person contest the decision. For most LLM features the engineering translation is: keep a human in the loop for high-stakes outputs, log what the model saw and produced for each decision, and design the appeal path before launch — not after the first complaint.
  • Models and personal data (EDPB Opinion 28/2024). The European Data Protection Board's December 2024 opinion on AI models says whether a model is anonymous is decided case by case: it must be "very unlikely" that personal data of people in the training data can be extracted, directly or through queries. It also applies a three-step test to legitimate interest as a basis for developing or deploying models (the processing must be strictly necessary, and the balance of rights must hold), and says that building a model on unlawfully processed data can affect whether deploying it is lawful unless it has been properly anonymised. The engineering reading: do not assume that "it is in the weights" means "it is anonymous" (Part 6), keep records of the data your fine-tuning sets came from, and ask legal how your jurisdiction's regulator applies the opinion. Source: EDPB news item, 18 December 2024.
  • International transfers — sending EU user data to a US provider requires a transfer mechanism (SCCs, adequacy decision, or the provider's EU region). Data residency alone doesn't satisfy this — it's about the legal mechanism.

7.3 US: CCPA/CPRA and the state patchwork#

The US has no single federal privacy law — it's a patchwork of state laws. The big ones:

  • CCPA/CPRA (California) — consumers can know, delete and opt out of the "sale" or "sharing" of personal information. "Sharing" for cross-context behavioural advertising includes some tracking/analytics — check whether your LLM analytics fall under it. Opt-out must be honoured via "Do Not Sell or Share" mechanisms.
  • Other state laws — Virginia, Colorado, Connecticut, Utah, and ~15 others have similar (but not identical) rights: access, deletion, opt-out of targeted advertising/sale, and sensitive-data opt-in. The practical approach: build to the strictest common denominator (California + Virginia + Colorado cover most requirements) and add state-specific rules as needed.
  • No private right of action — unlike GDPR, most US state laws are enforced by the attorney general, not individuals. But AG enforcement is real and fines are significant.

7.4 Sector rules: HIPAA, PCI DSS, children's privacy#

Sector-specific regimes can override or layer on top of the general privacy law:

  • HIPAA (US health data) — Protected Health Information (PHI) can only go to providers that sign a Business Associate Agreement (BAA), and a BAA covers only the endpoints and features the vendor lists. OpenAI offers a BAA (its "Business Associate and Healthcare Addendum") for eligible API endpoints, and your organisation must also be provisioned for a qualifying retention arrangement: OpenAI's data-controls page (read 11 November 2026) names Private Retention with Private Safety Processing and Safety Retention for processing PHI on BAA-eligible endpoints, and says Web Search with live internet access is not HIPAA eligible. Its HIPAA guide and older material call the requirement "Modified Retention", so use whichever term your OpenAI paperwork uses. The signing route has changed before (a search excerpt of the help-centre article describes accepting the BAA in the API Platform settings for organisations with established usage), so confirm the current route and your endpoint list with OpenAI (03.2, 10.5 has the side-by-side table). Anthropic offers HIPAA readiness with a signed BAA. For Google, the Google Cloud BAA covers the products listed on Google Cloud's HIPAA page (read 11 November 2026), which names the Agent Platform products ("Generative AI on Agent Platform", "Gemini Enterprise Agent Platform") and does not mention the Gemini API or AI Studio, so route PHI through Google Cloud, not the plain Gemini API. Without a BAA, PHI can't go to the API at all — it's that simple. 4.6 covers the contract controls.
  • PCI DSS (payment cards) — cardholder data (PAN, CVV) has strict handling rules; never send it to a model. Mask to last-4 at most; the card data stays in your PCI-scoped systems.
  • COPPA-class children's privacy — data about children under 13 (US) or under 16 (some EU states) faces the highest bar: verifiable parental consent, no behavioural advertising, strict retention limits. If your users could be children, design for the strictest regime (09.10, 5.1).
  • BIPA-class biometric laws — Illinois's Biometric Information Privacy Act (and similar state laws) require written consent, retention schedules and destruction policies for biometric data (face, voice, fingerprint). Voiceprints and face embeddings are biometric data — treat them accordingly.

7.5 Other jurisdictions: India DPDP and beyond#

  • India DPDP Act 2023 + Rules 2025 — notified November 2025, phased 18-month implementation. Key concepts: "Data Fiduciary" (the entity determining purpose), "Data Principal" (the individual), consent notice requirements, breach notification to the Data Protection Board, and significant penalties. Applies to processing in India and to foreign companies offering services to people in India. Engineering relevance: consent records, breach notification pipeline, data-map obligations.
  • UK GDPR — post-Brexit, the UK has its own GDPR (largely aligned with EU GDPR but with UK-specific provisions). The ICO is the regulator. If you have UK users, treat it as a separate regime.
  • Others — Brazil LGPD, Canada PIPEDA, Japan APPI, and dozens more. The pattern is consistent: consent/legitimate basis, minimisation, retention limits, erasure rights, breach notification. Build the mechanisms once; map them to each jurisdiction's specifics.

Regardless of jurisdiction, the engineering deliverables are the same family:

Obligation What to build
Data map An inventory of every store holding personal data: primary DB, vector store, caches, traces, memory, eval fixtures, provider-side state. For each: data class, purpose, retention, access controls, deletion path. This is the artifact a DPIA and a breach investigation both need.
Consent records For consent-based processing: what was consented to, when, how (versioned consent text), withdrawal mechanism. Store consent events as auditable records, not just a boolean flag.
Deletion pipeline A job that walks every store on an erasure request: primary DB → vector index → caches → traces → memory → eval fixtures → provider-side (conversation IDs, files) → backups (with expiry window). Write an audit record of what was deleted where.
Retention schedule Per-store retention limits enforced by TTLs and lifecycle rules; documented and reviewed. "Traces: 90 days, caches: 24h, vectors: source-doc lifetime, backups: 30-day rotation."
DSAR export A pipeline that assembles all of a user's data across stores into a portable export (JSON/CSV). This is also the debugging tool for "what do we know about this user?"
DPIA inputs The data map, retention schedule, threat model (lesson 12.1) and this lesson's leak-path inventory — the engineering inputs a DPIA requires.
Breach notification Detection (audit logs, anomaly alerts) → assessment (what data, how many users, what jurisdictions) → notification (users, regulators, within statutory windows — GDPR: 72h to the supervisory authority). Write the runbook before you need it.

Part 8: Privacy-preserving evaluation and debugging#

Deep-dive

The best eval sets come from production — real queries, real edge cases, real failure modes. But production data is the most sensitive data you have. The techniques for using it safely:

8.1 The problem: evals need real data but can't hold it#

An eval fixture is a copy of production data — queries, answers, documents, traces. That copy inherits every privacy obligation of the original, plus new ones: eval fixtures get shared with vendors, committed to repos, used to fine-tune judges, and kept forever. A production chat containing a customer's medical details becomes an eval fixture containing the same details, now in a less-controlled store.

8.2 Techniques for safe eval data#

  • Scrubbed traces. Apply scrub_text (or Presidio) to production traces before they become fixtures — PII spans become [EMAIL], [PHONE] etc. The eval still tests realistic inputs; the fixture no longer contains the sensitive values. The catch: scrubbing changes the data distribution (a [EMAIL] token isn't a real email), so measure whether the scrubbed eval still predicts production behaviour.
  • Synthetic replacements. Replace real values with generated ones that preserve structure — a fake name, a synthetic email, a made-up order ID. Lesson 10A.2 owns synthetic data; the key is format-preserving substitution so downstream parsing still works.
  • Vault-tokenised fixtures. Use the PiiVault pattern (4.3) on eval data — real structure, stable tokens, reversible only with vault access. The eval sees [PII_EMAIL_x] consistently; you can restore for debugging but the fixture itself is pseudonymised.
  • Access-controlled review. When humans must review real production data (labeling edge cases, judging quality), restrict access to a need-to-know group, log access, and apply the same retention limits as production. "The eval team can see it" is not an access control.
  • Consent for production data in evals. If your terms of service don't cover using user data for evaluation/improvement, you need explicit consent — or you use only data the user agreed to share. Check your ToS and privacy policy; this is a legal question, not a technical one.

8.3 Privacy-preserving eval patterns#

Pattern What it protects Trade-off
Scrubbed fixtures PII values in eval data Loses realism; may change eval behaviour
Synthetic data All PII, by construction May not match production distribution
Vault-tokenised PII values, reversible Vault becomes a sensitive store; tokens are linkable
Aggregated metrics Individual behaviour Only works for counts/rates, not per-example evals
Access-controlled review Raw production data Doesn't reduce exposure, just controls it
Differential privacy Aggregate statistics Research-grade; adds noise; not yet standard for LLM evals

8.4 The debugging side: privacy-safe traces#

Debugging production issues requires seeing what the system did — but traces contain the same PII as production. The privacy-safe pattern:

  • Metadata by default. Span names, durations, token counts, entity counts, error types — enough to debug most issues without content.
  • Content opt-in. When you need to see the actual prompt/response, enable content capture for a sampled subset, write-time-redacted, access-controlled, short-retention (1.3, lesson 11A.1).
  • Reproduction without exposure. For a specific bug, reproduce with a synthetic input that triggers the same code path, not the user's actual data. "The bug happens when a prompt contains an email and a card" is debuggable with fake values.
  • Error messages scrubbed. The error tracker gets scrub_text'd messages — enough to diagnose, not enough to leak (5.4).

The ways PII and sensitive data leak in production — symptom first, then cause, the signal that catches it, and the fix:

Symptom Likely cause Detection signal Fix
A user's email appears in another user's answer Retrieval/ACL filter missing or bypassed; shared cache key without scope Tenant-isolation test fails; canary query returns wrong tenant's chunk Server-side ACL filter before the model; scope in cache/memory keys (5.3)
The system prompt shows up in a user transcript Model induced to reveal instructions (LLM08:2026) Canary token CANARY-… appears in output/logs Assume leakage; remove secrets/PII from prompt; canary monitoring (5.2)
A support ticket's card number is now in the vector store PII ingested without detection/redaction Ingestion audit finds PAN-shaped spans in chunks Detect + vault/redact at ingestion, before embedding (Part 3, 4.3)
"Delete my data" leaves copies behind Deletion reaches primary DB but not vectors/cache/traces/provider state DSAR audit finds residual data in a secondary store Deletion pipeline walks every store + backups (4.8)
An eval fixture contains real customer chats Production data copied without scrubbing Fixture review finds live PII Scrub/synthetic/vault-tokenise fixtures; consent check (Part 8)
The fine-tuned model regurgitates a user's details User data baked into weights Canary memorisation test extracts planted PII Never fine-tune on raw user data; use tokenised/synthetic (Part 6)
A stack trace in the error tracker echoes the request body Exception handler returns/logs payload Error event contains email=/ssn= fields Scrub errors before logging/returning (5.4)
Session replay captures a payment form Analytics widget records all input fields Replay video shows card digits Mask input fields; restrict replay retention (5.5)
The detector misses "jane dot doe at example dot com" Obfuscation defeats regex/NER Labelled fixture recall < 80% on real data Normalise before detection; add NER/LLM pass for edge cases (3.6)
Provider "no training" policy assumed = no retention Abuse logs, stored state, files create copies Provider docs show 30-day abuse retention Contract controls: ZDR/BAA; pick providers whose windows fit (1.2)

Attack → defence, compressed: prompt injection → delimiter + least-context (12.2) · training-data extraction → don't fine-tune on user data (Part 6) · embedding inversion → treat vectors as sensitive (1.4) · cross-tenant leakage → server-side scope in every key (5.3) · system-prompt leakage → assume it leaks, canary it (5.2) · PII in logs → write-time scrub (5.1) · erasure requests → deletion pipeline across all stores (4.8).


Appendix: pii.py, consolidated#

The complete module, assembled from Parts A–D above. Save as pii.py (or llm_guard_kit/pii.py); it runs standalone with python3 pii.py and needs only the standard library. The __main__ block at the end reproduces the demo output quoted in 3.2, 3.4, 3.7 and 4.3.

python
"""llm_guard_kit/pii.py — PII and secret detection, vault tokenisation,
output scrubbing and detector evaluation. Standard library only.

Parts of this file are introduced across lesson 12.4, Parts 3-5.
Every function is deterministic; nothing here calls a model or the network.
"""
from __future__ import annotations

import hashlib
import unicodedata
import re
from dataclasses import dataclass, field
from typing import Callable, Protocol

_TOKEN_RE = re.compile(r"\[PII_[A-Z0-9_]+_[0-9a-f]{10}\]")   # shape of a vault token


# ---------------------------------------------------------------------------
# Validators — "is this candidate string actually a valid X?"
# A regex finds the shape; a validator proves the checksum.
# ---------------------------------------------------------------------------

def luhn_ok(digits: str) -> bool:
    """Luhn check digit (ISO/IEC 7812) used by payment card numbers."""
    total = 0
    for i, ch in enumerate(reversed(digits)):
        if not ch.isdecimal():      # also accepts non-ASCII digits, e.g. full-width 4242
            return False
        d = int(ch)
        if i % 2 == 1:
            d *= 2
            if d > 9:
                d -= 9
        total += d
    return total % 10 == 0


def card_digits_ok(candidate: str) -> bool:
    digits = re.sub(r"\D", "", candidate)
    return 12 <= len(digits) <= 19 and luhn_ok(digits)


def iban_ok(candidate: str) -> bool:
    """ISO 13616 IBAN check: rearrange, convert letters to digits, mod-97 == 1."""
    iban = re.sub(r"\s+", "", candidate).upper()
    if not re.fullmatch(r"[A-Z]{2}\d{2}[A-Z0-9]{11,30}", iban, re.ASCII):
        return False
    rearranged = iban[4:] + iban[:4]
    digits = "".join(str(int(c, 36)) if c.isalpha() else c for c in rearranged)
    remainder = 0
    for ch in digits:
        remainder = (remainder * 10 + (ord(ch) - 48)) % 97
    return remainder == 1


EMAIL_SHAPE = re.compile(
    r"^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}@"
    r"(?:[A-Za-z0-9-]{1,63}\.)+[A-Za-z]{2,63}$"
)


def email_ok(candidate: str) -> bool:
    return bool(EMAIL_SHAPE.match(candidate.strip()))


def ssn_us_ok(candidate: str) -> bool:
    """US SSN: format plus the published invalid ranges (no public checksum)."""
    m = re.fullmatch(r"(\d{3})-(\d{2})-(\d{4})", candidate.strip())
    if not m:
        return False
    area, group, serial = (int(g) for g in m.groups())
    return not (area == 0 or area == 666 or area >= 900 or group == 0 or serial == 0)


# Verhoeff dihedral-group tables — the checksum behind India's Aadhaar
# and several other national ID schemes.
_D5P = [
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
    [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
    [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
    [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
    [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
    [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
    [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
    [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
]
_D5N = [
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],
    [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
    [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],
    [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],
    [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
    [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],
    [7, 0, 4, 6, 9, 1, 3, 2, 5, 8],
]


def _verhoeff_checksum(digits: str) -> int:
    c = 0
    for i, ch in enumerate(reversed(digits)):
        c = _D5P[_D5N[i % 8][c]][int(ch)]   # int() handles any Unicode decimal digit
    return c


def verhoeff_check_digit(base: str) -> int:
    """Compute the Verhoeff check digit for a base digit string."""
    return next(d for d in range(10) if _verhoeff_checksum(base + str(d)) == 0)


def aadhaar_ok(candidate: str) -> bool:
    """12-digit Aadhaar-shaped number passing the Verhoeff checksum."""
    digits = re.sub(r"\D", "", candidate)
    return len(digits) == 12 and _verhoeff_checksum(digits) == 0


# ---------------------------------------------------------------------------
# Detectors — find candidate spans, validate, resolve overlaps.
# A Finding carries type + offsets + score, never the matched text:
# findings are safe to log; the text they point into is not.
# ---------------------------------------------------------------------------

@dataclass(frozen=True)
class Finding:
    entity_type: str
    start: int
    end: int
    score: float = 1.0

    def describe(self) -> str:
        return f"{self.entity_type}[{self.start}:{self.end}] score={self.score:.2f}"


def _phone_digits_ok(candidate: str) -> bool:
    # Only a digit-count check (E.164 allows 8-15) — the shape below is
    # permissive, so precision comes from the eval fixture, not this gate.
    n = sum(c.isdigit() for c in candidate)
    return 8 <= n <= 15


PHONE_SHAPE = re.compile(
    r"(?<![\w.:/+-])(?:\+\d{1,3}[ .-]?(?:\(\d{1,5}\)[ .-]?)?\d{2,5}(?:[ .-]?\d{2,5}){1,3}"
    r"|\(?\d{3,5}\)?[ -]\d{3,4}[ -]\d{3,5}(?:[ -]\d{1,4})?)(?![\w-])"
)
# Deliberately stricter than card_digits_ok (which accepts 12-19 digits):
# the shape requires >=13 digits so order IDs don't flood the candidates.
CARD_SHAPE = re.compile(r"(?<!\d)(?:\d[ \u00a0.-]?){12,18}\d(?!\d)")
# Bounded and anchored (local part <= 64 characters, domain <= 253): an unbounded
# "[...]+@" retried from every position is quadratic on a long "a.a.a.a..." run.
EMAIL_FIND = re.compile(
    r"(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,}\b")
# IGNORECASE: iban_ok() uppercases its input, and real text contains
# lowercase/mixed-case IBANs the validator would happily accept.
IBAN_FIND = re.compile(
    r"\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]{4}){2,7}(?:[ ]?[A-Z0-9]{1,3})?\b",
    re.IGNORECASE,
)
SSN_FIND = re.compile(r"\b\d{3}-\d{2}-\d{4}\b")
AADHAAR_FIND = re.compile(r"\b\d{4}[ -]?\d{4}[ -]?\d{4}\b")

# (entity_type, pattern, validator-or-None, score)
_DETECTORS: list[tuple[str, re.Pattern[str], Callable[[str], bool] | None, float]] = [
    ("EMAIL", EMAIL_FIND, email_ok, 0.95),
    ("IBAN", IBAN_FIND, iban_ok, 0.95),
    ("CREDIT_CARD", CARD_SHAPE, card_digits_ok, 0.90),
    ("SSN_US", SSN_FIND, ssn_us_ok, 0.90),
    ("AADHAAR", AADHAAR_FIND, aadhaar_ok, 0.90),
    ("PHONE", PHONE_SHAPE, _phone_digits_ok, 0.80),
]


def _overlaps(a: Finding, b: Finding) -> bool:
    return a.start < b.end and b.start < a.end


def _resolve_overlaps(candidates: list[Finding]) -> list[Finding]:
    """Sort by start offset (then score, then length) and keep the first
    claimant of each overlapping range. Score decides only between claims
    that start at the same character; a card-shaped run inside a longer
    IBAN loses to the IBAN because the IBAN starts first."""
    candidates.sort(key=lambda f: (f.start, -f.score, -(f.end - f.start)))
    kept: list[Finding] = []
    for f in candidates:
        if not any(_overlaps(f, k) for k in kept):
            kept.append(f)
    return sorted(kept, key=lambda f: f.start)


def _detect_candidates(text: str) -> list[Finding]:
    """Raw regex + validator candidates, before overlap resolution."""
    candidates: list[Finding] = []
    for entity, pattern, validator, score in _DETECTORS:
        for m in pattern.finditer(text):
            if validator is None or validator(m.group()):
                candidates.append(Finding(entity, m.start(), m.end(), score))
    return candidates


def detect_pii(text: str) -> list[Finding]:
    """Return non-overlapping PII findings (regex + validators only).
    For the NER layer, merge analyzer spans via detect_with_analyzer."""
    return _resolve_overlaps(_detect_candidates(text))


# Secret shapes — labels only, never the matched value.
SECRET_PATTERNS: list[tuple[str, re.Pattern[str]]] = [
    ("JWT", re.compile(r"(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}")),
    ("API_KEY", re.compile(
        r"(?<![A-Za-z0-9_-])(?:"
        r"sk-(?:ant-|or-v1-|or-|proj-)?[A-Za-z0-9_-]{16,}"
        r"|AIza[0-9A-Za-z_-]{30,}"
        r"|ya29\.[A-Za-z0-9_-]{20,}"
        r"|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}"
        r"|xai-[A-Za-z0-9]{20,}"
        r"|gsk_[A-Za-z0-9]{20,}"
        r"|hf_[A-Za-z0-9]{20,}"
        r"|(?:AKIA|ASIA)[0-9A-Z]{16}"
        r"|(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}"     # Stripe
        r"|xox[abeoprs]-[A-Za-z0-9-]{10,}"               # Slack
        r")")),
    ("PRIVATE_KEY", re.compile(r"-----BEGIN (?:[A-Z]+ )*PRIVATE KEY(?: BLOCK)?-----")),
    ("BEARER", re.compile(r"(?i)\bbearer\s+[A-Za-z0-9._\-]{12,}")),
    ("SECRET_KV", re.compile(
        # Matches DB_PASSWORD=..., aws_secret_access_key: ... and "token": "..." alike.
        r"""(?i)(?<![a-z0-9])(password|passwd|pwd|passphrase|secret|api[_-]?key|access[_-]?token|token)(?:[_-][a-z0-9]+)*(["']?\s*[:=]\s*["']?)(?!<redacted>|\[[A-Z_]+\])([^\s"',;&]{4,})""")),
    # Scheme length is capped and may not start inside a longer run of scheme
    # characters: "\b[a-z][a-z0-9+.-]*://" retried from every letter of a long
    # "a.a.a.a..." run is quadratic (12 s on 100 kB).
    ("URL_CREDENTIALS", re.compile(
        r"(?i)(?<![a-z0-9+.-])[a-z][a-z0-9+.-]{0,31}://[^\s/:@]+:[^\s/@]+@")),
    # "Authorization: Basic <base64>" and other schemes, not just Bearer.
    ("AUTH_HEADER", re.compile(
        r"""(?i)\bauthorization["']?\s*[:=]\s*["']?[a-z]+\s+[^\s"',;]{8,}""")),
    ("WEBHOOK_URL", re.compile(r"https://hooks\.slack\.com/services/T[A-Z0-9]{6,}/B[A-Z0-9]{6,}/[A-Za-z0-9]{16,}")),
]


def scan_secrets(text: str) -> list[str]:
    """Which credential shapes appear in `text`? Labels only — safe to log."""
    return sorted({label for label, pat in SECRET_PATTERNS if pat.search(text)})


# ---------------------------------------------------------------------------
# PiiVault — reversible pseudonymisation.
# PII is swapped for stable opaque tokens before text leaves your boundary;
# the token->value map stays inside the vault (a separate store in production).
# The model sees "contact [PII_EMAIL_1a2b3c4d5e]" and never the address.
# ---------------------------------------------------------------------------

class PiiVault:
    """Tokenise detected PII into stable surrogate tokens and restore them.

    Tokens are deterministic (entity + value hash + optional salt), so the
    same email always maps to the same token — preserving the co-reference
    the model needs ("email the same person twice") without revealing who.
    Determinism also means tokens are linkable across documents *within the
    same salt*: use a per-vault salt when isolation matters.
    """

    def __init__(self, salt: str = ""):
        self._salt = salt
        self._store: dict[str, str] = {}

    def _token_for(self, entity: str, value: str) -> str:
        digest = hashlib.sha256(
            f"{self._salt}\x00{entity}\x00{value}".encode("utf-8")
        ).hexdigest()[:10]
        token = f"[PII_{entity}_{digest}]"
        self._store[token] = value
        return token

    def tokenize(self, text: str) -> str:
        """Replace every detected PII span with its stable token."""
        findings = detect_pii(text)
        out, cursor = [], 0
        for f in findings:
            out.append(text[cursor:f.start])
            value = text[f.start:f.end]
            out.append(self._token_for(f.entity_type, value))
            cursor = f.end
        out.append(text[cursor:])
        return "".join(out)

    def restore(self, text: str) -> tuple[str, int]:
        """Swap known tokens back to their values. Returns (text, n_restored).
        Unknown tokens are left untouched — they may be model-invented."""
        restored = 0

        def swap(m: re.Match[str]) -> str:
            nonlocal restored
            value = self._store.get(m.group(0))
            if value is None:
                return m.group(0)
            restored += 1
            return value

        # One pass over the text: a restored value that happens to contain
        # token-shaped text is not itself restored again.
        return _TOKEN_RE.sub(swap, text), restored

    def __len__(self) -> int:
        return len(self._store)


# ---------------------------------------------------------------------------
# Output scrubbing — for anything that leaves the trust boundary:
# log lines, previews, eval fixtures, support dashboards.
# ---------------------------------------------------------------------------

def scrub_text(text: str) -> str:
    """Replace detected PII spans with [TYPE] markers and secret shapes
    with [SECRET_LABEL]. Span-based, so multi-word values are handled whole.

    The text is folded first (NFKC, so a full-width @ or digit becomes a plain
    one, and invisible format characters such as zero-width spaces are dropped),
    so the scrubbed output is the folded text, not byte-for-byte the input.

    Best-effort: removes what the detectors catch — names, addresses and
    obfuscated values still slip through (see 3.6)."""
    text = unicodedata.normalize("NFKC", text)
    text = "".join(ch for ch in text if unicodedata.category(ch) != "Cf")
    # Secrets first: in postgres://user:pw@db.example.com the email detector
    # would otherwise claim "pw@db.example.com" and the credential pattern
    # (which needs the "@") would never see it.
    scrubbed = text
    for label, pat in SECRET_PATTERNS:
        scrubbed = pat.sub(f"[{label}]", scrubbed)
    findings = detect_pii(scrubbed)
    out, cursor = [], 0
    for f in findings:
        out.append(scrubbed[cursor:f.start])
        out.append(f"[{f.entity_type}]")
        cursor = f.end
    out.append(scrubbed[cursor:])
    return "".join(out)


# ---------------------------------------------------------------------------
# Detector evaluation — precision/recall on a labelled fixture.
# A fixture entry is (text, [Expected(entity_type, start, end), ...]).
# Matching: same entity_type and span IoU >= 0.5 or containment.
# ---------------------------------------------------------------------------

@dataclass(frozen=True)
class Expected:
    entity_type: str
    start: int
    end: int


@dataclass
class DetectorReport:
    per_type: dict[str, dict[str, float]] = field(default_factory=dict)
    totals: dict[str, int] = field(default_factory=lambda: {"tp": 0, "fp": 0, "fn": 0})

    def add_counts(self, entity: str, tp: int, fp: int, fn: int) -> None:
        row = self.per_type.setdefault(entity, {"tp": 0, "fp": 0, "fn": 0})
        row["tp"] += tp; row["fp"] += fp; row["fn"] += fn
        self.totals["tp"] += tp; self.totals["fp"] += fp; self.totals["fn"] += fn


def _iou(a_start: int, a_end: int, b_start: int, b_end: int) -> float:
    inter = max(0, min(a_end, b_end) - max(a_start, b_start))
    union = max(a_end, b_end) - min(a_start, b_start)
    return inter / union if union else 0.0


def _match(findings: list[Finding], expected: list[Expected]) -> tuple[int, int, int]:
    """Greedy one-to-one matching by (entity_type, overlap). Returns tp, fp, fn.

    A finding matches an expected span of the same entity_type when their
    IoU is >= 0.5 or when one span contains the other — detectors routinely
    return tighter spans than a human label, and strict IoU would deflate recall.
    """
    pairs = []
    for i, f in enumerate(findings):
        for j, e in enumerate(expected):
            if f.entity_type != e.entity_type:
                continue
            iou = _iou(f.start, f.end, e.start, e.end)
            contained = (f.start >= e.start and f.end <= e.end) or (
                e.start >= f.start and e.end <= f.end
            )
            if iou >= 0.5 or contained:
                pairs.append((f.start, -iou, i, j))
    pairs.sort()
    used_f, used_e, tp = set(), set(), 0
    for _, _, i, j in pairs:
        if i not in used_f and j not in used_e:
            used_f.add(i); used_e.add(j); tp += 1
    return tp, len(findings) - tp, len(expected) - tp


def evaluate_detector(fixture: list[tuple[str, list[Expected]]]) -> DetectorReport:
    report = DetectorReport()
    for text, expected in fixture:
        findings = detect_pii(text)
        per_entity: dict[str, list[Finding]] = {}
        for f in findings:
            per_entity.setdefault(f.entity_type, []).append(f)
        per_expected: dict[str, list[Expected]] = {}
        for e in expected:
            per_expected.setdefault(e.entity_type, []).append(e)
        for entity in set(per_entity) | set(per_expected):
            tp, fp, fn = _match(per_entity.get(entity, []), per_expected.get(entity, []))
            report.add_counts(entity, tp, fp, fn)
    for row in report.per_type.values():
        p = row["tp"] / (row["tp"] + row["fp"]) if row["tp"] + row["fp"] else 0.0
        r = row["tp"] / (row["tp"] + row["fn"]) if row["tp"] + row["fn"] else 0.0
        row["precision"] = round(p, 3)
        row["recall"] = round(r, 3)
        row["f1"] = round(2 * p * r / (p + r), 3) if p + r else 0.0
    return report


# ---------------------------------------------------------------------------
# Presidio-style analyzer interface — swap implementations without changing
# call sites. FakePresidioAnalyzer is for tests; PresidioAnalyzer wraps the
# real package (uv add presidio-analyzer presidio-anonymizer).
# ---------------------------------------------------------------------------

@dataclass(frozen=True)
class Span:
    entity_type: str
    start: int
    end: int
    score: float = 1.0


class Analyzer(Protocol):
    def analyze(self, text: str, language: str = "en") -> list[Span]: ...


class FakePresidioAnalyzer:
    """Stand-in for presidio_analyzer.AnalyzerEngine in tests and keyless
    development. Returns canned spans; never sees the real package."""

    def __init__(self, canned: dict[str, list[Span]] | None = None):
        self._canned = canned or {}

    def analyze(self, text: str, language: str = "en") -> list[Span]:
        return list(self._canned.get(text, []))


class PresidioAnalyzer:
    """Adapter over the real Presidio AnalyzerEngine (lazy import)."""

    def __init__(self, entities: list[str] | None = None):
        try:
            from presidio_analyzer import AnalyzerEngine
        except ImportError as exc:
            raise RuntimeError(
                "presidio-analyzer not installed: "
                'uv add presidio-analyzer presidio-anonymizer'
            ) from exc
        self._engine = AnalyzerEngine()
        self._entities = entities

    def analyze(self, text: str, language: str = "en") -> list[Span]:
        kwargs = {"text": text, "language": language}
        if self._entities:
            kwargs["entities"] = self._entities
        return [
            Span(r.entity_type, r.start, r.end, r.score)
            for r in self._engine.analyze(**kwargs)
        ]


# Presidio's entity names mapped onto this file's Finding vocabulary.
# Presidio returns EMAIL_ADDRESS, PHONE_NUMBER, CREDIT_CARD, IBAN_CODE,
# US_SSN, PERSON, ... — unmapped names pass through unchanged.
PRESIDIO_TO_FINDING = {
    "EMAIL_ADDRESS": "EMAIL",
    "PHONE_NUMBER": "PHONE",
    "CREDIT_CARD": "CREDIT_CARD",
    "IBAN_CODE": "IBAN",
    "US_SSN": "SSN_US",
}


def _analyzer_candidates(
    analyzer: Analyzer,
    text: str,
    entity_map: dict[str, str] | None = None,
) -> list[Finding]:
    """Analyzer spans -> Finding candidates, with entity names mapped."""
    mapping = entity_map or PRESIDIO_TO_FINDING
    return [
        Finding(mapping.get(s.entity_type, s.entity_type), s.start, s.end, s.score)
        for s in analyzer.analyze(text)
    ]


def detect_with_analyzer(text: str, analyzer: Analyzer) -> list[Finding]:
    """detect_pii plus NER spans, merged and de-overlapped in one pass —
    claims that start at the same character go to the higher score,
    otherwise the earlier start wins."""
    return _resolve_overlaps(
        _detect_candidates(text) + _analyzer_candidates(analyzer, text)
    )


if __name__ == "__main__":
    samples = [
        "Contact jane.doe@example.com or call +1 (415) 555-0132 about invoice INV-9.",
        "Card 4242 4242 4242 4242 on file; IBAN GB29 NWBK 6016 1331 9268 19.",
        "Reach me at jane dot doe at example dot com — names need NER, not regex.",
        "My key is sk-ant-api03-EXAMPLEEXAMPLEEXAMPLE12 and order 12345678901.",
    ]
    for s in samples:
        print("TEXT:", s)
        print("  findings:", [f.describe() for f in detect_pii(s)])
        print("  secrets :", scan_secrets(s))
        print("  scrubbed:", scrub_text(s))
        print()

    # NER merge demo (3.4): analyzer spans are mapped onto Finding types and
    # share detect_pii's overlap resolution. FakePresidioAnalyzer returns
    # canned spans — swap in PresidioAnalyzer() for the real engine.
    ner_only = "Reach me at jane dot doe at example dot com — names need NER, not regex."
    fake = FakePresidioAnalyzer(canned={
        ner_only: [Span("PERSON", 12, 16, 0.72)],      # "jane"
    })
    print("NER-only :", [f.describe() for f in detect_with_analyzer(ner_only, fake)])

    merged = "Jane Doe can be reached at jane.doe@example.com or +1 (415) 555-0132."
    fake2 = FakePresidioAnalyzer(canned={
        merged: [
            Span("PERSON", 0, 8, 0.85),                # "Jane Doe"
            Span("EMAIL_ADDRESS", 27, 47, 0.85),       # Presidio name -> EMAIL
            Span("PHONE_NUMBER", 51, 68, 0.70),        # Presidio name -> PHONE
        ]
    })
    print("NER merge:", [f.describe() for f in detect_with_analyzer(merged, fake2)])

    vault = PiiVault(salt="demo")
    raw = "Jane Doe (jane.doe@example.com) asked about order 88213; card on file ends 4242."
    safe = vault.tokenize(raw)
    print("VAULT raw :", raw)
    print("VAULT safe:", safe)
    print("VAULT back:", vault.restore(safe))

    # Aadhaar demo: compute a check digit for a synthetic base.
    base = "23456789012"[:11]
    print("aadhaar example:", base + str(verhoeff_check_digit(base)),
          "valid:", aadhaar_ok(base + str(verhoeff_check_digit(base))))

    # Detector-evaluation demo (3.7): the labelled fixture. Offsets are
    # character positions — author them with text.index(...) or by running
    # detect_pii and checking each span, then freeze them.
    fixture = [
        ("Contact jane.doe@example.com or call +1 (415) 555-0132 about invoice INV-9.",
         [Expected("EMAIL", 8, 28), Expected("PHONE", 37, 54)]),
        ("Card 4242 4242 4242 4242 on file; IBAN GB29 NWBK 6016 1331 9268 19.",
         [Expected("CREDIT_CARD", 5, 24), Expected("IBAN", 39, 66)]),
        ("Reach me at jane dot doe at example dot com — names need NER, not regex.",
         [Expected("EMAIL", 12, 43)]),
        ("Your tracking number is 6604876475933; delivery Friday.", []),
    ]
    report = evaluate_detector(fixture)
    print("EVAL:")
    for entity, row in sorted(report.per_type.items()):
        print(f"  {entity:12} precision={row['precision']:.3f} "
              f"recall={row['recall']:.3f} f1={row['f1']:.3f}  "
              f"({row['tp']} TP, {row['fp']} FP, {row['fn']} FN)")

What this means for you#

If you are shipping an LLM feature this week: write the leak-path inventory for your system before you write another prompt — every store that holds user data, every provider that sees it, every copy that persists. Classify the data, pick the provider tier per class, and put detection at the two egress points that matter (ingestion into your stores, and anything leaving for a third party). If you are shipping something regulated — health, payments, children's data, EU users at scale — the mechanisms in 7.6 (data map, consent records, deletion pipeline, retention schedule, DSAR export) are engineering deliverables with lead times, not paperwork; start them before the feature, not after the audit. And hold the line on the two non-negotiables: never fine-tune on raw user data, and never let a shared cache, memory or retrieval path cross a tenant boundary. Everything else in this lesson is a dial you can turn; those two are walls.


Common misconceptions#

Misconception Reality
"The provider doesn't train on API data, so we're fine." No-training ≠ no-retention. Abuse logs, safety classifiers, stored state, files and caches all create copies with their own clocks — check both policies (1.2).
"PII detection is solved — just run Presidio." Presidio catches the structured and common unstructured entities well but still misses names without context, obfuscated values, quasi-identifiers and multimodal PII — measure it on your own fixture rather than trusting a headline number (3.7).
"Redacting the email makes it anonymous." Replacing jane@x.com with [EMAIL] removes the direct identifier but keeps the quasi-identifiers — age, location, job, behaviour — that re-identify anyway. Anonymisation is a much higher bar than redaction (2.2).
"The system prompt is secret because the model won't reveal it." Models reveal system prompts — that's OWASP LLM08:2026 (Hidden Context Exposure). Assume it leaks; don't put secrets or security-through-obscurity in it (5.2).
"Vectors are anonymised — you can't read text from them." Embedding inversion recovers ~92% of short inputs exactly, including names from clinical notes. Treat vectors like the text they encode (1.4).
"Fine-tuning on our data is safe because it's our data." Fine-tuning bakes data into weights that can't be selectively deleted and can be extracted by anyone with API access. Never fine-tune on raw user data (Part 6).
"We deleted the user's data, so we're compliant." Deletion must reach every copy: primary DB, vector index, caches, traces, memory, eval fixtures, provider-side state, and backups (with their rotation window). One missed store is a breach (4.8).
"The eval set is internal, so it doesn't need privacy controls." Eval fixtures are copies of production data — they inherit every obligation plus new ones (sharing, retention, access). Scrub or synthesise them (Part 8).

Key takeaways#

  • Data leaks everywhere, not just in prompts. Provider retention, logs/traces, caches, vector stores, memory, eval sets, fine-tuning data, model output, media and error messages are all copy points — map them all before designing protections.
  • Classify before you protect. Direct identifiers, quasi-identifiers, sensitive categories, secrets and confidential business data need different controls; the provider policy matrix is the output of classification.
  • Detection is a filter, not a guarantee. Validators + regex + NER catch the structured and unstructured PII; LLM detection catches context but leaks the data it's checking; secret scanners are separate. Measure precision/recall on your own fixture.
  • Minimise > tokenise > redact > synthetic > send raw. The PII vault enables reversible pseudonymisation that keeps the model working; synthetic substitution eliminates re-identification risk; local models and contract controls are the architectural alternatives.
  • Pseudonymised data is still personal data. The vault is a processing control, not anonymisation — it needs the same encryption, access control, audit and retention as raw data.
  • Output is a leak path too. Scan model output for PII/secrets; assume the system prompt leaks; isolate tenants in retrieval, memory and cache; scrub error messages.
  • Fine-tuning on user data is the highest-risk copy. It can't be selectively deleted and can be extracted — prefer RAG, use tokenised or synthetic data, and run canary memorisation tests.
  • Privacy law requires mechanisms, not just policies. Build data maps, consent records, deletion pipelines, retention schedules, DSAR export and DPIA inputs — the engineering artifacts that make any lawful basis workable.
  • Evals need real data but can't hold it. Scrubbed traces, synthetic replacements, vault-tokenised fixtures and access-controlled review let you evaluate safely.

Terms introduced in this lesson#

PII (Personally Identifiable Information)#

Data that can identify a natural person, alone or in combination with other data — the engineering term for what privacy law calls "personal data." (Introduced in lesson 12.4)

Direct identifier#

PII that identifies a person on its own — email, phone, government ID, full name with context, credentials. (Introduced in lesson 12.4)

Quasi-identifier#

Data that doesn't identify alone but re-identifies in combination — age, postcode, job title, behaviour patterns. (Introduced in lesson 12.4)

Sensitive category#

PII in legally-protected classes — health, biometric, children's, racial/ethnic, political, sexual orientation — carrying stricter regimes than ordinary PII. (Introduced in lesson 12.4)

Pseudonymisation#

Replacing direct identifiers with consistent tokens while keeping the mapping separately — reversible by the data controller, still personal data under GDPR. (Introduced in lesson 12.4)

PII vault#

A controlled store mapping pseudonymisation tokens back to original values — the reversible half of the tokenise/restore pattern. (Introduced in lesson 12.4)

k-anonymity#

A privacy property where every combination of quasi-identifier values is shared by at least k records — no individual stands out in a dataset. (Introduced in lesson 12.4)

Differential privacy#

A formal privacy guarantee where query output changes negligibly whether or not any single person's data is included, achieved by adding calibrated noise. (Introduced in lesson 12.4)

Data Subject Access Request (DSAR)#

A legal right (GDPR, CCPA) to access all personal data an organisation holds about you — requires an export pipeline across every store. (Introduced in lesson 12.4)

Data Protection Impact Assessment (DPIA)#

A required risk assessment for high-risk processing under GDPR — engineering inputs are the data map, retention schedule and threat model. (Introduced in lesson 12.4)

Business Associate Agreement (BAA)#

A HIPAA-required contract making a provider a "business associate" permitted to handle PHI — without it, health data can't go to the API. (Introduced in lesson 12.4)

Zero Data Retention (ZDR)#

A provider arrangement where prompts and responses aren't retained after processing — a contract control, not a default. (Introduced in lesson 12.4)

Membership inference#

An attack determining whether a specific person's data was in a training set or index — itself a privacy leak even without content extraction. (Introduced in lesson 12.4)

Embedding inversion#

Reconstructing text from its vector embedding — Morris et al. showed ~92% of short inputs recoverable, making vector stores as sensitive as source documents. (Introduced in lesson 12.4)

Training-data extraction#

An attack recovering verbatim memorised training examples by querying a model — Carlini et al. 2021 and Nasr et al. 2023 demonstrated it at scale. (Introduced in lesson 12.4)


Exercises#

  1. Build the leak-path inventory for a real system. Pick a production LLM feature (support chatbot, RAG search, agent). Map every data flow from 1.1 onto it: what data enters, where it goes, what copies persist, who can read each copy. Identify the three highest-risk leak paths and propose a control for each.

  2. Extend the detector. Add a detector for a PII type pii.py doesn't cover — passport numbers, driver's licence formats, or your country's national ID. Write the regex + validator, add it to _DETECTORS, and add fixture cases to evaluate_detector. Run it and report the precision/recall.

  3. Evaluate your detector honestly. Build a labelled fixture of 20-30 texts from your actual data (emails, support tickets, docs) with hand-labelled PII spans. Run evaluate_detector and report per-type precision/recall. Where does it fail? What's the fix — better patterns, NER, or accept the gap?

  4. Implement the vault round-trip in a pipeline. Take a sample prompt containing PII, tokenize it with PiiVault, show what the model would see, then restore the response. Write a test that verifies: (a) the tokenised text contains no raw PII, (b) restore recovers the original, (c) unknown tokens are left untouched.

  5. Design a deletion pipeline. For a system with a primary DB, vector store, cache, trace backend and memory store, write the deletion job that walks every store on an erasure request. Include the audit record and the backup-expiry handling.

  6. Audit a provider's data policy. Pick your current LLM provider. Find their data retention, training and ZDR policies (official docs). Map them onto the 2.6 policy matrix: which data classes can you send, which need contract controls, which are forbidden?

  7. Write the privacy section of a DPIA. Using your system's data map and this lesson's leak-path inventory, draft the engineering inputs a DPIA needs: what data, why, where it flows, retention, access controls, deletion path, and the risks you've identified.

  8. Test tenant isolation. If you have a multi-tenant system, write a test that verifies tenant A's data never appears in tenant B's retrieval, memory or cache results. Run it against every scope boundary.

Hints
  1. A good answer ends with three rows, each naming a store, the data class in it, who can read it and one concrete control from the checklist in 5.6. Check you included the derived copies (vectors, caches, traces, eval sets), not only the primary database.
  2. Add the regex to the detectors list as a (entity_type, pattern, validator, score) tuple and put the checksum in a *_ok function like luhn_ok. Add at least one positive, one lookalike negative (a number with the right shape but a bad checksum) and one text that contains none. Report precision and recall per type, not just overall.
  3. Expect low recall on names and addresses and decent precision on anything with a checksum. If you can only label a few texts, keep the hard cases (obfuscation, order IDs that look like phone numbers) in the fixture; they teach more than easy hits.
  4. With PiiVault(salt="demo"): safe = v.tokenize(text); assert that none of the raw email, phone or card strings is in safe; restored, n = v.restore(safe) should equal the original text with n equal to the number of tokens; and v.restore("[PII_EMAIL_deadbeef00]") should return the text unchanged with n == 0, because unknown tokens may be model-invented.
  5. The skeleton is: collect the user's identifiers, then for each store call its delete API, then verify with a read-back, then write one audit record (store, count, time, no values). Backups cannot be edited, so record the date each backup generation expires.
  6. Use the retention windows from the official pages linked in Further resources. A good answer marks each data class in your own matrix as allowed, needs a contract control (ZDR, BAA, regional endpoint) or forbidden.
  7. Reuse the table in 7.6 as the skeleton; the risks section should cite the leak paths you found in exercise 1.
  8. Create two tenants with a unique canary string each, query as tenant A for tenant B's canary through retrieval, memory recall and the cache, and assert nothing comes back. Run it in CI on every change to those layers.

Check yourself#

  1. What's the difference between "no training" and "no retention"?
  2. Why is pseudonymised data still personal data under GDPR?
  3. What's the difference between redaction and tokenisation?
  4. Why can't you fine-tune on raw user data?
  5. What are the output-side leak paths?
  6. What does a deletion pipeline need to reach?
  7. Why is detection not enough on its own?
  8. What's the difference between k-anonymity and differential privacy?
  9. Why does Finding store offsets rather than the matched text?
  10. What's the difference between the Luhn check and IBAN mod-97?
  11. When is LLM-based PII detection appropriate?
  12. What does GDPR's 72-hour clock cover, and what must exist before you need it?
  13. Why are deterministic vault tokens vulnerable to confirmation attacks, and what's the fix?

Further resources#


← 12.3 — Jailbreaks and Model-Level Safety | Module 12 overview | 12.5 — Guardrails and Output Validation →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close