Skip to content

Commit ecddfdc

Browse files
Merge pull request #321 from GenerationSoftware/fix/gen-2752-lifecycle-idle-barrier
Prevent idle triggers from passing pending lifecycle deliveries
2 parents 30a7e86 + 7c6be8b commit ecddfdc

2 files changed

Lines changed: 104 additions & 8 deletions

File tree

‎packages/api/src/postgres/automation-scheduler.ts‎

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,11 @@ export class AutomationScheduler {
5353
}
5454

5555
private async lifecycle() {
56-
const rows = await this.database.pool.query<any>(`SELECT t.tenant_id,t.id trigger_id,t.job_id,t.slug,t.config,r.id source_run_id,r.job_id source_job_id,r.state,r.updated_at
56+
// Drain the backlog before checking idle triggers. The idle query below
57+
// also guards against eligible unacknowledged deliveries so concurrent
58+
// scheduler passes cannot cross this ordering boundary.
59+
for (;;) {
60+
const rows = await this.database.pool.query<any>(`SELECT t.tenant_id,t.id trigger_id,t.job_id,t.slug,t.config,r.id source_run_id,r.job_id source_job_id,r.state,r.updated_at
5761
FROM app.triggers t
5862
JOIN app.jobs j ON j.tenant_id=t.tenant_id AND j.id=t.job_id
5963
JOIN app.runs r ON r.tenant_id=t.tenant_id
@@ -63,13 +67,17 @@ export class AutomationScheduler {
6367
AND r.state IN ('succeeded','failed','stopped')
6468
AND COALESCE(t.config->'states',t.config->'terminalStates','["succeeded","failed","stopped"]'::jsonb) ? r.state
6569
AND d.source_run_id IS NULL ORDER BY r.updated_at LIMIT 100`);
66-
for (const row of rows.rows) {
67-
const context = { sourceRunId: row.source_run_id, sourceJobId: row.source_job_id, state: row.state, completedAt: row.updated_at.toISOString() }, occurrence = { occurredAt: context.completedAt, externalId: `${row.source_run_id}:${row.state}`, metadata: context };
68-
// Acknowledge after invocation so transient failures remain retryable.
69-
// The stable claim key deduplicates concurrent passes and retries after
70-
// an invocation commits but its delivery acknowledgement fails.
71-
await new InvocationService(this.repository(row.tenant_id), value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)).invoke(row.job_id, { source: "jobLifecycle", triggerId: row.trigger_id, claimKey: `lifecycle:${row.trigger_id}:${row.source_run_id}:${row.state}`, context: { [row.slug]: context }, occurrence }).catch(skipFullQueue);
72-
await this.database.pool.query("INSERT INTO app.lifecycle_deliveries(tenant_id,trigger_id,source_run_id,terminal_state) VALUES ($1,$2,$3,$4) ON CONFLICT DO NOTHING", [row.tenant_id, row.trigger_id, row.source_run_id, row.state]);
70+
if (!rows.rows.length) break;
71+
for (const row of rows.rows) {
72+
const context = { sourceRunId: row.source_run_id, sourceJobId: row.source_job_id, state: row.state, completedAt: row.updated_at.toISOString() }, occurrence = { occurredAt: context.completedAt, externalId: `${row.source_run_id}:${row.state}`, metadata: context };
73+
// Acknowledge after invocation so transient failures remain retryable.
74+
// Queue-full is an intentional terminal outcome: no run is queued, so
75+
// acknowledging it permits idle triggers to proceed.
76+
// The stable claim key deduplicates retries after an invocation commits
77+
// but its delivery acknowledgement fails.
78+
await new InvocationService(this.repository(row.tenant_id), value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)).invoke(row.job_id, { source: "jobLifecycle", triggerId: row.trigger_id, claimKey: `lifecycle:${row.trigger_id}:${row.source_run_id}:${row.state}`, context: { [row.slug]: context }, occurrence }).catch(skipFullQueue);
79+
await this.database.pool.query("INSERT INTO app.lifecycle_deliveries(tenant_id,trigger_id,source_run_id,terminal_state) VALUES ($1,$2,$3,$4) ON CONFLICT DO NOTHING", [row.tenant_id, row.trigger_id, row.source_run_id, row.state]);
80+
}
7381
}
7482
}
7583

@@ -91,6 +99,27 @@ export class AutomationScheduler {
9199
WHERE newer.state IN ('succeeded','failed','stopped')
92100
AND (newer.updated_at,newer.id) > (r.updated_at,r.id)
93101
)
102+
AND NOT EXISTS (
103+
SELECT 1
104+
FROM jsonb_array_elements_text(t.config->'sourceJobIds') watched(value)
105+
JOIN app.runs pending_source ON pending_source.tenant_id=t.tenant_id
106+
AND pending_source.job_id=watched.value::uuid
107+
AND pending_source.state IN ('succeeded','failed','stopped')
108+
JOIN app.triggers lifecycle_trigger ON lifecycle_trigger.tenant_id=pending_source.tenant_id
109+
AND lifecycle_trigger.kind='jobLifecycle' AND lifecycle_trigger.enabled
110+
AND lifecycle_trigger.removed_at IS NULL
111+
AND COALESCE(lifecycle_trigger.config->'sourceJobIds',jsonb_build_array(lifecycle_trigger.config->>'sourceJobId')) ? pending_source.job_id::text
112+
AND COALESCE(lifecycle_trigger.config->'states',lifecycle_trigger.config->'terminalStates','["succeeded","failed","stopped"]'::jsonb) ? pending_source.state
113+
JOIN app.jobs lifecycle_job ON lifecycle_job.tenant_id=lifecycle_trigger.tenant_id
114+
AND lifecycle_job.id=lifecycle_trigger.job_id AND lifecycle_job.enabled
115+
WHERE NOT EXISTS (
116+
SELECT 1 FROM app.lifecycle_deliveries pending_delivery
117+
WHERE pending_delivery.tenant_id=lifecycle_trigger.tenant_id
118+
AND pending_delivery.trigger_id=lifecycle_trigger.id
119+
AND pending_delivery.source_run_id=pending_source.id
120+
AND pending_delivery.terminal_state=pending_source.state
121+
)
122+
)
94123
AND NOT EXISTS (SELECT 1 FROM app.lifecycle_deliveries d WHERE d.tenant_id=t.tenant_id AND d.trigger_id=t.id AND d.source_run_id=r.id AND d.terminal_state='runsZero')
95124
ORDER BY r.updated_at LIMIT 100`);
96125
for (const row of rows.rows) {

‎packages/api/test/job-lifecycle.postgres.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,73 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("job lifecycle delivery (Po
141141
expect(await invocations(a, target.id)).toMatchObject([{ source: "jobIdle" }]);
142142
});
143143

144+
it("holds an all-runs-complete trigger behind a pending lifecycle delivery", async () => {
145+
const a = await tenant(), source = await job(a), downstream = await job(a, { sourceJobIds: [source.id], states: ["succeeded"] });
146+
const idle = await job(a, { sourceJobIds: [source.id, downstream.id] }, true, "jobIdle");
147+
await complete(a, source);
148+
149+
// The database guard must work even when an idle pass races ahead of the
150+
// lifecycle pass (or a previous lifecycle pass has been delayed).
151+
await deliverIdle();
152+
expect(await invocations(a, idle.id)).toHaveLength(0);
153+
await deliver();
154+
await deliverIdle();
155+
expect(await invocations(a, downstream.id)).toHaveLength(1);
156+
expect(await invocations(a, idle.id)).toHaveLength(0);
157+
158+
const downstreamRun = await runs.claimNext();
159+
expect(downstreamRun?.jobId).toBe(downstream.id);
160+
await runs.consumeWakeHint();
161+
await runs.terminal(downstreamRun!, "succeeded", "stored", undefined, true);
162+
await deliverIdle();
163+
expect(await invocations(a, idle.id)).toHaveLength(1);
164+
});
165+
166+
it("drains lifecycle deliveries beyond the first 100 before firing all-runs-complete", async () => {
167+
const a = await tenant(), source = await job(a), downstream = await job(a, { sourceJobIds: [source.id], states: ["succeeded"] });
168+
const idle = await job(a, { sourceJobIds: [source.id, downstream.id] }, true, "jobIdle");
169+
for (let index = 0; index < 101; index++) await complete(a, source);
170+
171+
await deliver();
172+
expect((await database.pool.query("SELECT * FROM app.lifecycle_deliveries WHERE tenant_id=$1 AND trigger_id=$2", [a, downstream.triggers[0]!.id])).rows).toHaveLength(101);
173+
expect(await invocations(a, downstream.id)).toHaveLength(2);
174+
await deliverIdle();
175+
expect(await invocations(a, idle.id)).toHaveLength(0);
176+
177+
let downstreamRun = await runs.claimNext();
178+
expect(downstreamRun?.jobId).toBe(downstream.id);
179+
await runs.consumeWakeHint();
180+
await runs.terminal(downstreamRun!, "succeeded", "stored", undefined, true);
181+
downstreamRun = await runs.claimNext();
182+
expect(downstreamRun?.jobId).toBe(downstream.id);
183+
await runs.consumeWakeHint();
184+
await runs.terminal(downstreamRun!, "succeeded", "stored", undefined, true);
185+
await deliverIdle();
186+
expect(await invocations(a, idle.id)).toHaveLength(1);
187+
}, 20_000);
188+
189+
it("acknowledges a queue-full lifecycle delivery and lets idle proceed after existing work ends", async () => {
190+
const a = await tenant(), source = await job(a), downstream = await job(a, { sourceJobIds: [source.id], states: ["succeeded"] });
191+
const idle = await job(a, { sourceJobIds: [source.id, downstream.id] }, true, "jobIdle");
192+
const invoker = new InvocationService(repository(a), value => encrypt(value, key));
193+
const occupied = await invoker.invoke(downstream.id, { source: "manual", triggerId: downstream.triggers[0]!.id, claimKey: crypto.randomUUID(), context: {} });
194+
const waiter = await invoker.invoke(downstream.id, { source: "manual", triggerId: downstream.triggers[0]!.id, claimKey: crypto.randomUUID(), context: {} });
195+
const occupiedRun = await runs.claimNext();
196+
expect(occupiedRun?.id).toBe(occupied.run.id);
197+
await complete(a, source);
198+
await deliver();
199+
expect(await invocations(a, downstream.id)).toHaveLength(2);
200+
expect(await deliveries()).toHaveLength(1);
201+
await runs.consumeWakeHint();
202+
await runs.terminal(occupiedRun!, "succeeded", "stored", undefined, true);
203+
const waitingRun = await runs.claimNext();
204+
expect(waitingRun?.id).toBe(waiter.run.id);
205+
await runs.consumeWakeHint();
206+
await runs.terminal(waitingRun!, "succeeded", "stored", undefined, true);
207+
await deliverIdle();
208+
expect(await invocations(a, idle.id)).toHaveLength(1);
209+
});
210+
144211
it("matches each of multiple source IDs and legacy singular config with terminalStates", async () => {
145212
const a = await tenant(), first = await job(a), second = await job(a);
146213
const target = await job(a, { sourceJobIds: [first.id, second.id], states: ["succeeded", "stopped"] });

0 commit comments

Comments
 (0)