Sub topic 8
Choosing a redaction strategy
This chapter assumes you can write basic Python, read simple regular expressions, and already have a detector that returns (start, end, label) spans, as in the earlier chapters. Here you decide what to do with those spans before the text goes to a model.
The four strategies
A redaction strategy is the rule for replacing a detected span. Four are common.
| Strategy | Example output | Reversible | Keeps model useful |
|---|---|---|---|
| Remove | `Email about the invoice.` | No | Low. Sentence structure breaks. |
| Mask | `Email ***************` | No | Low to medium. Shows a value existed. |
| Replace with label | `Email <EMAIL>` | No | Medium. The model knows the type. |
| Numbered placeholder or hash | `Email <EMAIL_1>` | Yes, with a local mapping | High. Same value keeps the same token. |
Masking can leak information. Showing the last four digits of a card (**** 1111) is fine for display, but the length and shown characters still reveal part of the value.
A hash such as SHA-256 of an email is stable, so the same input always produces the same token. That helps with joins and counting. It is weak for low-entropy values like phone numbers or short names, because an attacker can hash every possible value and compare. Use a keyed hash (HMAC) with a secret key if you need stable tokens.
Matching the strategy to the use case
Ask two questions. Does the model need to reason about the value? Do you need the original back in the response?
- Summarizing a support ticket: label replacement is usually enough.
- Drafting a reply that must address the customer by name: use numbered placeholders and restore them afterward.
- Writing logs or analytics: remove or hash. You rarely need to restore anything there.
- Distinguishing two people in one conversation: numbered placeholders, so
<PERSON_1>and<PERSON_2>stay separate.
Implementing the strategies
The function below applies one strategy per label. It assumes spans do not overlap, which the pipeline chapter handled. It works from the end of the text backward so earlier offsets stay valid.
import hashlib
import hmac
SECRET_KEY = b"replace-with-a-real-secret"
def apply_strategy(value, label, strategy):
if strategy == "remove":
return ""
if strategy == "mask":
return "*" * len(value)
if strategy == "label":
return f"<{label}>"
if strategy == "hash":
digest = hmac.new(SECRET_KEY, value.encode(), hashlib.sha256).hexdigest()
return f"<{label}_{digest[:8]}>"
raise ValueError(f"Unknown strategy: {strategy}")
def redact_with_policy(text, spans, policy):
for start, end, label in sorted(spans, reverse=True):
strategy = policy.get(label, "label")
text = text[:start] + apply_strategy(text[start:end], label, strategy) + text[end:]
return text
message = "Email [email protected], card 4111 1111 1111 1111."
spans = [(6, 21, "EMAIL"), (28, 47, "CREDIT_CARD")]
policy = {"EMAIL": "hash", "CREDIT_CARD": "remove"}
print(redact_with_policy(message, spans, policy))The policy dictionary lets you set different rules per label. Unknown labels fall back to label, which is a safe default because it never keeps the original value.
Common mistakes
- Restoring with plain string replacement when one placeholder is a prefix of another, such as
<EMAIL_1>and<EMAIL_10>. Replace longer tokens first. - Using the same placeholder for different values, so the model merges two people into one.
- Storing the placeholder mapping next to the logs. The mapping holds the original values and needs the same protection as the raw data.
- Masking by fixed length (
****) when you want to hide the length. Use one constant string instead.
Exercise
A support assistant must write a reply that greets the customer by name, but the name must not reach the model provider. Which strategy fits, and where must the mapping live?
Show answer
Use numbered placeholders such as <PERSON1>. The mapping stays in your application, in memory or a protected store, and is never sent to the provider. After the model replies with <PERSON1>, you restore the real name locally.
Exercise
Why is a plain SHA-256 hash of a 10-digit phone number a weak redaction?
Show answer
There are only about ten billion possible numbers, so an attacker can hash all of them and match the result. A keyed hash (HMAC) with a secret key prevents this.