id: ai-agent-looping-flow-pause-or-disable
namespace: company.team
description: |
Pause a looping agent flow for real. Once an hour this flow reads the
real recent executions of one configured agent flow with the native
executions.Query task, tests them against genuine loop signatures, and
when a loop is found and remediation is opted in, it switches off that
flow's triggers with triggers.Toggle and kills its running executions
with executions.Kill, then reports what it did. Switching the triggers
off stops the flow firing, but a manual run stays possible, so the docs
say so plainly. With remediation off, a loop is reported but nothing is
switched off or killed, so remediation always needs a clear opt-in.
Runs since the last applied remediation only are counted, so an hour
later the same old failures cannot re-flag the flow. A detected loop
is always reported with its evidence, never left as a bare failed run.
The schedule trigger passes
the target flow identity explicitly, so a scheduled run cannot fail for
missing inputs, and a run that cannot read the history fails closed
instead of reporting a clean bill of health.
triggers:
- id: hourly_loop_remediation
type: io.kestra.plugin.core.trigger.Schedule
description: |
Hourly sweep of the configured agent flow. The trigger inputs below
pass the target flow identity explicitly (tenant, Kestra URL,
namespace, and agent flow id), so a scheduled run carries the
target identity without depending on manual input.
Repoint these four values at your own Kestra instance and agent
flow before relying on the defaults, which point at a local
instance and an example flow id as a runnable example.
cron: "0 * * * *"
inputs:
tenant: "main"
kestra_url: "http://localhost:8080"
namespace: "company.team"
agent_flow_id: "example-agent-flow"
inputs:
- id: tenant
type: STRING
displayName: Kestra tenant
description: Tenant segment of the Kestra API path. The default main tenant is
the open source default.
defaults: main
- id: kestra_url
type: STRING
displayName: Kestra URL
description: Base URL of the Kestra instance whose executions are read, with no
trailing slash.
defaults: http://localhost:8080
- id: namespace
type: STRING
displayName: Agent flow namespace
description: Namespace that holds the agent flow. Matched exactly.
defaults: company.team
- id: agent_flow_id
type: STRING
displayName: Agent flow id
description: Id of the AI agent flow whose execution history is watched and
whose triggers are switched off when a loop is found. The schedule trigger
passes this same value explicitly, so a scheduled run never fails for a
missing input. Repoint it at your real agent flow before relying on this
flow.
defaults: example-agent-flow
- id: apply_remediation
type: BOOL
displayName: Apply remediation
description: When true, a LOOP verdict switches off the target flow's triggers
and kills its running executions. When false (the default), a LOOP verdict
is only reported and nothing is switched off or killed, so the destructive
step needs a clear opt-in.
defaults: false
- id: lookback_hours
type: INT
displayName: Lookback window in hours
description: How far back the remediation flow reaches into the execution
history. Runs since the last applied remediation are counted even inside
this window, so the window is a cap, not the only filter.
defaults: 24
- id: max_consecutive_failures
type: INT
displayName: Maximum consecutive failures
description: A run of this many FAILED executions in a row, ending at the most
recent execution, counts as a failure loop.
defaults: 3
- id: max_repeated_task_failures
type: INT
displayName: Maximum repeated task failures
description: The same task failing in this many distinct executions of the agent
flow counts as a failure loop, even when successful runs sit between the
failures.
defaults: 3
- id: max_failure_percent
type: INT
displayName: Maximum failure percent
description: Failure percent above this cap counts as a failure loop, once the
minimum execution count below is met. Set to 100 to disable the rate rule
and rely on the loop rules only.
defaults: 50
- id: min_executions_for_rate
type: INT
displayName: Minimum executions for the rate rule
description: The rate rule only fires once at least this many executions of the
agent flow exist in the window, so two failures out of three runs cannot
trip a percent cap on a tiny sample.
defaults: 5
tasks:
- id: check_target_flow
type: io.kestra.plugin.kestra.flows.List
description: |
Pre-check that the target flow exists in the namespace before any
history is judged. The evaluation task fails closed with
INCONCLUSIVE when the target flow id is absent from this list, so
a typo in the flow id can never read as a clean history.
kestraUrl: "{{ inputs.kestra_url }}"
tenantId: "{{ inputs.tenant }}"
namespace: "{{ inputs.namespace }}"
auth:
apiToken: "{{ secret('KESTRA_API_TOKEN') }}"
- id: read_last_remediation
type: io.kestra.plugin.core.kv.Get
description: |
Read the timestamp of the last applied remediation from KV. The key
carries the target flow id, so two watched flows never share a
floor. Runs at or before that timestamp are excluded from the loop
signatures, so an hourly run cannot re-flag failures that were
already acted on. Missing KV (no remediation applied yet) falls
back to the lookback window only.
key: ai-agent-looping-flow-last-remediation-at-{{ inputs.agent_flow_id }}
errorOnMissing: false
- id: query_target_history
type: io.kestra.plugin.kestra.executions.Query
description: |
Read the recent executions of exactly the target flow with the
native Query task, filtered by namespace and flow id and limited
to the lookback window. FETCH returns the light rows in the task
output for the evaluation task below. Light rows carry no
taskRunList and no startDate, only the state with its dated
history, so the evaluation re-sorts by state history date and
fetches full executions for FAILED ids only.
kestraUrl: "{{ inputs.kestra_url }}"
tenantId: "{{ inputs.tenant }}"
namespace: "{{ inputs.namespace }}"
flowId: "{{ inputs.agent_flow_id }}"
timeRange: "PT{{ inputs.lookback_hours }}H"
size: 100
fetchType: FETCH
auth:
apiToken: "{{ secret('KESTRA_API_TOKEN') }}"
- id: evaluate_loop
type: io.kestra.plugin.scripts.python.Script
description: |
Test the queried executions against three loop signatures, namely
consecutive FAILED runs, the same task failing across several
runs, and failure percent above the cap. Nothing in this task is
sample data. The consecutive and rate signatures come from the
Query rows; the repeated-task signature fetches the full execution
for FAILED ids only (light rows carry no taskRunList), so one
detail call per failed execution, never per execution in the
window. Rows are re-sorted by state history date in evaluation
rather than trusting search order, and only runs after the last
applied remediation (or the lookback start when no remediation is
stored) are counted. Zero executions in the window yields CLEAR: a
flow with no runs since the last remediation (triggers off, or a
quiet flow) has no loop to act on. A run that cannot read the
history, finds the
target flow missing, finds rows with no datable state history, or
fails a FAILED-id detail fetch yields INCONCLUSIVE, never a clean
verdict for a history it could not judge, and the triage task
below fails the run on INCONCLUSIVE.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: python:3.12-slim
env:
TENANT: "{{ inputs.tenant }}"
KESTRA_URL: "{{ inputs.kestra_url }}"
NAMESPACE: "{{ inputs.namespace }}"
AGENT_FLOW_ID: "{{ inputs.agent_flow_id }}"
LOOKBACK_HOURS: "{{ inputs.lookback_hours }}"
MAX_CONSECUTIVE_FAILURES: "{{ inputs.max_consecutive_failures }}"
MAX_REPEATED_TASK_FAILURES: "{{ inputs.max_repeated_task_failures }}"
MAX_FAILURE_PERCENT: "{{ inputs.max_failure_percent }}"
MIN_EXECUTIONS_FOR_RATE: "{{ inputs.min_executions_for_rate }}"
LAST_REMEDIATION: "{{ outputs.read_last_remediation.value }}"
QUERY_ROWS: "{{ outputs.query_target_history.rows | toJson }}"
FLOWS_LIST: "{{ outputs.check_target_flow.flows | toJson }}"
KESTRA_API_TOKEN: "{{ secret('KESTRA_API_TOKEN') }}"
script: |
import json
import os
import urllib.error
import urllib.request
from datetime import datetime, timedelta, timezone
def http_get(url, token):
headers = {
"Accept": "application/json",
"User-Agent": "kestra-ai-agent-looping-flow-pause-or-disable",
}
if token:
headers["Authorization"] = "Bearer " + token
request = urllib.request.Request(url, method="GET", headers=headers)
try:
with urllib.request.urlopen(request, timeout=30) as response:
return response.status, response.read().decode("utf-8", "replace"), None
except urllib.error.HTTPError as err:
return err.code, err.read().decode("utf-8", "replace"), None
except Exception as err: # noqa: BLE001 - any transport failure is inconclusive
return None, "", str(err)
def state_of(obj):
state = obj.get("state", "") if isinstance(obj, dict) else ""
if isinstance(state, dict):
return state.get("current", "")
return state or ""
def row_date(obj):
# Light rows carry no startDate. The first state history entry
# is the run's creation, so it is the ordering and window key.
state = obj.get("state", {}) if isinstance(obj, dict) else {}
histories = state.get("histories", []) if isinstance(state, dict) else []
if isinstance(histories, list) and histories:
first = histories[0] if isinstance(histories[0], dict) else {}
value = first.get("date", "")
if isinstance(value, str) and value:
try:
return datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
return None
return None
def parse_date(value):
if not isinstance(value, str) or not value:
return None
try:
return datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
return None
def emit(outputs):
print("::" + json.dumps({"outputs": outputs}) + "::")
def inconclusive(reason):
emit({
"verdict": "INCONCLUSIVE",
"executions_checked": 0,
"failed_count": 0,
"consecutive_failures": 0,
"repeated_task_failures": 0,
"failure_percent": 0,
"running_execution_ids": [],
"reasons": [reason],
})
def main():
now = datetime.now(timezone.utc)
tenant = os.environ.get("TENANT", "main")
base = os.environ.get("KESTRA_URL", "").rstrip("/")
namespace = os.environ.get("NAMESPACE", "")
flow_id = os.environ.get("AGENT_FLOW_ID", "")
lookback = int(os.environ.get("LOOKBACK_HOURS", "24"))
max_consecutive = int(os.environ.get("MAX_CONSECUTIVE_FAILURES", "3"))
max_repeated = int(os.environ.get("MAX_REPEATED_TASK_FAILURES", "3"))
max_percent = int(os.environ.get("MAX_FAILURE_PERCENT", "50"))
min_for_rate = int(os.environ.get("MIN_EXECUTIONS_FOR_RATE", "5"))
token = os.environ.get("KESTRA_API_TOKEN", "")
if not flow_id:
inconclusive("agent_flow_id was empty, so no target flow could be judged")
return
try:
flows = json.loads(os.environ.get("FLOWS_LIST", "[]"))
except ValueError:
flows = []
if not isinstance(flows, list) or not any(
isinstance(f, dict) and f.get("id") == flow_id for f in flows
):
inconclusive("target flow %s not found in namespace %s" % (flow_id, namespace))
return
try:
rows = json.loads(os.environ.get("QUERY_ROWS", "[]"))
except ValueError:
rows = []
# FETCH returns rows as a list holding one list of executions.
if isinstance(rows, list) and len(rows) == 1 and isinstance(rows[0], list):
rows = rows[0]
if not isinstance(rows, list):
rows = []
window_start = now - timedelta(hours=lookback)
floor = parse_date(os.environ.get("LAST_REMEDIATION", ""))
if floor is not None and floor > window_start:
window_start = floor
dated = []
for row in rows:
if not isinstance(row, dict):
continue
started = row_date(row)
if started is None:
inconclusive("a queried execution carried no datable state history, so the window cannot be computed honestly")
return
if started > window_start:
dated.append((started, row))
if not dated:
emit({
"verdict": "CLEAR",
"executions_checked": 0,
"failed_count": 0,
"consecutive_failures": 0,
"repeated_task_failures": 0,
"failure_percent": 0,
"running_execution_ids": [],
"reasons": ["no executions of the target flow since the last remediation (or lookback start), so no loop signature can fire"],
})
return
# Re-sort by state history date, most recent first, rather
# than trusting search order.
dated.sort(key=lambda item: item[0], reverse=True)
watched = [row for _, row in dated]
failed_rows = [row for row in watched if state_of(row) == "FAILED"]
failed = len(failed_rows)
consecutive = 0
for row in watched:
state = state_of(row)
if state in ("RUNNING", "CREATED", "QUEUED", "KILLING"):
continue
if state == "FAILED":
consecutive += 1
else:
break
consecutive_failures = consecutive
running_ids = [
row.get("id") for row in watched
if state_of(row) in ("RUNNING", "CREATED", "QUEUED") and row.get("id")
]
# Repeated-task signature: full executions for FAILED ids only.
task_failure_counts = {}
for row in failed_rows:
execution_id = row.get("id", "")
if not execution_id:
continue
url = base + "/api/v1/" + tenant + "/executions/" + execution_id
status, body, error = http_get(url, token)
if status != 200:
inconclusive("could not fetch full execution %s for the repeated-task signature: %s" % (execution_id, error or body[:300]))
return
try:
detail = json.loads(body)
except ValueError:
inconclusive("full execution %s was not valid JSON" % execution_id)
return
task_runs = detail.get("taskRunList", []) if isinstance(detail, dict) else []
seen_here = set()
if isinstance(task_runs, list):
for task_run in task_runs:
if isinstance(task_run, dict) and state_of(task_run) == "FAILED":
task_id = task_run.get("taskId", "")
if task_id and task_id not in seen_here:
seen_here.add(task_id)
task_failure_counts[task_id] = task_failure_counts.get(task_id, 0) + 1
repeated = max(task_failure_counts.values()) if task_failure_counts else 0
failure_percent = round(100.0 * failed / len(watched)) if watched else 0
reasons = []
loop = False
if consecutive_failures >= max_consecutive:
loop = True
reasons.append("%d consecutive FAILED executions" % consecutive_failures)
if repeated >= max_repeated:
loop = True
reasons.append("same task failed in %d executions" % repeated)
if len(watched) >= min_for_rate and failure_percent > max_percent:
loop = True
reasons.append("failure rate %d percent above cap %d" % (failure_percent, max_percent))
if not loop:
reasons.append("no loop signature met")
emit({
"verdict": "LOOP" if loop else "CLEAR",
"executions_checked": len(watched),
"failed_count": failed,
"consecutive_failures": consecutive_failures,
"repeated_task_failures": repeated,
"failure_percent": failure_percent,
"running_execution_ids": running_ids,
"reasons": reasons,
})
main()
- id: remediate
type: io.kestra.plugin.core.flow.If
description: |
Act on the verdict, it does not merely report it. On a LOOP verdict
with apply_remediation true, it switches off all triggers of the
target flow with triggers.Toggle (no trigger id means every
trigger of the flow), kills each still running execution with
executions.Kill, and only then records the remediation time in KV,
so the next hourly run counts runs since this remediation only.
Switching triggers off stops the flow firing, but a manual run
stays possible, which the docs state plainly. If any step fails,
the run fails outright, so it never claims a remediation that did
not happen. On any other verdict, or on a LOOP verdict with
apply_remediation false, it makes no call at all.
condition: "{{ outputs.evaluate_loop.vars.verdict == 'LOOP' and
inputs.apply_remediation }}"
then:
- id: toggle_triggers
type: io.kestra.plugin.kestra.triggers.Toggle
description: Switch off every trigger of the target flow. With no trigger id
given, Toggle matches all triggers of the flow, and enabled false
switches them off.
kestraUrl: "{{ inputs.kestra_url }}"
tenantId: "{{ inputs.tenant }}"
namespace: "{{ inputs.namespace }}"
flowId: "{{ inputs.agent_flow_id }}"
enabled: false
auth:
apiToken: "{{ secret('KESTRA_API_TOKEN') }}"
- id: kill_running
type: io.kestra.plugin.core.flow.If
description: Kill running executions only when there are any, so an empty
running list never runs a loop over nothing.
condition: "{{ outputs.evaluate_loop.vars.running_execution_ids | length > 0 }}"
then:
- id: kill_each_running
type: io.kestra.plugin.core.flow.Loop
description: Kill each still running execution of the target flow, one Kill per
id.
values: "{{ outputs.evaluate_loop.vars.running_execution_ids }}"
tasks:
- id: kill_one
type: io.kestra.plugin.kestra.executions.Kill
description: Kill one running execution of the target flow.
kestraUrl: "{{ inputs.kestra_url }}"
tenantId: "{{ inputs.tenant }}"
executionId: "{{ item.value }}"
propagateKill: true
auth:
apiToken: "{{ secret('KESTRA_API_TOKEN') }}"
- id: record_remediation
type: io.kestra.plugin.core.kv.Set
description: Store the remediation time in KV after Toggle and Kill succeeded,
under the same per-flow key, so the next run counts only runs since
this remediation.
key: ai-agent-looping-flow-last-remediation-at-{{ inputs.agent_flow_id }}
value: "{{ now() }}"
- id: triage
type: io.kestra.plugin.core.flow.If
description: |
Fail closed on an unreadable history. An INCONCLUSIVE verdict means
the target flow was missing, the history could not be judged, or a
FAILED-id detail fetch failed, so the run fails instead of
reporting a clean bill of health. Any other verdict only logs what
was checked and what was done.
condition: "{{ outputs.evaluate_loop.vars.verdict == 'INCONCLUSIVE' }}"
then:
- id: fail_on_inconclusive
type: io.kestra.plugin.core.execution.Fail
description: Fail the execution when the history could not be judged, so an
unreadable state never passes as clean.
errorMessage: "AI agent looping flow pause or disable INCONCLUSIVE: {{
outputs.evaluate_loop.vars.reasons | toJson }}. No remediation was
claimed."
else:
- id: log_remediation
type: io.kestra.plugin.core.log.Log
description: Record the verdict, the counts, and the remediation action, so the
execution history proves what was checked and what was switched off or
killed.
message: "AI agent looping flow pause or disable {{
outputs.evaluate_loop.vars.verdict }}: {{
outputs.evaluate_loop.vars.executions_checked }} executions checked,
{{ outputs.evaluate_loop.vars.failed_count }} failed, action {{
(outputs.evaluate_loop.vars.verdict == 'LOOP' and
inputs.apply_remediation) ? 'toggled_and_killed' :
((outputs.evaluate_loop.vars.verdict == 'LOOP') ? 'held' : 'none') }},
triggers switched off for {{ inputs.agent_flow_id }}, killed {{
(outputs.evaluate_loop.vars.verdict == 'LOOP' and
inputs.apply_remediation) ?
(outputs.evaluate_loop.vars.running_execution_ids | length) : 0 }}.
Reasons: {{ outputs.evaluate_loop.vars.reasons | toJson }}."
- id: deliver
type: io.kestra.plugin.core.debug.Return
description: Report the verdict and the remediation outcome together, so a
downstream consumer can see both the loop evidence and what was acted on.
format: |
AI agent looping flow pause or disable {{ outputs.evaluate_loop.vars.verdict }}: {{ outputs.evaluate_loop.vars.executions_checked }} executions checked, action {{ (outputs.evaluate_loop.vars.verdict == 'LOOP' and inputs.apply_remediation) ? 'toggled_and_killed' : ((outputs.evaluate_loop.vars.verdict == 'LOOP') ? 'held' : 'none') }}, killed {{ (outputs.evaluate_loop.vars.verdict == 'LOOP' and inputs.apply_remediation) ? (outputs.evaluate_loop.vars.running_execution_ids | length) : 0 }}.
outputs:
- id: verdict
type: STRING
description: LOOP when a loop signature fired (remediation ran only with
apply_remediation true, otherwise held), CLEAR when the history was judged
and no loop fired, INCONCLUSIVE when the history could not be judged and
the run failed closed.
value: "{{ outputs.evaluate_loop.vars.verdict }}"
- id: action
type: STRING
description: Remediation action taken, toggled_and_killed, held (LOOP verdict
with apply_remediation false), or none.
value: "{{ (outputs.evaluate_loop.vars.verdict == 'LOOP' and
inputs.apply_remediation) ? 'toggled_and_killed' :
((outputs.evaluate_loop.vars.verdict == 'LOOP') ? 'held' : 'none') }}"