Inspiration

Data engineering teams face a silent, high-stakes crisis: as raw tables and staging data pipelines rapidly proliferate, sensitive Personally Identifiable Information (PII) like emails, phone numbers, and SSNs quietly slip into data platforms without documentation or masking policies. Manual audits are slow, error-prone, and reactive.

We were inspired by a simple question: What if an AI agent possessed full structural awareness of an organization’s data stack via DataHub, detected compliance risks on day zero, generated production-ready masking code, and updated the governance graph autonomously?

What it does

DataGuard is an end-to-end, metadata-driven governance agent that bridges the gap between context awareness and automated remediation:

Reads Context: Queries DataHub via the MCP Server / Python SDK to continuously inspect newly ingested dataset schemas and column metadata.

Detects & Analyzes: Evaluates column fields against privacy rules (GDPR, CCPA) to pinpoint untagged sensitive attributes.

Generates Remediation Code: Automatically compiles production-grade, anonymized dbt SQL models using secure hashing (SHA256) and masking (CONCAT/RIGHT) transformations.

Writes Back to DataHub: Crucially, DataGuard mutates the DataHub Context Graph by emitting Metadata Change Proposals (MCPs) to apply #PII-Sensitive tags and attach audit Assertions directly onto the dataset URN.

How we built it

Context Engine: Built on DataHub's Open Context Platform, utilizing the acryl-datahub Python SDK to interact with DataHub entities and schemas.

Agent Core: Developed in Python, combining rule-based schema inspection with metadata pattern extraction.

Code Generator: Built an automated code generation module that constructs dbt transformation models adhering to standard SQL data transformation specs.

Graph Writer: Implemented DataHub REST emitters to issue Metadata Change Proposals (MetadataChangeProposalWrapper), writing tags and data quality assertions directly back to the graph.

Challenges we ran into

Schema Mutability & Rest Emitters: Ensuring smooth Metadata Change Proposal (MCP) emissions to local DataHub GMS instances required deep dives into DataHub's aspect model specs (globalTags and assertionInfo).

Environment Configuration: Resolving pre-compiled Python binary wheel conflicts on local Windows Git Bash environments during automated build setups.

Accomplishments that we're proud of

Two-Way DataHub Integration: We didn't just read metadata from DataHub—we successfully closed the loop by writing back state updates (tags and assertions) to enrich the graph for future agents and human engineers.

Turnkey Outputs: Generated sample, testable dbt transformation artifacts in an /examples directory so judges and platform teams can verify code quality immediately.

Production-Ready Architecture: Clean, modular repository layout with 100% open-source compliance (Apache 2.0 License).

What we learned

The immense power of the Model Context Protocol (MCP) and DataHub's unified graph—having standard, queryable access to schemas and lineage fundamentally transforms how AI agents reason about data infrastructure.

How writing back execution results into a shared context platform prevents duplicate agent work and keeps human platform teams in the loop.

What's next for DataGuard: Autonomous PII Agent

Slack / Teams Integration: Sending human-in-the-loop notification prompts to dataset owners before auto-merging masking PRs into GitHub/GitLab.

Lineage-Aware Downstream Blocking: Leveraging DataHub’s column-level lineage graph to trace downstream BI dashboards or ML feature stores affected by newly flagged PII columns and automatically pausing untrusted pipelines.

Built With

Share this project:

Updates

posted an update

Here is the update post, evolution log, code snippet, and screenshot preview, completely revised without icons or emojis.


DataGuard: Autonomous PII Governance Agent — Development Update & Changelog

Public Update Post

Introducing DataGuard Agent: Autonomous PII Governance & dbt Remediation Engine

Data governance and compliance shouldn't mean endless manual tagging or writing tedious dbt masking queries. Meet DataGuard—an autonomous agent built for modern data stacks that detects untagged Personally Identifiable Information (PII), generates production-ready anonymized dbt models, and emits Metadata Change Proposals (MCPs) directly back to your DataHub catalog.

What's New in This Release?

  • Multi-Platform Target Selection: Choose target dataset URNs dynamically across PostgreSQL, Snowflake, and BigQuery directly from the Agent Control Panel.
  • Live Subprocess Execution Logging: Stream real-time terminal output, execution stages, and graph emission logs live in the Streamlit UI.
  • Anonymized dbt SQL Auto-Generation: Instantly compile dbt SQL transformation models with built-in MD5 hashing and regex masking for sensitive fields.
  • DataHub Graph Remediation: Emit automated MCP payloads to attach PII-Sensitive and GDPR-Restricted tags to target assets.
  • Adaptive Light/Dark Mode: Dynamic theme styling ensuring seamless usability across light and dark system settings.

Check out the full changelog below, grab the code snippet, and let us know what features you'd like to see next in the comments.


Product Evolution Log

Version 1.2.0 (Current Version)

  • Cross-Platform UTF-8 Subprocess Stream: Fixed Windows character encoding issues (cp1252 console crash) by enforcing UTF-8 streams for real-time subprocess logging across OS environments.
  • Full DataHub Client Mocking Fallback: Added defensive import fallbacks (DataHubGraphWriter, attach_pii_tags, and emit_pii_assertion) to ensure smooth demo execution in offline or cloud sandbox environments like Streamlit Community Cloud.
  • Theme-Native Visual System: Updated metric cards and navigation tabs to utilize Streamlit CSS variables (var(--secondary-background-color)), maintaining dark and light mode styling without visual breakage.

Version 1.1.0

  • Live Log Terminal Integration: Replaced static execution displays with dynamic subprocess.Popen log streaming.
  • DataHub Graph Writer Module: Integrated src/datahub_client/mcp_emitter.py for direct metadata assertions and tag emission.
  • Streamlit Web Interface: Built an interactive dashboard with audit tables, code previewers, and JSON payload inspection windows.

Version 1.0.0

  • Core Detection Engine: Initial release of src/agent/pii_detector.py for identifying sensitive schema patterns (email, phone_number, ssn).
  • dbt Template Engine: Auto-compilation of SQL transformation models inside examples/generated_dbt_model.sql.

Code Snippet Highlights

Here is the exact implementation used inside app.py to spawn the background agent process, set the PYTHONPATH, handle Windows UTF-8 execution safely, and stream terminal logs directly to the user interface:

import os
import subprocess
import streamlit as st

if st.sidebar.button("Trigger Agent Execution", use_container_width=True):
  with st.sidebar.spinner("Running agent..."):
    try:
      # Pass current environment with PYTHONPATH set to the root folder
      env = os.environ.copy()
      env["PYTHONPATH"] = "."
      env["PYTHONIOENCODING"] = "utf-8"  # Enforces UTF-8 output on Windows

      process = subprocess.Popen(
          ["python", "src/agent/runner.py"],
          stdout=subprocess.PIPE,
          stderr=subprocess.STDOUT,
          text=True,
          encoding="utf-8",
          errors="replace",
          bufsize=1,
          env=env,
      )

      log_box = st.sidebar.empty()
      full_logs = ""

      # Stream the output live to the UI
      for line in process.stdout:
        full_logs += line
        log_box.code(full_logs, language="bash")

      process.wait()
      if process.returncode == 0:
        st.sidebar.success("Pipeline executed successfully!")
      else:
        st.sidebar.error("Execution failed. Check log output.")
    except Exception as e:
      st.sidebar.error(f"Error: {e}")


Application Screenshot Preview

+---------------------------------------------------------------------------------------------+
| Agent Control Panel        | DataGuard: Autonomous PII Governance Agent                     |
| Target Dataset URN:        | Metadata-Driven Compliance, dbt Code Generation, & Graph    |
| [ analytics.users    v ]   |                                                             |
|                            | +-------------------+ +-------------------+ +-----------------+ |
| [ Trigger Execution ]      | | Target Dataset    | | Detected PII      | | Compliance      | |
|                            | | analytics.users   | | 2 (High Risk)     | | GDPR Enforced   | |
| Live Execution Logs:       | +-------------------+ +-------------------+ +-----------------+ |
| [1/4] Fetching URN...      |                                                             |
| [2/4] Detected: Email/Phone| [ Generated dbt Model ] [ DataHub MCP ] [ Audit Report ]     |
| [3/4] dbt Model Saved      | ----------------------------------------------------------- |
| [4/4] DataHub Tags Emitted | SELECT                                                      |
|                            |     MD5(user_id) AS user_id,                                |
| Agent Status: Online       |     REGEXP_REPLACE(email, '(?i)(?<=^.).*?(?=@)', '***') ... |
| Mode: Offline Fallback     | FROM {{ source('production', 'users') }}                    |
+---------------------------------------------------------------------------------------------+

Log in or sign up for Devpost to join the conversation.