5: Governance

    Use masking techniques as guard rails to meet a performance objective

    Masking exists at the boundary between a generative AI application and its sensitive inputs or outputs. The control replaces sensitive substrings (names, account numbers, secrets, identifiers, addresses, free-text PII) with a placeholder before the model sees them, and optionally reverses the placeholder back to the original value after the model has produced its response.

    Treating masking purely as a privacy control misses the question the exam asks: how does the chosen masking technique affect the performance objective the application is built to meet? The performance objective is almost always one of latency at a given percentile, token cost per request, retrieval quality, end-to-end answer quality, or a regulatory pass rate that itself has a latency budget attached.

    The reason masking lands in the governance chapter rather than the application development chapter is that the decision is rarely engineering-driven. The compliance team writes a rule that says "no raw account numbers may appear in a prompt sent to a pay-per-token endpoint." The engineering team has to honor that rule while still serving the agent inside the 1.5 second latency target the product owner committed to.

    Masking is how those two goals get reconciled, and the four common techniques each move the latency, accuracy, and reversibility levers differently.

    Mask categories and their performance footprint

    Key points

    There are four mask categories that the exam expects you to distinguish.

    The first is regex masking, where a precompiled pattern replaces matches with a fixed token like [EMAIL] or [PHONE].

    • Regex is the fastest technique because it runs in linear scan time and has no model dependency.
    • It works well for high-precision formats like emails, IP addresses, credit card numbers, and US Social Security numbers.
    • It is poor at masking unstructured PII like person names, free-text addresses, or rare identifier formats, because regex cannot read context.
    • Regex masking is the default for latency-critical inline guardrails because the per-request overhead is measured in microseconds.

    The second is NER-based masking, where a named-entity recognition model (such as a spaCy pipeline, a Presidio analyzer, or a small fine-tuned classifier served on CPU) tags spans by entity type, and the masker substitutes each span with a typed placeholder.

    • NER catches the long tail of PII that regex misses, especially names, organizations, and free-text locations, at the cost of an extra model call before the LLM call.
    • The added latency is the runtime of the NER model, typically 30 to 150 milliseconds on CPU for short prompts and longer for long-form inputs.

    The third is hashing and pseudonymization, where the sensitive value is replaced by a deterministic hash (SHA-256, HMAC with a secret key) or a lookup token.

    • Hashing is irreversible by design, so it is appropriate when the model never needs to refer back to the original value (analytics prompts, classification prompts) but is wrong when the model output must include the real value (a reply addressed to the customer by name).
    • Hashing has near-zero runtime cost beyond the regex match that found the value.

    The fourth is format-preserving tokenization, where the sensitive value is replaced by a synthetic value that matches the original format, and a per-session token map is held outside the prompt so the post-processor can swap the synthetic value back to the real one.

    Format-preserving tokenization is what most enterprise deployments end up with for customer-facing chat because the LLM keeps producing well-formed responses (the model still sees something that looks like a phone number, so it does not refuse or hallucinate around the placeholder), while the real value never reaches the model.

    💡 Exam Trap: "Mask" and "redact" are not interchangeable on the exam. Redaction is a destructive operation: the original value is gone. Masking implies that a token map may exist and a post-processing step can put the value back. If a question asks for a control that survives the round-trip back to the user, choose masking with a token map, not redaction.

    Pre-LLM and post-LLM masking

    A masking guardrail can sit on the input path, the output path, or both.

    Input masking runs before the prompt is sent to the model; output masking runs on the model response before it is returned to the caller or downstream tool. Both have distinct performance objectives.

    How it works

    Input masking serves three objectives.

    • The first is cost: scrubbing free-text identifiers stops the model from being asked to reason about values that are useless to the answer, which shrinks the prompt token count.
    • The second is compliance: if the model is hosted on a pay-per-token endpoint outside the customer's data region, the masker keeps regulated content from leaving the boundary.
    • The third is quality: an LLM that is asked to write a reply for "[CUSTOMER_NAME]" rather than for "Alex Rivera" produces less identity-leaked output, which is easier to audit and easier to re-target across customers.

    Output masking serves a different objective: it catches values that the model emitted from its own training data, from retrieved context, or from tool output that the input masker did not see.

    This is the layer that catches generated PII, leaked API keys, leaked internal endpoints, and any value the model invented that matches a sensitive pattern. Output masking is also the only layer that can intercept hallucinated PII, because by definition such values were never in the input.

    ⚠️ Anti-Pattern: Wiring only input masking and calling the chain compliant. Retrieved context, tool responses, and the model's own knowledge can each introduce sensitive values that the input layer never saw. A chain that masks input but not output passes raw PII to the caller whenever the LLM regurgitates training data or echoes a retrieved chunk.

    The token map and round-trip masking

    Format-preserving tokenization and reversible pseudonymization both depend on a per-request token map that lives outside the prompt.

    The map is a small dictionary keyed by placeholder, valued by original.

    The flow is:

    • extract sensitive spans,
    • generate placeholders,
    • store the placeholder-to-original pairs in the map,
    • send the masked prompt to the model,
    • receive the masked response,
    • walk the response and substitute placeholders back to originals using the map,
    • return the unmasked response to the caller.

    The map is per-request and per-session because the same placeholder must point to the same original within a conversation, otherwise a user reading the reply sees inconsistent names.

    import re
    from typing import Tuple
    
    EMAIL_RE = re.compile(r"[\w\.-]+@[\w\.-]+\.\w+")
    PHONE_RE = re.compile(r"\b\d{3}-\d{3}-\d{4}\b")
    
    def mask_with_map(text: str) -> Tuple[str, dict]:
     token_map = {}
     counters = {"EMAIL": 0, "PHONE": 0}
    
     def replace(match, kind):
     counters[kind] += 1
     placeholder = f"<{kind}_{counters[kind]}>"
     token_map[placeholder] = match.group(0)
     return placeholder
    
     text = EMAIL_RE.sub(lambda m: replace(m, "EMAIL"), text)
     text = PHONE_RE.sub(lambda m: replace(m, "PHONE"), text)
     return text, token_map
    
    def unmask(text: str, token_map: dict) -> str:
     for placeholder, original in token_map.items():
     text = text.replace(placeholder, original)
     return text
    

    This wraps cleanly inside a pyfunc model's predict method.

    The pre-processing hook builds the map, calls the LLM with the masked prompt, then the post-processing hook reverses the map.

    Because the pyfunc returns the unmasked reply to the caller while never sending the original values to the LLM, the contract from Chapter 1 holds:

    • the chain inputs and outputs match the documented schema,
    • the boundary control sits inside the chain rather than as an external middleware.

    AI Gateway as a masking enforcement plane

    Mosaic AI Gateway lets a platform team apply PII detection policies to every served endpoint behind the gateway without code changes to each chain.

    The PII detection guardrail offered by AI Gateway can be configured per endpoint with two modes:

    • BLOCK rejects requests containing detected PII
    • MASK substitutes detected entities with type placeholders before the call reaches the model

    The advantage is centralization: one team owns the policy, every endpoint inherits it, and the audit log lives in a single Unity Catalog table.

    The trade-off the exam probes is what AI Gateway masking cannot do. It cannot maintain a token map for round-trip reversal because the post-processor does not have the original value (the gateway saw the original, but the chain only sees the masked text). If the chain output must include the customer name on the reply, the chain itself has to mask, not the gateway.

    Use AI Gateway masking when the application can tolerate placeholders in the response (internal analytics, classification, summarization without name retention) and use chain-internal masking with a token map when the response must look natural to the end user.

    📊 Limit: Mosaic AI Gateway guardrail evaluation runs on every request and adds measurable latency. The PII guardrail and content safety guardrail each add a model inference call. Budget the gateway latency into the P95 target for the endpoint, and run a load test with guardrails enabled before quoting an SLA.

    Choosing masking against the performance objective

    The exam phrases questions as "the team must meet objective X; which masking technique is appropriate?" Below is the decision frame.

    • If the objective is lowest possible latency on a short prompt, choose regex masking inside the chain.
    • Regex adds microseconds, accepts known patterns, and never calls another model.
    • If the objective is highest recall on PII coverage across multilingual or unstructured text, choose NER-based masking.
    • Accept the 30 to 150 millisecond hit per request.
    • Run the NER model on the same cluster as the chain to avoid network hops.
    • If the objective is round-trip presentation in the final reply (the user must see the real name), choose format-preserving tokenization with a per-request token map kept in the pyfunc state.
    • The map lifetime is the request; do not persist it.
    • If the objective is irreversible removal for an offline analytics workflow, choose hashing or full redaction.
    • Reversibility here would be a liability.
    • If the objective is centralized policy enforcement across many endpoints owned by different teams, choose AI Gateway PII guardrails in MASK mode.
    • Lose round-trip reversal, gain audit centralization and zero per-chain code.

    🎯 Scenario: A bank ships a wealth-management agent that must address the client by name in every response. Compliance forbids raw account numbers from reaching the third-party LLM. Latency target is 1.2 seconds at P95. The team should use format-preserving tokenization for account numbers (model sees a fake but well-formed account number, post-processor maps back if the response references it), keep client names unmasked because they are needed in the reply, and add an output regex scan that blocks any response containing an account number not in the original token map. AI Gateway masking would break the round-trip and is the wrong choice here.

    Decision Anchor

    Choose regex masking when the patterns are well-defined and the latency budget is tight.

    Choose NER masking when free-text PII recall matters more than latency.

    Choose format-preserving tokenization when the reply must show the real value back to the user.

    Choose AI Gateway masking when the policy must apply uniformly across many endpoints and the application can accept placeholders in the response.

    Code: NER masking with Presidio inside a pyfunc

    import mlflow.pyfunc
    from presidio_analyzer import AnalyzerEngine
    from presidio_anonymizer import AnonymizerEngine
    from presidio_anonymizer.entities import OperatorConfig
    
    class MaskedChain(mlflow.pyfunc.PythonModel):
     def load_context(self, context):
     self.analyzer = AnalyzerEngine()
     self.anonymizer = AnonymizerEngine()
     from databricks.sdk import WorkspaceClient
     self.w = WorkspaceClient()
    
     def _mask(self, text):
     results = self.analyzer.analyze(
     text=text,
     entities=["PERSON", "PHONE_NUMBER", "EMAIL_ADDRESS", "CREDIT_CARD"],
     language="en",
     )
     token_map = {}
     operators = {
     "DEFAULT": OperatorConfig("replace", {"new_value": "<MASKED>"}),
     }
     anon = self.anonymizer.anonymize(text=text, analyzer_results=results, operators=operators)
     for item in anon.items:
     token_map[anon.text[item.start:item.end]] = text[item.start:item.end]
     return anon.text, token_map
    
     def predict(self, context, model_input):
     prompt = model_input["prompt"].iloc[0]
     masked, token_map = self._mask(prompt)
     resp = self.w.serving_endpoints.query(
     name="prod-chat-endpoint",
     messages=[{"role": "user", "content": masked}],
     )
     reply = resp.choices[0].message.content
     for placeholder, original in token_map.items():
     reply = reply.replace(placeholder, original)
     return [reply]
    

    Masking limits and quotas

    • The Mosaic AI Gateway PII guardrail supports a fixed list of entity types per release; rare entity types may need a custom chain-side scanner.
    • Token maps must be held in process memory for the request lifetime. Do not persist them to logs, do not return them in the response payload, and do not write them to inference tables.
    • Output masking must run after any output parser. A JSON parser that fails because a masked token violated the schema will leak the original in the parser error message if the masker runs before the parser.
    • Regex masking on long texts has linear cost in input length; very long contexts (over 100k tokens) push the masker into the same latency band as small NER models.

    💡 Exam Trap: Questions about meeting a latency objective with masking often list four techniques. The trap is selecting NER because it sounds more thorough. Read the latency target. If the budget is sub-300 millisecond P95 and the prompt is short, regex masking is the answer even when NER would catch a slightly broader set of entities.

    ⚠️ Anti-Pattern: Storing the token map in the same inference table that logs prompts and responses. The table becomes a clear-text lookup for every masked value. Keep the token map ephemeral, in process memory only, for the duration of one request.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the Databricks - Gen AI Engineer Associate learning hub.