Masking PII in RAG retrieval chunks with NeMo Guardrails

Masking personal data in retrieved knowledge before it reaches the prompt, using NeMo Guardrails retrieval rails, and layering it on top of access control in your retrieval layer.

On this page

Masking PII in RAG retrieval chunks with NeMo Guardrails: why retrieved content needs its own rail

NeMo Guardrails retrieval rails can mask PII in retrieved chunks before they enter the prompt. Consider a team whose RAG assistant pulls policy documents, support tickets and customer records into the prompt. Those chunks may carry names, account numbers or health details that the user asking the question has no business seeing, and the model will happily repeat them. NeMo Guardrails provides five rail types: input rails, dialog rails, retrieval rails for RAG chunks, execution rails for custom actions and tools, and output rails. The retrieval rail is the one that inspects knowledge after the retriever returns it and before the chunk reaches the model, so it is the only place where the content itself is filtered at that boundary.

Retrieved content deserves its own rail because it is a separate trust boundary. Users type into the input rail, but the text that reaches the prompt from a knowledge base was written by someone else, may be stale, and may have been ingested without a privacy review. Teams should reach for retrieval rails when their documents contain personal data, or when the corpus mixes permission levels, such as HR files beside general handbooks. Before enabling a rail, confirm which detectors your retrieval rail can call in your configuration, which entity types they cover, and how the rail reacts to a chunk that is only partly sensitive.

The masking is a filter, not a replacement for access control. A retrieval rail reduces what the model sees, but it does not decide which documents a user may read, and a misconfigured detector can miss an identifier. Keep document-level permissions in the retrieval layer, enforce them on the query before results are returned, and treat the rail as a second line of defense. Test both layers together with records each user is and is not entitled to see.

How a retrieved chunk moves through the retrieval rail to the prompt

The diagram starts at the user query, which the retriever runs against a vector store with access filters applied before anything is returned. Retrieved chunks then cross the trust boundary from the knowledge store into the application, where the retrieval rail scans them with a PII detector and either masks or blocks each match. Only the surviving chunks reach prompt assembly, the LLM and the output rails. Check that the access filter runs before the rail, because the rail protects personal data in what the model sees, not who is allowed to retrieve it.

Access filters run before the retrieval rail, which masks or blocks PII in chunks.

How the retrieval rail engine processes chunks

The retrieval rail is one of the five rail types in NeMo Guardrails, alongside input, dialog, execution and output rails. It sits between your retriever and prompt construction. Retrieved chunks are passed to the rail as text, the configured flows run over each chunk, and the rail returns the chunk or a modified version of it for the prompt to be built from. This means the engine sees the knowledge your application pulls in, not only what the user typed. Confirm the exact hook point and the chunk data structure in the release you deploy (0.25.0 is the current release), because the engine internals are the part most likely to change between versions.

The wiring lives in three places. A config.yml file declares the models and enables the retrieval rail. Optional Python actions hold custom code that a flow can call, and Colang files define the flows that decide what happens to each chunk. Colang 1.0 is the default dialect and Colang 2.0 is also supported, so the first decision is which dialect your team will maintain. Keep one dialect per configuration. The NeMo Guardrails documentation describes the rail types, and the Colang 2 migration guide notes that converted configurations still need manual review. The PII detector is attached through these files, so its check is declared and reviewed alongside the other rails.

The same configuration runs in two ways. Your application can call it through the Python API and load the configuration folder in process, or you can run the guardrails server, which loads configurations from a folder and exposes an HTTP API. A Dockerfile is provided to build a server image. Choose the path before you write retrieval code, because it decides where chunks cross a network boundary and where logs are written. Confirm the supported Python versions for your release, since 0.25.0 requires Python 3.11, 3.12 or 3.13. Then test the chunk path end to end in the mode you will run in production, including a chunk that contains personal data and a chunk that does not.

Choosing a masking method for retrieved chunks

Presidio runs inside the NeMo Guardrails process, so retrieved chunks are scanned on the same host that assembles the prompt, and detection does not call a separate service. It is the most direct starting point when the entities you need are common identifiers such as names, email addresses and phone numbers, and when your team wants the fewest moving parts. Confirm the entity list and spaCy model you plan to install, because both determine coverage and resource use.

  • Where it runs: in the same Python process as the rails, with the spaCy model installed alongside it.
  • What it detects: a predefined set of entity types. Names and some numeric identifiers produce false positives, so test against your own documents.
  • Data handling: chunk text stays inside your process during detection and is not sent to an external detection service.
  • When it fits: internal knowledge bases with mostly standard personal data and a platform team that wants a small operational footprint.

Before relying on it for regulated content, check the entity list and score threshold against a sample of your own chunks.

When to mask a chunk and when to drop it

This table compares masking a retrieved chunk, blocking it, and removing the source document from retrieval, across user experience, answer quality, what the model still sees, and logging. Read each row as the consequence of choosing that option, then match the outcome to the content type: policy documents usually need their answers preserved, while customer records usually need the personal data kept out of the prompt entirely.

ConsiderationMask the chunkBlock the chunkRemove the document from retrieval
Best fitPolicy text that contains an incidental name, phone number or email in a contact lineChunks where the personal data is the whole point, such as a single customer record returned for an unrelated questionSource files that should never be searchable by the assistant, such as HR case files or customer exports
User experienceAnswer arrives normally, with placeholders where personal data wasAnswer omits that passage, and the user may see a generic refusal or a partial answerAssistant answers as if the document does not exist, which may look like a knowledge gap
Answer qualityUsually preserved, provided the masked placeholder does not break the sentence meaningCan drop the only passage that answers the question, lowering recallLowest recall for that content, so answers may be wrong or incomplete
What the model still seesMasked text and placeholders, not the original valuesNothing from the chunk enters the promptNothing from the document is retrieved
Logging and tracesConfirm whether original chunk text is written to logs or traces before masking is appliedConfirm whether blocked chunk content is recorded in the rejection logDocument may still be indexed, so confirm index and embedding stores handle personal data
Control to confirmRetrieval rail detector coverage for the entity types in that corpusRule that identifies the chunk and the fallback responseAccess control in the retrieval layer, enforced before ranking
Main riskDetector misses or over-masks names and identifiers, so testing on real samples is requiredUsers lose answers and may retry in ways that increase exposureStale copies remain in the vector index after the source changes

Setting up retrieval PII rails step by step

This sequence takes a RAG application from a working NeMo Guardrails install to a configuration where personal data in retrieved chunks is detected and masked before it reaches the prompt, with a test at each stage to confirm it.

  1. Confirm Python version and package version

    Your engineer checks that the runtime is Python 3.11, 3.12 or 3.13, since NeMo Guardrails 0.25.0 requires one of these. Then they confirm the package version they plan to install, using the current release of 0.25.0 as the reference point, and pin it in the project's dependency file so the build is repeatable. Done when the interpreter reports a supported version and the pinned version appears in the lock or requirements file. Ask your platform team whether they have an internal mirror for PyPI packages, as that changes how the pin is recorded.

  2. Install NeMo Guardrails and the detector

    Install the nemoguardrails package from PyPI into an isolated virtual environment or container image, then add the detector you have chosen for retrieval rails, such as the Presidio components or a Private AI or GLiNER-PII connection, following that detector's own installation notes. Confirm the install by importing the library in Python and printing its version. Done when the import succeeds and the detector's dependencies resolve without conflicts. Record which detector packages and model files were installed, because the model files are what your security reviewers will ask about later.

  3. Write config.yml with the retrieval rail

    Create a configuration folder with a config.yml that declares the model, the retrieval rail and the chosen PII detector, along with the actions to run for each rail. Keep the retrieval rail separate from input and output rails so the team can see exactly where masking happens. Confirm the file parses by loading the configuration in the library without starting a model call. Done when the configuration loads and the retrieval rail appears in the list of active rails. Note that Colang 1.0 is the default, so state the Colang version explicitly in the file if you use Colang 2.0.

  4. Add Colang or Python actions for masking

    Add the Colang flow or Python action that receives the retrieved chunks, runs the detector over each chunk, and replaces detected spans with placeholders before the chunks are passed to the prompt. Decide whether the action blocks the chunk or masks it, and record that decision in the action's comments. Test the action by calling it directly with a chunk that contains a made-up name and account number. Done when the action returns the chunk with those values replaced and the function returns without errors on a chunk that contains no personal data.

  5. Wire retriever output through the rail

    Connect your retriever so that every chunk it returns passes through the retrieval rail before the prompt template is filled. This is the step where the rail stops being a plan and becomes part of the request path. Use the library's retrieval rail entry point, keep the original chunks out of the prompt, and make sure the retriever's metadata fields are not copied into the prompt unmasked. Done when a test query produces a log entry showing the rail ran on each chunk, and the prompt object contains no unmasked chunk text.

  6. Test with known personal data samples

    Build a small test set of chunks that contain personal data your team has created for testing, including names, email addresses, phone numbers, identifiers and text with no personal data at all. Run each chunk through the rail and record what was detected, what was masked and what was missed. Include some borderline strings such as product names that look like names to measure false positives. Done when the results are saved as a table your security and privacy reviewers can read. Use only synthetic data in this step, not production records.

  7. Verify masked output reaches the prompt

    Run an end-to-end query against the retriever and inspect the exact prompt sent to the model, not only the final answer. Confirm that placeholders appear where personal data was in the chunk and that the original values do not appear in the prompt, in the model response or in the rail's logs at the level you have configured. Also check the response for values that the model may have reconstructed. Done when the prompt capture shows masked content only, and the team signs off on the test table from the previous step.

  8. Confirm the retrieval layer enforces access rules

    Check that the masking rail does not replace access control. Run queries as users with different permissions and confirm that each user receives only the chunks their access policy allows before the rail runs. Masking reduces exposure inside an allowed result, while the retrieval layer decides which documents are eligible at all. Done when the access test results match the policy and the rail's output for each user is recorded alongside the permission model you tested.

How PII masking combines with access control in the retrieval layer

Masking does not replace permission filters on the retriever. The order matters: enforce document and row permissions at retrieval first, then apply the PII rail to the chunks that user is allowed to see. Masking reduces what the model and the final answer expose, but it cannot grant access to anything the retriever would not otherwise return. If a user cannot read a document, a retrieval rail that redacts its contents still leaves the user with a path to that data, because the redacted text, its position in the answer and any surrounding phrasing can still reveal what the document held. Treat the rail as a second layer of minimization, not as an authorization control.

In practice, the retrieval layer should filter by the caller's identity before any chunk reaches NeMo Guardrails. Your vector store or search index (for example, a Qdrant collection or OpenSearch index you operate) should apply metadata filters or per-tenant collections derived from the authenticated user's group membership, not from a value the client sends in the request. The retrieval rail then sees only the permitted chunks and masks personal data in them before they are placed in the prompt. Confirm with your retrieval component's documentation which filter operators and access controls it supports, and test that a filter failure returns zero chunks rather than an unfiltered result.

The larger risk is masked content leaking through channels outside the chunk text. Citations, source titles, file paths, document IDs, section headings and chunk metadata often carry names or account identifiers even when the body is masked, and they are returned to the user by default in many RAG front ends. Check that the rail covers the fields your application returns, not only the main text. Also verify that the rail output is what gets logged and cached, since an unmasked copy in a trace or semantic cache undermines the control. Build a test set of documents the user cannot access and confirm that neither the answer, the citations nor the metadata reveal their existence or content.

Security and operational risks of retrieval masking

Masking personal data in retrieved chunks reduces exposure, but the masking layer adds its own failure modes. The cards below cover what detectors miss, what the surrounding system records, how stale data persists, and where the detectors run.

Detector misses on names and identifiers

Off-the-shelf detectors are strongest on common entity types and weakest on personal names, free-text identifiers and internal codes. A chunk can pass the rail with a customer name or account reference still in it. Test the rail against a sample of your own documents, including the identifiers your business actually stores, and decide whether regex rules or a second detector must cover the gap. Expect misses, and plan a review path for them.

NeMo Guardrails docs

Sensitive data in logs and traces

Retrieval rails sit in a request path that is often instrumented. Chunk text, the detected entities and the rewritten prompt can end up in application logs, traces or observability backends even when the model never sees the raw data. Confirm which fields your deployment writes, who can read them, and how long they are kept. The masking layer protects nothing if the telemetry stores the original text next to the masked output.

Content capture settings

Guardrails tooling can record prompts, retrieved context and responses for debugging. Whether that capture is enabled, and where it goes, decides whether masked data stays masked after the request ends. Make the capture setting an explicit, reviewed configuration item rather than a default you inherit. Ask whether capture is off in production, and whether a debugging mode can be switched on without a change record.

Stale indexes that keep old personal data

A rail masks chunks at retrieval time, but the vector index and document store still hold the unmasked original. If a source document is corrected or a person asks for erasure, the index may keep serving the old text. Decide whether masking happens before embedding, at query time, or both, and define a re-indexing process that removes deleted source content. Confirm with your team how deletions propagate from the source system to the index.

Denial of service from detector latency

Every retrieved chunk passes through the detector before the prompt is built. A slow or overloaded detector delays every answer, and a large retrieval set multiplies the cost. Under load, the detector can become the bottleneck for the whole assistant. Measure latency at your expected query volume and chunk count, set timeouts, and define whether the system fails closed or open when the detector is unavailable. Ask which behavior your risk owner has approved.

Detectors and models inside the network

Retrieved knowledge often contains the most sensitive material in an assistant. Sending chunks to a cloud detection API moves that data outside your boundary before any masking happens. Run detectors, local safety models and any Private AI or GLiNER-PII containers in your own cloud account or data center, and confirm that the rail configuration makes no outbound calls. Document this as an architecture decision that your security team can review.

Questions teams ask about masking PII in RAG chunks

What drives the effort and cost of masking PII in RAG chunks?

The main drivers are how many document sources feed the retrieval index, how much personal data those documents contain, and how many detector types you need. Each source has its own format, from PDFs and tickets to wiki pages and database exports, and each format needs extraction and chunk-level testing before a rail can be trusted. Detector choice matters too: a built-in Presidio setup has different work than a self-hosted GLiNER-PII container or a Private AI server, which needs its own deployment, sizing and access review. Ask any partner to price these items separately, and ask what is one-time build work (rail configuration, test corpus, documentation) versus recurring work (retesting after new sources are added, updating NeMo Guardrails, reviewing false positives). Infrastructure cost for the runtime and any model containers is paid from your own budget.

How long does a typical PII masking setup for retrieval take?

No fixed duration applies because the work depends on the number of sources, the volume of documents and the detector you choose. A narrow setup with one knowledge base and a built-in detector is much smaller than a multi-source deployment with custom identifiers and a separate model container. The schedule is usually set by three things: how long it takes to get access to the source systems and a representative sample, how many rounds of false-positive review the business accepts, and how long security sign-off takes on the final configuration. Ask for a written plan with milestones and the dependencies each one waits on, and confirm which items depend on your change approval process.

What must our team provide before the work starts?

Three inputs decide most of the early work. First, representative sample documents from each knowledge source, including the messy ones such as scanned files, exported tickets and pages with embedded tables, because chunking changes what the detector sees. Second, the permission model of the retrieval layer: which groups can read which documents, and whether the access filter runs before or after the PII rail. Third, the detector decision: which entity types matter, whether data may leave your network, and who approves the false-positive trade-off. You also need a named owner for the configuration and someone who can approve logs and test data handling.

Can our own engineers do this without an implementation partner?

Yes, if your team has Python, container and retrieval engineering experience and time to test thoroughly. NeMo Guardrails is an Apache 2.0 open-source library, so the software itself carries no license fee, and the config.yml and Colang files are readable by any engineer on the team. The work that usually stretches internal teams is the test corpus, the false-positive review and the evidence trail for security and privacy reviewers. Confirm your Python version against the requirements of the release you pick, since NeMo Guardrails 0.25.0 requires Python 3.11, 3.12 or 3.13. A partner adds value mainly where you need faster review cycles, documented evidence or a second pair of hands on the retrieval integration.

Does masking PII in retrieved chunks satisfy a privacy review on its own?

No. Masking reduces the personal data that reaches the model prompt, but a privacy review also looks at what is stored in the vector index, what is written to logs and traces, who can retrieve the original documents, and how long each record is kept. Masking at retrieval time leaves the raw text in the index unless you also control ingestion. Reviewers usually ask for a data flow diagram, the access control design, the test results on a representative corpus and the retention settings for logs. Confirm the requirements with your privacy office and with the auditors or certification bodies who will assess your controls, since DeployOpen prepares evidence but does not issue assessments or attestations.

How does PII masking combine with access control in the retrieval layer?

Access control decides which chunks a user may see, and the PII rail decides what personal data remains in the chunks that reach the prompt. The two must be designed together. If the rail runs on chunks a user is not allowed to read, masked text can still reveal that a record exists, so the permission filter normally runs first and the rail runs on the authorized set. Test this with accounts from each permission group and confirm that retrieval filters, metadata and the rail configuration behave the same way after each change.

What should we check when false positives mask useful content?

Start by measuring which entity types trigger on your real documents, because names, product codes and identifiers often look like personal data to detectors. Adjust score thresholds, add allow lists where the business agrees, and use regex rails for internal identifiers the detectors miss, then test each change against a labeled sample. Keep a record of the decisions and the people who approved them. Also check that masked placeholders still let the model answer the question, since over-masking can make answers unusable even when privacy controls work as intended.

How DeployOpen scopes and delivers retrieval PII rails

DeployOpen plans, builds, tests and hands over retrieval PII rails for NeMo Guardrails inside the client's own infrastructure, so that personal data in retrieved chunks is masked before it reaches the prompt. Engagements start from a written scope that names the knowledge sources, detectors and access rules involved, and the work is documented so your security and compliance teams can review it.

How we scope

  • Inventory the knowledge sources, indexes and document types that feed retrieval, and the personal data each one may contain.
  • Agree in writing which PII entities, detectors and masking or blocking behavior apply to retrieved chunks.
  • Confirm the NeMo Guardrails version, Python runtime and hosting model before any configuration work starts.

How we build

  • Configure the retrieval rail so chunks are checked and masked before they are added to the prompt context.
  • Align the rail with the access control already enforced in the retrieval layer, so masking never replaces authorization.
  • Test with representative chunks, including names, identifiers and false positives, and record the results for review.

How we hand over

  • Deliver configuration files, custom actions and a runbook that explains each retrieval rail and its settings.
  • Provide test cases and a findings log that show which chunk types were masked, blocked or passed through.
  • Walk your engineering and compliance teams through the evidence, so they can review the rail without relying on us.

How we support

  • Ongoing support, upgrades and continuous testing are available as a retainer after handover.
  • Plan retests whenever knowledge sources, detectors or the NeMo Guardrails version change, and confirm upgrade steps against the release notes.
  • Ask for a quote based on the written scope, which sets out the one-time build work and any recurring support separately.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.