id: dbt-orphaned-warehouse-relation-cleanup-guard
namespace: company.team
description: |
Find PostgreSQL tables and views that remain after a dbt model was renamed or deleted.
dbt's manifest is the source of truth for model relations. The flow reads the target schema
through PostgreSQL information_schema, reports exact orphan candidates and only drops them
through dbt run-operation after a fresh recheck and human approval.
concurrency:
limit: 1
behavior: QUEUE
inputs:
- id: postgres_url
type: STRING
displayName: PostgreSQL JDBC URL
defaults: "{{ secret('POSTGRES_URL') }}"
description: JDBC URL for the warehouse database.
- id: postgres_host
type: STRING
displayName: PostgreSQL host for dbt
defaults: "localhost"
description: Hostname reachable from the dbt Docker task runner.
- id: postgres_port
type: INT
displayName: PostgreSQL port for dbt
defaults: 5432
- id: postgres_database
type: STRING
displayName: PostgreSQL database for dbt
defaults: "postgres"
- id: postgres_user
type: STRING
displayName: PostgreSQL user
defaults: "{{ secret('POSTGRES_USER') }}"
- id: postgres_password
type: SECRET
displayName: PostgreSQL password
defaults: "{{ secret('POSTGRES_PASSWORD') }}"
- id: target_schema
type: STRING
displayName: dbt target schema
defaults: "analytics"
description: Only this simple PostgreSQL identifier is eligible for cleanup.
- id: docker_network
type: STRING
displayName: Docker network for dbt tasks
defaults: "bridge"
description: Docker network that can reach the warehouse host.
- id: auto_remediate
type: BOOL
displayName: Allow relation drops
defaults: false
- id: dry_run
type: BOOL
displayName: Dry run
defaults: true
description: Must be false together with auto_remediate for any drop to run.
variables:
dbt_profiles: |
warehouse:
target: target
outputs:
target:
type: postgres
host: "{{ inputs.postgres_host }}"
port: {{ inputs.postgres_port }}
user: "{{ inputs.postgres_user }}"
password: "{{ inputs.postgres_password }}"
dbname: "{{ inputs.postgres_database }}"
schema: "{{ inputs.target_schema }}"
threads: 1
connect_timeout: 10
manifest_relations: >-
{{
fromJson(read(outputs.list_models.outputFiles["target/manifest.json"])).nodes
| jq('[.[] | select(.resource_type == "model" or .resource_type == "seed" or .resource_type == "snapshot") | {schema_name: .schema, identifier: (.alias // .name)}]')
| first }}
candidate_projection: >-
[.[] | select(.classification == "orphan") | {schema_name: .table_schema,
identifier: .table_name, relation_type: .relation_type}]
audit_sql: |
WITH manifest AS (
SELECT schema_name, identifier
FROM jsonb_to_recordset(CAST(:manifest_json AS jsonb)) AS m(schema_name text, identifier text)
), warehouse AS (
SELECT table_schema,
table_name,
table_type,
CASE WHEN table_type = 'BASE TABLE' THEN 'table' ELSE 'view' END AS relation_type
FROM information_schema.tables
WHERE table_schema = :target_schema
AND table_type IN ('BASE TABLE', 'VIEW')
)
SELECT w.table_schema,
w.table_name,
w.table_type,
w.relation_type,
CASE WHEN EXISTS (
SELECT 1 FROM manifest m
WHERE m.schema_name = w.table_schema AND m.identifier = w.table_name
) THEN 'protected_manifest'
WHEN w.table_name !~ '^[A-Za-z_][A-Za-z0-9_]*$' THEN 'protected_identifier'
ELSE 'orphan' END AS classification
FROM warehouse w
ORDER BY w.table_schema, w.table_name
candidate_sql: |
WITH manifest AS (
SELECT schema_name, identifier
FROM jsonb_to_recordset(CAST(:manifest_json AS jsonb)) AS m(schema_name text, identifier text)
)
SELECT t.table_schema,
t.table_name,
t.table_type,
CASE WHEN t.table_type = 'BASE TABLE' THEN 'table' ELSE 'view' END AS relation_type,
NOT EXISTS (
SELECT 1 FROM manifest m
WHERE m.schema_name = t.table_schema AND m.identifier = t.table_name
) AS still_orphan,
(NOT EXISTS (
SELECT 1 FROM manifest m
WHERE m.schema_name = t.table_schema AND m.identifier = t.table_name
) AND CASE WHEN t.table_type = 'BASE TABLE' THEN 'table' ELSE 'view' END = :relation_type) AS eligible
FROM information_schema.tables t
WHERE t.table_schema = :target_schema
AND t.table_name = :identifier
AND t.table_type IN ('BASE TABLE', 'VIEW')
drop_macro: |
{% macro drop_orphan_relation(schema_name, identifier, relation_type) %}
{% if schema_name != target.schema %}
{{ exceptions.raise_compiler_error('Refusing schema outside the dbt target: ' ~ schema_name) }}
{% endif %}
{% set relation = adapter.get_relation(database=target.database, schema=schema_name, identifier=identifier) %}
{% if relation is none %}
{{ exceptions.raise_compiler_error('Relation disappeared before drop: ' ~ schema_name ~ '.' ~ identifier) }}
{% endif %}
{% if (relation.type | lower) != (relation_type | lower) %}
{{ exceptions.raise_compiler_error('Relation type changed before drop: ' ~ schema_name ~ '.' ~ identifier) }}
{% endif %}
{% do adapter.drop_relation(relation) %}
{% endmacro %}
tasks:
- id: validate_schema
type: io.kestra.plugin.jdbc.postgresql.Query
description: Validate the target schema as a simple PostgreSQL identifier before
any dbt task renders it into a profile.
url: "{{ inputs.postgres_url }}"
username: "{{ inputs.postgres_user }}"
password: "{{ inputs.postgres_password }}"
fetchType: FETCH_ONE
parameters:
target_schema: "{{ inputs.target_schema }}"
sql: "SELECT :target_schema ~ '^[A-Za-z_][A-Za-z0-9_]*$' AS valid,
:target_schema AS target_schema"
- id: reject_schema
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.validate_schema.row.valid != true }}"
then:
- id: invalid_schema
type: io.kestra.plugin.core.execution.Fail
errorMessage: "target_schema must match ^[A-Za-z_][A-Za-z0-9_]*$; refusing to
inspect or change any relation."
- id: deps
type: io.kestra.plugin.dbt.cli.DbtCLI
description: Run dbt deps before reading the manifest through the current dbt CLI task.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
containerImage: ghcr.io/kestra-io/dbt-postgres:latest
commands:
- dbt deps
namespaceFiles:
enabled: true
profiles: "{{ render(vars.dbt_profiles) }}"
parseRunResults: false
- id: list_models
type: io.kestra.plugin.dbt.cli.DbtCLI
description: Run dbt ls to generate the authoritative manifest and retain it as
a task output file.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
containerImage: ghcr.io/kestra-io/dbt-postgres:latest
commands:
- dbt ls --select resource_type:model
namespaceFiles:
enabled: true
profiles: "{{ render(vars.dbt_profiles) }}"
outputFiles:
- target/manifest.json
parseRunResults: false
- id: audit
type: io.kestra.plugin.jdbc.postgresql.Query
description: Compare information_schema.tables with model relations from the dbt
manifest. The query is read-only and classifies protected lookalikes.
url: "{{ inputs.postgres_url }}"
username: "{{ inputs.postgres_user }}"
password: "{{ inputs.postgres_password }}"
fetchType: FETCH
parameters:
target_schema: "{{ inputs.target_schema }}"
manifest_json: "{{ render(vars.manifest_relations) }}"
sql: "{{ render(vars.audit_sql) }}"
- id: summary
type: io.kestra.plugin.core.log.Log
message: >-
dbt relation audit in {{ inputs.target_schema }} found {{
outputs.audit.rows | jq('map(select(.classification == "orphan")) |
length') | first }} orphan candidate(s) across {{ outputs.audit.size }}
warehouse relations. {% for r in outputs.audit.rows %}{{ r.classification
}} {{ r.table_schema }}.{{ r.table_name }} ({{ r.table_type }}). {% endfor
%}
- id: route
type: io.kestra.plugin.core.flow.If
condition: "{{ (outputs.audit.rows | jq('map(select(.classification ==
\"orphan\")) | length') | first) > 0 }}"
then:
- id: alert
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alert on orphan candidates without changing the warehouse.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: >-
{{ {'text': 'dbt found ' ~ (outputs.audit.rows |
jq('map(select(.classification == "orphan")) | length') | first) ~ '
orphan relation(s) in schema ' ~ inputs.target_schema ~ ': ' ~
(outputs.audit.rows | jq('map(select(.classification == "orphan") |
("\(.table_schema).\(.table_name)")) | join(", ")') | first) ~ '.
auto_remediate=' ~ inputs.auto_remediate ~ ', dry_run=' ~
inputs.dry_run ~ '. No relation is dropped unless both gates and
approval pass.'} | toJson }}
- id: remediation_gate
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.auto_remediate and not inputs.dry_run }}"
then:
- id: approval
type: io.kestra.plugin.core.flow.Pause
pauseDuration: PT2H
description: A table or view drop is irreversible. Resume with approved true
only after reviewing the exact candidates above.
onResume:
- id: approved
type: BOOL
defaults: false
description: Approve dropping exactly the orphan relations listed above.
- id: approved_branch
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approval.onResume.approved ?? false }}"
then:
- id: deps_recheck
type: io.kestra.plugin.dbt.cli.DbtCLI
description: Run dbt deps after approval so the manifest snapshot is current.
runIf: "{{ outputs.approval.onResume.approved ?? false }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
containerImage: ghcr.io/kestra-io/dbt-postgres:latest
commands:
- dbt deps
namespaceFiles:
enabled: true
profiles: "{{ render(vars.dbt_profiles) }}"
parseRunResults: false
- id: list_recheck
type: io.kestra.plugin.dbt.cli.DbtCLI
description: Run dbt ls immediately before the write to refresh the manifest.
runIf: "{{ outputs.approval.onResume.approved ?? false }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
containerImage: ghcr.io/kestra-io/dbt-postgres:latest
commands:
- dbt ls --select resource_type:model
namespaceFiles:
enabled: true
profiles: "{{ render(vars.dbt_profiles) }}"
outputFiles:
- target/manifest.json
parseRunResults: false
- id: recheck
type: io.kestra.plugin.jdbc.postgresql.Query
description: Re-read information_schema and compare the candidate set after the
approval pause.
runIf: "{{ outputs.approval.onResume.approved ?? false }}"
url: "{{ inputs.postgres_url }}"
username: "{{ inputs.postgres_user }}"
password: "{{ inputs.postgres_password }}"
fetchType: FETCH
parameters:
target_schema: "{{ inputs.target_schema }}"
manifest_json: "{{
fromJson(read(outputs.list_recheck.outputFiles[\"target/manif\
est.json\"])).nodes | jq('[.[] | select(.resource_type ==
\"model\" or .resource_type == \"seed\" or .resource_type ==
\"snapshot\") | {schema_name: .schema, identifier: (.alias
// .name)}]') | first }}"
sql: "{{ render(vars.audit_sql) }}"
- id: stale_guard
type: io.kestra.plugin.core.flow.If
runIf: "{{ outputs.approval.onResume.approved ?? false }}"
condition: >-
{{ (outputs.recheck.rows | jq('[.[] | select(.classification
== "orphan") | {schema_name: .table_schema, identifier:
.table_name, relation_type: .relation_type}] |
sort_by([.schema_name, .identifier])') | first)
!= (outputs.audit.rows | jq('[.[] | select(.classification == "orphan") | {schema_name: .table_schema, identifier: .table_name, relation_type: .relation_type}] | sort_by([.schema_name, .identifier])') | first) }}
then:
- id: stale_plan
type: io.kestra.plugin.core.execution.Fail
errorMessage: "The manifest or warehouse changed during approval. No relation
was dropped; review the fresh audit and approve a new
run."
else:
- id: remediate
type: io.kestra.plugin.core.flow.Loop
description: Re-read each relation immediately before its serialized dbt drop.
concurrencyLimit: 1
values: "{{ outputs.recheck.rows | jq('[.[] | select(.classification ==
\"orphan\") | {schema_name: .table_schema, identifier:
.table_name, relation_type: .relation_type}]') | first }}"
tasks:
- id: confirm_candidate
type: io.kestra.plugin.jdbc.postgresql.Query
description: Confirm this exact relation is still the same orphan immediately
before run-operation.
url: "{{ inputs.postgres_url }}"
username: "{{ inputs.postgres_user }}"
password: "{{ inputs.postgres_password }}"
fetchType: FETCH_ONE
parameters:
target_schema: "{{ inputs.target_schema }}"
identifier: "{{ fromJson(item.value).identifier }}"
manifest_json: "{{
fromJson(read(outputs.list_recheck.outputFiles[\"target/manif\
est.json\"])).nodes | jq('[.[] |
select(.resource_type == \"model\" or .resource_type
== \"seed\" or .resource_type == \"snapshot\") |
{schema_name: .schema, identifier: (.alias //
.name)}]') | first }}"
sql: "{{ render(vars.candidate_sql) }}"
- id: write_if_current
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.confirm_candidate.row.still_orphan ?? false }}"
then:
- id: drop_relation
type: io.kestra.plugin.dbt.cli.DbtCLI
description: Use dbt's adapter to drop this already-confirmed table or view. The
macro refuses schema or type changes and never
uses CASCADE.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
containerImage: ghcr.io/kestra-io/dbt-postgres:latest
namespaceFiles:
enabled: true
profiles: "{{ render(vars.dbt_profiles) }}"
inputFiles:
macros/drop_orphan_relation.sql: "{{ vars.drop_macro }}"
commands:
- "dbt run-operation drop_orphan_relation --args
'{{ fromJson(item.value) | toJson }}'"
parseRunResults: false
else:
- id: candidate_changed
type: io.kestra.plugin.core.execution.Fail
errorMessage: "A planned relation changed or disappeared before its write. The
loop stopped without acting on the old snapshot."
- id: deps_verify
type: io.kestra.plugin.dbt.cli.DbtCLI
description: Run dbt deps before the final verification manifest.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
containerImage: ghcr.io/kestra-io/dbt-postgres:latest
commands:
- dbt deps
namespaceFiles:
enabled: true
profiles: "{{ render(vars.dbt_profiles) }}"
parseRunResults: false
- id: list_verify
type: io.kestra.plugin.dbt.cli.DbtCLI
description: Run dbt ls for a fresh post-write verification manifest.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
containerImage: ghcr.io/kestra-io/dbt-postgres:latest
commands:
- dbt ls --select resource_type:model
namespaceFiles:
enabled: true
profiles: "{{ render(vars.dbt_profiles) }}"
outputFiles:
- target/manifest.json
parseRunResults: false
- id: verify
type: io.kestra.plugin.jdbc.postgresql.Query
description: Read the warehouse again and prove every orphan candidate is gone.
url: "{{ inputs.postgres_url }}"
username: "{{ inputs.postgres_user }}"
password: "{{ inputs.postgres_password }}"
fetchType: FETCH
parameters:
target_schema: "{{ inputs.target_schema }}"
manifest_json: "{{
fromJson(read(outputs.list_verify.outputFiles[\"target/manife\
st.json\"])).nodes | jq('[.[] | select(.resource_type ==
\"model\" or .resource_type == \"seed\" or
.resource_type == \"snapshot\") | {schema_name: .schema,
identifier: (.alias // .name)}]') | first }}"
sql: "{{ render(vars.audit_sql) }}"
- id: verify_result
type: io.kestra.plugin.core.flow.If
condition: "{{ (outputs.verify.rows | jq('map(select(.classification ==
\"orphan\")) | length') | first) > 0 }}"
then:
- id: remediation_failed
type: io.kestra.plugin.core.execution.Fail
errorMessage: >-
The dbt drop completed but orphaned relations remain
in information_schema: {{ outputs.verify.rows |
jq('map(select(.classification == "orphan") |
("\(.table_schema).\(.table_name)")) | join(", ")') |
first }}
else:
- id: remediated
type: io.kestra.plugin.core.log.Log
message: "Verified: no relation remains in {{ inputs.target_schema }} outside
the fresh dbt manifest."
else:
- id: declined
type: io.kestra.plugin.core.log.Log
message: "Approval was declined or timed out. No relation was dropped."
else:
- id: dry_run
type: io.kestra.plugin.core.log.Log
message: >-
Dry run only: {{ outputs.audit.rows |
jq('map(select(.classification == "orphan") |
("\(.table_schema).\(.table_name)")) | join(", ")') | first }}
remain as candidates. Set auto_remediate=true and dry_run=false to
request approval.
else:
- id: clean
type: io.kestra.plugin.core.log.Log
message: "No orphaned warehouse relation in {{ inputs.target_schema }}."
errors:
- id: alert_flow_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: >-
{{ {'text': 'dbt orphaned relation guard failed for schema ' ~
inputs.target_schema ~ ' (execution ' ~ execution.id ~ '). Warehouse state
is unknown; inspect the execution before retrying.'} | toJson }}
triggers:
- id: scheduled_audit
type: io.kestra.plugin.core.trigger.Schedule
description: Disabled by default and pinned to read-only inputs.
cron: "0 4 * * *"
disabled: true
inputs:
auto_remediate: false
dry_run: true