Zero Labs
Industry News / AI

Unity Catalog is Blind. Here’s How We Gave It X‑Ray Vision with Purview.

Source · Towards AI By Chettri S.

From the publisher’s feed, collected in the ZeroLabs newsroom.

Govern your data lake end‑to‑end: architecture, secure setup, production notebooks, RBAC, and monitoring.End‑to‑end architecture of the Databricks–Purview governance pipeline. From left to right: external sources land raw data into ADLS Gen2. Auto Loader ingests into Bronze (append‑only). Silver cleanses, quarantines bad rows, and upserts via MERGE. Gold aggregates for reporting. A self‑hosted IR uses a managed identity to pull a read‑only PAT from Key Vault, scans Unity Catalog metadata, and pushes it to Purview. Separately, Spark’s OpenLineage listener sends lineage events directly to Purview. RBAC and dynamic masking enforce least privilege. A monitoring notebook checks row counts and rejection rates, posts a Teams card, and fails the job on threshold breach — with alerts landing back in Purview.Three months ago, I got paged at 2 AM. A dashboard that the CFO checks every morning showed California customer counts dropping by 40%. I spent the first hour checking whether the Gold table had been overwritten by a bad job. It hadn’t. The second hour was me manually chasing lineage: Which upstream table changed? Did the Silver cleanse start dropping null states? I finally found the root cause at 5 AM, a source system had changed its state column from two‑letter codes to full names, and the Silver validation regex rejected them.That night made me realise: governance isn’t about policies on a wiki. It’s about visibility when something breaks. Unity Catalog is great at enforcement so it stops the wrong person from seeing PII. But it doesn’t give you a searchable map of your pipeline. Microsoft Purview does. Connecting them turned my 3‑hour firefight into a 90‑second lineage lookup. This guide walks you through exactly how to build that bridge.1. Why you will hit the governance wallDatabricks Unity Catalog is excellent at enforcing governance, but it is blind to the outside world.It handles permissions beautifully: row‑level security, column masking, fine‑grained access. But it does not give a compliance officer a browsable catalog they can search without writing SQL. It does not give a data steward a lineage graph they can click through. And it does not give an on‑call engineer a quick answer when a Gold KPI moves unexpectedly.That is not a criticism, it’s a scope mismatch. Unity Catalog is an enforcement engine. Microsoft Purview is a visibility engine. You need both.Four problems disappear once they are connected:Regulatory compliance becomes provable. GDPR Article 30 requires a complete record of processing activities. HIPAA needs audit trails for every PHI access. The EU AI Act (2024) demands provenance tracking for AI training data. With Purview scanning Unity Catalog automatically, that record builds itself.The metadata gap closes: Data stewards can browse the entire catalog like every table, schema, classification, and owner without knowing SQL or holding a Databricks seat.Lineage becomes a debugging tool: Every upstream table that feeds a Gold metric is one click away. Multi‑hour root‑cause investigations become 90‑second lookups.AI governance stops being a future problem. For ML workloads, you need to prove which dataset trained which model. A lineage graph that covers Delta tables today extends to model registries tomorrow.2. The six moving partsThink of this as a relay race.Unity Catalog (Databricks): The brain. Holds all table metadata names, schemas, permissions, owners. The source of truth.Azure Key Vault: The bouncer. Holds secrets like API tokens. No credentials in scripts or notebooks.Self‑Hosted Integration Runtime (SHIR): The translator. A small Windows agent on a VM inside your Azure network. It talks to Databricks on one side and Purview on the other, translating Unity Catalog metadata into a format Purview understands.Microsoft Purview: The library. Where all metadata and lineage land. A search UI a compliance team can actually use, plus a REST API for automation.ADLS Gen2: The physical storage layer for Delta tables. Purview, once configured with a scan rule set, can classify files using built‑in system patterns (e.g., credit card numbers, email addresses). Hierarchical namespace must be on, and the firewall must allow the SHIR VM’s IP.OpenLineage: The open standard (Linux Foundation) that makes lineage automatic → see openlineage.io. Spark jobs emit structured lineage events; Purview ingests them natively via HTTP. No custom transformation required.Diagram1 — High‑level architecture of the Databricks‑Purview governance pipeline. Arrows show credential‑free data flow. The SHIR VM pulls a read‑only PAT from Key Vault using its managed identity, scans Unity Catalog, and pushes metadata to Purview. Separately, Spark jobs emit OpenLineage events directly to Purview’s lineage API.Purpose: Gives readers a single, shareable mental model before diving into configuration steps.3. The secure credential handshake (45 minutes)The secure credential chain is where most implementations break. Do it in this order.Step 1: Generate a narrowly scoped PATYou need a Databricks Personal Access Token. Give it USE CATALOG read‑only scope, nothing broader. A 90‑day expiry works; set a calendar reminder to rotate it.DATABRICKS_HOST="https://adb-.azuredatabricks.net"ADMIN_TOKEN=""curl -s -X POST \ "${DATABRICKS_HOST}/api/2.0/token/create" \ -H "Authorization: Bearer ${ADMIN_TOKEN}" \ -H "Content-Type: application/json" \ -d '{ "lifetime_seconds": 7776000, "comment": "purview-shir-scanner - read-only Unity Catalog scan" }' | jq '.token_value'Step 2: Store it in Key Vault immediatelyThe moment the token exists, it goes into Key Vault not into a .env file or a notebook variable.az keyvault secret set \ --vault-name "mycompany-kv-prod" \ --name "databricks-purview-pat" \ --value "" \ --expires "$(date -v+90d '+%Y-%m-%dT%H:%M:%SZ')"az keyvault set-policy \ --name "mycompany-kv-prod" \ --object-id "" \ --secret-permissions getUse Managed Identity for SHIR , not a username/password. The credential chain becomes fully automated: SHIR authenticates to Key Vault, fetches the PAT, scans Unity Catalog, and pushes metadata to Purview.Step 3: Deploy and configure SHIROn a Windows VM with outbound internet, install the Self‑Hosted Integration Runtime then during setup, point it at the Key Vault URL and secret name. Test that it can retrieve the PAT before moving on debugging SHIR auth errors afterward is painful.Step 4: Configure Spark for OpenLineageIn the Databricks cluster’s Advanced Options → Spark Config, add:On a Windows VM with outbound internet, install the Self‑Hosted Integration Runtime [Microsoft docs link].During setup, point it at the Key Vault URL and secret name. Test that it can retrieve the PAT before moving on debugging SHIR auth errors afterward is painful.Step 5: Run the first scanIn the Purview portal, go to New Scan → Azure Databricks. Enter the workspace URL, select the Key Vault secret, choose Unity Catalog as the source type. Hit run.Within a few minutes, Databricks tables appear in the Purview Data Map with schemas, classifications, and the first lineage edges already populated.At this point, the connection is live. Next comes actual data movement.4. Why the medallion pattern matters for governanceBefore the code, a quick word on why each layer exists.Bronze is your source of truth. Append‑only,untransformed. If something looks wrong three months from now, Bronze is what you audit against. Never modify it.Silver is your quality checkpoint. You validate, deduplicate, and standardise. Bad rows do not get silently dropped here, they go to a quarantine table that compliance can audit.Gold is your contract with consumers. Analysts, BI tools, and dashboards read from Gold. The data here is aggregated, optimised for query performance, and owned by a team accountable for its accuracy.Purview tracks lineage across all three layers automatically. Clicking any Gold table in the Purview UI will show every upstream table that fed it, with row counts and quality metrics attached.5. Bronze — land it fast, land it cleanBronze has one job: get data from source to a Delta table, exactly as it arrived, as efficiently as possible. Use Auto Loader (cloudFiles) for exactly‑once incremental ingestion with automatic schema evolution.The production notebook below includes a quality gate at the end: if zero rows are written, the job fails.# =============================================================================# BRONZE - Incremental Raw Ingestion (Auto Loader + Delta)# Purview lineage: ADLS source → prod_catalog.bronze.raw_customers# =============================================================================import loggingfrom pyspark.sql import functions as Ffrom pyspark.sql.types import StructType, StructField, StringType, IntegerTypelogger = logging.getLogger("bronze.ingest")SOURCE_PATH = "abfss://raw-data@prodadls.dfs.core.windows.net/customers/"CHECKPOINT_PATH = "abfss://checkpoints@prodadls.dfs.core.windows.net/bronze/raw_customers/"TARGET_TABLE = "prod_catalog.bronze.raw_customers"CUSTOMER_SCHEMA = StructType([ StructField("customer_id", IntegerType(), nullable=False), StructField("email", StringType(), nullable=True), StructField("first_name", StringType(), nullable=True), StructField("last_name", StringType(), nullable=True), StructField("state", StringType(), nullable=True), StructField("signup_date", StringType(), nullable=True),])spark.sql("CREATE CATALOG IF NOT EXISTS prod_catalog COMMENT 'Production data platform - governed by Microsoft Purview'")spark.sql("CREATE SCHEMA IF NOT EXISTS prod_catalog.bronze COMMENT 'Raw ingestion layer - append-only, no transformations'")raw_stream = ( spark.readStream .format("cloudFiles") .option("cloudFiles.format", "json") .option("cloudFiles.schemaLocation", CHECKPOINT_PATH + "_schema") .option("cloudFiles.schemaEvolutionMode", "addNewColumns") .option("maxFilesPerTrigger", "1000") .schema(CUSTOMER_SCHEMA) .load(SOURCE_PATH) .withColumn("ingested_at", F.current_timestamp()) .withColumn("source_file", F.input_file_name()) .withColumn("ingest_date", F.to_date(F.current_timestamp())))query = ( raw_stream.writeStream .format("delta") .option("checkpointLocation", CHECKPOINT_PATH) .option("mergeSchema", "true") .partitionBy("ingest_date") .outputMode("append") .trigger(availableNow=True) .toTable(TARGET_TABLE))query.awaitTermination()row_count = spark.table(TARGET_TABLE).count()dbutils.jobs.taskValues.set(key="bronze_row_count", value=row_count)assert row_count > 0, "Bronze FAILED: zero rows written - check upstream source"logger.info(f"✅ Bronze complete. rows={row_count:,}")Bronze ingestion notebook using Auto Loader. The trigger(availableNow=True) makes it Workflow‑friendly. The quality gate prevents silent failures.6. Silver — the quality checkpoint nobody skipsThis is the most important notebook in the pipeline. Silver is where bad data stops.Two design decisions worth holding firm on:Use MERGE, not overwrite. Overwriting Silver on every run kills incremental efficiency and removes any ability to audit what changed. MERGE (upsert by customer_id) keeps each run fast and history intact.Quarantine rejected rows, never drop them. Every row that fails validation goes to silver._quarantine_customers. Compliance can then see exactly which records were rejected and why.# =============================================================================# SILVER - Cleanse, Validate, and Upsert (MERGE)# Purview lineage: bronze.raw_customers → silver.customers# bronze.raw_customers → silver._quarantine_customers# =============================================================================import loggingfrom pyspark.sql import functions as Ffrom pyspark.sql import Windowfrom delta.tables import DeltaTablelogger = logging.getLogger("silver.cleanse")SOURCE_TABLE = "prod_catalog.bronze.raw_customers"TARGET_TABLE = "prod_catalog.silver.customers"QUARANTINE_TABLE = "prod_catalog.silver._quarantine_customers"spark.sql("CREATE SCHEMA IF NOT EXISTS prod_catalog.silver COMMENT 'Cleansed, validated, deduplicated data'")spark.sql(f""" CREATE TABLE IF NOT EXISTS {TARGET_TABLE} ( customer_id INT NOT NULL, email STRING, first_name STRING, last_name STRING, state STRING, signup_date DATE, updated_at TIMESTAMP, _source_file STRING ) USING DELTA PARTITIONED BY (state) TBLPROPERTIES ( 'delta.enableChangeDataFeed' = 'true', 'purview.classification' = 'customer_pii', 'purview.owner' = 'data-engineering@mycompany.com' ) COMMENT 'Cleansed customer master - SCD Type 1 upsert from bronze'""")spark.sql(f""" CREATE TABLE IF NOT EXISTS {QUARANTINE_TABLE} ( customer_id INT, raw_record STRING, rejection_reason STRING, rejected_at TIMESTAMP, source_file STRING ) USING DELTA COMMENT 'Rejected rows - auditable record for compliance'""")# Incremental readtry: last_watermark = spark.sql(f"SELECT MAX(updated_at) FROM {TARGET_TABLE}").collect()[0][0]except: last_watermark = Nonebronze_df = spark.table(SOURCE_TABLE)if last_watermark: bronze_df = bronze_df.filter(F.col("ingested_at") > last_watermark)EMAIL_REGEX = r'^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$'normalized_df = ( bronze_df .withColumn("email", F.lower(F.trim(F.col("email")))) .withColumn("first_name", F.initcap(F.trim(F.col("first_name")))) .withColumn("last_name", F.initcap(F.trim(F.col("last_name")))) .withColumn("state", F.upper(F.trim(F.col("state")))) .withColumn("signup_date", F.to_date(F.col("signup_date"), "yyyy-MM-dd")) .withColumn("updated_at", F.current_timestamp()))valid_df = ( normalized_df .filter(F.col("customer_id").isNotNull()) .filter(F.col("email").rlike(EMAIL_REGEX)) .filter(F.col("state").isNotNull()))rejected_df = ( normalized_df .filter( F.col("customer_id").isNull() | ~F.col("email").rlike(EMAIL_REGEX) | F.col("state").isNull() ) .withColumn("raw_record", F.to_json(F.struct("*"))) .withColumn("rejection_reason", F.when( F.col("customer_id").isNull(), F.lit("null_customer_id")).otherwise( F.when(~F.col("email").rlike(EMAIL_REGEX), F.lit("invalid_email")).otherwise( F.lit("null_state")))) .withColumn("rejected_at", F.current_timestamp()) .select("customer_id", "raw_record", "rejection_reason", "rejected_at", "source_file"))# Deduplicatew = Window.partitionBy("customer_id").orderBy(F.desc("ingested_at"))deduped_df = ( valid_df .withColumn("_rank", F.row_number().over(w)) .filter(F.col("_rank") == 1) .drop("_rank", "ingested_at", "ingest_date") .withColumnRenamed("source_file", "_source_file"))# MERGEDeltaTable.forName(spark, TARGET_TABLE).alias("tgt").merge( deduped_df.alias("src"), "tgt.customer_id = src.customer_id").whenMatchedUpdateAll().whenNotMatchedInsertAll().execute()if rejected_df.count() > 0: rejected_df.write.format("delta").mode("append").saveAsTable(QUARANTINE_TABLE)rejection_rate = rejected_df.count() / max(bronze_df.count(), 1)silver_count = spark.table(TARGET_TABLE).count()dbutils.jobs.taskValues.set(key="silver_row_count", value=silver_count)dbutils.jobs.taskValues.set(key="rejection_rate_pct", value=round(rejection_rate * 100, 2))assert rejection_rate logger.info(f"✅ Silver complete. rows={silver_count:,} rejected={rejection_rate:.2%}")Silver notebook with quarantine table. Every rejected row is preserved, and the rejection rate is monitored. Purview captures lineage to both the clean table and the quarantine table.7. Gold — serve fast, merge safeGold is the public face of the pipeline. Analysts and BI tools read from here, so query performance matters. Use Z‑Order to optimise for the most common filter patterns (state and report_date), and MERGE on rerun to avoid duplicate rows.# =============================================================================# GOLD - Customer Counts by State (Reporting-Ready)# Purview lineage: silver.customers → gold.customer_counts_by_state# =============================================================================import loggingfrom pyspark.sql import functions as Ffrom delta.tables import DeltaTablelogger = logging.getLogger("gold.aggregate")SOURCE_TABLE = "prod_catalog.silver.customers"TARGET_TABLE = "prod_catalog.gold.customer_counts_by_state"spark.sql("CREATE SCHEMA IF NOT EXISTS prod_catalog.gold COMMENT 'Aggregated, reporting-ready - served to BI tools'")spark.sql(f""" CREATE TABLE IF NOT EXISTS {TARGET_TABLE} ( state STRING NOT NULL, num_customers BIGINT NOT NULL, pct_of_total DOUBLE, report_date DATE NOT NULL ) USING DELTA TBLPROPERTIES ( 'purview.classification' = 'aggregated_analytics', 'purview.owner' = 'analytics-team@mycompany.com', 'purview.sensitivity' = 'public' ) COMMENT 'Daily customer count by US state - source: silver.customers'""")silver_df = spark.table(SOURCE_TABLE).filter(F.col("state").isNotNull())total_customers = silver_df.count()gold_df = ( silver_df .groupBy("state") .agg(F.count("*").alias("num_customers")) .withColumn("pct_of_total", F.round(F.col("num_customers") / F.lit(total_customers) * 100, 2)) .withColumn("report_date", F.current_date()))DeltaTable.forName(spark, TARGET_TABLE).alias("tgt").merge( gold_df.alias("src"), "tgt.state = src.state AND tgt.report_date = src.report_date").whenMatchedUpdateAll().whenNotMatchedInsertAll().execute()spark.sql(f"OPTIMIZE {TARGET_TABLE} ZORDER BY (state, report_date)")logger.info(f"✅ Gold complete. total_customers={total_customers:,}")Gold aggregation notebook with MERGE to avoid duplicates and Z‑Order for BI performance. Purview shows full lineage from Bronze → Silver → Gold.8. Three teams, three views of reality (RBAC)Governance without access control is decoration. Below is a least‑privilege model for three personas using Unity Catalog’s three‑level hierarchy.-- Analytics: Gold onlyGRANT USE CATALOG ON CATALOG prod_catalog TO analytics_team;GRANT USE SCHEMA ON SCHEMA prod_catalog.gold TO analytics_team;GRANT SELECT ON SCHEMA prod_catalog.gold TO analytics_team;REVOKE ALL PRIVILEGES ON SCHEMA prod_catalog.silver FROM analytics_team;REVOKE ALL PRIVILEGES ON SCHEMA prod_catalog.bronze FROM analytics_team;-- Engineering: read/write Silver and BronzeGRANT USE CATALOG ON CATALOG prod_catalog TO engineers_team;GRANT USE SCHEMA ON SCHEMA prod_catalog.bronze TO engineers_team;GRANT USE SCHEMA ON SCHEMA prod_catalog.silver TO engineers_team;GRANT SELECT, MODIFY ON SCHEMA prod_catalog.bronze TO engineers_team;GRANT SELECT, MODIFY ON SCHEMA prod_catalog.silver TO engineers_team;GRANT CREATE TABLE ON SCHEMA prod_catalog.silver TO engineers_team;-- Compliance: read everything, including quarantineGRANT USE CATALOG ON CATALOG prod_catalog TO compliance_team;GRANT USE SCHEMA ON SCHEMA prod_catalog.bronze TO compliance_team;GRANT USE SCHEMA ON SCHEMA prod_catalog.silver TO compliance_team;GRANT USE SCHEMA ON SCHEMA prod_catalog.gold TO compliance_team;GRANT SELECT ON SCHEMA prod_catalog.bronze TO compliance_team;GRANT SELECT ON SCHEMA prod_catalog.silver TO compliance_team;GRANT SELECT ON SCHEMA prod_catalog.gold TO compliance_team;Dynamic PII maskingAnalysts should not see raw email addresses. A single function handles this without application‑level changes:CREATE OR REPLACE FUNCTION prod_catalog.silver.mask_email( email STRING, groups ARRAY)RETURNS STRINGRETURN CASE WHEN array_contains(groups, 'engineers_team') OR array_contains(groups, 'compliance_team') THEN email ELSE regexp_replace(email, '^(.{2})(.*)(@.*)', '$1***$3')END;ALTER TABLE prod_catalog.silver.customers ALTER COLUMN email SET MASK prod_catalog.silver.mask_email USING COLUMNS (current_groups());When an analyst queries silver.customers, they see jo***@gmail.com. An engineer sees the full email. Purview picks up the masking policy as metadata on the next scan.9. The monitoring notebookA pipeline that fails silently is worse than no pipeline. This final notebook runs as the last task in the Databricks Workflow, after all three layers have completed. It posts a Teams card with key metrics. If anything crosses a threshold, it raises an exception, which fails the Workflow and triggers a job failure alert.Prerequisite: Create a Databricks secret scope named prod-secrets and add teams-webhook-url with your Teams incoming webhook URL.# =============================================================================# MONITOR - Post-run validation + Teams alerting# Last task in Databricks Workflow (depends on all 3 pipeline tasks)# =============================================================================import requests, loggingfrom datetime import datetimelogger = logging.getLogger("pipeline.monitor")TEAMS_WEBHOOK = dbutils.secrets.get(scope="prod-secrets", key="teams-webhook-url")bronze_count = dbutils.jobs.taskValues.get("bronze_ingest", "bronze_row_count", default=0)silver_count = dbutils.jobs.taskValues.get("silver_cleanse", "silver_row_count", default=0)rejection_rate = dbutils.jobs.taskValues.get("silver_cleanse", "rejection_rate_pct", default=0.0)MIN_BRONZE_ROWS = 100_000MAX_REJECTION_PCT = 5.0alerts = []if bronze_count if rejection_rate > MAX_REJECTION_PCT: alerts.append(f"⚠️ Rejection rate {rejection_rate:.1f}% exceeds 5%")status = "🔴 ALERT" if alerts else "✅ HEALTHY"card = { "@type": "MessageCard", "themeColor": "FF0000" if alerts else "00A86B", "summary": f"Pipeline {status}", "sections": [{ "activityTitle": f"Databricks Pipeline - {status}", "activitySubtitle": datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC"), "facts": [ {"name": "Bronze rows", "value": f"{bronze_count:,}"}, {"name": "Silver rows", "value": f"{silver_count:,}"}, {"name": "Rejection rate", "value": f"{rejection_rate:.1f}%"}, ] + [{"name": "Alert", "value": a} for a in alerts], }],}requests.post(TEAMS_WEBHOOK, json=card, timeout=10)if alerts: raise ValueError(f"Monitor FAILED: {'; '.join(alerts)}")logger.info("✅ Pipeline healthy. Purview lineage updated on next scan.")Monitoring notebook as a Workflow task. It reads task values from previous steps, posts a Teams card, and fails the job if thresholds are breached.10. What this costsPurview: One capacity unit (CU) is roughly $1,200 per month and handles approximately 2 million metadata operations (see Azure Purview pricing). For a small-to-medium team scanning daily, one CU is plenty.Self-Hosted IR: Runs on a cheap Windows VM, around $50 per month.Databricks compute: Normal pipeline costs. The governance layer adds almost no overhead.Key Vault: Costs are negligible.The biggest investment is your time to set it up, about half a day for a competent engineer.Final checklist before going livePAT token stored in Key Vault, not in codeSHIR installed on a VM with managed identityKey Vault access policy grants “Get” to that identityPurview scan configured and successfully completedAt least one pipeline step (Bronze, Silver, or Gold) has runA table is searchable in Purview and shows its columnsThe lineage graph shows edges between tablesCalendar reminder set to rotate the PAT in 90 daysMonitoring alert configured (Teams, email, or Slack)Final thoughtsGovernance is often treated as a compliance checkbox, something you suffer through once a quarter. But when your pipeline breaks at 2 AM, good governance turns into a superpower. With Databricks and Purview connected, you stop chasing lineage by hand. You stop explaining to auditors why you “don’t really have a catalog.” You start treating metadata as a first-class citizen.The pattern we’ve built here: Bronze quarantine, Silver validation with MERGE, Gold aggregates, RBAC with dynamic masking, and monitoring that actually catches failures, works for pipelines of any size. Start with one critical table. Prove the lineage works. Then expand.For unusual errors, the OpenLineage Slack community tends to be more helpful than official Microsoft documentation alone. And remember: the quarantine table is your safety net. Test it on a small dataset first. It’s entirely possible to build a “clean” pipeline that silently quarantines 20% of your data and no one notices for months. The monitoring thresholds are what save you. Tune them to your real data volume.Now go build that bridge. Your 2 AM self will thank you.ReferencesEuropean Parliament and Council. (2016). General Data Protection Regulation (GDPR), Article 30. EUR-Lex.European Parliament. (2024). EU Artificial Intelligence Act — Legislative resolution of 13 March 2024.OpenLineage. (n.d.). OpenLineage: An open standard for lineage metadata. Linux Foundation.Microsoft Azure. (2025). Azure Purview pricing — Capacity units.OpenLineage. (n.d.). OpenLineage Slack community.Unity Catalog is Blind. Here’s How We Gave It X‑Ray Vision with Purview. was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.