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.
GLiNER-PII is a model-based detector delivered as a NIM container, which you can host locally or call through a hosted endpoint. It is the option to evaluate when the categories you need go beyond a standard entity list, because you define the labels to detect and the masking placeholders that replace them. Hosting it locally requires GPU capacity, so the sizing decision belongs in the design phase, not after the rails are live.
- Where it runs: a local container in your cluster or data center, or a hosted endpoint if your terms allow it.
- What it detects: the label set you configure, which can cover broader categories than a standard entity list.
- Data handling: a local container keeps chunk text inside your network. A hosted endpoint sends chunk text to that service, so review its processing and retention terms first.
- When it fits: knowledge bases with domain-specific personal data categories and a team able to run GPU-backed containers.
Confirm the label set, the placeholder format and the GPU requirements for your model version with NVIDIA's current documentation before you build the retrieval rail.
Private AI provides detection and masking through a dedicated server, which can be deployed as a cloud service or as a container you run. A dedicated server separates detection from your application hosts, which some procurement and security reviews ask for and which some teams prefer for ownership of scaling and patching. Its data handling depends on the deployment model, so the containerized and cloud options should be assessed separately.
- Where it runs: a Private AI server reached over the network from the NeMo Guardrails host, either as a cloud service or as a container in your environment.
- What it detects: the entity coverage and languages in the vendor's current product documentation, which you should verify for your locale.
- Data handling: a containerized deployment keeps chunk text inside your network. A cloud deployment sends chunk text to the vendor, so check its retention and processing commitments.
- When it fits: organizations that need a vendor-supported detector behind a separate service, with licensing and support terms in place.
Ask the vendor for its entity list, supported languages, deployment options and data retention terms in writing, and test coverage on a sample of your own chunks before comparing it with the open-source detectors.
Regex rails match patterns you write, which makes them the practical choice for internal identifiers that off-the-shelf detectors do not know, such as account numbers, medical record numbers and internal ticket IDs. They run in process, so matching adds no external call. Their coverage is exactly the patterns you define, which means the main risk is over-matching, not missed detection of standard personal data.
- Where it runs: in the NeMo Guardrails process, configured alongside the other rails.
- What it detects: only the formats your patterns describe, such as a fixed prefix followed by a set number of digits.
- Data handling: matching happens locally with no external service involved.
- When it fits: identifiers with a consistent, documented format that your organization already controls.
Illustratively, a pattern for a nine-digit number will also match many numeric strings that are not identifiers, so test each pattern against a representative corpus before it blocks or masks production retrieval.
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.
| Consideration | Mask the chunk | Block the chunk | Remove the document from retrieval |
|---|---|---|---|
| Best fit | Policy text that contains an incidental name, phone number or email in a contact line | Chunks where the personal data is the whole point, such as a single customer record returned for an unrelated question | Source files that should never be searchable by the assistant, such as HR case files or customer exports |
| User experience | Answer arrives normally, with placeholders where personal data was | Answer omits that passage, and the user may see a generic refusal or a partial answer | Assistant answers as if the document does not exist, which may look like a knowledge gap |
| Answer quality | Usually preserved, provided the masked placeholder does not break the sentence meaning | Can drop the only passage that answers the question, lowering recall | Lowest recall for that content, so answers may be wrong or incomplete |
| What the model still sees | Masked text and placeholders, not the original values | Nothing from the chunk enters the prompt | Nothing from the document is retrieved |
| Logging and traces | Confirm whether original chunk text is written to logs or traces before masking is applied | Confirm whether blocked chunk content is recorded in the rejection log | Document may still be indexed, so confirm index and embedding stores handle personal data |
| Control to confirm | Retrieval rail detector coverage for the entity types in that corpus | Rule that identifies the chunk and the fallback response | Access control in the retrieval layer, enforced before ranking |
| Main risk | Detector misses or over-masks names and identifiers, so testing on real samples is required | Users lose answers and may retry in ways that increase exposure | Stale 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.
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.
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.
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.
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.
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.
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.
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.
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 docsSensitive 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.

