Enterprise data platforms manage tens of thousands of tables, schemas, and views spanning BigQuery, Spanner, and Cloud Storage. While Knowledge Catalog provides a centralized metadata foundation, enterprise catalogs suffer from continuous metadata decay: severed pipeline lineage, unclassified PII, missing policy tags, blank descriptions, and unmonitored schema mutations.
Static rule-based validation scripts fall short because metadata evaluation requires semantic reasoning: understanding business domain context, inferring privacy sensitivity from column names, and prioritizing compliance risks.
In this article, we will build an automated metadata governance service using Python, Google Cloud knowledge catalog, Gemini 3 Pro, Gemini 3.8 Flash, and Google Cloud Run. Instead of packing all logic into a single monolithic script, we split the workflow across specialized audit sub-agents coordinated by a central orchestrator.
Architecture overview
The system follows an asynchronous agent orchestration pattern:
-
Catalog Extractor: Collects raw entry schemas, column definitions, existing tags, and linked resource IDs from knowledge catalog.
-
Lineage Auditor: Queries Dataplex Lineage links to detect broken DAGs, orphaned tables, and terminal sinks.
-
Taxonomy & Security Agent (Gemini 3 Pro): Inspects schemas and attached tags to spot unclassified PII, missing column-level policy tags, and unmasked secrets.
-
Documentation & Drift Agent (Gemini 3.8 Flash): Flags undocumented tables and columns, proposing business descriptions and glossary tags.
-
Remediation Orchestrator: Synthesizes sub-agent findings into a composite Catalog Health Score and generates an automated Dataplex Tag remediation payload.
1. Setup dependencies
Create a requirements.txt file using the updated google-genai SDK (version 2.0.0+):
fastapi>=0.110.0
uvicorn>=0.28.0
httpx>=0.27.0
google-cloud-dataplex>=2.0.0
google-cloud-datacatalog>=3.19.0
google-cloud-datacatalog-lineage>=0.3.0
google-cloud-bigquery>=3.20.0
google-genai>=2.0.0
pydantic>=2.6.0
opentelemetry-api>=1.24.0
opentelemetry-sdk>=1.24.0
opentelemetry-instrumentation-fastapi>=0.45b0
2. Reading metadata from Knowledge Catalog
The first component is catalog_client.py. It pulls the target entry’s schema, column modes, and attached Dataplex tags, isolating the Dataplex API calls so downstream agents receive clean Python dictionaries.
catalog_client.py
from google.cloud import datacatalog_v1
from google.cloud import dataplex_v1
class DataplexMetadataClient:
def __init__(self, project_id: str, location: str = "us-central1"):
self.project_id = project_id
self.location = location
self.datacatalog_client = datacatalog_v1.DataCatalogClient()
self.dataplex_client = dataplex_v1.DataplexServiceClient()
def get_table_metadata(self, entry_name: str) -> dict:
"""Fetches table schema, column descriptions, and attached tags."""
try:
entry = self.datacatalog_client.get_entry(name=entry_name)
tags = list(self.datacatalog_client.list_tags(parent=entry.name))
columns = []
if entry.schema and entry.schema.columns:
for col in entry.schema.columns:
columns.append({
"name": col.column,
"type": col.type_,
"description": col.description or "",
"mode": col.mode or "NULLABLE",
})
attached_tags = [
{
"template": t.template_display_name or t.template,
"fields": {
k: str(v.string_value or v.enum_value)
for k, v in t.fields.items()
},
}
for t in tags
]
return {
"entry_name": entry.name,
"display_name": entry.display_name,
"description": entry.description or "",
"linked_resource": entry.linked_resource,
"columns": columns,
"tags": attached_tags,
}
except Exception as e:
return {"error": f"Failed to retrieve entry {entry_name}: {str(e)}"}
3. Building specialized governance sub-agents
A. Lineage Auditor: verifying pipeline continuity
Rather than returning a binary pass/fail, lineage_agent.py diagnoses the structural status of the dependency graph using the Data Catalog Lineage API.
# lineage_agent.py
from google.cloud import datacatalog_lineage_v1
class LineageAuditor:
def __init__(self, project_id: str, location: str = "us-central1"):
self.client = datacatalog_lineage_v1.LineageClient()
self.location = location
self.project_id = project_id
def audit_lineage(self, linked_resource: str) -> dict:
"""Verifies if the table has registered upstream and downstream lineage links."""
parent = f"projects/{self.project_id}/locations/{self.location}"
request = datacatalog_lineage_v1.SearchLinksRequest(
parent=parent,
target=datacatalog_lineage_v1.EntityReference(
fully_qualified_name=linked_resource
),
)
links = list(self.client.search_links(request=request))
has_upstream = any(
link.target.fully_qualified_name == linked_resource for link in links
)
has_downstream = any(
link.source.fully_qualified_name == linked_resource for link in links
)
gaps = []
if not links:
gaps.append("CRITICAL_LINEAGE_GAP: No upstream or downstream lineage registered.")
elif not has_upstream:
gaps.append("ORPHAN_SOURCE_GAP: Table has downstream consumers but no documented source pipeline.")
elif not has_downstream:
gaps.append("TERMINAL_SINK_GAP: Table has upstream inputs but no registered downstream consumers.")
return {
"link_count": len(links),
"lineage_gaps": gaps,
"status": "PASS" if not gaps else "FAIL",
}
B. Security & Taxonomy Auditor: detecting PII with Gemini 3 Pro
Schema data types (like STRING or BYTES) provide no explicit signal about whether a column contains sensitive personally identifiable information.
In security_agent.py, we employ Gemini 3 Pro with structured JSON output mode to inspect column names, infer security implications, and check for missing fine-grained IAM policy tags.
# security_agent.py
import json
from google import genai
from google.genai import types
class SecurityTaxonomyAuditor:
def __init__(self):
self.client = genai.Client()
def audit_security_and_pii(
self,
table_name: str,
columns: list[dict],
existing_tags: list[dict]
) -> dict:
"""Uses Gemini 3 Pro to detect unclassified PII, missing policy tags, and masking gaps."""
schema_context = json.dumps(columns, indent=2)
tags_context = json.dumps(existing_tags, indent=2)
prompt = f"""
You are a Cloud Data Governance and Compliance Expert inspecting Google Cloud Dataplex metadata.
Table: {table_name}
Columns:
{schema_context}
Existing Applied Tags:
{tags_context}
Tasks:
1. Identify any columns containing PII, Financial Data, Secrets, or Credentials that LACK policy/taxonomy tags.
2. Identify whether column-level masking policies appear missing for sensitive fields.
3. Output strict JSON with the following structure:
{{
"unclassified_pii_columns": ["col1", "col2"],
"missing_policy_tags": ["High_Security_PII", "Mask_Email"],
"risk_level": "HIGH | MEDIUM | LOW",
"justification": "Clear reasoning behind the risk classification"
}}
"""
response = self.client.models.generate_content(
model="gemini-3-pro",
contents=prompt,
config=types.GenerateContentConfig(
response_mime_type="application/json"
),
)
return json.loads(response.text)
C. Documentation & Drift Auditor: synthesizing descriptions with Gemini 3.8 Flash
Generating rich documentation across hundreds of columns requires speed and cost efficiency. drift_agent.py leverages Gemini 3.8 Flash—engineered for long-horizon agent execution and enterprise workflows—to detect documentation gaps and produce contextual business descriptions.
# drift_agent.py
import json
from google import genai
from google.genai import types
class DriftAndQualityAuditor:
def __init__(self):
self.client = genai.Client()
def audit_documentation_and_drift(self, table_metadata: dict) -> dict:
"""Evaluates documentation completeness and generates glossary recommendations using Gemini 3.8 Flash."""
columns = table_metadata.get("columns", [])
empty_cols = [c["name"] for c in columns if not c.get("description")]
table_desc = table_metadata.get("description", "")
prompt = f"""
Evaluate metadata completeness for database table: {table_metadata.get('display_name')}.
Table Description: '{table_desc}'
Columns with empty descriptions: {empty_cols}
Total columns: {len(columns)}
Produce recommended business descriptions for missing attributes and identify catalog gaps.
Respond in strict JSON:
{{
"missing_table_description": {"true" if not table_desc else "false"},
"missing_column_descriptions_count": {len(empty_cols)},
"missing_column_list": {json.dumps(empty_cols)},
"suggested_table_description": "Clear professional description if missing",
"glossary_terms_needed": ["Term1", "Term2"]
}}
"""
response = self.client.models.generate_content(
model="gemini-3.8-flash",
contents=prompt,
config=types.GenerateContentConfig(
response_mime_type="application/json"
),
)
return json.loads(response.text)
4. Orchestration & Catalog Health Index
In orchestrator.py, we expose a FastAPI endpoint /audit-entry. The orchestrator executes parallel sub-agent audits, calculates an explainable Catalog Health Score (0–100), and outputs a remediation payload ready for Dataplex Tag application.
# orchestrator.py
import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from catalog_client import DataplexMetadataClient
from lineage_agent import LineageAuditor
from security_agent import SecurityTaxonomyAuditor
from drift_agent import DriftAndQualityAuditor
app = FastAPI(title="Dataplex Autonomous Metadata Governance Engine")
PROJECT_ID = os.environ.get("GCP_PROJECT_ID", "your-gcp-project")
metadata_client = DataplexMetadataClient(project_id=PROJECT_ID)
lineage_auditor = LineageAuditor(project_id=PROJECT_ID)
security_auditor = SecurityTaxonomyAuditor()
drift_auditor = DriftAndQualityAuditor()
class AuditRequest(BaseModel):
entry_name: str # Format: projects/{p}/locations/{l}/entryGroups/{g}/entries/{e}
@app.post("/audit-entry")
async def run_metadata_audit(request: AuditRequest):
meta = metadata_client.get_table_metadata(request.entry_name)
if "error" in meta:
raise HTTPException(status_code=404, detail=meta["error"])
linked_resource = meta.get("linked_resource", "")
# Execute audits across sub-agents
lineage_results = lineage_auditor.audit_lineage(linked_resource)
security_results = security_auditor.audit_security_and_pii(
table_name=meta.get("display_name", ""),
columns=meta.get("columns", []),
existing_tags=meta.get("tags", []),
)
drift_results = drift_auditor.audit_documentation_and_drift(meta)
# Calculate explainable score penalties
penalties = 0
if lineage_results["lineage_gaps"]:
penalties += 30
if security_results["unclassified_pii_columns"]:
penalties += 40
if drift_results["missing_table_description"]:
penalties += 15
if drift_results["missing_column_descriptions_count"] > 0:
penalties += 15
health_score = max(0, 100 - penalties)
return {
"entry": meta["display_name"],
"catalog_health_score": health_score,
"gaps_detected": {
"lineage": lineage_results["lineage_gaps"],
"security_and_taxonomy": security_results,
"documentation_and_glossary": drift_results,
},
"remediation_action": {
"apply_dataplex_aspect_tag": {
"template": f"projects/{PROJECT_ID}/locations/us-central1/tagTemplates/governance_aspect",
"fields": {
"audit_status": "FLAGGED_FOR_REMEDIATION",
"pii_risk_level": security_results.get("risk_level", "LOW"),
"suggested_description": drift_results.get(
"suggested_table_description", ""
),
},
}
},
}
5. Packaging & deployment to Google Cloud Run
Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
ENV PORT=8080
CMD uvicorn orchestrator:app --host 0.0.0.0 --port ${PORT}
Deployment commands
Enable the required APIs:
gcloud services enable \
run.googleapis.com \
datacatalog.googleapis.com \
dataplex.googleapis.com \
datalineage.googleapis.com \
aiplatform.googleapis.com
Assign necessary IAM roles to the Cloud Run service account:
PROJECT_ID=$(gcloud config get-value project)
PROJECT_NUM=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")
SA_EMAIL="${PROJECT_NUM}-compute@developer.gserviceaccount.com"
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:${SA_EMAIL}" \
--role="roles/datacatalog.viewer"
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:${SA_EMAIL}" \
--role="roles/datacatalog.tagEditor"
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:${SA_EMAIL}" \
--role="roles/datalineage.viewer"
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:${SA_EMAIL}" \
--role="roles/aiplatform.user"
Deploy the container service to Cloud Run:
gcloud run deploy dataplex-metadata-agent \
--source . \
--region us-central1 \
--set-env-vars "GCP_PROJECT_ID=${PROJECT_ID}" \
--no-allow-unauthenticated \
--quiet
6. Testing the audit pipeline
Trigger the audit against any BigQuery table registered in Dataplex:
SERVICE_URL=$(gcloud run services describe dataplex-metadata-agent --region us-central1 --format="value(status.url)")
# Format the Dataplex Entry Name for a target BigQuery table
TARGET_FQN="bigquery.googleapis.com/projects/${PROJECT_ID}/datasets/analytics_dw/tables/user_transactions"
ENTRY_NAME="projects/${PROJECT_ID}/locations/us-central1/entryGroups/@bigquery/entries/$(echo -n "$TARGET_FQN" | base64)"
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-identity-token)" \
-H "Content-Type: application/json" \
-d "{\"entry_name\": \"${ENTRY_NAME}\"}" \
"${SERVICE_URL}/audit-entry"
Conclusion
Modern data governance cannot rely on human stewards manually auditing thousands of catalog entries. By orchestrating specialized sub-agents powered by Gemini 3 Pro and Gemini 3.8 Flash, teams can turn Knowledge Catalog from a passive inventory into an active, self-healing governance engine.
Happy cataloging!
