Sub topic 13
Limits and Defense in Depth
This chapter assumes you have worked through the earlier chapters. You should know how regex, checksum and NER detectors return labelled spans. You should also know how redaction and reversible placeholders work, and what precision and recall mean. Here the question changes from "how do I detect personal data?" to "what is left over when detection is done, and what else must protect it?"
Why detection is never complete
Every detector in this tutorial makes errors. A regex misses formats you did not anticipate. A checksum rejects a real number that has a typo. An NER model misses names it has not seen. Measuring detection quality gives you a number, but a good number is not a guarantee.
Recall is the fraction of real personal data that you find. Suppose your recall is 98%, which is good. If your app handles 100,000 messages a day and each contains one identifier, about 2,000 identifiers reach the model provider unredacted every day. The rate looks small, but the volume makes it a steady leak. Treat redaction as something that reduces exposure, not as something that removes it.
Common failure modes
| Failure mode | Example | Why detectors miss it |
|---|---|---|
| Unusual formats | `ana at example dot com` | Regex expects `@` and `.` |
| Obfuscation and typos | `4111 1111 1111 111l` | Pattern or checksum fails |
| Context-dependent names | "Jordan called" vs. "I visited Jordan" | NER guesses person or place wrongly |
| Low-resource languages | Names in scripts or languages the model was not trained on | NER recall drops sharply |
| Non-text content | Scanned PDFs, screenshots, audio transcripts | Text detectors never see the data |
| Indirect descriptions | "the only cardiologist in a town of 800 people" | No identifier string exists |
| Split values | A number pasted across two messages | Detection runs per message |
Re-identification through quasi-identifiers
Removing direct identifiers does not make data anonymous. Quasi-identifiers are attributes that are harmless alone but identify a person in combination, such as postcode, birth date, gender, job title and employer. Research by Latanya Sweeney is widely cited for showing that a large majority of the US population is unique on just ZIP code, gender and date of birth.
Your detector may mask every name and email in a support ticket. The ticket can still say "a 54-year-old female pilot in a small Alaskan town". Anyone who can search public records can narrow that to one person. A language model can also combine such clues, and it can infer attributes you never wrote down, such as health conditions or origin, from writing style and topic.
Residual risk created by redaction itself
Redaction adds some risks of its own:
- The mapping is sensitive. The placeholder-to-original dictionary holds exactly the data you removed. If you persist it or log it, you have rebuilt the leak.
- Consistent pseudonyms link records. If
<PERSON_1>always means the same person across sessions, the provider can still build a profile of that person, even without the name. - Placeholders carry structure.
<EMAIL_1>tells the model that an email address was there. That is usually fine, but it can reveal that a conversation involved, say, a medical record number. - Placeholders can break tasks. If a model must reason about a name's gender or a country's phone format, redaction removes the signal and answer quality drops.
Defense in depth
Defense in depth means stacking independent controls so that one failure does not expose the data. Redaction is one layer. The others reduce what reaches it, limit the damage when it fails, or catch the failure afterwards.
- Minimize. The cheapest personal data to protect is data you never collected. Do not put a full customer record in the prompt when the task needs one field. Do not ask users for identifiers the feature does not need.
- Redact. Run the detection pipeline before model calls, on retrieved documents and on logs, as covered in the placement chapter.
- Provider controls. Check the provider's retention period, whether prompts are used for training, and where data is processed. Use zero-retention or enterprise options where they exist. Sign a data processing agreement if regulation requires one.
- Output scanning. Run detection on model replies too. A reply that contains an identifier you did not send may come from retrieved context, from the model's training data, or from a hallucination that happens to look real.
- Log scrubbing and retention. Logs often outlive everything else. Scrub them at write time and expire them on a schedule.
- Monitor and audit. Sample traffic, review misses, and feed each miss back into your labelled test set.
Other controls apply around these layers: access control on who can read logs and mappings, encryption at rest, and per-tenant isolation for retrieval indexes. They are not specific to LLMs, but they matter, because a redaction failure becomes much less harmful when few people can see the data.
Fail closed
Decide up front what happens when a detector crashes, times out or returns nonsense. If the pipeline sends the original text on error, an outage in your detector becomes a data leak. Failing closed means the request is blocked, and the user gets an error instead of an unprotected call. Some products accept failing open for low-risk text. Make that a deliberate decision per data class.
A guard with output scanning and log scrubbing
The example below combines three layers in one runnable script: fail-closed input redaction, output scanning, and a logging filter. It uses simple email and phone regexes. In a real system you would plug in your full hybrid pipeline.
import logging
import re
EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")
PHONE_RE = re.compile(r"\+?\d[\d ()-]{7,}\d")
class LeakBlocked(Exception):
pass
def detect(text):
spans = []
for label, rx in (("EMAIL", EMAIL_RE), ("PHONE", PHONE_RE)):
spans += [(m.start(), m.end(), label) for m in rx.finditer(text)]
return sorted(spans)
def redact(text, spans):
mapping, parts, counts, pos = {}, [], {}, 0
for start, end, label in spans:
counts[label] = counts.get(label, 0) + 1
token = f"<{label}_{counts[label]}>"
mapping[token] = text[start:end]
parts += [text[pos:start], token]
pos = end
parts.append(text[pos:])
return "".join(parts), mapping
def guarded_call(user_text, call_llm):
try:
spans = detect(user_text)
except Exception as exc: # fail closed: never send unchecked text
raise LeakBlocked("detector failed; request not sent") from exc
safe_text, mapping = redact(user_text, spans)
reply = call_llm(safe_text)
unexpected = detect(reply) # placeholders do not match, real values do
if unexpected:
raise LeakBlocked(f"reply has {len(unexpected)} unexpected identifier(s)")
for token, original in mapping.items():
reply = reply.replace(token, original)
return reply
class RedactingFilter(logging.Filter):
def filter(self, record):
message = record.getMessage()
record.msg, _ = redact(message, detect(message))
record.args = None
return True
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
logger = logging.getLogger("app")
logger.addFilter(RedactingFilter())
def echo_llm(prompt):
return f"Noted: {prompt}"
def leaky_llm(prompt):
return "Try writing to [email protected]"
print(guarded_call("Email [email protected] or call +44 20 7946 0958", echo_llm))
try:
guarded_call("Hello there", leaky_llm)
except LeakBlocked as exc:
print("blocked:", exc)
logger.info("User [email protected] asked about an invoice")Run it and you should see three results:
- The restored reply, which contains the original email and phone number.
- A
blocked:line, because the second model reply contained an email the application never sent. - A log line where the email appears as
<EMAIL_1>.
The filter discards the mapping (_), so logs hold no way back to the original values.
A few limits of this guard are worth knowing:
- Output scanning cannot tell a memorized real address from a harmless example address, so it will sometimes block replies that were fine. Expect false positives and decide whether to block, redact or flag for review.
- Scrubbing only covers log records that pass through this logger. Print statements, exception tracebacks from other libraries, and third-party tracing tools bypass it.
- Detection of the reply happens before restoration. If you scanned after restoring, every restored value would trigger a block.
Deciding how much is enough
There is no universal threshold. Match the controls to the harm that a leak would cause.
- Low sensitivity (public product questions): light redaction of emails and phone numbers, short log retention.
- Moderate sensitivity (customer support with account details): full hybrid pipeline, output scanning, scrubbed logs, a provider with no training on your data.
- High sensitivity (health, financial, children's data): minimize aggressively, consider a self-hosted model so the data never leaves your boundary, require human review of detector misses, and involve your legal or privacy team.
A review checklist
Before you ship, walk through these questions:
- Where does personal data enter (users, retrieval, tools, uploads), and is each entry point covered?
- What do you measure as recall for each entity type, and on which languages and formats?
- What happens when the detector fails or times out?
- Which stores keep raw text, mappings or embeddings, and how long?
- Who can read logs and traces?
- What is your process when a user reports that their data leaked, and can you find and delete it?
- How do missed detections get back into your test set?
Exercise
A service has 99% recall on email addresses and handles 50,000 messages a day, each with exactly one email address. Roughly how many unredacted addresses reach the provider each day, and name two layers other than better detection that would reduce the harm.
Show answer
About 500 (1% of 50,000). Two layers that reduce harm: choose a provider option with zero data retention and no training on your data, and minimize what goes into the prompt so fewer messages contain an email at all. Scrubbing logs and restricting access to them also counts.
Exercise
In the guard above, why is the reply scanned before the placeholders are restored instead of after?
Show answer
Restoration puts the user's real emails and phone numbers back into the reply. Scanning afterwards would detect those and block every reply that used a placeholder. Scanning first means any identifier that matches is one the application did not send, so it is unexpected and worth blocking or reviewing.
Exercise
A support ticket has all names, emails and phone numbers masked, but it still reads "the only dentist in a village of 300, born in March 1971". Which concept explains why this is still risky, and why will your detectors not catch it?
Show answer
Re-identification through quasi-identifiers. Occupation, a small location and a birth month and year together can single out one person. No fixed pattern or named entity marks them as identifiers, so regex, checksum and NER detectors do not flag them. Reducing the risk requires generalizing or removing the details (minimization), not pattern-based redaction.