Page MenuHomePhabricator

Apply Iceberg table maintenance to all dbt marts
Open, Needs TriagePublic

Description

Currently, Iceberg tables only get Iceberg maintenance if they are declared in datasets.yaml. dbt marts don't need to be declared in datasets.yaml if they have no downstream dependencies, but still need Iceberg maintenance.

Acceptance criteria

  • dbt marts have Iceberg maintenance applied by default to control the number of files.

Implementation notes

We could require that marts be declared in datasets.yaml, but a more robust solution is probably to write some automation that detects every Iceberg table within our main production databases and applies maintenance to those, whether they're produced with dbt or not.

If we go that way, datasets.yaml would no longer be used to opt in to table maintenance (as it would be on by default), but could still hold parameters for specific Iceberg tables or even opt outs if we find that we need that.

Event Timeline

We could require that marts be declared in datasets.yaml, but a more robust solution is probably to write some automation that detects every Iceberg table within our main production databases and applies maintenance to those, whether they're produced with dbt or not.

We still want to know exactly what datasets where mutated, how, and at what cadence. Otherwise we may lose data and not know why. We also want anything declared in datasets.yaml to win.

Thus, it would be great if whoever picks up this work comes up with a proposal first.

Automated retention pruning for dbt staging/intermediate Iceberg tables

Summary

Add a new daily Airflow DAG that automatically discovers dbt-produced staging (stg_) and intermediate (int_) Iceberg tables across the lake and deletes partitions older than a configurable retention window (default 7 days), without requiring these tables to be declared in the global config/datasets.yaml. Mart tables are never touched by this system.

Motivation

The number and data volume of dbt staging/intermediate tables has grown exponentially, pushing HDFS usage toward its capacity limit. Per the dbt style guide (dbt-jobs-style-guide.wikitext), staging and intermediate models are:

  • explicitly ephemeral by design — "one staging model per source table... no joins, no aggregation" and intermediate models are "not yet a final deliverable"
  • fully recomputable, since dbt can always re-derive them from source data or upstream marts on backfill

Mart tables are the opposite: they are the published deliverables consumers and dashboards read, and must never be auto-pruned.

We already have a declarative maintenance system for this exact kind of operation — config/datasets.yaml plus the table_maintenance_iceberg_<schedule> DAGs (see wmf_airflow_common/factories/table_maintenance_iceberg_dag_factory.py), which already supports a data_delete action per dataset. That system is the wrong fit here unmodified: datasets.yaml is intentionally scoped to datasets meant for org-wide discovery, and declaring every transient stg_/int_ table there would pollute a file every Airflow user reads, and would not scale with the number of these tables (which is the very problem we're trying to solve).

Proposal

Discovery: catalog scan by naming convention

A new task queries the Spark/Hive catalog directly for Iceberg tables whose unqualified name starts with stg_ or int_ — the prefix is a hard rule in the style guide ("Staging and intermediate models MUST carry their prefix"). Scanning the physical catalog, rather than dbt's YAML/SQL source, is deliberate: several staging/intermediate models are materialized='ephemeral' (pure CTEs with no physical table at all), and a catalog scan skips those automatically with no separate "is this actually a table" check needed.

I considered scoping the scan to a fixed list of dbt-managed schemas, but that list would need to stay in sync with dbt_project.yml's per-domain schema assignments every time a new domain is added. Whether to do a full-catalog scan or a scoped one is left open below pending a cost check against the Hive Metastore.

Exclusion: datasets.yaml always wins

After discovery, any table whose fully-qualified name already appears as a table_name in config/datasets.yaml is dropped from the candidate list entirely, regardless of what that entry's own maintenance config says. Presence there is a deliberate declaration that the table is managed by the existing, org-wide system, which takes precedence, full stop.

Partition-column detection

For each remaining candidate, the pruning task resolves the table's Iceberg partition-transform column via DESCRIBE TABLE EXTENDED, parsed the same way mediawiki_sqoop_snapshot() (dbt-jobs/macros/dates.sql) already parses SHOW PARTITIONS output today — no new convention or per-table declaration required for the common case. A table whose partitioning can't be confidently resolved (composite spec, unpartitioned, non-time transform) is skipped and reported, never guessed at.

Pruning mechanism

Reusing IcebergDataset directly is not viable: it raises an error if maintenance is enabled without a produced_by producer, which discovered tables won't have. Instead, a small dedicated Spark SQL task builder issues, per table:

DELETE FROM <table> WHERE <partition_col> < <cutoff>

mirroring the data_delete pattern already used in IcebergDataset.get_maintenance_tasks(). cutoff = data_interval_start - retention_days, with a default retention of 7 days, overridable per table via a small opt-in YAML file (e.g. main/dags/<new_dag>/config/overrides.yaml) used only for exceptions — a different retention, an explicit exclusion, or a manual partition-column override — not for declaring every table the way datasets.yaml would require.

Two safety guards are required, not optional:

  • refuse to execute any DELETE whose predicate is empty, unparsable, or whose cutoff falls inside a minimum floor (e.g. never prune data newer than 1 day) — an empty/malformed predicate on an Iceberg DELETE silently deletes the entire table
  • ship with a dry-run mode (log the resolved table list, partition column, and cutoff without executing) so the candidate list and cutoffs can be validated against production before deletes are enabled

Audit trail

Every run writes one row per candidate table to a new Iceberg table, e.g. wmf_data_ops.stg_int_pruning_audit — the same schema already used for iceberg_wmf_data_ops_data_quality_metrics / _alerts in config/datasets.yaml. Each row records: table name, run date, action (pruned / skipped_excluded / skipped_undetected_partition / error), partition column used, retention days applied, cutoff, and rows/files removed where obtainable from the Iceberg DELETE/snapshot summary. This audit table is a real deliverable, not ephemeral, so it is declared normally in datasets.yaml with its own maintenance like any other mart.

Costs and open questions

  • Catalog-scan cost and scope. Full-catalog scan vs. a scoped schema list needs validation against real Hive Metastore load before committing to one.
  • Concurrency with dbt's own writes. An Iceberg DELETE running concurrently with a same-day dbt insert_overwrite on the same table risks a commit conflict. This needs a scheduling strategy — e.g. depending on the known dbt DAGs' completion — that is deliberately left out of this proposal.
  • Partition-column auto-detection is new engineering. The only existing precedent is the SHOW PARTITIONS text-parsing in mediawiki_sqoop_snapshot(); a short spike is needed before committing to a timeline for DESCRIBE TABLE EXTENDED parsing.
  • 7-day default is a starting point, not a guarantee. Teams with unusually large ephemeral tables may need a shorter override sooner than a general rollout would reach them.
  • Ownership and location of the new DAG/config — under main/dags/, or alongside main/dags/maintenance/table_maintenance_iceberg_dag.py — is undecided.

Alternatives considered

  • Dedicated dbt_staging/dbt_intermediate schema. The cleanest long-term signal (no naming-convention reliance), but schema today is assigned per domain in dbt_project.yml (e.g. infrastructure-metrics puts staging, intermediate, and marts all in wmf_traffic), so this would require migrating every domain and risks breaking anything already pointed at current table locations. Rejected for v1; worth revisiting if schema-per-layer is ever adopted for other reasons.
  • Declare every stg_/int_ table in config/datasets.yaml and reuse the existing table_maintenance_iceberg_<schedule> DAGs unmodified. Reuses proven, already-shipped machinery, but directly contradicts the goal of keeping datasets.yaml scoped to intentionally-published, org-wide datasets, and doesn't scale with the number of ephemeral tables (the very problem being solved).
  • dbt manifest/tag-based discovery. The most precise signal available — dbt already tags every model (staging/intermediate/marts) in dbt_project.yml, and resolves each model's exact schema/materialization in manifest.json, with no reliance on naming discipline. Not chosen for v1 because dbt-jobs has no established mechanism today for publishing manifest.json outside its ephemeral Skein/YARN run; wiring that up is its own project. Worth a follow-up once that gap is closed.

Acceptance criteria

  • Team agrees catalog-scan-by-naming-convention (not schema migration, not manifest-based) is the right v1 discovery mechanism.
  • Team agrees "presence in datasets.yaml always wins" as the exclusion rule, requiring no further per-table opt-out inside datasets.yaml itself.
  • Default retention (7 days) and the override-only YAML file's location are agreed.
  • Auto-detect-with-skip-and-alert is agreed as the partition-column resolution strategy, with skipped tables surfaced rather than silently ignored.
  • Follow-up tasks are filed for: catalog-scan cost validation, the dbt/pruning concurrency strategy, and the audit-table schema.

Some comments on the approach below:

I considered scoping the scan to a fixed list of dbt-managed schemas, but that list would need to stay in sync with dbt_project.yml's per-domain schema assignments every time a new domain is added. Whether to do a full-catalog scan or a scoped one is left open below pending a cost check against the Hive Metastore.

I think we should still have a new config file that declares the patterns to match rather than hard code one pattern. This file could declare something like wmf_traffic.*_int_* and match it. Further, such a file could have a list of patterns to DELETE data from, or to just apply the other regular Iceberg maintenance (like snapshot expiration, data compation, etc.).

Instead, a small dedicated Spark SQL task builder issues, per table:

DELETE FROM <table> WHERE <partition_col> < <cutoff>

For my understanding then, do all dbt tables follow the exact same partitioning strategy? If they do not, we could just expire Iceberg snapshots instead of deleting data?

Every run writes one row per candidate table to a new Iceberg table, e.g. wmf_data_ops.stg_int_pruning_audit

This is a great idea. I don't want to scope creep this effort, but if we do this, we should plan to eventually extend datasets.yaml to also support writing to this table. Today the "audit" is kept on Airflow, and once it clears DagRun history, which I think we have set to 1 year, then the audit is gone.

Partition-column auto-detection is new engineering. The only existing precedent is the SHOW PARTITIONS text-parsing in mediawiki_sqoop_snapshot(); a short spike is needed before committing to a timeline for DESCRIBE TABLE EXTENDED parsing.

Agreed that this sounds complicated. Let's try to go around this.

Ownership and location of the new DAG/config — under main/dags/, or alongside main/dags/maintenance/table_maintenance_iceberg_dag.py — is undecided.

Just a reminder: the config can be global, but the DAG (or DAGs) must be declared on the Airflow instance with the service user that owns the dataset. Otherwise the mutations will fail.

CC @JAllemandou for if he has time to review this proposal as well.

I'm in agreement with the almost every comment @xcollazo has made above.
The only point I'd like to discuss is data deletion vs iceberg maintenance only.
It's pretty sure there will be cases where we'll want data-deletion in addition to iceberg maintenance, and the other way around too.
Also, the data-deletion case brings in the time-column to be used for deletion (named partition-column parsing in the above).
I can't think of a better solution than what has been described above, with adaptations as Xabriel commented.

Thanks for the comments, @xcollazo and @JAllemandou !

For my understanding then, do all dbt tables follow the exact same partitioning strategy?

They do not follow the exact same partitioning strategy, at least there's no requirement on dbt model authors to do so. The models do eventually end up following similar patterns in partitioning strategy, with a DATE or DATETIME type of column to serve as the time dimension.

If they do not, we could just expire Iceberg snapshots instead of deleting data?

I looked into whether expiring snapshots alone would be enough, and for these tables it isn't. (this also addresses @JAllemandou comment)

expire_snapshots only deletes data files that no remaining snapshot references. The current snapshot is always kept, so any file that is still part of the table's current state is never deleted.
A commit removes the files from the table's current state: an overwrite, a DELETE, a merge, a compaction, or a full table replace. expire_snapshots then physically deletes them, once no retained snapshot references them.

So without DELETEs, expire_snapshot would remove files only in the case of say a backfill that overwrite existing rows.

This is a great idea. I don't want to scope creep this effort, but if we do this, we should plan to eventually extend datasets.yaml to also support writing to this table. Today the "audit" is kept on Airflow, and once it clears DagRun history, which I think we have set to 1 year, then the audit is gone.

Fully agree on this, I think it's a worthwhile effort.

Just a reminder: the config can be global, but the DAG (or DAGs) must be declared on the Airflow instance with the service user that owns the dataset. Otherwise the mutations will fail.

I think we already do something similar with datasets.yaml if I'm not mistaken? We run Iceberg maintenance DAGs in every instance, and they all read from the same global config? We should just extend that same approach, which could also possibly help with the shared Audit table effort mentioned above.

My next step is to work on fleshing out some details about that global configuration file, schema/table patterns, partition column patterns etc.

Just thought of something important:

Just a reminder: the config can be global, but the DAG (or DAGs) must be declared on the Airflow instance with the service user that owns the dataset. Otherwise the mutations will fail.

I don't think we need to declare these pruning DAGs on multiple instances since all DBT DAGs are being run from main, and plans for the future would involve migrating to a dedicated dbt instance - we would never end up using multiple instances anyway.

Just thought of something important:

Just a reminder: the config can be global, but the DAG (or DAGs) must be declared on the Airflow instance with the service user that owns the dataset. Otherwise the mutations will fail.

I don't think we need to declare these pruning DAGs on multiple instances since all DBT DAGs are being run from main, and plans for the future would involve migrating to a dedicated dbt instance - we would never end up using multiple instances anyway.

Got it. But this brings up another question: we had decided elsewhere that it was ok for DPE to not fully own databases like wmf_traffic and wmf_contributors, and a bunch of dbt jobs now write to those databases from the dbt Airflow jobs, and like you mention, today these are run with the analytics service user.

In a future were dbt DAGs are run from their own Airflow instance, we'd need to figure out a database mapping that allows that new dbt service user to own its own databases, or perhaps continue the shared databases but the legwork for proper ownership would need to be done.

@xcollazo correct, we will need a dbt_analytics user and user group, with Kerberos ticketing.

OK here's the proposed config file layout. It intentionally reuses some existing components from datasets.yaml, and I believe it is flexible enough to facilitate easy creation of rules that will cover all of our use cases.

@xcollazo @JAllemandou

Config: global rules file

A new global config next to datasets.yaml, one file per team for ownership. A rule states policy — which tables, how long to keep them, which maintenance to run. It does not have to split by table layout.

# config/iceberg_maintenance_rules/<team>.yaml
rules:
- name: infra_metrics_staging
  schema: wmf_traffic
  tables: [stg_*, int_*]          # globs, matched only inside `schema`
  maintenance:                    # same keys and defaults as `maintenance` in datasets.yaml
    schedule: "@daily"
    expire_snapshots:
      older_than_days: 1          # needed for the DELETE to free storage
  retention:                      # optional; omit for maintenance-only rules (e.g. marts)
    retain: 30 days               # days | weeks | months | years; >= a global floor
    time_columns: [day, hour, ymd]  # accepted; each table must have exactly one

- name: contributors_staging
  schema: wmf_contributors
  tables: [base_*, dedup_*, int_*, stg_*]
  exclude: [stg_retention_edits, stg_first_constructive_edit]  # 1-year policy, own rule
  maintenance: {schedule: "@monthly", expire_snapshots: {older_than_days: 1}}
  retention:
    retain: 3 months
    time_columns: [month, week, revert_month, revert_window_close_month]

- name: infra_metrics_marts
  schema: wmf_traffic
  tables: [some_mart_*]
  maintenance:
    schedule: "@weekly"
  • The maintenance block reuses the datasets.yaml schema and IcebergDataset.DEFAULT_MAINTENANCE, so people configure both systems the same way.
  • There is no global retention default., each rule states its own retain
  • There is no produced_by section. All dbt jobs run on main, so all rules run there.

Matching and exclusion

  • At runtime, each rule will expand with SHOW TABLES IN <schema>, filtered by its globs and excludes.
  • Any table declared in datasets.yaml is dropped. Presence there always wins, regardless of its maintenance settings.

Retention: accepted time columns, checked at runtime

Almost every physical staging-layer table has one date-like time column — a date or timestamp holding the start of its period (DATE_TRUNC('MONTH', …), TRUNC(…, 'MONTH'), MAKE_DATE(y, m, 1), CAST(DATE_TRUNC('WEEK', …) AS DATE)), or an ISO yyyy-MM-dd string. Only the column name varies. The one exception is year/month/day integers. So:

  • time_columns lists the column names a rule accepts. ymd is a reserved name for the year/month/day integer layout.
  • Per table, the task will check the list against DESCRIBE TABLE (column names and types only). If exactly one entry matches, it uses that one. If none or several match, it skips the table and reports it. An overrides: {<table>: <column>} map on the rule settles those cases explicitly.
  • The retain unit must be at least as coarse as the table's period: a monthly table needs months or years, not days. Otherwise the cutoff can fall inside a period, and a partition that still holds in-window rows gets deleted.
  • No auto-detection: the rule names the columns, and the task only picks among them. A free-form where is deliberately not supported. Such tables still use datasets.yaml, where a reviewer reads each predicate.
  • The time column does not have to be a partition column. A non-partition column works, but the DELETE rewrites files instead of dropping whole partitions. CI flags this case.

This plan works for me.
I have questions though about the year/month/day case: I don't understand why this still exists if we're using Iceberg. And not having it would simplify the retention cases. Could it be something we ask from DBT users?

It seems like it's mostly models in infrastructure-metrics written by @KCVelaga_WMF :) KC, would you mind chiming in on this? Do these models need such a partitioning layout?

┌──────────────┬──────────────────────────────────────┐
│    Layer     │                Model                 │
├──────────────┼──────────────────────────────────────┤
│ staging      │ stg_pageview_actor                   │
├──────────────┼──────────────────────────────────────┤
│ staging      │ stg_webrequest_requestctl_pageviews  │
├──────────────┼──────────────────────────────────────┤
│ staging      │ stg_webrequest_upload_bandwidth      │
├──────────────┼──────────────────────────────────────┤
│ intermediate │ int_pageview_actor_daily             │
├──────────────┼──────────────────────────────────────┤
│ intermediate │ int_webrequest_requestctl_daily      │
├──────────────┼──────────────────────────────────────┤
│ marts        │ mrt_automated_requests_blocked_daily │
├──────────────┼──────────────────────────────────────┤
│ marts        │ mrt_upload_bandwidth_hourly          │
└──────────────┴──────────────────────────────────────┘

Not really. I set these up when I didn't have much knowledge of Iceberg tables and partitioning :)

These should be updated to use a single date / timestamp format column, and partition based on that. Given all these will be updated, this case can be ignored.

Q: should these models be updated first before for this work to proceed, or can be they done later or in parallel? I can prioritize accordingly.

@KCVelaga_WMF we can continue our work on this ticket without the updated models. We will however need them updated before we configure those tables to be maintained under this system.

@KCVelaga_WMF we can continue our work on this ticket without the updated models. We will however need them updated before we configure those tables to be maintained under this system.

+1 to this approach. We do not need to block this work on a dbt refactor, but as an incentive for us to not forget about it, it would be best to not support it in the automated maintenance system.

OK, I've removed support for YMD and updated the MR.

Change #1364496 had a related patch set uploaded (by Aleksandar Mastilovic; author: Aleksandar Mastilovic):

[analytics/refinery@master] Add the Iceberg maintenance audit table

https://gerrit.wikimedia.org/r/1364496

Change #1364496 merged by Aleksandar Mastilovic:

[analytics/refinery@master] Add the Iceberg maintenance audit table

https://gerrit.wikimedia.org/r/1364496

The DAG supporting this feature has been merged but the rules defining which table are maintained will come after further consultation with dbt developers.