feat(sdk): metric column lineage, metric consumers and semantic-model metadata gaps

Merged
SG
19h ago
+3845-309

Summary

The Python SDK (datahub.sdk) can now write the metric lineage the metadata model already supports. This PR supersedes #20001 and #20166. It brings their SDK work onto current master, applies the open review feedback on both, and fills SDK gaps that the semantic-model connectors (Snowflake, dbt, Databricks Unity Catalog, Cube and MicroStrategy) work around today.

Metric column lineage (from #20001)

  • Metric takes upstream_fields (the logical columns the metric reads), with set_, add_ and remove_ methods for fields and datasets. Each column's dataset is added to the upstream datasets automatically, as the server requires.
  • set_upstream_datasets is not deprecated. By default it keeps the columns whose dataset is still upstream, so a dataset-only update does not wipe column lineage. upstream_fields=[...] or [] replaces the columns.
  • Bad dataset or column inputs raise one error type, InvalidUpstreamUrnError, which is both an SdkUsageError and an InvalidUrnError.

What this PR changes from #21741, and why

#21741 was merged to master while this PR was open, and it is not released yet. It also added Metric.upstream_fields, set_upstream_fields and the upstream_fields property. This PR keeps those names. It changes four of #21741's behaviours, so that Metric handles inconsistent input the way the rest of datahub.sdk does.

#Reverted (#21741)NowWhy
1A field whose dataset is not in upstream_datasets raises ValueError.The field's dataset is added to upstream_datasets.Elsewhere the SDK derives the dataset edge from column lineage instead of rejecting the input. Both Dataset(upstreams={upstream: {col: [...]}}) and client.lineage.add_lineage(..., column_lineage=...) do this. Callers don't have to keep the two lists in sync themselves.
2set_upstream_datasets raises ValueError when it removes a dataset that still has fields.That dataset's fields are dropped, and the other fields are kept.Dataset.set_upstreams replaces dataset and column lineage together and never raises. A dataset-only update always gives a valid aspect instead of failing.
3Bad input raises ValueError.Bad input raises InvalidUpstreamUrnError, which is both an SdkUsageError and an InvalidUrnError.SdkUsageError is the SDK's error for misuse, and callers that already catch InvalidUrnError still catch it. SchemaFieldKeyError follows the same pattern.
4upstream_fields takes one field or a list.It takes a list only, like upstream_datasets.The two arguments now take the same shape, and the private union type is no longer in public signatures.

Impact. The only caller on master is the MicroStrategy connector (#21737). Every field it passes already has its dataset in upstream_datasets, and it always calls set_upstream_fields, so its output is the same under either rule. No examples or docs used the reverted behaviour. #21741's two ValueError tests are rewritten to check the new behaviour: the missing dataset is added, and the removed dataset's fields are dropped.

Metric no longer clears lineage it was not given

  • Before, Metric(...) always wrote empty metricRelationships and metricUpstreams. Writing a Metric to update only its description or owners wiped its metric-to-metric and dataset lineage in DataHub.
  • Now derived_from, parent_metric, related_metrics, upstream_datasets and upstream_fields follow the SDK convention: None (the default) leaves DataHub's value alone, and a list, including [], replaces it.
  • The forced empty aspect existed so a metric is found by the hasParentMetric=false search that lists a model's top-level metrics. To keep that without wiping anything, a Metric with no relationships set sends an empty generic patch on metricRelationships: it creates the default aspect when DataHub has none and changes nothing otherwise. Verified against a local server. client.entities.create() writes the default aspect directly. The patch goes through a new Entity._extra_mcps() hook, sent by as_workunits() and the entity client, so as_mcps() keeps returning whole aspects only.
  • parent_metric and related_metrics are new, with set_ / add_ / remove_ methods. The three share one aspect, which is written whole when any of them is set, so the producer that owns them passes all three.
  • Cube and dbt simple metrics now pass derived_from=[], so they still clear stale metric-to-metric edges. Unity and MicroStrategy already passed it. No golden changes.
  • upstream_fields without upstream_datasets still writes metricUpstreams, with the columns' datasets as its upstream datasets; this is documented on Metric.
  • Breaking for scripts that relied on the clearing; listed in docs/how/breaking-changes.md.

Metric readers (from #20166)

  • Chart, Dashboard and Dataset take upstream_metrics, with set_, add_ and remove_ methods. Leaving it out keeps what the server has; [] clears it.
  • Chart input datasets and dataset upstreams are now parsed as dataset URNs. A metric URN is rejected with a hint to use upstream_metrics.

Consistent set_ / add_ / remove_ behaviour (SDK-wide fixes)

The SDK convention is: set_* replaces the whole list, add_* adds one item, and remove_* removes one item. Tags, terms, owners, Chart.set_input_datasets and Dataset.set_upstreams follow it. While adding the metric methods we found several existing methods that did not, and fixed them here so the new and old methods behave the same.

What changedWhy
Dashboard.set_input_datasets, set_charts and set_dashboards now replace the list. They used to append to it.With append, set_* could not remove anything, and calling it on an entity read from DataHub silently duplicated edges. Its behaviour also depended on the entity type, unlike every other set_* in the SDK.
These setters parse every input before changing anything. They drop duplicates, keep order, and keep the existing edge (created stamp, properties) for URNs that stay.One bad URN in the list used to leave a half-updated entity. Re-emitting an entity read from DataHub must not lose edge metadata nobody asked to change.
The shared remove_list_unique helper now removes every matching item. This fixes every remove_* method that uses it: tags, terms, owners, links and others.It popped items while looping over the list, so it skipped the item after each removal. An entity with adjacent duplicates, which can come back from the server, kept one after remove_*.
Chart.remove_input_dataset, Dashboard.remove_input_dataset, remove_upstream_metric and the derived_from methods parse URNs the same way as their set_ / add_ siblings.A wrong entity type, such as a dataset URN as a metric, raised a different error depending on the method, or none at all. Now set_, add_ and remove_ reject it with the same InvalidUpstreamUrnError and a hint.
upstream_metrics, Metric.upstream_datasets and Metric.upstream_fields return None when the aspect (or fieldUpstreams) is unset, and a list, possibly empty, when it is set. Use metric.upstream_datasets or [] to iterate.An unset aspect is left alone on upsert while [] clears it, so callers need to tell the two apart. Dataset.upstreams and browse_path already work this way.
The new metric methods follow the same rules. set_upstream_metrics and set_derived_from drop duplicates and keep the metadata of edges that stay. add_upstream_metric skips duplicates. remove_upstream_metric removes every match and does nothing when no aspect is set. The Metric upstream dataset and field methods behave the same way.remove_upstream_metric on an entity with no aspect would otherwise create an empty one, and an upsert would then clear every metric edge on the server, not just the one removed.

The set_* changes are breaking for scripts that relied on append, so they are listed in docs/how/breaking-changes.md, with the add_* method to use instead. So are Metric(...) no longer clearing lineage it was not given, and Metric.upstream_datasets returning None, since that getter is already released. The only connectors that call these setters (Omni and ThoughtSpot) call set_charts once on a new dashboard, so their output does not change.

Lineage client

  • add_lineage supports dataset → metric, column → metric, metric → metric, and metric → chart, dashboard or dataset. Like every other route, each call sends a patch that adds the edge, keyed by destinationUrn, and keeps the other edges. These aspects have no server-side patch template, so the patch is a generic one (supported for every aspect since v1.4.0, before the metric aspects existed). A column edge and its parent dataset edge go in one proposal, because the server validates each proposal on its own. Adding an edge that already exists replaces it, including the parent dataset edge written with a column.
  • New patch builders back these routes: MetricPatchBuilder (add_upstream_dataset, add_upstream_field, add_derived_from) and add_upstream_metric / remove_upstream_metric on the chart, dashboard and dataset patch builders.
  • get_lineage returns names and descriptions for metric results.

Semantic model metadata

  • Metric and SemanticModel get external_url, subtype and browse_path. They can't belong to a container, so browse_path places them in the browse tree. It takes the same input as parent_container, and also a single URN or name as a one-entry path. Any other type raises an error instead of writing an empty path. parent_container itself is unchanged.
  • SemanticModelDataset passes through parent_container, custom_properties, external_url, display_name, qualified_name, created and last_modified.
  • Fields of a logical dataset accept terms and structured_properties.

Examples and docs

  • New examples: metric_create.py, metric_update_upstreams.py, chart_add_upstream_metrics.py and lineage_metric_add.py. semantic_model_create.py now shows metric column lineage and logical-to-physical column lineage.
  • New sections in the Semantic Models & Metrics and Lineage tutorials, including how to remove a logical dataset from a model (soft-delete it).
  • An entry in docs/how/breaking-changes.md.

Not in this PR

Connectors will start using these features in follow-up PRs, one per connector: Snowflake metric column lineage (the connector part of #20001), dbt and Cube metric column lineage, Unity and MicroStrategy column lineage, and replacing the connectors' browse-path and container workarounds.

DataJob lineage semantics (set_ / add_ / remove_, edges and getters) are left for a follow-up PR.

No connector golden changes: like #21741, fieldUpstreams is written only when the metric has columns or upstream_fields is given (an explicit [] is kept). An upsert replaces the whole metricUpstreams aspect, so leaving it out clears stale column edges just as [] does. The MetricUpstreams.pdl guidance to always write [] matters for PATCH or merge writes, which the SDK does not use.

Test plan

  • New and updated unit tests: tests/unit/sdk/test_metric.py, tests/unit/sdk/test_semantic_model.py, tests/unit/sdk_v2/test_upstream_metrics.py, tests/unit/sdk_v2/test_lineage_client.py, tests/unit/specific/test_metric_patch.py
  • SDK, dbt, Cube, Unity, MicroStrategy and Snowflake unit tests pass, and the dbt, Cube and Unity semantic-model golden tests pass
  • ./gradlew :metadata-ingestion:lint (ruff and mypy, including the examples)
  • Against a local DataHub:
    • Writes and reads round-trip, and the lineage client calls work.
    • A dataset-only update keeps column lineage.
    • get_lineage shows the metric's chart and derived metric.
    • The server rejects a column whose dataset is not upstream, and a dataset ↔ metric cycle.

Checklist

  • The PR conforms to DataHub's Contributing Guideline (particularly PR Title Format)
  • Links to related issues (if applicable)
  • Tests for the changes have been added/updated (if applicable)
  • Docs related to the changes have been added/updated (if applicable). If a new feature has been added a Usage Guide has been added for the same.
  • For any breaking change/potential downtime/deprecation/big changes an entry has been made in Breaking Changes

🤖 Generated with Claude Code


Summary by cubic

The Python SDK can now write metric column lineage, metric readers, and the remaining semantic-model metadata, closing gaps the Snowflake, dbt, Databricks Unity, Cube, and MicroStrategy connectors currently work around.

New features

  • Metric accepts upstream_fields for column-level lineage; the parent dataset of each column is added to the upstream datasets automatically, and passing upstream_fields alone replaces the upstream datasets. derived_from now accepts only metric URNs or a Metric, set_derived_from dedupes entries while keeping the stamps and properties of entries that stay, and add_derived_from validates its input before touching the local aspect.
  • Metric gains parent_metric and related_metrics with set_, add_, and remove_ methods; set_parent_metric rejects self-references.
  • Chart, Dashboard, and Dataset accept upstream_metrics with set_, add_, and remove_ methods. remove_* now removes every matching item, fixing a bug where an adjacent duplicate could survive.
  • client.lineage.add_lineage supports dataset → metric, column → metric, metric → metric, and metric → chart, dashboard, or dataset. New edges get created/lastModified stamps; existing server edges keep theirs. get_lineage stays compatible with servers before v1.7.0.
  • Metric and SemanticModel get external_url, subtype, and browse_path, which also accepts a bare string or tuple as a one-entry path and rejects unsupported types via set_browse_path while parent_container stays unchanged. SemanticModelDataset passes through the remaining dataset properties, and logical fields accept terms and structured_properties.
  • Cube and dbt simple metrics pass derived_from=[] so stale metric-to-metric edges are cleared.

Breaking changes (documented in docs/how/breaking-changes.md)

  • Chart input datasets and dataset upstreams now reject non-dataset URNs; use upstream_metrics to record metric readers.
  • List set_* methods on Dashboard now replace the list instead of appending, and keep the metadata of edges that stay; use the new add_/remove_ methods to change one item.
  • Lineage arguments now follow the SDK convention: None leaves the server's value alone (a re-emitted Metric no longer wipes lineage it was not given), while a list, including [], replaces it. Metric remove_* methods no-op when the local entity has no aspect, so re-emitting can't clear the server's edges by accident.
  • Metric.upstream_datasets and upstream_fields return None when unset, so callers can tell an unset aspect from an explicit [].

Docs and examples cover the new lineage routes, including removing a logical dataset from a semantic model; the semantic-model and lineage tutorials and the breaking-changes.md entry are updated.