Mental model
An edge PII filter runs detection on a device, maps the detector's findings back to the original text, and replaces selected spans before the request crosses the network. Its privacy value depends on what it misses, what it redacts incorrectly, and where the original text can still leak. Local processing reduces one exposure path; it does not make sensitive data risk-free.
Treat the filter as a staged data boundary. A detector can use recognizers, statistical NER, and context, while a separate anonymizer decides which spans to replace. Microsoft's Presidio describes that analyzer/anonymizer split, but its documented Analyzer is a Python component; a browser product needs a detector that actually runs locally, such as a local model or purpose-built rules. Calling a remote Presidio service before redaction moves the original text off the device and defeats a local-only guarantee.
The detector should return offsets into the exact text being filtered. JavaScript string slicing uses UTF-16 code units, while tokenizers or native models may return UTF-8 bytes or Unicode code-point offsets. Convert offsets once at the adapter boundary and test names with emoji, combining marks, right-to-left scripts, and surrogate pairs. Do not normalize or rewrite the text between detection and replacement unless offsets are remapped to the changed string.
Learning outcomes
- Separate local PII detection from the policy that replaces or retains each finding.
- Compute precision and recall from a labeled test set and identify the privacy meaning of false negatives.
- Implement deterministic span replacement without logging the original values.
Theory
For a chosen entity class and confidence threshold, define true positives as labeled PII spans the detector finds, false negatives as labeled spans it misses, and false positives as detector spans that are not PII. Then
TP, FP, and FN are counts of entity spans, so both ratios are dimensionless. Precision estimates how often a replacement is warranted; recall estimates how much labeled sensitive content the filter catches. Raising a confidence threshold may reduce false redactions while increasing missed PII. A single combined score hides that trade-off, and performance for email addresses cannot stand in for performance on account numbers, addresses, or names.
Keep detection and redaction policy separate. First collect candidates with entity type, confidence, and offsets. Next apply a threshold calibrated for that entity and workflow, reject malformed offsets, and merge overlapping accepted spans. Finally replace the union of spans in descending offset order so earlier slices do not shift later positions. If the application needs coreference, use short-lived placeholders such as PERSON_1 only within one request; never store the reverse mapping in analytics or a persistent conversation by default.
Worked example
On a manually labeled set of 1,000 sensitive spans, suppose the local detector catches 940, misses 60, and emits 1,050 candidate spans. It therefore has TP = 940, FN = 60, and FP = 110: precision is 940 / 1,050 = 89.5%, while recall is 940 / 1,000 = 94%. That looks strong as a summary, but the filter still leaves 60 labeled spans unredacted per 1,000 in this sample. The team must decide whether those misses are acceptable for a search query, a support ticket, or an identity document; the ratio does not make that risk decision for them.
Build evaluation examples from the languages, input lengths, entity types, and misspellings users actually submit. Split tuning examples from the holdout set, report counts beside each percentage, and inspect false negatives by category. A model update can change both offsets and recall, so bind the deployed model revision and detector configuration to the evaluation report.
Trade-offs
| Redaction choice | Preserves | Risk or cost |
|---|---|---|
Replace with [REDACTED] | Minimal sensitive detail | Can remove context the model needs to answer |
| Use a request-scoped typed placeholder | Some entity role and repeated references | Entity labels and linkage still reveal information |
| Keep text and warn the user | Original wording | Depends on the user noticing and acting on the warning |
| Block unsupported input | Strong fail-closed boundary | Interrupts workflows and can reject harmless text |
Confidence is not a privacy policy. A high-confidence name detector can still miss an unusual spelling, and a low-confidence financial identifier might deserve a user confirmation instead of silent pass-through. A generic [PERSON] placeholder leaks less than a stable identifier but may damage pronoun resolution; a per-request stable placeholder preserves more meaning while adding linkability inside that request. Choose per entity and purpose, then document the policy in the interface.
Failure modes and misconceptions
- The browser filter is described as complete protection. Unrecognized identifiers, indirect clues, uploaded files, and text generated after the initial scan can still contain sensitive data. Keep server-side access, retention, and privacy controls in place.
- A detector calls a remote service. Sending the original text to a cloud NER endpoint before masking crosses the boundary. Make local execution observable and fail closed if the detector silently falls back to a server.
- Offsets are measured against a different string. Unicode normalization, newline conversion, or UTF-8 versus UTF-16 indexing can mask the wrong substring. Preserve the scanned string and validate offset behavior with non-ASCII fixtures.
- Overlapping findings reveal a gap. Replacing the first span can shift indices or leave an overlap tail untouched. Merge accepted intervals against the original string, then replace from right to left.
- False positives remove useful context. Over-redaction can make a query unusable or hide a medical term that is not identifying. Measure precision by entity and let users inspect or correct a sanitized preview when policy permits.
- The raw prompt enters telemetry. Crash reports, session replay, debug logs, or saved detector inputs can recreate the disclosure the filter was meant to avoid. Log model revision and aggregate counts, not the source string or recovered values.
Decision scenario
A browser assistant receives a pasted tax form. Its local test suite reaches 94% recall on email and phone spans, but the detector has only been evaluated on synthetic addresses and has weak coverage for tax identifiers. The app must not silently send the full form because the common categories scored well. It should pause, explain that this document type is outside the validated detector boundary, and offer a user-reviewed sanitized preview or a workflow that never sends the document. Keep any server-side controls active even when local redaction is enabled.
Diagram and measurement
The edge boundary is: keep source text on device, run a local recognizer, reconcile and validate spans, replace only the accepted intervals, then transmit the sanitized payload under the request's privacy policy. The original value should not enter application logs at any stage.
Implementation pattern
The detector adapter supplies offsets in JavaScript UTF-16 code units for the unchanged text. This function applies a caller-selected threshold, merges overlapping findings, and replaces from right to left. Production thresholds should be calibrated separately for each entity type and tested against Unicode input.
typescripttype Finding = { start: number; end: number; confidence: number };export function redactSpans(text: string,findings: readonly Finding[],threshold: number,): { text: string; redactedSpanCount: number } {const accepted = findings.filter((item) =>Number.isInteger(item.start) && Number.isInteger(item.end) &&item.start >= 0 && item.end > item.start && item.end <= text.length &&Number.isFinite(item.confidence) && item.confidence >= threshold,).sort((a, b) => a.start - b.start || a.end - b.end);const merged: Array<{ start: number; end: number }> = [];for (const item of accepted) {const previous = merged.at(-1);if (previous && item.start < previous.end) {previous.end = Math.max(previous.end, item.end);} else {merged.push({ start: item.start, end: item.end });}}let sanitized = text;for (const span of merged.reverse()) {sanitized = sanitized.slice(0, span.start) + "[REDACTED]" + sanitized.slice(span.end);}return { text: sanitized, redactedSpanCount: merged.length };}
This routine only transforms spans; it does not certify that the detector found every identifier or that the request is safe to transmit. Keep the raw-to-placeholder map out of logs, and preserve the server's independent authorization and retention checks.