id: elasticsearch-forcemerge-deleted-docs-reclaim-guard
namespace: company.team
description: |
Find cold Elasticsearch indices wasting disk on deleted documents, run
POST /<index>/_forcemerge?only_expunge_deletes=true behind a dry run and
an approval gate to compact those segments, then re-read _stats and fail
the run if the deleted-doc ratio did not come back down. The flow refuses
any index that is still being written to, which is the Elasticsearch
force-merge footgun.
inputs:
- id: elasticsearch_url
type: STRING
defaults: "http://localhost:9200"
description: Base URL of the Elasticsearch cluster, scheme host and port.
- id: elasticsearch_username
type: STRING
defaults: ""
description: Overrides the ELASTICSEARCH_USERNAME secret when set. Leave empty
to use the secret. On a cluster with security disabled set any value,
because it is ignored there and the secret is then not read.
- id: elasticsearch_password
type: STRING
defaults: ""
description: Overrides the ELASTICSEARCH_PASSWORD secret when set. Leave empty
to use the secret. On a cluster with security disabled set any value,
because it is ignored there and the secret is then not read.
- id: index_pattern
type: STRING
defaults: "*"
description: Index or pattern to inspect. Defaults to every index.
- id: include_system_indices
type: BOOL
defaults: false
description: >-
When true, dot-prefixed and hidden indices are inspected too. Off by
default because those belong to Elasticsearch and its plugins.
- id: min_deleted_pct
type: INT
defaults: 20
description: >-
An index is flagged once its deleted documents are at least this percent
of all documents still held in its segments (live plus deleted). Force
merge expunge only rewrites a segment whose deletes are above
index.merge.policy.expunge_deletes_allowed (10 percent by default), so
keep this above that.
- id: min_total_docs
type: INT
defaults: 1000
description: >-
Ignore an index that holds fewer than this many documents (live plus
deleted). A tiny index wastes little disk and a high ratio on it is noise.
- id: require_write_block
type: BOOL
defaults: true
description: >-
When true an index must carry index.blocks.write or index.blocks.read_only
to be eligible, which is positive proof it stopped taking writes (the
state ILM sets before its own force-merge). When false an index with no
block still qualifies if it showed no write activity across the probe
window.
- id: write_probe_wait
type: DURATION
defaults: PT10S
description: >-
Gap between the two indexing samples used to tell whether an index is
still receiving writes. If indexing.index_total moves across this window
the index is refused. Raise it on a cluster written in bursts.
- id: max_merge_per_run
type: INT
defaults: 10
description: >-
The flow refuses to force merge when more indices than this are eligible
in one pass. Force merge is heavy IO, so a long list is kicked back for
review rather than run all at once.
- id: verify_wait
type: DURATION
defaults: PT5S
description: >-
Settle time after the force merge before re-reading _stats. Force merge is
synchronous so this is a small margin, not a poll.
- id: dry_run
type: BOOL
defaults: true
description: When true the flow only reports, it never force merges an index.
- id: auto_remediate
type: BOOL
defaults: false
description: When true and dry_run is false the flow force merges the eligible
indices after approval.
triggers:
- id: nightly
type: io.kestra.plugin.core.trigger.Schedule
description: Scan for deleted-doc bloat every night in safe report-only mode.
Force merge is heavy IO, so it runs off peak.
cron: "0 3 * * *"
disabled: true
inputs:
dry_run: true
auto_remediate: false
tasks:
- id: detect_cluster
type: io.kestra.plugin.elasticsearch.Request
description: Read cluster health for context and as the baseline reachability check.
connection:
hosts:
- "{{ inputs.elasticsearch_url }}"
basicAuth:
username: "{{ inputs.elasticsearch_username != '' ?
inputs.elasticsearch_username : secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ inputs.elasticsearch_password != '' ?
inputs.elasticsearch_password : secret('ELASTICSEARCH_PASSWORD') }}"
method: GET
endpoint: "_cluster/health"
- id: detect_stats_before
type: io.kestra.plugin.elasticsearch.Request
description: >-
First _stats sample. Reads primary-shard doc counts for the deleted ratio
and the indexing counters for the write-activity probe. Primaries are read
so a replica does not double count the same documents.
connection:
hosts:
- "{{ inputs.elasticsearch_url }}"
basicAuth:
username: "{{ inputs.elasticsearch_username != '' ?
inputs.elasticsearch_username : secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ inputs.elasticsearch_password != '' ?
inputs.elasticsearch_password : secret('ELASTICSEARCH_PASSWORD') }}"
method: GET
endpoint: "{{ inputs.index_pattern }}/_stats/docs,indexing"
parameters:
expand_wildcards: "open,hidden"
filter_path: "indices.*.primaries.docs.count,indices.*.primaries.docs.deleted,i\
ndices.*.primaries.indexing.index_total,indices.*.primaries.indexing.in\
dex_current"
- id: detect_settings
type: io.kestra.plugin.elasticsearch.Request
description: Read the write blocks and the hidden flag for every matching index,
so a cold index is told apart from a live one and system indices can be
filtered out.
connection:
hosts:
- "{{ inputs.elasticsearch_url }}"
basicAuth:
username: "{{ inputs.elasticsearch_username != '' ?
inputs.elasticsearch_username : secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ inputs.elasticsearch_password != '' ?
inputs.elasticsearch_password : secret('ELASTICSEARCH_PASSWORD') }}"
method: GET
endpoint: "{{ inputs.index_pattern
}}/_settings/index.blocks.write,index.blocks.read_only,index.blocks.read_\
only_allow_delete,index.hidden"
parameters:
flat_settings: "true"
expand_wildcards: "open,hidden"
- id: probe_wait
type: io.kestra.plugin.core.flow.Sleep
description: >-
Wait between the two indexing samples. If indexing.index_total climbs
across this gap the index is still taking writes and must not be force
merged.
duration: "{{ inputs.write_probe_wait }}"
- id: detect_stats_after
type: io.kestra.plugin.elasticsearch.Request
description: Second _stats sample. The doc counts for the ratio come from this
later read and index_total here against the first read is the
write-activity signal.
connection:
hosts:
- "{{ inputs.elasticsearch_url }}"
basicAuth:
username: "{{ inputs.elasticsearch_username != '' ?
inputs.elasticsearch_username : secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ inputs.elasticsearch_password != '' ?
inputs.elasticsearch_password : secret('ELASTICSEARCH_PASSWORD') }}"
method: GET
endpoint: "{{ inputs.index_pattern }}/_stats/docs,indexing"
parameters:
expand_wildcards: "open,hidden"
filter_path: "indices.*.primaries.docs.count,indices.*.primaries.docs.deleted,i\
ndices.*.primaries.indexing.index_total,indices.*.primaries.indexing.in\
dex_current"
- id: check_reads
type: io.kestra.plugin.core.flow.If
description: >-
The Request task reports task success on any HTTP status, so every read is
gated on its status here. A 404 on the pattern would otherwise pass for a
healthy cluster with nothing to reclaim.
condition: "{{ outputs.detect_cluster.status != 200 or
outputs.detect_stats_before.status != 200 or
outputs.detect_settings.status != 200 or outputs.detect_stats_after.status
!= 200 }}"
then:
- id: fail_reads
type: io.kestra.plugin.core.execution.Fail
description: Fail when the cluster could not be read so nothing downstream acts
on a partial picture.
errorMessage: >-
Could not read the cluster. health {{ outputs.detect_cluster.status
}}, stats before {{ outputs.detect_stats_before.status }}, settings {{
outputs.detect_settings.status }}, stats after {{
outputs.detect_stats_after.status }}.
- id: plan
type: io.kestra.plugin.core.output.OutputValues
description: >-
Build the candidate list. An index is a candidate when its deleted share
of held docs is at least min_deleted_pct and it holds at least
min_total_docs. Each candidate is then marked eligible only when it is not
receiving writes (index_total steady across the probe, no in-flight
indexing), carries no disk read-only block and has a write block unless
require_write_block is off.
values:
cluster_status: "{{ outputs.detect_cluster.response | jq('.status') | first }}"
inspected: "{{ outputs.detect_stats_after.response | jq('(.indices // {}) |
length') | first }}"
candidates_json: >-
{{ {'a': outputs.detect_stats_after.response, 'b':
outputs.detect_stats_before.response, 's':
outputs.detect_settings.response, 'inc': inputs.include_system_indices,
'minpct': inputs.min_deleted_pct, 'mindocs': inputs.min_total_docs,
'reqblock': inputs.require_write_block} | toJson | jq('. as $r |
($r.a.indices // {}) as $A | ($r.b.indices // {}) as $B | ($r.s // {})
as $S | [ $A | to_entries[] | .key as $k | .value.primaries as $p |
(($p.docs.count) // 0) as $cnt | (($p.docs.deleted) // 0) as $del |
($cnt + $del) as $held | (if $held > 0 then ($del * 100 / $held) else 0
end) as $ratio | select($ratio >= $r.minpct) | select($held >=
$r.mindocs) | (($p.indexing.index_total) // 0) as $ta |
(($p.indexing.index_current) // 0) as $ca |
($B[$k].primaries.indexing.index_total) as $tb |
((($S[$k].settings["index.blocks.write"]) // "false") == "true") as $wb
| ((($S[$k].settings["index.blocks.read_only"]) // "false") == "true")
as $ro | ((($S[$k].settings["index.blocks.read_only_allow_delete"]) //
"false") == "true") as $rod | ((($S[$k].settings["index.hidden"]) //
"false") == "true") as $hid | ($wb or $ro) as $blk | (if $tb == null
then true else ($ta > $tb) end) as $moved | ($ca > 0) as $inflight |
(($rod | not) and ($moved | not) and ($inflight | not) and ($blk or
($r.reqblock | not))) as $elig | (if $elig then "" else (if $rod then
"disk read-only block set (index.blocks.read_only_allow_delete), do not
force merge under disk pressure" else (if $moved then
"indexing.index_total moved across the probe window, the index is still
receiving writes" else (if $inflight then "indexing operations are in
flight (index_current above zero)" else "no write block present and
require_write_block is true, so there is no proof the index stopped
taking writes" end) end) end) end) as $reason | {index: $k, count: $cnt,
deleted: $del, held: $held, blk: $blk, diskblk: $rod, moved: $moved,
cur: $ca, eligible: $elig, reason: $reason, system: (($k |
startswith(".")) or $hid)} ] | map(select($r.inc or (.system ==
false)))') | first | toJson }}
- id: summary
type: io.kestra.plugin.core.output.OutputValues
description: Split the candidates into the eligible merge set and the refused
set and build a readable line for each. The percent is printed as a
truncated integer so a float like 50.0 never reaches the log.
values:
merge_json: "{{ outputs.plan.values.candidates_json | jq('[.[] |
select(.eligible)]') | first | toJson }}"
refused_json: "{{ outputs.plan.values.candidates_json | jq('[.[] |
select(.eligible | not)]') | first | toJson }}"
merge_names: >-
{{ outputs.plan.values.candidates_json | jq('[.[] | select(.eligible) |
.index + " (" + (.held|tostring) + " held, " + (.deleted|tostring) + "
deleted, " + ((.deleted * 100 / .held)|tostring|split(".")|.[0]) + "
percent)"] | join(" | ")') | first }}
refused_names: >-
{{ outputs.plan.values.candidates_json | jq('[.[] | select(.eligible |
not) | .index + " (" + ((.deleted * 100 /
.held)|tostring|split(".")|.[0]) + " percent deleted, REFUSED: " +
.reason + ")"] | join(" | ")') | first }}
- id: report
type: io.kestra.plugin.core.log.Log
description: Record the cluster context, the eligible merge set, the refused set
and the mode.
message: |
Deleted-doc reclaim scan on pattern {{ inputs.index_pattern }}.
Cluster status {{ outputs.plan.values.cluster_status }}. Indices inspected: {{ outputs.plan.values.inspected }}.
Threshold: {{ inputs.min_deleted_pct }} percent deleted, minimum {{ inputs.min_total_docs }} docs held. require_write_block={{ inputs.require_write_block }}.
Eligible to force merge: {{ outputs.summary.values.merge_json | jq('length') | first }}. {{ outputs.summary.values.merge_names }}
Refused because they are not provably read-only: {{ outputs.summary.values.refused_json | jq('length') | first }}. {{ outputs.summary.values.refused_names }}
This compacts segments to drop already-deleted docs. It deletes no live data and is not a retention flow.
Mode dry_run={{ inputs.dry_run }} auto_remediate={{ inputs.auto_remediate }} max_merge_per_run={{ inputs.max_merge_per_run }} write_probe_wait={{ inputs.write_probe_wait }}.
- id: alert_detected_gate
type: io.kestra.plugin.core.flow.If
description: Alert Slack the moment bloat is found, before and apart from any
remediation decision, so a plain scan or a dry run both alert.
condition: "{{ (outputs.plan.values.candidates_json | jq('length') | first) > 0 }}"
then:
- id: alert_detected
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Post the eligible and refused indices and whether a force merge
will run on this pass. The payload is built as a map then serialized
so an index name cannot break the JSON.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: >-
{{ {'text': 'Elasticsearch deleted-doc reclaim guard: ' ~
(outputs.plan.values.candidates_json | jq('length') | first) ~ '
index(es) on pattern ' ~ inputs.index_pattern ~ ' hold more than ' ~
inputs.min_deleted_pct ~ ' percent deleted docs wasting disk. Eligible
to force merge: ' ~ (outputs.summary.values.merge_json | jq('length')
| first) ~ '. ' ~ outputs.summary.values.merge_names ~ '. Refused as
not provably read-only: ' ~ (outputs.summary.values.refused_json |
jq('length') | first) ~ '. ' ~ outputs.summary.values.refused_names ~
'. dry_run=' ~ inputs.dry_run ~ ' auto_remediate=' ~
inputs.auto_remediate ~ '.'} | toJson }}
- id: route
type: io.kestra.plugin.core.flow.If
description: Act only when an eligible index is present and the operator asked
for a real change.
condition: "{{ (outputs.summary.values.merge_json | jq('length') | first) > 0
and inputs.auto_remediate and not inputs.dry_run }}"
then:
- id: cap_gate
type: io.kestra.plugin.core.flow.If
description: >-
Force merge only while the eligible list is small. Force merge is
heavy IO, so a long list is kicked back rather than run all at once,
which would saturate the cluster.
condition: "{{ (outputs.summary.values.merge_json | jq('length') | first) <=
inputs.max_merge_per_run }}"
then:
- id: approval_gate
type: io.kestra.plugin.core.flow.Pause
description: >-
Hold the run until a human approves the force merge. It is heavy
IO on the data path, so it never starts on its own.
pauseDuration: PT2H
behavior: FAIL
onResume:
- id: approved
type: BOOL
defaults: false
description: >-
Set true to force merge the eligible indices to expunge
deletes. Anything else leaves them untouched.
- id: apply
type: io.kestra.plugin.core.flow.If
description: Run the force merge only on an explicit approval. An unanswered
gate never reads as approval.
condition: "{{ outputs.approval_gate.onResume.approved ?? false }}"
then:
- id: remediate_forcemerge
type: io.kestra.plugin.core.flow.Loop
description: >-
Remediation loop. One POST
_forcemerge?only_expunge_deletes=true per eligible index,
concurrencyLimit 1 so the merges run in turn and never pile
heavy IO on the cluster at once. allowFailure so one rejected
merge does not stop the pass and the re-read stays the real
gate.
concurrencyLimit: 1
values: "{{ outputs.summary.values.merge_json }}"
tasks:
- id: forcemerge_one
type: io.kestra.plugin.elasticsearch.Request
description: Compact one index, expunging only segments whose deletes are above
the index expunge threshold. only_expunge_deletes does not
force one giant segment, so it does not create the segment
that can never merge again.
allowFailure: true
connection:
hosts:
- "{{ inputs.elasticsearch_url }}"
basicAuth:
username: "{{ inputs.elasticsearch_username != '' ?
inputs.elasticsearch_username :
secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ inputs.elasticsearch_password != '' ?
inputs.elasticsearch_password :
secret('ELASTICSEARCH_PASSWORD') }}"
method: POST
endpoint: "{{ fromJson(item.value).index }}/_forcemerge"
parameters:
only_expunge_deletes: "true"
- id: forcemerge_log
type: io.kestra.plugin.core.log.Log
message: >-
POST {{ fromJson(item.value).index
}}/_forcemerge?only_expunge_deletes=true on {{
fromJson(item.value).deleted }} deleted of {{
fromJson(item.value).held }} held returned HTTP {{
outputs.forcemerge_one.status }}.
- id: settle
type: io.kestra.plugin.core.flow.Sleep
description: Small settle before the re-read. Force merge is synchronous so the
segment stats are already updated, this is only a margin.
duration: "{{ inputs.verify_wait }}"
- id: reverify_stats
type: io.kestra.plugin.elasticsearch.Request
description: Re-read primary doc counts so the verdict comes from the cluster
itself, not from the force merge call returning 200.
connection:
hosts:
- "{{ inputs.elasticsearch_url }}"
basicAuth:
username: "{{ inputs.elasticsearch_username != '' ?
inputs.elasticsearch_username :
secret('ELASTICSEARCH_USERNAME') }}"
password: "{{ inputs.elasticsearch_password != '' ?
inputs.elasticsearch_password :
secret('ELASTICSEARCH_PASSWORD') }}"
method: GET
endpoint: "{{ inputs.index_pattern }}/_stats/docs"
parameters:
expand_wildcards: "open,hidden"
filter_path: "indices.*.primaries.docs.count,indices.*.primaries.docs.deleted"
- id: verify_plan
type: io.kestra.plugin.core.output.OutputValues
description: >-
Keep the merged indices whose deleted ratio is still at or
above the threshold, meaning the space did not come back. It
also records the before and after counts so the drop is on the
record.
values:
still_json: >-
{{ {'t': outputs.summary.values.merge_json, 'r':
outputs.reverify_stats.response, 'minpct':
inputs.min_deleted_pct} | toJson | jq('. as $x | ($x.t |
fromjson) as $t | ($x.r.indices // {}) as $A | [ $t[] |
.index as $i | ($A[$i].primaries // {}) as $p |
(($p.docs.count) // 0) as $cnt | (($p.docs.deleted) // 0) as
$del | ($cnt + $del) as $held | (if $held > 0 then ($del *
100 / $held) else 0 end) as $ratio | select($ratio >=
$x.minpct) | {index: $i, count: $cnt, deleted: $del, held:
$held, pct: ($ratio|tostring|split(".")|.[0])} ]') | first |
toJson }}
still_names: >-
{{ {'t': outputs.summary.values.merge_json, 'r':
outputs.reverify_stats.response, 'minpct':
inputs.min_deleted_pct} | toJson | jq('. as $x | ($x.t |
fromjson) as $t | ($x.r.indices // {}) as $A | [ $t[] |
.index as $i | ($A[$i].primaries // {}) as $p |
(($p.docs.count) // 0) as $cnt | (($p.docs.deleted) // 0) as
$del | ($cnt + $del) as $held | (if $held > 0 then ($del *
100 / $held) else 0 end) as $ratio | select($ratio >=
$x.minpct) | ($i + " (" + ($del|tostring) + " deleted of " +
($held|tostring) + " held, " +
($ratio|tostring|split(".")|.[0]) + " percent)") ] | join("
| ")') | first }}
after_summary: >-
{{ {'t': outputs.summary.values.merge_json, 'r':
outputs.reverify_stats.response} | toJson | jq('. as $x |
($x.t | fromjson) as $t | ($x.r.indices // {}) as $A | [
$t[] | .index as $i | ($i + ": deleted " +
(.deleted|tostring) + " to " +
((($A[$i].primaries.docs.deleted) // -1)|tostring) + ", held
" + (.held|tostring) + " to " +
(((($A[$i].primaries.docs.count) // 0) +
(($A[$i].primaries.docs.deleted) // 0))|tostring)) ] |
join(" | ")') | first }}
- id: verify_report
type: io.kestra.plugin.core.log.Log
description: Record the state after the pass so the audit trail carries the
result.
message: |
After the pass on pattern {{ inputs.index_pattern }}.
Reclaim per index: {{ outputs.verify_plan.values.after_summary }}.
Still over the {{ inputs.min_deleted_pct }} percent threshold of the {{ outputs.summary.values.merge_json | jq('length') | first }} merged: {{ outputs.verify_plan.values.still_json | jq('length') | first }}. {{ outputs.verify_plan.values.still_names }}
- id: verify_result
type: io.kestra.plugin.core.flow.If
description: Pass only when every merged index dropped below the threshold,
otherwise fail loudly.
condition: "{{ outputs.reverify_stats.status != 200 or
(outputs.verify_plan.values.still_json | jq('length') | first)
> 0 }}"
then:
- id: remediation_failed
type: io.kestra.plugin.core.execution.Fail
description: Fail when an index is still over the threshold so a merge that
reclaimed nothing is never reported as green.
errorMessage: >-
{{ outputs.verify_plan.values.still_json | jq('length') |
first }} of {{ outputs.summary.values.merge_json |
jq('length') | first }} merged index(es) are still at or
above {{ inputs.min_deleted_pct }} percent deleted: {{
outputs.verify_plan.values.still_names }}. Re-read status
{{ outputs.reverify_stats.status }}. only_expunge_deletes
rewrites a segment only when its deletes are above
index.merge.policy.expunge_deletes_allowed and it skips a
segment past max_merged_segment, so a segment set either
side of those keeps its deletes. Check those settings on
the index.
else:
- id: remediated
type: io.kestra.plugin.core.log.Log
description: Record that every merged index came back under the threshold.
message: >-
Reclaimed and verified. {{
outputs.summary.values.merge_json | jq('length') | first
}} index(es) were above {{ inputs.min_deleted_pct }}
percent deleted, 0 of them after the merge. {{
outputs.verify_plan.values.after_summary }}.
else:
- id: not_approved
type: io.kestra.plugin.core.log.Log
description: Record that approval was withheld so nothing was merged.
message: >-
Approval not granted, so no index was force merged. {{
outputs.summary.values.merge_json | jq('length') | first }}
index(es) are still carrying deleted-doc bloat: {{
outputs.summary.values.merge_names }}.
else:
- id: refuse_report
type: io.kestra.plugin.core.log.Log
description: Record that the flow refused to act because too many indices were
eligible at once.
message: >-
Refusing to force merge. {{ outputs.summary.values.merge_json |
jq('length') | first }} index(es) are eligible against
max_merge_per_run {{ inputs.max_merge_per_run }}. Force merge is
heavy IO, so narrow index_pattern or raise max_merge_per_run once
you have reviewed the list. Eligible: {{
outputs.summary.values.merge_names }}.
- id: fail_cap
type: io.kestra.plugin.core.execution.Fail
description: Fail so the alert fires, force merging a list this long at once
would saturate the cluster.
errorMessage: >-
{{ outputs.summary.values.merge_json | jq('length') | first }}
eligible index(es) exceed max_merge_per_run {{
inputs.max_merge_per_run }}, so nothing was merged. Narrow the
pattern or raise the cap after review.
else:
- id: report_only
type: io.kestra.plugin.core.log.Log
description: Record a no-change outcome, either nothing is eligible, everything
was refused as still being written to or the run is in report mode.
message: >-
No force merge on pattern {{ inputs.index_pattern }}. Eligible {{
outputs.summary.values.merge_json | jq('length') | first }}, refused
{{ outputs.summary.values.refused_json | jq('length') | first }},
dry_run {{ inputs.dry_run }}, auto_remediate {{ inputs.auto_remediate
}}.
errors:
- id: alert
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alert Slack on any failure so a refused pass or a merge that
reclaimed nothing is never silent.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: >-
{{ {'text': 'elasticsearch-forcemerge-deleted-docs-reclaim-guard failed in
flow ' ~ flow.id ~ ' (execution ' ~ execution.id ~ ') on pattern ' ~
inputs.index_pattern ~ '. One of these happened: the cluster could not be
read, more indices were eligible than max_merge_per_run allows, a merged
index was still over the deleted threshold afterwards. Check the execution
logs.'} | toJson }}