id: kafka-schema-registry-subject-version-pruning-guard
namespace: company.team
description: |
Prune the version history of a Confluent Schema Registry subject down to the newest `keep_n`
versions, oldest first, behind an approval gate, then re-read the subject and fail the run if it is
still over the target. A subject under active schema evolution gains a version on every change and
the registry never prunes them, so a subject that has evolved weekly for two years carries more than
a hundred versions. Nothing breaks, it just gets expensive to live with: the `_schemas` storage topic
grows, a version listing becomes unreadable and nobody can say which old version still matters.
The delete is a SOFT delete, so the version leaves the active list while its global schema id stays
resolvable and a consumer still holding that id can keep deserialising old messages. The newest
version is never a target, because that is the one producers register against.
inputs:
- id: schema_registry_url
type: STRING
displayName: Schema Registry URL
description: Base URL of the Confluent Schema Registry, with no trailing slash.
defaults: http://localhost:8081
- id: bootstrap_servers
type: STRING
displayName: Kafka bootstrap servers
description: Comma separated broker list, used to read the live topic set that
scopes the prune.
defaults: localhost:9092
- id: keep_n
type: INT
displayName: Active versions to keep per subject
description: A subject with more active versions than this is pruned down to it,
oldest first. Must be at least 1, because the newest version is the one
producers register against. The flow refuses the run rather than deleting
it.
defaults: 20
- id: subjects
type: ARRAY
itemType: STRING
displayName: Subjects to prune
description: Leave empty to cover every registered subject backing a live topic
under the TopicNameStrategy. Name subjects here to cover those instead.
defaults: []
- id: exempt_subjects
type: ARRAY
itemType: STRING
displayName: Subjects never pruned
description: Subjects whose full version history is kept whatever its length,
for example one under audit. Never read, never changed.
defaults: []
- id: permanent_delete
type: BOOL
displayName: Hard delete instead of soft delete
description: Leave false. True frees the global schema ids as well, so a
consumer holding a pruned id can no longer deserialise and the data is
unrecoverable. It also needs a second confirmation on the approval step.
defaults: false
- id: auto_remediate
type: BOOL
displayName: Auto remediate
defaults: false
- id: dry_run
type: BOOL
displayName: Dry run
description: Must be false, together with auto_remediate, for any version to be deleted.
defaults: true
variables:
audit_key: "sr_versions_{{ inputs.schema_registry_url | slugify }}"
prune_key: "sr_pruned_{{ inputs.schema_registry_url | slugify }}"
verify_key: "sr_prune_verify_{{ inputs.schema_registry_url | slugify }}"
tasks:
- id: list_subjects
type: io.kestra.plugin.core.http.Request
description: Read-only. Every subject the registry serves right now.
method: GET
uri: "{{ inputs.schema_registry_url }}/subjects"
- id: list_topics
type: io.kestra.plugin.kafka.TopicList
description: Read-only AdminClient call. The live topic set is what scopes the
prune, so a subject whose topic is gone keeps its whole history and is
never read or written here.
properties:
bootstrap.servers: "{{ inputs.bootstrap_servers }}"
- id: scope
type: io.kestra.plugin.core.output.OutputValues
description: In scope are the registered subjects backing a live topic (or the
named list) minus the exempt ones. Internal topics are dropped.
values:
subject_list: >-
{{ {'reg': fromJson(outputs.list_subjects.body), 'topics':
outputs.list_topics.topics, 'sel': inputs.subjects, 'ex':
inputs.exempt_subjects} | jq('.reg as $reg | .sel as $sel | .ex as $ex |
([ .topics[] | select(startswith("_") | not) ]) as $pt | (($pt | map(. +
"-value")) + ($pt | map(. + "-key"))) as $exp | (if ($sel | length) > 0
then ($reg - ($reg - $sel)) else ($reg - ($reg - $exp)) end) as $base |
(($base - $ex) | sort)') | first | toJson }}
- id: in_scope
type: io.kestra.plugin.core.flow.If
condition: "{{ fromJson(outputs.scope.values.subject_list) | length > 0 }}"
then:
- id: reset_audit
type: io.kestra.plugin.core.kv.Set
description: The audit accumulator is rebuilt from scratch every run. No ttl, so
the read back inside the run can never hit an expired key.
key: "{{ render(vars.audit_key) }}"
kvType: JSON
value: "{}"
- id: audit
type: io.kestra.plugin.core.flow.Loop
description: Read the active version list of every in scope subject. One at a
time, because each iteration folds its row into a single accumulator.
concurrencyLimit: 1
values: "{{ outputs.scope.values.subject_list }}"
tasks:
- id: read_versions
type: io.kestra.plugin.core.http.Request
description: Read-only. The active versions of this subject. A 404 means every
version was already deleted, which is read as zero active
versions.
method: GET
uri: "{{ inputs.schema_registry_url }}/subjects/{{ item.value }}/versions"
options:
allowFailed: true
- id: row_merge
type: io.kestra.plugin.core.output.OutputValues
description: Observed facts only. The keep_n comparison happens once, in assess.
values:
merged: >-
{{ {'cur': (kv(render(vars.audit_key), errorOnMissing=false) ??
'{}'), 'subject': item.value, 'code':
outputs.read_versions.code, 'body': outputs.read_versions.body}
| jq('(.cur | if type=="string" then (if .=="" then {} else
fromjson end) else . end) as $c | (if .code == 200 then (.body |
fromjson | sort) elif .code == 404 then [] else error("Schema
Registry answered an unexpected status " + (.code | tostring) +
" for " + .subject) end) as $vs | {subject: .subject, active:
($vs | length), versions: $vs} as $row | $c + {(.subject):
$row}') | first | toJson }}
- id: row_save
type: io.kestra.plugin.core.kv.Set
key: "{{ render(vars.audit_key) }}"
kvType: JSON
value: "{{ outputs.row_merge.values.merged }}"
- id: assess
type: io.kestra.plugin.core.output.OutputValues
description: A version is a prune target when fewer than keep_n versions sit
above it. That rule keeps the newest keep_n whatever the numbering
gaps are. It marks a subject unsafe when keep_n is zero, because the
newest version would then be a target.
values:
result: >-
{{ {'rows': (kv(render(vars.audit_key), errorOnMissing=false) ??
'{}'), 'keep': inputs.keep_n} | jq('(.rows | if type=="string" then
(if .=="" then {} else fromjson end) else . end) as $r | .keep as $k
| [ $r[] | .versions as $vs | {subject: .subject, active: .active,
latest: ($vs | max), prune: [ $vs[] | . as $v | select(([ $vs[] |
select(. >= $v) ] | length) > $k) ]} | . + {keep_after: (.active -
(.prune | length)), unsafe: ((.latest != null) and (([.latest] -
.prune) | length) == 0)} ] as $all | ([ $all[] | select((.prune |
length) > 0) ] | sort_by(.subject)) as $over | {audited: ($r |
length), count: ($over | length), total_targets: ([ $over[] |
.prune[] ] | length), subjects: ($over | map(.subject)), targets: [
$over[] | .subject as $s | .prune[] | {subject: $s, version: .} ],
unsafe: [ $over[] | select(.unsafe) | .subject ], detail: $over,
summary: ([ $over[] | .subject + " [" + (.active | tostring) + "
active, prune " + (.prune | map(tostring) | join(",")) + ", keeping
newest " + (.keep_after | tostring) + " up to v" + (.latest |
tostring) + "]" ] | join("; "))}') | first | toJson }}
- id: route
type: io.kestra.plugin.core.flow.If
condition: "{{ fromJson(outputs.assess.values.result).count > 0 }}"
then:
- id: log_findings
type: io.kestra.plugin.core.log.Log
message: >-
Version history scan on {{ inputs.schema_registry_url }}: {{
fromJson(outputs.assess.values.result).audited }} subjects
audited, {{ fromJson(outputs.assess.values.result).count }} over
the keep_n of {{ inputs.keep_n }}, {{
fromJson(outputs.assess.values.result).total_targets }} versions
would be pruned oldest first. {{
fromJson(outputs.assess.values.result).summary }}.
permanent_delete={{ inputs.permanent_delete }} auto_remediate={{
inputs.auto_remediate }} dry_run={{ inputs.dry_run }}.
- id: alert
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: >-
{{ {'text': 'Schema Registry ' ~ inputs.schema_registry_url ~ ': '
~ (fromJson(outputs.assess.values.result).count) ~ ' of ' ~
(fromJson(outputs.assess.values.result).audited) ~ ' audited
subjects carry more than ' ~ inputs.keep_n ~ ' active versions, '
~ (fromJson(outputs.assess.values.result).total_targets) ~ '
versions over target. ' ~
(fromJson(outputs.assess.values.result).summary) ~ '.
permanent_delete=' ~ inputs.permanent_delete ~ ' auto_remediate='
~ inputs.auto_remediate ~ ' dry_run=' ~ inputs.dry_run ~ '.'} |
toJson }}
- id: safety_gate
type: io.kestra.plugin.core.flow.If
description: The newest version of a subject is never deletable. If the computed
target set reaches it, the run stops here instead of pruning
anything.
condition: "{{ fromJson(outputs.assess.values.result).unsafe | length > 0 }}"
then:
- id: refuse_latest
type: io.kestra.plugin.core.execution.Fail
errorMessage: >-
keep_n is {{ inputs.keep_n }}, so the newest version of {{
fromJson(outputs.assess.values.result).unsafe | jq('join(",
")') | first }} would be deleted. That is the version
producers register against, so nothing was pruned. Set keep_n
to 1 or more.
else:
- id: remediate_gate
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.auto_remediate and not inputs.dry_run and
fromJson(outputs.assess.values.result).total_targets > 0 }}"
then:
- id: approve
type: io.kestra.plugin.core.flow.Pause
description: >-
Resume with approved=true to prune the versions listed by
log_findings. With permanent_delete true you must also
pass confirm_permanent=true, because a hard delete is
unrecoverable. Resume without them or kill the execution
to cancel.
onResume:
- id: approved
type: BOOL
displayName: Approve pruning the oldest versions down to keep_n
required: false
- id: confirm_permanent
type: BOOL
displayName: Confirm a hard delete, which frees the schema ids and cannot be
undone
required: false
- id: do_prune
type: io.kestra.plugin.core.flow.If
condition: "{{ (outputs.approve.onResume.approved ?? false) and ((not
inputs.permanent_delete) or
(outputs.approve.onResume.confirm_permanent ?? false)) }}"
then:
- id: reset_pruned
type: io.kestra.plugin.core.kv.Set
key: "{{ render(vars.prune_key) }}"
kvType: JSON
value: "{}"
- id: remediate_prune
type: io.kestra.plugin.core.flow.Loop
description: Remediation. Delete one version at a time, oldest first, recording
the global schema id it carried before the delete so
the verify step can prove the id survived.
concurrencyLimit: 1
values: "{{ fromJson(outputs.assess.values.result).targets | toJson }}"
tasks:
- id: read_version_id
type: io.kestra.plugin.core.http.Request
description: Read-only. It runs before the delete. The global schema id behind
this version is what a consumer holds in a message
header, so it is captured here to be checked
afterwards.
method: GET
uri: "{{ inputs.schema_registry_url }}/subjects/{{ fromJson(item.value).subject
}}/versions/{{ fromJson(item.value).version }}"
options:
allowFailed: true
- id: soft_delete
type: io.kestra.plugin.core.http.Request
description: The prune. A plain DELETE on a version is a soft delete, so the
version leaves the active list and its schema id
stays resolvable. allowFailed lets a rejected
delete fall through to the re-read, which is the
authority.
method: DELETE
uri: "{{ inputs.schema_registry_url }}/subjects/{{ fromJson(item.value).subject
}}/versions/{{ fromJson(item.value).version }}"
options:
allowFailed: true
- id: hard_gate
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.permanent_delete }}"
then:
- id: hard_delete
type: io.kestra.plugin.core.http.Request
description: Only when permanent_delete and confirm_permanent are both set. This
frees the schema id, so a consumer holding it
can no longer resolve the schema.
method: DELETE
uri: "{{ inputs.schema_registry_url }}/subjects/{{ fromJson(item.value).subject
}}/versions/{{ fromJson(item.value).version
}}?permanent=true"
options:
allowFailed: true
- id: resolve_id
type: io.kestra.plugin.core.http.Request
description: Read-only. Ask the registry for the schema by the global id this
version carried. A 200 after a soft delete is the
proof the prune did not break an old consumer.
method: GET
uri: "{{ inputs.schema_registry_url }}/schemas/ids/{{
fromJson(outputs.read_version_id.body).id ?? 0 }}"
options:
allowFailed: true
- id: pruned_merge
type: io.kestra.plugin.core.output.OutputValues
values:
merged: >-
{{ {'cur': (kv(render(vars.prune_key),
errorOnMissing=false) ?? '{}'), 'subject':
fromJson(item.value).subject, 'version':
fromJson(item.value).version, 'rcode':
outputs.read_version_id.code, 'rbody':
outputs.read_version_id.body, 'dcode':
outputs.soft_delete.code, 'icode':
outputs.resolve_id.code} | jq('(.cur | if
type=="string" then (if .=="" then {} else
fromjson end) else . end) as $c | (.subject +
"@v" + (.version | tostring)) as $k | {key: $k,
subject: .subject, version: .version, read_code:
.rcode, schema_id: (if .rcode == 200 then
(.rbody | fromjson | .id) else null end),
delete_code: .dcode, resolve_code: .icode} as
$row | $c + {($k): $row}') | first | toJson }}
- id: pruned_save
type: io.kestra.plugin.core.kv.Set
key: "{{ render(vars.prune_key) }}"
kvType: JSON
value: "{{ outputs.pruned_merge.values.merged }}"
- id: reset_verify
type: io.kestra.plugin.core.kv.Set
key: "{{ render(vars.verify_key) }}"
kvType: JSON
value: "{}"
- id: verify
type: io.kestra.plugin.core.flow.Loop
description: Read the active version list again, straight from the registry, for
every subject that was pruned.
concurrencyLimit: 1
values: "{{ fromJson(outputs.assess.values.result).subjects | toJson }}"
tasks:
- id: recheck_versions
type: io.kestra.plugin.core.http.Request
method: GET
uri: "{{ inputs.schema_registry_url }}/subjects/{{ item.value }}/versions"
options:
allowFailed: true
- id: recheck_merge
type: io.kestra.plugin.core.output.OutputValues
values:
merged: >-
{{ {'cur': (kv(render(vars.verify_key),
errorOnMissing=false) ?? '{}'), 'subject':
item.value, 'code':
outputs.recheck_versions.code, 'body':
outputs.recheck_versions.body} | jq('(.cur | if
type=="string" then (if .=="" then {} else
fromjson end) else . end) as $c | (if .code ==
200 then (.body | fromjson | sort) else
error("Schema Registry answered " + (.code |
tostring) + " on the re-read of " + .subject +
", so the prune is not verified") end) as $vs |
{subject: .subject, active: ($vs | length),
latest: ($vs | max)} as $row | $c + {(.subject):
$row}') | first | toJson }}
- id: recheck_save
type: io.kestra.plugin.core.kv.Set
key: "{{ render(vars.verify_key) }}"
kvType: JSON
value: "{{ outputs.recheck_merge.values.merged }}"
- id: verify_assess
type: io.kestra.plugin.core.output.OutputValues
description: >-
Two independent failures are counted. A subject still
over keep_n means the prune did not land. A pruned
version whose schema id stopped resolving means a soft
delete behaved like a hard delete, which would break a
consumer. That is only expected when permanent_delete
was asked for.
values:
result: >-
{{ {'rows': (kv(render(vars.verify_key),
errorOnMissing=false) ?? '{}'), 'pruned':
(kv(render(vars.prune_key), errorOnMissing=false) ??
'{}'), 'keep': inputs.keep_n, 'perm':
inputs.permanent_delete} | jq('(.rows | if
type=="string" then (if .=="" then {} else fromjson
end) else . end) as $r | (.pruned | if
type=="string" then (if .=="" then {} else fromjson
end) else . end) as $p | .keep as $k | .perm as
$perm | ([ $r[] | select(.active > $k) ] |
sort_by(.subject)) as $still | ([ $p[] |
select(.read_code == 200 and .resolve_code != 200) ]
| sort_by(.key)) as $lost | {checked: ($r | length),
pruned_count: ($p | length), still_over: ($still |
length), lost: (if $perm then 0 else ($lost |
length) end), freed: (if $perm then ($lost | length)
else 0 end), bad: (($still | length) + (if $perm
then 0 else ($lost | length) end)), still_summary:
([ $still[] | .subject + " [" + (.active | tostring)
+ " active, target " + ($k | tostring) + "]" ] |
join("; ")), lost_summary: ([ $lost[] | .key + "
[schema id " + (.schema_id | tostring) + " answers "
+ (.resolve_code | tostring) + "]" ] | join("; ")),
ok_summary: ([ $r[] | .subject + " [" + (.active |
tostring) + " active, newest v" + (.latest |
tostring) + "]" ] | join("; "))}') | first | toJson
}}
- id: verify_result
type: io.kestra.plugin.core.flow.If
condition: "{{ fromJson(outputs.verify_assess.values.result).bad > 0 }}"
then:
- id: prune_failed
type: io.kestra.plugin.core.execution.Fail
errorMessage: >-
Prune ran, but the re-read does not agree. {{
fromJson(outputs.verify_assess.values.result).still_over
}} subjects are still over keep_n of {{
inputs.keep_n }} ({{
fromJson(outputs.verify_assess.values.result).still_summary
}}). {{
fromJson(outputs.verify_assess.values.result).lost
}} pruned versions lost their global schema id ({{
fromJson(outputs.verify_assess.values.result).lost_summary
}}), which a soft delete must never do. Check
whether the subject is read only, whether a
producer registered a new version during the pause
or whether something else hard deleted the schema.
else:
- id: pruned_ok
type: io.kestra.plugin.core.log.Log
message: >-
Pruned {{
fromJson(outputs.verify_assess.values.result).pruned_count
}} versions across {{
fromJson(outputs.verify_assess.values.result).checked
}} subjects. Now {{
fromJson(outputs.verify_assess.values.result).ok_summary
}}. Schema ids freed by a hard delete: {{
fromJson(outputs.verify_assess.values.result).freed
}}. Every soft deleted version still resolves by
its global schema id, so a consumer holding an old
id can still deserialise.
else:
- id: not_approved
type: io.kestra.plugin.core.log.Log
message: >-
Nothing was deleted. Either the resume carried no
approval or permanent_delete was set without
confirm_permanent. approved={{
outputs.approve.onResume.approved ?? false }}
permanent_delete={{ inputs.permanent_delete }}
confirm_permanent={{
outputs.approve.onResume.confirm_permanent ?? false
}}.
else:
- id: report_only
type: io.kestra.plugin.core.log.Log
message: >-
Reported only. {{
fromJson(outputs.assess.values.result).total_targets }}
versions are over the keep_n of {{ inputs.keep_n }} and
nothing was deleted, because auto_remediate={{
inputs.auto_remediate }} and dry_run={{ inputs.dry_run }}.
Set auto_remediate true and dry_run false to be offered
the approval step.
else:
- id: all_within
type: io.kestra.plugin.core.log.Log
message: >-
Every one of the {{ fromJson(outputs.assess.values.result).audited
}} audited subjects on {{ inputs.schema_registry_url }} holds {{
inputs.keep_n }} or fewer active versions. No version history to
prune.
else:
- id: no_subjects
type: io.kestra.plugin.core.log.Log
message: >-
No subject on {{ inputs.schema_registry_url }} is in scope. Either the
registry has no subjects, none of them backs a live Kafka topic under
the TopicNameStrategy or every candidate is exempt. Nothing read,
nothing changed.
errors:
- id: alert_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: >-
{{ {'text': 'Kafka schema registry subject version pruning guard failed on
' ~ inputs.schema_registry_url ~ ' (execution ' ~ execution.id ~ '). No
version was deleted unless a log line says pruned. Check the logs.'} |
toJson }}
triggers:
- id: weekly_scan
type: io.kestra.plugin.core.trigger.Schedule
description: Shipped disabled and always in safe mode.
cron: "0 4 * * 1"
disabled: true
inputs:
auto_remediate: false
dry_run: true
permanent_delete: false