What you will be able to do
- Choose between dropping a document with a classifier and masking entities while keeping the document, based on where in the text the problem lives
- Enforce a content filter as a declarative pipeline expectation, choosing warn, drop, fail or quarantine
- Explain why access controls, encryption and gateway redaction do not replace cleaning the text before it is indexed
- Recognise when the fix is to replace a data source rather than filter it
Key concept
Source-side mitigation — Problematic text is handled in the data pipeline, before chunking and embedding, because whatever reaches the index can be retrieved and passed to the model. You choose the mechanism from the shape of the problem: drop the whole document, mask the offending entities, or enforce the rule as a pipeline expectation.
1.What counts as problematic text, and where to stop it
A RAG application repeats whatever its corpus contains. Some ingested documents carry harmful language, and some carry sensitive values such as social security numbers. Others may have been planted on purpose: every document source you feed an agent is a potential route for a data poisoning attack. None of these is a relevance problem. The document might match the user's question perfectly and still be unsafe to retrieve.
The place to deal with it is the preprocessing stage of the unstructured data pipeline. That stage sits after ingestion and parsing and before chunking, embedding and indexing. Once a chunk is embedded and written to a vector index, any query that lands near it can retrieve it. Controls that come later either act after retrieval has already happened or don't touch the text at all.
Cleaning downstream doesn't cost you the original. The recommended practice is to ingest raw source data into its own target table for preservation, traceability and auditing. You then write a separate cleaned table for embedding. A dropped or masked record still exists in the raw table, so you can recover it if a filter turns out to be too aggressive.
There are three mitigation alternatives, and each fits a different shape of problem:
- Drop the document with a classifier when the whole document is the problem.
- Mask the offending entities and keep the document when only some values are the problem.
- Enforce either rule as a declarative pipeline expectation, so the check runs, and is measured, on every record that flows through.
Checkpoint 1 of 9· Put it in order
Your RAG corpus contains some toxic documents and some emails with social security numbers in them. Put these pipeline steps in order so the problem text is handled where this lesson says it should be.
- 1.Ingest the raw source documents into their own target table
- 2.Chunk the cleaned text
- 3.Parse the raw documents into text
- 4.Filter out or mask the problematic text, writing a separate cleaned table
- 5.Embed the chunks and write them to the vector index
Filtering is part of preprocessing. It comes after ingestion and parsing and before chunking, because any embedded and indexed chunk can be retrieved. The raw table is written first and kept, so a dropped or masked record can still be recovered.
“filtering out unwanted information, the next step is to break it down into smaller, manageable units called chunks.”Source: docs.databricks.com
Sources1
2.Dropping documents with a safety classifier
Running a classifier over each document and using its prediction as a filter is the right tool when the content itself is the defect. Filtering out whole documents that don't belong covers the general idea of a document filter. Here the filter has a safety goal rather than a relevance goal: the classifier scores toxicity, and documents above a threshold never reach the embedding table. The same pattern works with a PII detector when a document's only value is the sensitive data it holds.
Consider a nightly job that loads raw product-review files into the Delta table behind a RAG index. Some files mix real reviews with spam boilerplate and entries full of profanity. Two steps belong in that ingestion pipeline before the embedding table is written. The first is a text-cleaning step that strips boilerplate, the same way parsing strips headers, footers and special characters. The second is a content filter that removes the flagged entries. A profane review has no salvageable part, so dropping it loses nothing the assistant needs.
Some fixes look plausible but act on the wrong layer. Re-ranking at query time only reorders retrieved chunks, so a profane chunk is still in the index and can still reach the model. Changing how Auto Loader discovers files, or allowing schema evolution, affects how rows arrive and has no effect on what the rows say.
Checkpoint 2 of 9· Check yourself
A community-forum assistant indexes user posts from a Delta table. Reviewers find that many posts are spam or full of abuse, and none of that text is worth keeping. What should the team add so these posts stop reaching the model?
When the whole post is the problem, you score each one with a classifier and drop the flagged posts before embedding, so they never enter the index. Re-ranking and top-k only change which retrieved chunks get used, so the bad chunks stay in the index. Auto Loader settings change how rows arrive, not what the rows say.
“applying a toxicity classifier to the document to produce a prediction you can use as a filter”Source: docs.databricks.com
Checkpoint 3 of 9· Exam question
A nightly Auto Loader job ingests a directory of raw product review text files into a Delta table that feeds a RAG application's vector index. Some files mix legitimate reviews with spam boilerplate and profanity-laden entries. What should be added to the ingestion pipeline to best mitigate this before the reviews are embedded?
Correct answer: A — A text cleaning and content-filtering transformation that strips boilerplate and removes flagged entries before the table used for embedding is written
- A. Cleaning and filtering the text before the embedding table is written removes spam boilerplate and flagged content at the source, so the vector index never contains the problematic entries in the first place.
- B. Re-ranking still returns the profanity-laden chunk within the retrieved set, only lower in the order, so the problematic text can still reach the model's context window and influence the response.
- C. Schema evolution controls how Auto Loader handles new or changing columns in incoming files; it has no effect on filtering offensive or spam text within the review content itself.
- D. Switching the file discovery mechanism changes how new files are detected for ingestion, but it does not inspect or clean the text content of the reviews being loaded.
Sources1
3.Masking entities and keeping the document
Dropping is the wrong choice when a document is valuable and only a few values in it are dangerous. Take an HR assistant built on years of archived employee emails, where the bodies contain social security numbers and salary figures. If you drop every email that contains one, the assistant loses most of its knowledge. If you keep the emails as they are, the assistant can retrieve those values for anyone who asks. The fix is to mask the values in the text during data preparation, before the text is chunked and embedded.
In SQL, ai_mask(content, labels) calls a Databricks-hosted model through Foundation Model APIs to mask the entity types you list, and returns the text with each match replaced by [MASKED]. Each element of labels names a type of information to mask. You pick the labels to fit the corpus, for example 'person' and 'email'. Because a model rather than a pattern does the detection, it can find free-text entities like names. It is tuned for English and needs Databricks Runtime 15.4 LTS or above, and it isn't available on Databricks SQL Classic.
> SELECT ai_mask(
'John Doe lives in New York. His email is john.doe@example.com.',
array('person', 'email')
);
"[MASKED] lives in New York. His email is [MASKED]."Controls on the source table don't fix this. Where source-table masks stop explains why. Column masks, index permissions and encryption at rest decide who can read a table. They don't change the text the retriever passes to the model once the emails have been chunked into an index. Restricting the index to HR administrators, or encrypting the Delta table with a customer-managed key, leaves the SSNs in every chunk the assistant retrieves.
Gateway redaction is the fallback for when the data source itself can't be cleaned. Sensitive Data Detection (PII block/redact) replaces each matched value with a placeholder such as [US_SSN] on the input, the output or both. That is useful protection, but it acts after retrieval has already pulled the unmasked chunk. It also matches patterns, so names, locations and organizations need an LLM judge rather than this policy. Mask in the pipeline wherever you can, and treat the gateway as a second layer.
Checkpoint 4 of 9· Check yourself
An insurer's claims assistant is built on ten years of adjusters' notes. The notes are the assistant's main source of knowledge, but many of them name claimants and include their email addresses. Which change should the team make so those values can't be retrieved and the notes stay useful?
The notes are valuable and only some values in them are dangerous, so you mask those entities during data preparation, before chunking and embedding. ai_mask uses a model, so it can also find free-text names. Dropping the notes would throw away most of the assistant's knowledge. Column masks, index permissions and encryption only control who can read the data. The names and emails would still be in every chunk the retriever passes to the model.
“The ai_mask() function allows you to invoke a state-of-the-art AI model to mask specified entities in a given text using SQL.”Source: docs.databricks.com
Checkpoint 5 of 9· Exam question
An internal HR assistant retrieves context from a Delta table built from years of archived employee emails. A review finds that many emails contain employee social security numbers and salary figures embedded in the body text. What is the best way to mitigate this before the data feeds the RAG pipeline?
Correct answer: A — Add a PII detection and redaction step to the data preparation pipeline so sensitive values are masked or removed before the text is embedded and indexed
- A. Detecting and redacting PII during data preparation removes sensitive values from the source text before it is ever embedded, preventing SSNs and salaries from entering the retrievable index at all.
- B. An output guardrail only inspects the model's final response; the sensitive values remain embedded in the vector index and can still be retrieved into the model's context window during generation.
- C. Restricting access to the index controls who can query it, but it does not remove the SSNs and salaries from the archived email text, so the underlying problematic content is still present.
- D. Encrypting the table at rest protects against unauthorized storage access but does not strip PII from the text, so the sensitive values are still exposed to anyone permitted to query the index.
4.Enforcing content filters as pipeline expectations
An expectation turns a content rule into a declared, monitored part of the pipeline instead of a WHERE clause buried in a notebook. Expectations are optional clauses on a pipeline's materialized view, streaming table or view. Each one has a unique name and a SQL Boolean constraint that is checked against every record. The pipeline UI tracks how many records pass and fail, so a sudden rise in flagged documents shows up as a metric instead of a silent drop in recall.
A constraint can't contain custom Python functions, external service calls, or subqueries that reference other tables. A toxicity model or PII detector therefore can't run inside EXPECT (...). Run the classifier, or ai_mask, in an earlier step that writes its result to a column, such as a score or a flag. The expectation then checks that column with plain SQL.
The action on violation sets how hard the filter is. Warn keeps the row and counts it. That suits a new classifier whose threshold you are still tuning, because you see how many documents it would remove before it removes any. Drop keeps flagged rows out of the target table, which is the usual setting for a content filter in front of an embedding table. Fail stops the update and rolls it back, which fits a rule where even one violating record means something upstream is broken.
| Action | Python | SQL | Effect on a flagged record |
|---|---|---|---|
| Warn (default) | expect | EXPECT (...) with no ON VIOLATION | Kept in the target; counted in metrics |
| Drop | expect_or_drop | ON VIOLATION DROP ROW | Removed from the target; counted in metrics |
| Fail | expect_or_fail | ON VIOLATION FAIL UPDATE | Update stops and the transaction rolls back |
@dp.expect_or_drop("valid_current_page", "current_page_id IS NOT NULL AND current_page_title IS NOT NULL")
CONSTRAINT valid_current_page EXPECT (current_page_id IS NOT NULL and current_page_title IS NOT NULL) ON VIOLATION DROP ROWQuarantine sits between warn and drop. Instead of discarding flagged rows, the pipeline tags each row with an is_quarantined column computed from the negation of the rules. Downstream views then read valid and quarantined rows separately. For problematic text, this lets a reviewer check what the classifier rejected while only clean rows go on to embedding.
@dp.table(
temporary=True,
partition_cols=["is_quarantined"],
)
@dp.expect_all(rules)
def trips_data_quarantine():
return (
spark.readStream.table("raw_trips_data").withColumn("is_quarantined", expr(quarantine_rules))
)Checkpoint 6 of 9· Fill the gap
Records that violate this rule must be kept out of the target table, and the pipeline must still count them in its metrics. The update must not stop. Which decorator fills the blank?
@dp. ? ("valid_current_page", "current_page_id IS NOT NULL AND current_page_title IS NOT NULL")expect_or_drop removes violating records from the target and still counts them in the metrics. Plain expect is the warn action, so violating records stay in the table. expect_or_fail stops the update and rolls it back.
Source: docs.databricks.comCheckpoint 7 of 9· Check yourself
A data engineer wants a pipeline expectation to keep documents that a toxicity model flags out of the embedding table. How should the model be wired into the pipeline?
A constraint must be plain SQL. It can't contain custom Python functions, external service calls, or subqueries that reference other tables. Run the classifier in an earlier step that writes a score column, and have the expectation test that column.
“Constraints must use valid SQL syntax and cannot contain the following:”Source: docs.databricks.com
5.Choosing the alternative
Start with the question of where the problem lives. If it is the whole document, drop it. If it is a few values inside a useful document, mask them. If the rule must run on every record of a recurring pipeline with visible metrics, declare it as an expectation on top of whichever of the first two you chose. The gateway is for text you couldn't clean at the source.
| Problem in the source | Recommended alternative | Why not the obvious other choice |
|---|---|---|
| Toxic, spam or profane entries | Toxicity classifier as a filter; drop before the embedding table | Masking would keep text that has no value |
| SSNs, names or salaries inside useful documents | ai_mask (or PII detection and redaction) in data preparation, then index | Dropping loses the knowledge; table ACLs leave the values in chunks |
| Content rule on a recurring ingestion | Score column plus expect_or_drop, or a quarantine split | Constraints cannot call the classifier themselves |
| Source you do not control and cannot clean | system.ai.detect_sensitive_data redacting at the gateway | Acts after retrieval and misses free-text entities |
| Corpus you have no right to use | Replace it with first-party or suitably licensed content | No text transformation changes the source's terms |
In the last row the problem isn't the text at all. A corpus scraped from third-party blogs with unclear reuse terms carries copyright and licensing risk however you chunk it, cite it or disclaim it in the system prompt. Smaller chunks, citation links and a fair-use note in the prompt all leave the same material in the index. Choosing the corpus is the first component of the data pipeline, so the mitigation is to replace the source with first-party content or a dataset whose license explicitly permits this use. The legal reasoning behind that decision is covered in legal and licensing requirements for data sources.
Checkpoint 8 of 9· Match them up
Match each data-source situation to the mitigation this lesson recommends for it.
Tap a term, then the definition that fits it.
Choose by where the problem lives. Drop documents that are wholly bad, mask entities in documents worth keeping, and enforce the rule as a score column plus expect_or_drop on a recurring pipeline. Use gateway redaction only for sources you can't clean. A licensing problem is about the source itself, so the fix is to replace the source.
“consider including a step in your pipeline to filter out these documents by using any metadata, such as applying a toxicity classifier to the document”Source: docs.databricks.com
Checkpoint 9 of 9· Exam question
A product team is building a RAG assistant using articles scraped from third-party blogs with unclear reuse terms. Legal flags that the scraped corpus creates copyright and licensing risk for the company. What should the team recommend to mitigate this risk in the data source?
Correct answer: A — Replace the scraped blog corpus with first-party content or a dataset under a license that explicitly permits this use
- A. Swapping in first-party content or a dataset with a license that clearly permits the intended use removes the legal risk at its source, since the corpus no longer relies on ambiguous reuse terms.
- B. Citing the source URL may be good practice for attribution, but it does not resolve the underlying licensing uncertainty about whether the company is permitted to reuse and redistribute the scraped content.
- C. Shortening the chunk size changes how much text is retrieved per query, but the content still originates from a corpus with unresolved reuse rights, so the licensing risk remains unchanged.
- D. A fair-use disclaimer in the prompt is not a legal determination and does not change the actual licensing status of the scraped content, so the underlying risk to the company persists.
Sources1
Sources
(6)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/agents/tutorials/ai-cookbook/quality-data-pipeline-ragOfficial docs
“any document sources you feed into your agent are potential attack vectors for bad actors to launch data poisoning attacks”
↩︎ What counts as problematic text, and where to stop it“raw source data should be ingested and stored in a target table. This approach ensures data preservation, traceability, and auditing.”
↩︎ What counts as problematic text, and where to stop it“applying a toxicity classifier to the document to produce a prediction you can use as a filter”
↩︎ Dropping documents with a safety classifier“Preprocess the extracted text to remove irrelevant or noisy information, such as headers, footers, or special characters.”
↩︎ Dropping documents with a safety classifier“Corpus composition and ingestion: Select the right data sources and content based on the specific use case.”
↩︎ Choosing the alternative“other documents may contain sensitive information you do not want to expose through your agent”
↩︎ Key concept“filtering out unwanted information, the next step is to break it down into smaller, manageable units called chunks.”
↩︎ Checkpoint“consider including a step in your pipeline to filter out these documents by using any metadata, such as applying a toxicity classifier to the document”
↩︎ Checkpoint - 2.
“The underlying language model can handle several languages, but this AI Function is tuned for English.”
↩︎ Masking entities and keeping the document“The ai_mask() function allows you to invoke a state-of-the-art AI model to mask specified entities in a given text”
↩︎ Exam trap 4“The ai_mask() function allows you to invoke a state-of-the-art AI model to mask specified entities in a given text using SQL.”
↩︎ Checkpoint - 3.https://docs.databricks.com/aws/en/data-governance/unity-catalog/service-policies/detect-sensitive-dataOfficial docs
“Databricks replaces each matched value with a placeholder token, such as [US_SSN], and forwards the rewritten content.”
↩︎ Masking entities and keeping the document“Names, locations, and organizations, and other free-text entities that need language understanding to identify.”
↩︎ Exam trap 1“Identifiers that are only a run of digits with no checksum or standard format”
↩︎ Prediction - 4.https://docs.databricks.com/aws/en/ldp/expectationsOfficial docs
“Expectations provide greater insight into data quality metrics and allow you to fail updates or drop records when detecting invalid records.”
↩︎ Enforcing content filters as pipeline expectations“When invalid records are unacceptable, use the expect_or_fail operator to stop execution immediately when a record fails validation.”
↩︎ Enforcing content filters as pipeline expectations“Constraints must use valid SQL syntax and cannot contain the following:”
↩︎ Exam trap 3“Constraints must use valid SQL syntax and cannot contain the following:”
↩︎ Checkpoint - 5.
“enable separate processing paths for valid and invalid records in downstream operations.”
↩︎ Enforcing content filters as pipeline expectations
Also cited
- https://docs.databricks.com/gcp/en/ldp/expectationsOfficial docs
“Retaining invalid records is the default behavior for expectations.”
↩︎ Exam trap 2“Retaining invalid records is the default behavior for expectations.”
↩︎ Prediction