Sub topic 8
Choosing a redaction strategy
Once a detector returns (start, end, label) spans, you still have to decide what goes into the text in their place. The choice affects three things: how much information leaks, how well the model can still do its job, and whether you can undo the change later.
This chapter assumes you can write the span-returning detectors from the earlier chapters. It also assumes you know basic Python and have called an LLM API. Reversible placeholders and restoring responses get their own chapter, so this one only sets them up.
The four basic strategies
Each strategy turns a detected value into a replacement string. They differ in how much of the original survives.
| Strategy | Example output for `[email protected]` | Keeps | Loses |
|---|---|---|---|
| Mask | `***@******e.com` | Length, format, some characters | Most content, but partial leaks are possible |
| Label placeholder | `<EMAIL>` | The type of the value | Identity and linkage |
| Numbered placeholder | `<EMAIL_1>` | Type and which mentions are the same value | Identity |
| Keyed hash | `<EMAIL_9f2c41ab>` | Type and a stable pseudonym across documents | Identity, if the key stays secret |
| Remove | (empty string) | Nothing | Everything, including the fact that something was there |
Masking
Masking replaces characters with a fixed symbol such as *. It is the familiar "card ending in 1111" pattern. It suits output that a human reads, such as receipts or support screens, where the last few characters help someone confirm "yes, that is my card."
Masking is a weak default for LLM input, for three reasons:
- Partial masks leak. The masked email above still shows the end of the domain. For a short value such as a 6-digit code, keeping four characters reveals most of it.
- The mask keeps the original length, and length is itself a signal.
- A model sees
***@******e.comas noise. It cannot tell whether the string was an email, a code, or a corrupted token.
Use masking when a human needs a recognizable hint. Use a fixed number of kept characters, and never keep more than a third of the value.
Label placeholders
Replacing the value with its type, as in <EMAIL> or <PERSON>, is the most common choice for prompts. The model still understands the sentence structure ("send the invoice to <EMAIL>"), and nothing about the value remains.
The weakness shows up when the text mentions several values of the same type. In "Ana met Bob, then Ana called Carol", plain labels give "<PERSON> met <PERSON>, then <PERSON> called <PERSON>". The model can no longer tell who did what.
Numbered placeholders
Numbering fixes that problem. Within one text, the same value always gets the same token, so you get <PERSON_1> met <PERSON_2>, then <PERSON_1> called <PERSON_3>. The numbering is also what makes reversal possible, because each token maps back to one original value in a mapping you keep locally.
Number by distinct value, not by occurrence. The redact function in the earlier chapter counts occurrences, so the same email mentioned twice becomes <EMAIL_1> and <EMAIL_2>. The code below fixes that.
Hashing
A hash gives a deterministic pseudonym. The same input always produces the same token, even across separate documents or sessions. That lets you count distinct users in logs, join records, or spot repeated senders without storing the raw value.
A plain sha256(value) is unsafe for most personal data. Phone numbers, national IDs, and many emails come from small or predictable spaces. An attacker who gets the hashes can hash every candidate and compare. Use a keyed hash (HMAC) with a secret that is stored outside the log pipeline. Normalize the value before hashing, for example by lowercasing emails, or the same address will produce different tokens.
Removal
Deleting the span is the strictest option and sometimes the right one. Examples are an internal ticket ID that adds nothing to a summarization task, or a signature block the model should never see. The cost is that the sentence may become ungrammatical or ambiguous, and the model cannot tell that information was removed. For most prompts a label placeholder is safer than deletion, because it preserves the shape of the sentence.
One implementation, several policies
The code below applies a different strategy per label. It numbers placeholders by distinct value and uses an HMAC for hashes. It runs as shown and needs only the standard library.
import hashlib
import hmac
import os
SECRET = os.environ.get("REDACTION_KEY", "dev-only-key").encode()
def mask(value, keep_last=4):
"""Replace letters and digits with '*', keeping separators and the last few characters."""
alnum_total = sum(c.isalnum() for c in value)
seen = 0
out = []
for c in value:
if c.isalnum():
seen += 1
out.append(c if seen > alnum_total - keep_last else "*")
else:
out.append(c)
return "".join(out)
def keyed_hash(label, value):
digest = hmac.new(SECRET, value.strip().lower().encode(), hashlib.sha256)
return f"<{label}_{digest.hexdigest()[:8]}>"
def apply_policy(text, spans, policy):
"""spans: non-overlapping (start, end, label). policy: label -> strategy name."""
seen = {} # (label, value) -> number
counts = {} # label -> highest number used
parts, pos = [], 0
for start, end, label in sorted(spans):
value = text[start:end]
strategy = policy.get(label, "label")
if strategy == "mask":
repl = mask(value)
elif strategy == "hash":
repl = keyed_hash(label, value)
elif strategy == "remove":
repl = ""
elif strategy == "numbered":
key = (label, value)
if key not in seen:
counts[label] = counts.get(label, 0) + 1
seen[key] = counts[label]
repl = f"<{label}_{seen[key]}>"
else:
repl = f"<{label}>"
parts.append(text[pos:start])
parts.append(repl)
pos = end
parts.append(text[pos:])
return "".join(parts)
text = "Card 4111 1111 1111 1111. Ana ([email protected]) wrote twice: [email protected]."
card = "4111 1111 1111 1111"
email = "[email protected]"
first = text.index(email)
second = text.index(email, first + 1)
spans = [
(text.index(card), text.index(card) + len(card), "CREDIT_CARD"),
(first, first + len(email), "EMAIL"),
(second, second + len(email), "EMAIL"),
]
print(apply_policy(text, spans, {"CREDIT_CARD": "mask", "EMAIL": "numbered"}))
print(apply_policy(text, spans, {"CREDIT_CARD": "remove", "EMAIL": "hash"}))The first call prints Card **** **** **** 1111. Ana (<EMAIL_1>) wrote twice: <EMAIL_1>. Both email mentions get the same token because they are the same value. The second call prints the same hash token twice, and the exact hex digits depend on your key.
Two details in the code are easy to miss. mask counts only alphanumeric characters, so the separators in a card number survive and the output keeps its readable shape. keyed_hash strips and lowercases before hashing, so [email protected] and [email protected] produce the same token.
Choosing by use case
Start from what the redacted text is for, then pick the strategy. The diagram shows the usual order of questions.
Typical assignments look like this:
- Prompts to an external model: numbered placeholders for names, emails, and phone numbers. These are the values the model refers to in its answer.
- Log storage: keyed hashes for user identifiers, so analysts can count and group events. Remove or label everything else.
- Analytics exports: labels or removal. Nobody downstream needs to reverse them.
- Customer-facing screens: masks with the last few characters kept.
You can mix strategies in one pipeline, as apply_policy does. A single policy for every label is usually wrong, because a card number and a person's name are used differently.
Edge cases that cause bugs
Placeholder collisions
If the input text already contains <EMAIL_1>, restoring a response will replace it with a real value that was never in the mapping, or fail silently. Check for the placeholder pattern in the input before redacting. Pick a format that is unlikely in real text, or escape existing occurrences.
Overlapping spans
Two detectors can report overlapping spans. A name inside an email address is a common case. apply_policy assumes the spans do not overlap. Resolve overlaps before this step, for example by keeping the longer or higher-scoring span. With overlaps present, the text slices would be duplicated or dropped.
Short hash prefixes
The code keeps 8 hex characters, which is 32 bits. That is fine for a single conversation or a small log. In a large dataset, collisions become likely once you have tens of thousands of distinct values, because of the birthday effect. Keep more characters if you need uniqueness, and decide on length from your data volume.
Case and format drift
The same person may appear as Ana Lopez, ana lopez, and Ana. Numbering by exact string treats them as three people. Normalizing helps for case, but linking Ana to Ana Lopez is a harder problem that regex-style rules do not solve. Accept the limit, and tell downstream users that the numbering is by exact string.
Order of operations
Always compute replacements from the original text and original offsets. If you replace one span and then use the old offsets of later spans, everything after the first replacement shifts. The code avoids this by building the output left to right from the original string.
Checking your choice
Before you ship a strategy, run it on a handful of real-looking examples and check three things. First, read the output and confirm no value survives in a partial form. Second, send the redacted text to the model and confirm the answer is still useful. Third, if you plan to restore values, confirm that every token in the model's reply exists in your mapping. The next chapter covers that last step in detail.
Exercise
A support team wants to log chat messages for later analysis. Analysts must be able to count how many distinct customers contacted support each week, but must never see email addresses. Which strategy should the pipeline apply to email addresses before logging, and what two precautions does it need?
Show answer
Use a keyed hash (HMAC with a secret key) so the same customer always gets the same token and distinct customers can be counted. The two precautions are: normalize the value first (strip whitespace and lowercase) so one address always yields one token, and store the key outside the log system, because an unkeyed or leaked-key hash can be reversed by hashing guessed addresses. Also keep enough hex characters in the token to avoid collisions at your volume.
Exercise
The text "Ana met Bob, then Ana called Carol" is redacted with plain label placeholders. What goes wrong when the model answers "who called Carol?", and which strategy fixes it?
Show answer
Every name becomes <PERSON>, so the model cannot tell that the first and fourth mentions are the same person or which person called Carol. Numbered placeholders fix it: the text becomes "<PERSON1> met <PERSON2>, then <PERSON1> called <PERSON3>", and the model can answer <PERSON_1>. Restoring the response from a local mapping then turns it back into "Ana".