Skip to content

Commit 3668bbf

Browse files
author
Agent
committed
fix(core): terminalize permanently stalled tasks through whenExhausted
Recovery archived permanently stalled task messages but left their tasks and runs active. Treat the permanent-stall marker as exhaustion in fail_task() without inflating attempts_count, and use a separate escalation cron transaction to apply the existing fail, skip, or skip-cascade policy to marked started and queued tasks. Preserve terminal-state guards, diagnostic markers, stored queue routing, and installed recovery schedules and activation choices. Restore saved cron booleans exactly in the upgrade guidance rather than enabling every paused job; reject malformed saved state and require the snapshot to survive the SQL session. Preserve recorded enabled values in the deployment guide too. Combine the changes from dd41e5dfe and d4831bd79 onto the independent 689-terminalize-stalled branch based on main. Recalculate atlas.sum for this branch without the unrelated worker-startup migration from #696. The original commits remain recoverable at backup/689-misplaced-d4831bd79. Fix the relocation in the upgrade fixture script: the escalation fixture still named 20261102104928_pgflow_worker_startup_handshake.sql as its baseline, a migration that exists only on the #711 branch; it now stops at 20261001194538_pgflow_telemetry_endpoint_fix.sql, the last migration before the escalation one on this base. Also replace the pg_isready readiness wait with a wait for the second 'database system is ready to accept connections' container log line: the pinned image initializes PGDATA on every start, so pg_isready can pass against the short-lived initdb temp server and psql then fails on the removed socket (observed on the leading_step fixture). Fresh runtime validation on this base: 300 pgTAP files plus every upgrade fixture including the new escalation cron states; core eslint, build, strict and vitest type checks, unit tests, and generated-types/migration verification; 279 edge-worker unit tests, 70 integration tests, 13 edge-function E2E tests, 14 portable-runtime E2E tests, and the edge-worker prepush gate; website build, lint, and typecheck; dsl and cli builds. core lint:sqruff fails on four schema files this PR does not touch, identically on main, so that pre-existing breakage stays out of scope. One environmental stop: the stopped_at CPU-clock-limit E2E test timed out once under load and passed unchanged after a fresh test environment. Fixes #689
1 parent f67145b commit 3668bbf

15 files changed

Lines changed: 1344 additions & 33 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@pgflow/core": minor
3+
---
4+
5+
Terminalize permanently stalled tasks through the step's `whenExhausted` policy. A new `pgflow.escalate_permanently_stalled()` function, scheduled as its own `pgflow_escalate_permanently_stalled` cron job, hands tasks marked with `permanently_stalled_at` to `fail_task()`, which now treats the marker as exhaustion regardless of remaining attempts: the run fails, the step skips or cascades per policy, dependents start, and siblings are cancelled or archived. `attempts_count` stays untouched as committed task claims, and ordinary failure callbacks on a marked task exhaust it instead of requeueing against its archived message. Includes the SQL migration (which preserves an absent or paused recovery cron job and copies the installed recovery interval), generated types, and upgrade guidance with a stamped-backlog inventory query.

‎pkgs/core/schemas/0063_function_setup_requeue_stalled_tasks_cron.sql‎

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,31 +9,56 @@ set search_path = pgflow, cron, pg_temp
99
as $$
1010
declare
1111
job_id bigint;
12+
escalate_job_id bigint;
1213
begin
13-
-- Remove existing job if any
14+
-- Remove existing jobs if any
1415
begin
1516
perform cron.unschedule('pgflow_requeue_stalled_tasks');
1617
exception
1718
when others then null;
1819
end;
1920

20-
-- Schedule the new job
21+
begin
22+
perform cron.unschedule('pgflow_escalate_permanently_stalled');
23+
exception
24+
when others then null;
25+
end;
26+
27+
-- Schedule the recovery job
2128
job_id := cron.schedule(
2229
job_name => 'pgflow_requeue_stalled_tasks',
2330
schedule => setup_requeue_stalled_tasks_cron.cron_interval,
2431
command => 'select pgflow.requeue_stalled_tasks()'
2532
);
2633

27-
return format('Scheduled pgflow_requeue_stalled_tasks (every %s, job_id=%s)',
28-
setup_requeue_stalled_tasks_cron.cron_interval, job_id);
34+
-- Schedule escalation as its own job so it runs in a separate transaction
35+
-- after recovery commits: recovery locks step_tasks first, while
36+
-- fail_task() (driven by escalation) locks the run and step first (#689).
37+
-- Holding one job's locks across both calls would invert that order
38+
-- against live workers.
39+
escalate_job_id := cron.schedule(
40+
job_name => 'pgflow_escalate_permanently_stalled',
41+
schedule => setup_requeue_stalled_tasks_cron.cron_interval,
42+
command => 'select pgflow.escalate_permanently_stalled()'
43+
);
44+
45+
return format(
46+
'Scheduled pgflow_requeue_stalled_tasks (every %s, job_id=%s) and pgflow_escalate_permanently_stalled (job_id=%s)',
47+
setup_requeue_stalled_tasks_cron.cron_interval,
48+
job_id,
49+
escalate_job_id
50+
);
2951
end;
3052
$$;
3153

3254
comment on function pgflow.setup_requeue_stalled_tasks_cron(text) is
33-
'Sets up cron job to automatically requeue stalled tasks.
34-
Schedules pgflow_requeue_stalled_tasks at the specified cron_interval (default: 15 seconds).
35-
Replaces existing job if it exists (idempotent).
36-
Returns a confirmation message with job ID.';
55+
'Sets up cron jobs to automatically recover and terminalize stalled tasks.
56+
Schedules pgflow_requeue_stalled_tasks and pgflow_escalate_permanently_stalled
57+
at the specified cron_interval (default: 15 seconds).
58+
Escalation runs as a separate job so recovery commits before fail_task()
59+
locks are taken (#689).
60+
Replaces existing jobs if they exist (idempotent).
61+
Returns a confirmation message with job IDs.';
3762

3863
-- Automatically set up the cron job when migration runs
3964
select pgflow.setup_requeue_stalled_tasks_cron();
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
-- Terminalize permanently stalled tasks through the step's when_exhausted
2+
-- policy (#689). requeue_stalled_tasks() archives the message and stamps
3+
-- permanently_stalled_at but leaves the task nonterminal; this function hands
4+
-- each marked task to fail_task(), which treats the marker as exhaustion and
5+
-- decides whether the run fails, the step skips, dependents start, and
6+
-- siblings are cancelled or archived.
7+
--
8+
-- Lock order matches fail_task(): lock the run and step first, then the task,
9+
-- so recovery (which locks step_tasks first) and live workers cannot deadlock.
10+
-- The candidate loop is a deliberate exception to the declarative-first SQL
11+
-- style: each candidate needs its own lock-and-recheck sequence before
12+
-- fail_task() runs, which a set operation cannot interleave.
13+
-- Runs as its own cron job, in a separate transaction from recovery, so
14+
-- recovery's locks are released before escalation begins. Safe to repeat:
15+
-- candidates are rechecked under lock, and rows already terminalized by
16+
-- fail_task() lose their nonterminal status and stop matching.
17+
create or replace function pgflow.escalate_permanently_stalled()
18+
returns int
19+
language plpgsql
20+
security definer
21+
set search_path = ''
22+
as $$
23+
declare
24+
v_candidate record;
25+
v_run_status text;
26+
v_step_status text;
27+
v_task_status text;
28+
v_stalled_at timestamptz;
29+
v_escalated int := 0;
30+
begin
31+
-- Pick up every marked nonterminal task, including marked queued leftovers
32+
-- requeued by older callbacks and rows stamped by earlier deployments
33+
for v_candidate in
34+
select
35+
st.run_id,
36+
st.step_slug,
37+
st.task_index
38+
from pgflow.step_tasks st
39+
where st.status in ('started', 'queued')
40+
and st.permanently_stalled_at is not null
41+
order by st.run_id, st.step_slug, st.task_index
42+
loop
43+
-- Lock and recheck the run and step: if either left 'started', that
44+
-- transition owns the task's terminal state and escalation must not
45+
-- fight it
46+
select r.status, step_state.status into v_run_status, v_step_status
47+
from pgflow.runs r
48+
join pgflow.step_states step_state on step_state.run_id = r.run_id
49+
where r.run_id = v_candidate.run_id
50+
and step_state.step_slug = v_candidate.step_slug
51+
for update of r, step_state;
52+
53+
if v_run_status = 'started' and v_step_status = 'started' then
54+
-- Lock and recheck the task: recovery or a live callback may have
55+
-- transitioned it while this pass waited for the run and step locks
56+
select st.status, st.permanently_stalled_at
57+
into v_task_status, v_stalled_at
58+
from pgflow.step_tasks st
59+
where st.run_id = v_candidate.run_id
60+
and st.step_slug = v_candidate.step_slug
61+
and st.task_index = v_candidate.task_index
62+
for update;
63+
64+
if v_task_status in ('started', 'queued') and v_stalled_at is not null then
65+
-- fail_task() treats the marker as exhaustion and applies
66+
-- when_exhausted; attempts_count stays untouched (#689)
67+
perform pgflow.fail_task(
68+
run_id => v_candidate.run_id,
69+
step_slug => v_candidate.step_slug,
70+
task_index => v_candidate.task_index,
71+
error_message => 'permanently stalled: worker did not report after 3 requeues'
72+
);
73+
v_escalated := v_escalated + 1;
74+
end if;
75+
end if;
76+
end loop;
77+
78+
return v_escalated;
79+
end;
80+
$$;

‎pkgs/core/schemas/0100_function_fail_task.sql‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -87,23 +87,37 @@ WITH flow_info AS (
8787
fail_or_retry_task as (
8888
UPDATE pgflow.step_tasks as task
8989
SET
90+
-- Exhaustion: attempts_count reached max_attempts, or stalled-task
91+
-- recovery gave up on the task (permanently_stalled_at set). A marked
92+
-- task exhausts regardless of its remaining attempts: its message was
93+
-- archived, so a retry could never be delivered. attempts_count stays
94+
-- untouched; it records committed claims (#689).
9095
status = CASE
91-
WHEN task.attempts_count < (SELECT opt_max_attempts FROM config) THEN 'queued'
96+
WHEN task.permanently_stalled_at IS NULL
97+
AND task.attempts_count < (SELECT opt_max_attempts FROM config) THEN 'queued'
9298
ELSE 'failed'
9399
END,
94100
failed_at = CASE
95-
WHEN task.attempts_count >= (SELECT opt_max_attempts FROM config) THEN now()
96-
ELSE NULL
101+
WHEN task.permanently_stalled_at IS NULL
102+
AND task.attempts_count < (SELECT opt_max_attempts FROM config) THEN NULL
103+
ELSE now()
97104
END,
98105
started_at = CASE
99-
WHEN task.attempts_count < (SELECT opt_max_attempts FROM config) THEN NULL
106+
WHEN task.permanently_stalled_at IS NULL
107+
AND task.attempts_count < (SELECT opt_max_attempts FROM config) THEN NULL
100108
ELSE task.started_at
101109
END,
102110
error_message = fail_task.error_message
103111
WHERE task.run_id = fail_task.run_id
104112
AND task.step_slug = fail_task.step_slug
105113
AND task.task_index = fail_task.task_index
106-
AND task.status = 'started'
114+
AND (
115+
task.status = 'started'
116+
-- Marked queued leftovers from older callbacks: terminalize them too.
117+
-- Ordinary unmarked queued tasks stay unchanged (a recovery requeue
118+
-- owns their next attempt).
119+
OR (task.status = 'queued' AND task.permanently_stalled_at IS NOT NULL)
120+
)
107121
RETURNING *
108122
),
109123
-- Determine if task exhausted retries and get when_exhausted mode

‎pkgs/core/scripts/run-upgrade-fixture‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,12 @@ start_container() {
4343
CONTAINER="$1"
4444
echo "upgrade fixture: starting postgres container $CONTAINER"
4545
docker run -d --name "$CONTAINER" "$IMAGE" >/dev/null
46+
# The image initializes PGDATA on every start: the initdb temp server and
47+
# then the final server each log "ready to accept connections", so waiting
48+
# for the second occurrence skips the temp-server window that fools
49+
# pg_isready (socket vanishes between temp server stop and final server start).
4650
local waited=0
47-
until docker exec "$CONTAINER" pg_isready -U postgres >/dev/null 2>&1; do
51+
until [ "$(docker logs "$CONTAINER" 2>&1 | grep -c 'database system is ready to accept connections')" -ge 2 ]; do
4852
((waited+=1))
4953
if ((waited > 30)); then
5054
echo "upgrade fixture: $CONTAINER never became ready" >&2
@@ -218,3 +222,62 @@ SQL
218222
done
219223

220224
echo "upgrade fixture: PASS (0.16.0 slug conflict rollbacks)"
225+
226+
# =====================================================================
227+
# Fixture 5: escalation cron scheduling across upgrade states (#689)
228+
# =====================================================================
229+
# The escalation migration schedules pgflow_escalate_permanently_stalled
230+
# only where scheduled recovery already exists, copies the installed
231+
# recovery interval, and mirrors the recovery job's paused state. Proves:
232+
# 1. active recovery at a custom interval gains an active escalation job
233+
# at that interval, while the recovery job itself is untouched,
234+
# 2. paused (active = false) recovery gains a paused escalation job,
235+
# 3. an intentionally absent recovery job gains no escalation job.
236+
ESCALATION_BASELINE='20261001194538_pgflow_telemetry_endpoint_fix.sql'
237+
escalation_migration=$(ls supabase/migrations/*_pgflow_escalate_permanently_stalled.sql)
238+
239+
for cron_case in active paused absent; do
240+
start_container "pgflow-upgrade-fixture-escalation-${cron_case}"
241+
242+
echo "upgrade fixture escalation ${cron_case}: applying supabase baseline schema"
243+
psql_in < atlas/supabase-baseline-schema.sql
244+
245+
echo "upgrade fixture escalation ${cron_case}: applying pgflow migrations up to ($ESCALATION_BASELINE)"
246+
apply_migrations_up_to "$ESCALATION_BASELINE"
247+
248+
case "$cron_case" in
249+
active)
250+
psql_in <<'SQL'
251+
SELECT cron.alter_job(
252+
job_id => job.jobid,
253+
schedule => '45 seconds'
254+
)
255+
FROM cron.job job
256+
WHERE job.jobname = 'pgflow_requeue_stalled_tasks';
257+
SQL
258+
;;
259+
paused)
260+
psql_in <<'SQL'
261+
SELECT cron.alter_job(
262+
job_id => job.jobid,
263+
schedule => '45 seconds',
264+
active => false
265+
)
266+
FROM cron.job job
267+
WHERE job.jobname = 'pgflow_requeue_stalled_tasks';
268+
SQL
269+
;;
270+
absent)
271+
psql_in <<'SQL'
272+
SELECT cron.unschedule('pgflow_requeue_stalled_tasks');
273+
SQL
274+
;;
275+
esac
276+
277+
echo "upgrade fixture escalation ${cron_case}: applying migration $(basename "$escalation_migration")"
278+
psql_in < "$escalation_migration"
279+
280+
sed "s/__CASE__/${cron_case}/g" supabase/upgrade_fixture/assertions_escalation_cron.sql | psql_in
281+
done
282+
283+
echo "upgrade fixture: PASS (escalation cron scheduling states)"

‎pkgs/core/src/database-types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,7 @@ export type Database = {
582582
request_id: number
583583
}[]
584584
}
585+
escalate_permanently_stalled: { Args: never; Returns: number }
585586
fail_task: {
586587
Args: {
587588
error_message: string

0 commit comments

Comments
 (0)