Skip to content
aswin-giridharPublic

About

A pre-deployment release gate for ML models, backed by DataHub. Walks lineage, blocks unsafe releases with named gaps, writes the verdict back into the graph.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

mlgate — a pre-deployment release gate for ML models, backed by DataHub

Built for Build with DataHub: The Agent Hackathon — challenge category: Production ML Agents.

mlgate answers one question a model owner has to answer before every production deploy, and currently answers by hand: is the data this model learned from actually trustworthy?

It walks the model's lineage backwards through DataHub — deployment → model → features → source datasets — evaluates a rule pack against every asset it finds, returns PASS / BLOCK with named blockers, and writes the verdict back into DataHub so the next person or agent inherits the finding instead of rediscovering it.

$ mlgate check urn:li:mlModel:(urn:li:dataPlatform:mlflow,order_fraud_scorer_v3,PROD) --publish
mlgate  order_fraud_scorer_v3   [pack: base@cfd736294999]
  urn:li:mlModel:(urn:li:dataPlatform:mlflow,order_fraud_scorer_v3,PROD)

  Walked 9 assets across the model's upstream lineage

  BLOCK   3 blocker(s), 5 warning(s)
  ──────────────────────────────────────────────────────────────────
  [BLOCK] device_events              no freshness assertion on this training input
  [BLOCK] device_events              no owner assigned
  [BLOCK] device_events              column 'device_fingerprint' is tagged PII, reaches a feature, and has no description
  [WARN ] order_fraud_scorer_v3      model has no owner assigned
  [WARN ] ORDERS                     15 schema change(s) since training (add)
  [WARN ] device_events              4 schema change(s) since training (add)
  [WARN ] CUSTOMERS                  22 schema change(s) since training (add)
  [WARN ] order_fraud_features_v3    last materialized 41d ago (limit 30d)

  ✓ JUnit written to examples/junit-BLOCK.xml
  Writing back to DataHub ...
   + tag   urn:li:tag:Governance:ReleaseBlocked -> model
   + tag   urn:li:tag:Governance:MissingOwner -> b2fd91.order_entry_db.fraud.device_events
   + tag   urn:li:tag:Governance:NoFreshnessAssertion -> b2fd91.order_entry_db.fraud.device_events
   + tag   urn:li:tag:Governance:SchemaDrift -> b2fd91.order_entry_db.fraud.device_events
   + tag   urn:li:tag:Governance:UndocumentedPII -> b2fd91.order_entry_db.fraud.device_events
   + tag   urn:li:tag:Governance:SchemaDrift -> b2fd91.order_entry_db.order_entry.orders
   + tag   urn:li:tag:Governance:SchemaDrift -> b2fd91.order_entry_db.order_entry.customers
   + tag   urn:li:tag:Governance:StaleFeatures -> order_fraud_features_v3
   + props release_blockers, release_checked_at, release_findings_fingerprint, release_gate_version, release_readiness, release_rule_pack, release_rule_pack_hash, release_warnings
   + doc   Model Release Dossier -> DataHub Documentation tab
   + doc   file:///mnt/e/Hackathon/build_with_datahub_2026/mlgate/examples/dossier-BLOCK.md
   + run   gate run recorded: BLOCK @ 2026-08-10T19:29:38+00:00
   ✓ verified — read back 8 tag(s) and 8 property(ies) from DataHub
   ✓ dossier written to examples/dossier-BLOCK.md

Exit code 1, so it drops straight into CI.


The problem

Before a model ships, someone should check whether its training inputs are owned, documented, monitored, and unchanged since training. Doing that by hand means opening the catalog and walking a dozen tables one at a time. So in practice nobody does it, and models reach production trained on tables nobody owns, containing PII nobody flagged, from sources that quietly stopped updating weeks ago.

DataHub already stores every one of those facts — owners, PII tags, freshness assertions, lineage, schema history. What it does not do is form an opinion about them. There is no "is this model safe to ship?" answer anywhere in the product.

mlgate is that opinion, and it puts the answer back in the catalog.


How it uses DataHub

Reads (entity API, /entities/{urn}):

Entity What is read
mlModel MLModelProperties — features, deployments, training metadata, ownership
mlFeature MLFeatureProperties.sources — the datasets behind each feature
mlFeatureTable MLFeatureTableProperties — materialization recency
dataset SchemaMetadata (columns, PII tags, descriptions), Ownership, DatasetProperties
mlModelDeployment deployment context

It also reads DataHub's relationship graph and Timeline API:

API Used for
GET /relationships?direction=OUTGOING&types=DownstreamOf transitive upstream lineage (depth-capped, cycle-safe)
GET /relationships?direction=INCOMING&types=Asserts real Assertion entities on a dataset
GET /openapi/v3/entity/assertion/{urn} assertion type (FRESHNESS) — note the legacy /entities API returns HTTP 500 for assertions
GET /openapi/v2/timeline/v1/{urn}?categories=TECHNICAL_SCHEMA real schema changes since the model trained

Writes back — four distinct paths:

Write Target Aspect
Governance:ReleaseBlocked / ReleaseApproved the model GlobalTags
Governance:MissingOwner, UndocumentedPII, NoFreshnessAssertion, SchemaDrift, StaleFeatures each offending asset GlobalTags
release_readiness, release_checked_at, release_rule_pack, release_blockers, release_warnings the model MLModelProperties.customProperties
Model Release Dossier the model InstitutionalMemory

Tag writes are read-modify-write — GlobalTags is a full-replace aspect, so blindly emitting would delete tags somebody else set.

The seeder also contributes ML metadata to the graph: showcase-ecommerce ships no ML entities at all, so seed/emit_lineage.py emits the full dataset → MLFeatureTable → MLModel → MLModelDeployment chain on top of the real order_entry tables.


Two design decisions worth calling out

1. It reads the entity API, never the search API. DataHub's search index lags the entity store. Immediately after a write, a search returns zero hits while the entity is already durably stored. A gate that walked lineage via search would find nothing, report no findings, and print PASS — approving a model for production because an index was a few seconds behind. So: entity API only, and an empty walk raises an error (exit 2) rather than passing. "Absent" and "broken" must never produce the same value.

2. The verdict is deterministic — BLOCK iff any finding has severity BLOCK. No score, no threshold, no tuned constant. A gate with a calibrated number is a gate whose number can be wrong in a way nobody notices. Severity lives in the rule pack, where a human sets it deliberately.

And it is verified to separate: the repo ships a deliberately broken model and a clean one, and make verify asserts BLOCK and PASS respectively. A gate that nothing can pass — or that everything passes — is not measuring anything.


Rule packs

Rule logic is Python (registered by id); rule policy is YAML. Two packs ship:

  • base — generic ML release hygiene
  • regulated — same rules, tightened policy for credit decisioning, insurance pricing or clinical decision support: staleness limit drops 30d → 14d, and schema drift plus an unowned model become blockers
# mlgate/packs/base.yaml
rules:
  no_owner:              { severity: BLOCK, applies_to: [dataset] }
  undocumented_pii:      { severity: BLOCK, pii_tag: PII }
  no_freshness_assertion:{ severity: BLOCK }
  stale_feature_table:   { severity: WARN,  max_age_days: 30 }
  schema_drift_since_training: { severity: WARN }
  model_unowned:         { severity: WARN }
  undeployed_or_undocumented_deployment: { severity: WARN }

Adding a rule is one decorated function plus one YAML entry.


Setup

Requires Docker, Python 3.10+, and ~8 GB for DataHub.

# 1. DataHub
pip install 'acryl-datahub[datahub-rest]'
datahub docker quickstart                 # ~9 min cold start; UI at :9002 (datahub/datahub)
datahub datapack load showcase-ecommerce  # real e-commerce catalog to build on

# 2. mlgate
git clone <this-repo> && cd mlgate
pip install -r requirements.txt
export DATAHUB_GMS_URL=http://localhost:8080
export PYTHONPATH=.

# 3. Seed the ML lineage graph (showcase-ecommerce ships no ML entities)
python seed/emit_lineage.py

# 4. Gate the broken model, and write the verdict back
python -m mlgate.cli check "urn:li:mlModel:(urn:li:dataPlatform:mlflow,order_fraud_scorer_v3,PROD)" --publish

# 5. Gate the clean model
python -m mlgate.cli check "urn:li:mlModel:(urn:li:dataPlatform:mlflow,order_fraud_scorer_v4,PROD)"

Then open http://localhost:9002, find order_fraud_scorer_v3, and see the governance tags, readiness properties and dossier the gate just wrote.

Use in CI

- name: Gate model release
  run: python -m mlgate.cli check "$MODEL_URN" --pack regulated --publish
  # exit 0 = PASS, 1 = BLOCK, 2 = could not evaluate

Use it from an agent — the DataHub Skill

mlgate ships as a DataHub Skill (skills/datahub-release-gate/SKILL.md), written to the same conventions as the official datahub-skills registry, so an agent can drive the gate conversationally rather than by memorising a CLI.

> is order_fraud_scorer_v3 safe to ship?

The skill instructs the agent to confirm the URN before gating, pick a rule pack (and say if it thinks regulated applies rather than silently escalating severity), explain each blocker in terms of why it matters for this model, ask before --publish since that mutates a catalog other people read, and quote the post-write verification rather than the write's own success response.

It also encodes the failure mode that matters most: never report PASS when you could not evaluate.

Pair it with the DataHub MCP server for catalog search and lineage exploration — .mcp.json in this repo is ready to use:

uvx mcp-server-datahub@latest      # DataHub Core; NOT http://<gms>:8080/mcp — see note below

Note for DataHub Core users: the Agent Context Kit docs give the self-hosted MCP endpoint as http://<gms-host>:8080/mcp. That path returns 404 on Core — it's the Cloud shape. Core runs MCP as a separate local process via uvx mcp-server-datahub@latest.

Tests

python -m pytest tests/ -q       # 31 unit tests, no DataHub required
bash tests/acceptance.sh         # 45 end-to-end checks against live DataHub
make verify                      # the separation proof, on its own

The tests run entirely on synthetic Entity objects, so you can evaluate the rule logic without standing up DataHub. The load-bearing one is test_gate_separates — it asserts a broken model BLOCKs and a clean one PASSes under the same rules. There is also a test that a documented PII column is not flagged: a rule that fires on everything is as useless as one that fires on nothing.

tests/acceptance.sh exercises every command, flag, rule and error path against a live DataHub and asserts the observed behaviour — exit codes, which rules fire, that a waiver expires, that --dry-run writes nothing, that fix then --reset round-trips. Its output is committed at examples/acceptance-run.txt.

The harness was itself validated by mutation: breaking the verdict logic (always PASS) and disabling a rule both produce failures, and reverting returns it to green. A suite that cannot fail is not measuring anything.

Note if you run mlgate fix against the demo: it genuinely repairs device_events, which means the broken model stops being broken. python seed/emit_lineage.py --reset restores the defects so the demo can be run again.

Commands

mlgate check <model-urn> [--pack base|regulated] [--publish|--dry-run] [--junit F]
mlgate scan  [--workers N]         # fleet view: which models would fail today?
mlgate watch [--interval 300]      # re-gate on a schedule; report only changes
mlgate fix   <model-urn> --rule no_owner --rule no_freshness_assertion [--dry-run]

scan answers the question a platform lead actually asks:

  VERDICT   BLOCK  WARN  MODEL
  ──────────────────────────────────────────────────────────────
  BLOCK         4     5  order_fraud_scorer_v3
  ERROR         0     0  mlgate_spike_model  (LineageError)
  PASS          0     3  order_fraud_scorer_v4

  1 of 3 would be blocked today; 1 could not be evaluated

Note that an un-evaluable model is reported as ERROR, never folded in with the passes.

fix writes the missing metadata back — and refuses what it cannot do honestly:

  applied 2 fix(es):
   + owner urn:li:corpuser:datahub -> device_events
   + freshness assertion -> device_events
   - skipped: undocumented_pii — a generated description would satisfy the rule
     while telling a human nothing — document the column deliberately

watch — a monitor, not just a checkpoint

A gate answers "is this safe now?" once. But a model that passed on Monday is unsafe on Thursday when an upstream loses its owner or a freshness assertion starts failing — and nobody re-runs the gate.

mlgate watch closes that loop. It re-gates on a schedule and compares each model's findings fingerprint against the one mlgate last wrote to DataHub, so unchanged models stay silent and only transitions are reported:

  mlgate watch   every 300s   [pack: base]
  Ctrl-C to stop. Only CHANGES are reported.

  round 1: 3 model(s), no change

  CHANGED       order_fraud_scorer_v3  BLOCK  (3 blocker(s), 5 warning(s))
    fingerprint ce3097e771da07ec -> 3a8e727b4c02966e
      [BLOCK] device_events: no freshness assertion on this training input
      ↳ verdict written back to DataHub

Losing visibility of a model (lineage gone, DataHub unreachable) is reported as ERROR — a model you can no longer evaluate is a change worth shouting about, and silence there would be the bug.

Exemptions — why the gate stays switched on

The usual fate of a release gate is being disabled the first time it blocks something with a known, accepted gap. So waivers are first-class, and every one must carry a reason, an expiry and an approver — the pack loader rejects it otherwise:

exemptions:
  - rule: no_freshness_assertion
    asset: "*device_events"          # glob; a bare token still matches as substring
    reason: "legacy fraud source; assertion tracked in DATA-4471"
    until: 2026-09-30T00:00:00+00:00
    approved_by: urn:li:corpuser:datahub

A live waiver downgrades the finding to INFO with the reason and approver printed inline. An expired waiver is ignored — the rule fires again and the expiry is reported:

  ! expired waiver ignored: no_freshness_assertion on device_events (expired 2026-07-01)

An expiring waiver is honest; a permanently disabled rule is not.

Sample outputs — examples/

Committed so you can judge the output without running anything.

File What it is
gate-report-BLOCK.txt Terminal output for the broken model
gate-report-PASS.txt Terminal output for the clean model
gate-report-EXEMPTION.txt A live waiver downgrading a blocker to INFO
gate-report-DEEP-LINEAGE.txt 250-asset transitive walk with truncation reported
gate-report-REGULATED.txt The stricter pack blocking a model base passes
gate-report-OVERRIDE.txt / dossier-OVERRIDE.md Attributed break-glass override
watch-round.txt One monitoring round
acceptance-run.txt Full 45-check acceptance sweep output
scan-fleet.txt Fleet scan across every model in the catalog
fix-dry-run.txt mlgate fix, including what it refuses to auto-fix
publish-dry-run.txt Exactly what --publish would write
verdict-BLOCK.json / verdict-PASS.json Machine-readable verdicts (the CI contract)
junit-BLOCK.xml JUnit XML for CI
dossier-BLOCK.md / dossier-PASS.md Generated Model Release Dossiers

Column-level precision

Two columns on device_events are undocumented PII. Only one actually reaches a feature. A column-blind check flags both — one of which is a false positive on data the model never sees.

mlgate reads the feature-engineering job's DataJobInputOutput.inputDatasetFields — the place DataHub actually models column-level flow — and narrows accordingly:

[BLOCK] device_events  column 'device_fingerprint' is tagged PII, reaches a feature,
                       and has no description

ip_address is not reported: PII, undocumented, but never consumed.

Two implementation notes worth recording, both found empirically:

  • MLFeatureProperties.sources accepts dataset URNs only — DataHub rejects a schemaField URN there with HTTP 422. Column-level truth belongs on the job, not the feature.
  • When no column lineage is declared, the rule stays coarse and says so ("no column-level lineage; cannot confirm it reaches the model") rather than silently narrowing. Narrowing on absent data would turn a false positive into a false negative — the worse direction.

Verdict history

Every --publish records the run as a DataProcessInstance linked to the model, with the verdict, counts, rule-pack hash and findings fingerprint, and a SUCCESS/FAILURE result. The series is queryable in DataHub, so "blocked nine days running, same fingerprint" is a question the catalog can answer — not just the latest verdict overwriting the previous one.

History is best-effort by design: if recording it fails, the failure is reported but never blocks the verdict itself.

Existence is not governance

Checking that a freshness assertion exists is not the same as checking that it passes. A dataset with a permanently-failing freshness assertion is stale — and used to read as perfectly governed. An assertion that has never run proves nothing at all.

The rule distinguishes four states:

State Verdict
No assertion of type FRESHNESS BLOCK
Assertion exists and is failing BLOCK — "this input is stale"
Assertion exists but has never run UNVERIFIABLE (WARN under base, BLOCK under regulated)
Assertion exists and is passing clean

Read in one GraphQL call per dataset (assertions { info { type } runEvents { total failed succeeded } }), so type and outcome come together.

"Cannot check" is not "fine"

The rules distinguish three states, not two: compliant, violating, and unverifiable.

If a dataset has no schema in the catalog, its PII exposure cannot be checked. If a feature table records no materialization timestamp, its staleness cannot be checked. Earlier these produced zero findings, and the model passed — absent evidence presented as evidence of absence, which for a safety tool is the dangerous direction to fail in.

Now each reports explicitly, at a severity the pack sets:

unverifiable_severity_default: WARN      # base
unverifiable_severity_default: BLOCK     # regulated — you cannot ship what you cannot inspect
[WARN ] some_table    no schema in the catalog — PII exposure cannot be checked
[WARN ] feat_v2       no materialization timestamp — staleness cannot be checked

This came out of the acceptance sweep: no_owner was checking whether an Ownership aspect existed rather than whether it had any owners, so a dataset with zero owners passed. Fixing that one instance prompted a sweep for the whole class, which found three more.

Break-glass override

Real gates get overridden. Pretending otherwise is how gates get deleted instead.

mlgate check "$MODEL" --override \
  --override-reason "hotfix for INC-882; owner assignment lands tomorrow" \
  --override-by urn:li:corpuser:alice --publish

An override never erases the block. The blockers still stand in the report, a Governance:ReleaseOverridden tag is added beside ReleaseBlocked, and release_override_by / _at / _reason are written to the model. The dossier gets a banner naming who accepted the risk. Exit code becomes 0 so the deploy proceeds — the record is permanent.

--override without --override-reason and --override-by is refused: an unattributed override is indistinguishable from a disabled gate. And re-running without --override clears the previous override attribution, so no model looks permanently excused.

Scale

The deep-lineage demo model sources from the analytics.order_details mart, which has ~109 real upstreams in showcase-ecommerce:

  Walked 250 assets across the model's upstream lineage
  ! lineage truncated at 250 assets (depth 3): 58 upstream asset(s) not evaluated;
    findings may be incomplete

  BLOCK   45 blocker(s), 24 warning(s)

4.0 seconds for 250 assets — entities are fetched in batches of 50 via /entitiesV2, not one request per asset. Note that truncation is reported with an exact count. A bounded search that presents itself as exhaustive is a lie, and for a safety tool that lie is the dangerous direction.

Known limitations and roadmap

Stated plainly, because a gate whose boundaries you can't trust isn't a gate.

Gap Why it matters
watch polls; it does not subscribe It re-gates on an interval rather than reacting to DataHub's metadata change events. Correct, but not instant, and it costs a full walk per round.
Column lineage must be declared Precision depends on a feature-engineering job publishing inputDatasetFields. Where a team has not modelled that, the PII rule correctly stays coarse and says so — but it cannot infer columns that nobody recorded.
Dossier hash is integrity, not provenance It proves the document was not edited; it does not prove who produced it. Real audit use wants a signature and a trusted timestamp.
Acceptance suite mutates shared state It runs fix and --reset against live DataHub, so ordering and index lag matter. One flake was observed across repeated runs; unit tests are deterministic, the end-to-end suite is not fully.

Scope — what this is not

The dossier records data-provenance readiness: whether every input is owned, documented, monitored, and unchanged since training. That evidence is a precondition for frameworks such as the NIST AI Risk Management Framework and EU AI Act technical documentation.

It is not a compliance certification and asserts conformity with no regulation. It records what the catalog knows at the timestamp on the report, and cannot attest to anything the catalog does not track.

Also not built, and deliberately so: no web UI, no multi-agent orchestration, no scheduled runs. One path, working end to end.


Repository layout

skills/datahub-release-gate/SKILL.md   DataHub Skill — drive the gate from an agent
.mcp.json               DataHub MCP server config (Core: uvx mcp-server-datahub)
tests/test_engine.py    unit tests — no DataHub required
seed/contract.py        frozen URN scheme — the interface every module imports
seed/emit_lineage.py    emits the ML lineage graph (broken + clean variants)
mlgate/walker.py        lineage traversal (entity API, cycle-safe, fails loudly)
mlgate/engine.py        rule registry, pack loader, deterministic verdict
mlgate/packs/*.yaml     rule packs — base, regulated
mlgate/cli.py           `mlgate check`
writeback/publish.py    tags, properties, dossier attachment + read-back verification
writeback/dossier.py    dossier renderer
examples/               committed sample outputs

License

Apache 2.0 — see LICENSE.

About

A pre-deployment release gate for ML models, backed by DataHub. Walks lineage, blocks unsafe releases with named gaps, writes the verdict back into the graph.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages