Query icon
If icon
Fail icon
DbtCLI icon
Docker icon
Log icon
SlackIncomingWebhook icon
Pause icon
Loop icon
Schedule icon

dbt Orphaned Warehouse Relation Cleanup Guard

Compare dbt model relations to PostgreSQL information_schema, then safely remove approved orphaned tables and views.

Categories
Data

Safety

A renamed or deleted dbt model leaves its old PostgreSQL table or view behind. The old and new relations can both answer successfully so dashboards continue serving stale data without an obvious error. Dropping a relation is irreversible, so this flow uses five guards:

Guard What it stops
Manifest versus information_schema comparison A name that dbt still owns is never a candidate
Schema and identifier allow-list System schemas, other schemas and awkward identifiers stay protected
auto_remediate, dry_run, Pause approval and post-approval recheck An unattended or stale plan cannot issue a drop
Per-relation re-read and final catalog audit A changed target or ineffective write fails the run
Flow level queue with limit 1 A second run starting while one waits for approval and reaching the same drops

How it works

  1. validate_schema (io.kestra.plugin.jdbc.postgresql.Query) accepts only a simple PostgreSQL identifier for the target schema.
  2. deps and list_models (io.kestra.plugin.dbt.cli.DbtCLI) run dbt deps and dbt ls in the namespace dbt project and save target/manifest.json as the relation list (models, seeds and snapshots).
  3. audit (io.kestra.plugin.jdbc.postgresql.Query) reads information_schema.tables and assigns one of three labels: protected_manifest, protected_identifier or orphan.
  4. Orphans produce a Slack alert. The default path ends after the read. With both change inputs enabled a Pause waits for approval then deps_recheck, list_recheck and recheck build a fresh candidate set. A changed set fails before any write.
  5. remediate (io.kestra.plugin.core.flow.Loop) serializes candidates. confirm_candidate re-reads each exact identifier immediately before drop_relation (io.kestra.plugin.dbt.cli.DbtCLI) runs the drop_orphan_relation macro. The macro quotes the adapter relation and refuses schema or type changes.
  6. deps_verify, list_verify and verify read the system again. The flow fails if any relation in the target schema is still absent from the fresh manifest.

What you get

  • An exact list of stale tables and views with their table type.
  • Safe dry-run and scheduled audit defaults with no warehouse writes.
  • A human approval point with a stale-plan check before each serialized dbt drop.
  • A post-write information_schema proof that reports remaining orphans as a failed execution.

Who it's for

  • Analytics platform teams cleaning up schemas after dbt model renames and deletions.
  • Warehouse owners who need a reviewable relation inventory before destructive maintenance.
  • Teams that want dbt's adapter semantics for table and view drops inside a Kestra execution.

Why orchestrate this with Kestra

dbt can list models and run macros but it does not schedule a catalog reconciliation or hold a human approval in one execution. It also does not retain the before and after audit. Kestra supplies the disabled safe schedule, Slack alert, Pause, serialized Loop, stale-plan branch and failure state that make an irreversible cleanup reviewable.

Tested end to end

Kestra 2.0.6 ran the flow with the bundled dbt and PostgreSQL tasks, the dbt-postgres image (dbt 1.11.7) and PostgreSQL 16. The fixture holds two dbt models (orders, payments), an old table customers_old from a renamed model, an old view events_old from a deleted model and three protected lookalikes (a name with a space, a Unicode name and a name ending in a hyphen). Every outcome was confirmed with psql against the catalog, separately from the flow's own reads.

In the approved run exactly the two orphans were dropped and the manifest relations and the lookalikes stayed. A role that may read but does not own a table could not drop it, the run failed and the table stayed. A relation created or removed during the Pause failed the run before any drop. The database password is a SECRET input and was absent from every execution, child execution and log.

Case Execution Result
Healthy: every relation is a dbt model 6VoYU7bu8uZ0jXwMs9mGO7 SUCCESS. Clean branch, no alert, schema unchanged
Dry run: two orphans among seven relations 4dz30HWDbFW2GddToLuLF1 SUCCESS. Orphans customers_old (table) and events_old (view) reported, schema unchanged
Declined approval 6uEkaR5ZnLDJVd0huIlT2g SUCCESS. No drop, schema unchanged
Approved cleanup 2LgBYKP3FkfYXZdmrQ1D3d SUCCESS. Both orphans dropped and verified; orders, payments and three protected lookalikes kept; orders rows intact
Second run queued behind a paused run 5902HpHS3itVzvVStzOTRs SUCCESS. The second run stayed QUEUED while the first waited for approval and found both orphans still present
Repeat ZtMOPR2GPd8QSPc5E2AFJ SUCCESS. Clean branch, no approval, no drop
Drop refused by PostgreSQL 5rnaGkiSVKcALDPmHAVjs7 FAILED as intended. The role may read but does not own the table; drop_relation failed and the table stayed
New orphan created during the Pause 5vBr4Nbsq9kPQLeP4Sp8EY FAILED as intended. Stale plan refused before any drop
Orphan removed during the Pause 1n1bDp6YBHUISACzK3Gt3x FAILED as intended. Stale plan refused, the other orphan kept
Only protected lookalikes 3otURNMeBGkgpt9YYeE2Ga SUCCESS. Spaces, Unicode and a trailing hyphen are never candidates
Malicious schema name 1d8wpHmF6fsfmOeq8ayn1k FAILED as intended at validate_schema, no dbt task ran
39 orphans 1Jh5tM9XlXdylSg5YQM7qx SUCCESS. All 39 reported across 41 relations, schema unchanged
Second PostgreSQL: healthy 5cDJMVKZQEB3XVTSoRN3fd SUCCESS
Second PostgreSQL: dry run 36wGuBSLIZtr1x4vDyp9Tw SUCCESS. Same two orphans
Second PostgreSQL: approved cleanup 5eD0mQJnRc1n471O4GgFu8 SUCCESS. Same two orphans dropped, protected relations kept
Second PostgreSQL: new orphan during the Pause 1AEHO8TqBEONWACYDrns3x FAILED as intended

Prerequisites

  • Kestra OSS 2.0.6 with Docker task-runner access and the dbt-postgres image.
  • A dbt project uploaded as namespace files with a PostgreSQL profile target matching the flow inputs.
  • A PostgreSQL role that can read information_schema.tables. Remediation needs ownership of the approved tables and views or ownership of their schema. A relation the role cannot read is invisible to the audit.

Secrets

  • POSTGRES_URL: JDBC URL used by the PostgreSQL catalog tasks.
  • POSTGRES_USER and POSTGRES_PASSWORD: credentials for catalog reads.
  • SLACK_WEBHOOK_URL: incoming webhook for findings and failures.

Inputs

Input Default Purpose
postgres_url {{ secret('POSTGRES_URL') }} JDBC connection used for catalog reads
postgres_host localhost Host used by dbt inside its Docker runner
postgres_port 5432 dbt connection port
postgres_database postgres dbt database
postgres_user {{ secret('POSTGRES_USER') }} dbt user
postgres_password {{ secret('POSTGRES_PASSWORD') }} dbt password, a SECRET input
target_schema analytics Exact schema to reconcile
docker_network bridge Network visible to dbt task containers
auto_remediate false Allow the approval branch
dry_run true Must be false before a drop can run

Quick start

  1. Add the four secrets and upload the dbt project files to the namespace.
  2. Set the PostgreSQL inputs and target_schema then run with the defaults.
  3. Review the Slack alert and execution audit. No relation changes on the default path.
  4. For a reviewed cleanup run set auto_remediate=true and dry_run=false, inspect the Pause candidates and resume with approved=true.
  5. Confirm the final verification reports zero relations outside the fresh manifest before enabling an external schedule. The included schedule is disabled.

How to extend

  • Add an allow-list for relation prefixes when a schema contains intentionally unmanaged tables.
  • Add a retention window backed by a warehouse metadata table when a rename needs a grace period.
  • Run the audit after a dbt deployment so stale relations are found while the change is still familiar.

Limits: executions of this flow run one at a time, so a scheduled audit queues while a run waits for approval; another writer to the schema between the last read and the drop is caught by the macro and the final audit, not prevented. The detector treats manifest absence as ownership evidence and skips identifiers outside the safe ASCII pattern. It does not infer whether an unmanaged table is still used by a dashboard. Views are dropped without CASCADE so dependent objects cause a failed write and remain for manual review.

Links

This blueprint was created by zkasuran.

See How

New to Kestra?

Use blueprints to kickstart your first workflows.