diff --git a/packages/api/migrations/0030_lifecycle_transition_outbox.sql b/packages/api/migrations/0030_lifecycle_transition_outbox.sql new file mode 100644 index 00000000..6b80c13c --- /dev/null +++ b/packages/api/migrations/0030_lifecycle_transition_outbox.sql @@ -0,0 +1,51 @@ +-- Lifecycle events are captured at the terminal transition, while the run and +-- trigger configuration are serialized with a tenant-scoped transaction lock. +CREATE TABLE app.lifecycle_events ( + event_id bigserial PRIMARY KEY, + tenant_id uuid NOT NULL, + trigger_id uuid NOT NULL, + source_run_id uuid NOT NULL, + terminal_state text NOT NULL CHECK (terminal_state IN ('succeeded','failed','stopped')), + occurred_at timestamptz NOT NULL DEFAULT clock_timestamp(), + UNIQUE (tenant_id,trigger_id,source_run_id,terminal_state), + FOREIGN KEY (tenant_id,trigger_id) REFERENCES app.triggers(tenant_id,id) ON DELETE CASCADE, + FOREIGN KEY (tenant_id,source_run_id) REFERENCES app.runs(tenant_id,id) ON DELETE CASCADE +); +CREATE INDEX lifecycle_events_pending ON app.lifecycle_events(event_id); + +CREATE FUNCTION app.capture_lifecycle_transition() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.state IN ('succeeded','failed','stopped') AND OLD.state IS DISTINCT FROM NEW.state THEN + PERFORM pg_advisory_xact_lock(hashtextextended(NEW.tenant_id::text, 0)); + INSERT INTO app.lifecycle_events(tenant_id,trigger_id,source_run_id,terminal_state) + SELECT NEW.tenant_id,t.id,NEW.id,NEW.state + FROM app.triggers t + JOIN app.jobs j ON j.tenant_id=t.tenant_id AND j.id=t.job_id + WHERE t.tenant_id=NEW.tenant_id AND t.kind='jobLifecycle' + AND t.enabled AND t.removed_at IS NULL AND j.enabled + AND COALESCE(t.config->'sourceJobIds',jsonb_build_array(t.config->>'sourceJobId')) ? NEW.job_id::text + AND COALESCE(t.config->'states',t.config->'terminalStates','["succeeded","failed","stopped"]'::jsonb) ? NEW.state + ON CONFLICT DO NOTHING; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER app_capture_lifecycle_transition + AFTER UPDATE OF state ON app.runs + FOR EACH ROW EXECUTE FUNCTION app.capture_lifecycle_transition(); + +-- Preserve only work the old scheduler had already committed an invocation +-- for but had not yet acknowledged. Current terminal state alone is not proof +-- that an old subscription was waiting for a delivery. +INSERT INTO app.lifecycle_events(tenant_id,trigger_id,source_run_id,terminal_state) +SELECT t.tenant_id,t.id,r.id,r.state +FROM app.triggers t +JOIN app.jobs j ON j.tenant_id=t.tenant_id AND j.id=t.job_id +JOIN app.runs r ON r.tenant_id=t.tenant_id + AND COALESCE(t.config->'sourceJobIds',jsonb_build_array(t.config->>'sourceJobId')) ? r.job_id::text +JOIN app.invocations i ON i.tenant_id=t.tenant_id AND i.job_id=t.job_id AND i.trigger_id=t.id + AND i.claim_key='lifecycle:'||t.id::text||':'||r.id::text||':'||r.state +WHERE t.kind='jobLifecycle' AND t.enabled AND t.removed_at IS NULL AND j.enabled + AND r.state IN ('succeeded','failed','stopped') + AND COALESCE(t.config->'states',t.config->'terminalStates','["succeeded","failed","stopped"]'::jsonb) ? r.state + 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=r.state) +ON CONFLICT DO NOTHING; diff --git a/packages/api/src/postgres/automation-scheduler.ts b/packages/api/src/postgres/automation-scheduler.ts index b0ce2cfb..933285ab 100644 --- a/packages/api/src/postgres/automation-scheduler.ts +++ b/packages/api/src/postgres/automation-scheduler.ts @@ -57,20 +57,17 @@ export class AutomationScheduler { // also guards against eligible unacknowledged deliveries so concurrent // scheduler passes cannot cross this ordering boundary. for (;;) { - const rows = await this.database.pool.query(`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 - ,r.job_result + const rows = await this.database.pool.query(`SELECT t.tenant_id,t.id trigger_id,t.job_id,t.slug,e.source_run_id,r.job_id source_job_id,e.terminal_state state,e.occurred_at,r.job_result FROM app.triggers t JOIN app.jobs j ON j.tenant_id=t.tenant_id AND j.id=t.job_id - JOIN app.runs r ON r.tenant_id=t.tenant_id - AND COALESCE(t.config->'sourceJobIds',jsonb_build_array(t.config->>'sourceJobId')) ? r.job_id::text - LEFT JOIN app.lifecycle_deliveries d ON d.tenant_id=t.tenant_id AND d.trigger_id=t.id AND d.source_run_id=r.id AND d.terminal_state=r.state + JOIN app.lifecycle_events e ON e.tenant_id=t.tenant_id AND e.trigger_id=t.id + JOIN app.runs r ON r.tenant_id=e.tenant_id AND r.id=e.source_run_id + LEFT JOIN app.lifecycle_deliveries d ON d.tenant_id=e.tenant_id AND d.trigger_id=e.trigger_id AND d.source_run_id=e.source_run_id AND d.terminal_state=e.terminal_state WHERE t.kind='jobLifecycle' AND t.enabled AND t.removed_at IS NULL AND j.enabled - AND r.state IN ('succeeded','failed','stopped') - AND COALESCE(t.config->'states',t.config->'terminalStates','["succeeded","failed","stopped"]'::jsonb) ? r.state - AND d.source_run_id IS NULL ORDER BY r.updated_at LIMIT 100`); + AND d.source_run_id IS NULL ORDER BY e.event_id LIMIT 100`); if (!rows.rows.length) break; for (const row of rows.rows) { - const context = { sourceRunId: row.source_run_id, sourceJobId: row.source_job_id, state: row.state, completedAt: row.updated_at.toISOString(), outputs: row.job_result?.outputs ?? null }, occurrence = { occurredAt: context.completedAt, externalId: `${row.source_run_id}:${row.state}`, metadata: context }; + const context = { sourceRunId: row.source_run_id, sourceJobId: row.source_job_id, state: row.state, completedAt: row.occurred_at.toISOString(), outputs: row.job_result?.outputs ?? null }, occurrence = { occurredAt: context.completedAt, externalId: `${row.source_run_id}:${row.state}`, metadata: context }; // Acknowledge after invocation so transient failures remain retryable. // Queue-full is an intentional terminal outcome: no run is queued, so // acknowledging it permits idle triggers to proceed. @@ -109,16 +106,15 @@ export class AutomationScheduler { JOIN app.triggers lifecycle_trigger ON lifecycle_trigger.tenant_id=pending_source.tenant_id AND lifecycle_trigger.kind='jobLifecycle' AND lifecycle_trigger.enabled AND lifecycle_trigger.removed_at IS NULL - AND COALESCE(lifecycle_trigger.config->'sourceJobIds',jsonb_build_array(lifecycle_trigger.config->>'sourceJobId')) ? pending_source.job_id::text - AND COALESCE(lifecycle_trigger.config->'states',lifecycle_trigger.config->'terminalStates','["succeeded","failed","stopped"]'::jsonb) ? pending_source.state JOIN app.jobs lifecycle_job ON lifecycle_job.tenant_id=lifecycle_trigger.tenant_id AND lifecycle_job.id=lifecycle_trigger.job_id AND lifecycle_job.enabled - WHERE NOT EXISTS ( - SELECT 1 FROM app.lifecycle_deliveries pending_delivery - WHERE pending_delivery.tenant_id=lifecycle_trigger.tenant_id - AND pending_delivery.trigger_id=lifecycle_trigger.id - AND pending_delivery.source_run_id=pending_source.id - AND pending_delivery.terminal_state=pending_source.state + WHERE EXISTS ( + SELECT 1 FROM app.lifecycle_events pending_event + WHERE pending_event.tenant_id=lifecycle_trigger.tenant_id AND pending_event.trigger_id=lifecycle_trigger.id + AND pending_event.source_run_id=pending_source.id AND pending_event.terminal_state=pending_source.state + AND NOT EXISTS (SELECT 1 FROM app.lifecycle_deliveries pending_delivery + WHERE pending_delivery.tenant_id=pending_event.tenant_id AND pending_delivery.trigger_id=pending_event.trigger_id + AND pending_delivery.source_run_id=pending_event.source_run_id AND pending_delivery.terminal_state=pending_event.terminal_state) ) ) 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') diff --git a/packages/api/src/postgres/job-repository.ts b/packages/api/src/postgres/job-repository.ts index fd63ee4b..56c2633d 100644 --- a/packages/api/src/postgres/job-repository.ts +++ b/packages/api/src/postgres/job-repository.ts @@ -50,6 +50,7 @@ export class PostgresJobRepository implements JobRepository { async create(job: Job): Promise { return this.database.orm.transaction(async tx => { + await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${this.tenantId}::text, 0))`); const [row] = await tx.insert(jobs).values({ tenantId: this.tenantId, id: job.id, projectId: job.projectId ?? await this.defaultProjectId(tx), name: job.name, slug: job.slug, encryptedPromptTemplate: await this.encrypt(job.promptTemplate), encryptedRunNameTemplate: job.runNameTemplate ? await this.encrypt(job.runNameTemplate) : "", executionConfig: job.executionConfig, runScopes: job.runScopes ?? [...DEFAULT_RUN_SCOPES], tags: job.tags ?? [], model: job.model, effort: job.effort ?? "", concurrencyLimit: job.concurrencyLimit, enabled: job.enabled, createdAt: new Date(job.createdAt), updatedAt: new Date(job.updatedAt) }).returning(); await this.reconcileTriggers(tx, job, []); await this.reconcileSkills(tx, job, []); @@ -59,6 +60,7 @@ export class PostgresJobRepository implements JobRepository { async update(job: Job, expectedUpdatedAt?: string): Promise { return this.database.orm.transaction(async tx => { + await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${this.tenantId}::text, 0))`); const [current] = await tx.select().from(jobs).where(and(eq(jobs.tenantId, this.tenantId), eq(jobs.id, job.id))).for("update").limit(1); if (!current) throw new Error("Job not found"); if (expectedUpdatedAt && current.updatedAt.toISOString() !== expectedUpdatedAt) throw new StaleJobEdit("Job changed since it was loaded"); @@ -86,6 +88,7 @@ export class PostgresJobRepository implements JobRepository { async setEnabled(id: string, enabled: boolean, changedAt: string): Promise { return this.database.orm.transaction(async tx => { + await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${this.tenantId}::text, 0))`); const [job] = await tx.update(jobs).set({ enabled, updatedAt: sql`greatest(${new Date(changedAt)}::timestamptz, date_trunc('milliseconds', ${jobs.updatedAt}) + interval '1 millisecond')` }).where(and(eq(jobs.tenantId, this.tenantId), eq(jobs.id, id))).returning(); if (!job) return false; const schedules: TriggerRow[] = await tx.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, id), eq(triggers.kind, "schedule"), isNull(triggers.removedAt))); diff --git a/packages/api/src/postgres/run-query-repository.ts b/packages/api/src/postgres/run-query-repository.ts index a7722fbb..14700218 100644 --- a/packages/api/src/postgres/run-query-repository.ts +++ b/packages/api/src/postgres/run-query-repository.ts @@ -99,6 +99,7 @@ export class RunQueryRepository { async activity(runId: string) { return (await this.database.pool.query("SELECT action,detail,created_at FROM app.run_activity WHERE tenant_id=$1 AND run_id=$2 ORDER BY created_at,id", [this.tenantId, runId])).rows; } async stop(runId: string) { return this.database.transaction(async client => { + await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0))", [this.tenantId]); const result = await client.query("UPDATE app.job_runs SET state=CASE WHEN state='reserved' THEN 'stopped' ELSE 'stopping' END,next_poll_at=CASE WHEN state='reserved' THEN NULL ELSE now() END,updated_at=now() WHERE tenant_id=$1 AND id=$2 AND state IN ('reserved','starting','running','blocked','stopping') RETURNING id,state", [this.tenantId, runId]); const row = result.rows[0]; if (row?.state === "stopped") await client.query("UPDATE app.runs SET state='stopped',claim_released=true,vm_cleanup_complete=true,updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, runId]); diff --git a/packages/api/src/postgres/run-repository.ts b/packages/api/src/postgres/run-repository.ts index 1c3051c5..5c3b180b 100644 --- a/packages/api/src/postgres/run-repository.ts +++ b/packages/api/src/postgres/run-repository.ts @@ -114,6 +114,7 @@ export class RunRepository { async terminal(run: PersistedRun, state: "succeeded" | "failed" | "stopped", artifactState: "stored" | "partial" | "failed", error?: string, cleanupComplete = false): Promise { await this.database.transaction(async client => { + await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0))", [run.tenantId]); const current = (await client.query<{ state: ExecutionState }>("SELECT state FROM app.job_runs WHERE tenant_id=$1 AND id=$2 AND state IN ('starting','running','blocked','stopping') FOR UPDATE", [run.tenantId, run.id])).rows[0]; if (!current) return; const saved = (await client.query<{ agent_error_reason: string | null }>("SELECT agent_error_reason FROM app.runs WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [run.tenantId, run.id])).rows[0]; diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 1e01c44a..4926283d 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -91,6 +91,7 @@ export const jobEditDeliveries = app.table("job_edit_deliveries", { tenantId: uuid("tenant_id").notNull(), eventId: uuid("event_id").notNull(), triggerId: uuid("trigger_id").notNull(), sourceJobId: uuid("source_job_id").notNull(), editedAt: timestamp("edited_at", { withTimezone: true }).notNull(), }, t => [primaryKey({ columns: [t.tenantId, t.eventId, t.triggerId] }), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.sourceJobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), index("job_edit_deliveries_pending").on(t.editedAt, t.eventId)]); export const lifecycleDeliveries = app.table("lifecycle_deliveries", { tenantId: uuid("tenant_id").notNull(), triggerId: uuid("trigger_id").notNull(), sourceRunId: uuid("source_run_id").notNull(), terminalState: text("terminal_state").notNull(), createdAt: createdAt() }, t => [primaryKey({ columns: [t.tenantId, t.triggerId, t.sourceRunId, t.terminalState] }), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.sourceRunId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade")]); +export const lifecycleEvents = app.table("lifecycle_events", { eventId: bigint("event_id", { mode: "number" }).primaryKey(), tenantId: uuid("tenant_id").notNull(), triggerId: uuid("trigger_id").notNull(), sourceRunId: uuid("source_run_id").notNull(), terminalState: text("terminal_state").notNull(), occurredAt: timestamp("occurred_at", { withTimezone: true, mode: "date" }).notNull().defaultNow() }, t => [unique().on(t.tenantId, t.triggerId, t.sourceRunId, t.terminalState), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.sourceRunId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade"), index("lifecycle_events_pending").on(t.eventId)]); export const jobEvents = app.table("job_events", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), provider: text("provider").notNull(), deliveryId: text("delivery_id").notNull(), outcome: text("outcome").notNull(), detail: text("detail").notNull(), receivedAt: timestamp("received_at", { withTimezone: true }).notNull().defaultNow() }, t => [primaryKey({ columns: [t.tenantId, t.id] }), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), index("job_events_by_job").on(t.tenantId, t.jobId, t.receivedAt)]); export const webhookDeliveries = app.table("webhook_deliveries", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), provider: text("provider").notNull(), deliveryId: text("delivery_id").notNull(), eventType: text("event_type").notNull().default("unknown"), eventAction: text("event_action").notNull().default("unknown"), outcome: text("outcome").notNull(), detail: text("detail").notNull(), receivedAt: timestamp("received_at", { withTimezone: true }).notNull().defaultNow() }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.provider, t.deliveryId)]); export const webhookDeliveryEvents = app.table("webhook_delivery_events", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), deliveryId: uuid("delivery_id").notNull(), jobId: uuid("job_id"), outcome: text("outcome").notNull(), detail: text("detail").notNull(), createdAt: createdAt() }, t => [primaryKey({ columns: [t.tenantId, t.id] }), foreignKey({ columns: [t.tenantId, t.deliveryId], foreignColumns: [webhookDeliveries.tenantId, webhookDeliveries.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade")]); @@ -137,7 +138,7 @@ export const runRelations = relations(runs, ({ one, many }) => ({ export const databaseSchema = { schemaMigrations, tenants, oauthConnections, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, connections, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runCredentials, runs, runArtifacts, - runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, jobEditDeliveries, jobEvents, + runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, lifecycleEvents, jobEditDeliveries, jobEvents, webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, runTraceCursors, runTraceChunks, runTraceProjections, traceReplayLimits, traceReplayOperations, tenantRelations, jobRelations, triggerRelations, invocationRelations, runRelations, diff --git a/packages/api/test/job-lifecycle.postgres.test.ts b/packages/api/test/job-lifecycle.postgres.test.ts index 05677954..a558694b 100644 --- a/packages/api/test/job-lifecycle.postgres.test.ts +++ b/packages/api/test/job-lifecycle.postgres.test.ts @@ -46,6 +46,17 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("job lifecycle delivery (Po await runs.terminal(run!, state, "stored", undefined, true); return result.run.id; } + async function start(tenantId: string, source: Job) { + const result = await new InvocationService(repository(tenantId), value => encrypt(value, key)).invoke(source.id, { source: "manual", triggerId: source.triggers[0]!.id, claimKey: crypto.randomUUID(), context: {} }); + const run = await runs.claimNext(); + expect(run?.id).toBe(result.run.id); + await runs.consumeWakeHint(); + return run!; + } + async function updateTrigger(tenantId: string, value: Job, change: (trigger: Trigger) => Trigger, promptTemplate = value.promptTemplate) { + const trigger = change(value.triggers[0]!); + return repository(tenantId).update({ ...value, promptTemplate, triggers: [trigger], updatedAt: new Date().toISOString() }); + } const invocations = async (tenantId: string, jobId: string) => (await database.pool.query("SELECT * FROM app.invocations WHERE tenant_id=$1 AND job_id=$2", [tenantId, jobId])).rows; const deliveries = async () => (await database.pool.query("SELECT * FROM app.lifecycle_deliveries WHERE tenant_id=ANY($1::uuid[])", [tenants])).rows; afterAll(async () => { @@ -73,6 +84,85 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("job lifecycle delivery (Po expect(await deliveries()).toHaveLength(1); }); + it("does not replay terminal history when a trigger is created disabled then enabled", async () => { + const a = await tenant(), source = await job(a); + await complete(a, source, "failed"); + let target = await job(a, { sourceJobIds: [source.id], states: ["failed"] }, false); + await deliver(); + expect(await invocations(a, target.id)).toHaveLength(0); + target = await updateTrigger(a, target, trigger => ({ ...trigger, enabled: true })); + await deliver(); + await deliver(); + expect(await invocations(a, target.id)).toHaveLength(0); + + const activeRun = await start(a, source); + // This run began before the subscription, but its terminal transition is after it. + await runs.terminal(activeRun, "failed", "stored", undefined, true); + await Promise.all([deliver(), deliver()]); + expect(await invocations(a, target.id)).toHaveLength(1); + expect(await invocations(a, target.id)).toMatchObject([{ context: { "trigger-1": { sourceRunId: activeRun.id, state: "failed" } } }]); + }); + + it("keeps captured terminal work pending through disable, config edits, and re-enable", async () => { + const a = await tenant(), source = await job(a), other = await job(a); + let target = await job(a, { sourceJobIds: [source.id], states: ["failed"] }); + const pendingRun = await complete(a, source, "failed"); + target = await updateTrigger(a, target, trigger => ({ ...trigger, enabled: false })); + await deliver(); + expect(await invocations(a, target.id)).toHaveLength(0); + + // A watched-source/state change establishes the future matching set, while + // the already snapshotted event remains a legitimate pending delivery. + target = await updateTrigger(a, target, trigger => ({ ...trigger, config: { sourceJobIds: [other.id], states: ["succeeded"] } }), "{{trigger-1.state}} edited"); + await deliver(); + expect(await invocations(a, target.id)).toHaveLength(0); + target = await updateTrigger(a, target, trigger => ({ ...trigger, enabled: true })); + await deliver(); + expect(await invocations(a, target.id)).toMatchObject([{ context: { "trigger-1": { sourceRunId: pendingRun, state: "failed" } } }]); + const targetRun = await runs.claimNext(); + expect(targetRun?.jobId).toBe(target.id); + await runs.consumeWakeHint(); + await runs.terminal(targetRun!, "succeeded", "stored", undefined, true); + + await complete(a, source, "succeeded"); + await deliver(); + expect(await invocations(a, target.id)).toHaveLength(1); + await complete(a, other, "succeeded"); + await Promise.all([deliver(), deliver()]); + expect(await invocations(a, target.id)).toHaveLength(2); + }); + + it("does not create lifecycle work from unrelated prompt edits or re-enabling", async () => { + const a = await tenant(), source = await job(a); + await complete(a, source, "failed"); + let target = await job(a, { sourceJobIds: [source.id], states: ["failed"] }); + target = await updateTrigger(a, target, trigger => ({ ...trigger }), "unrelated prompt edit"); + target = await updateTrigger(a, target, trigger => ({ ...trigger, enabled: false })); + target = await updateTrigger(a, target, trigger => ({ ...trigger, enabled: true })); + await deliver(); + expect(await invocations(a, target.id)).toHaveLength(0); + await complete(a, source, "failed"); + await deliver(); + expect(await invocations(a, target.id)).toHaveLength(1); + }); + + it("starts a replacement trigger at its own subscription boundary", async () => { + const a = await tenant(), source = await job(a); + await complete(a, source, "failed"); + const target = await job(a, { sourceJobIds: [source.id], states: ["failed"] }); + const oldTriggerId = target.triggers[0]!.id; + const replacement: Trigger = { ...target.triggers[0]!, id: crypto.randomUUID(), createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }; + const updated = await repository(a).update({ ...target, triggers: [replacement], updatedAt: new Date().toISOString() }); + expect(updated.triggers[0]!.id).not.toBe(oldTriggerId); + await deliver(); + expect(await invocations(a, target.id)).toHaveLength(0); + + await complete(a, source, "failed"); + await deliver(); + expect(await invocations(a, target.id)).toHaveLength(1); + expect((await database.pool.query("SELECT * FROM app.lifecycle_events WHERE tenant_id=$1 AND trigger_id=$2", [a, replacement.id])).rows).toHaveLength(1); + }); + it("snapshots a code script and structured trigger context when queued", async () => { const a = await tenant(), id = crypto.randomUUID(), timestamp = new Date().toISOString(); const trigger: Trigger = { id: crypto.randomUUID(), jobId: id, kind: "manual", slug: "trigger-1", enabled: true, config: {}, createdAt: timestamp, updatedAt: timestamp }; diff --git a/packages/docs/integrations/triggers.mdx b/packages/docs/integrations/triggers.mdx index 6392dcd3..2fa93bbd 100644 --- a/packages/docs/integrations/triggers.mdx +++ b/packages/docs/integrations/triggers.mdx @@ -7,6 +7,8 @@ Schedule config is `{cron, timezone}`. Webhook config supports `linear` (`projec Lifecycle config is `{sourceJobIds, states}`, where states are `succeeded`, `failed`, `stopped`, or `edited`. Triggers have stable server-generated slugs (`trigger-1`, `trigger-2`, …); use them in Mustache templates. Disabled triggers do not fire. +Terminal lifecycle events (`succeeded`, `failed`, and `stopped`) are recorded transactionally when a watched run changes into that state. Creating a subscription, enabling a disabled subscription, re-enabling it, or changing its watched jobs or states starts matching from subsequent terminal transitions; existing terminal runs are not replayed. A run already in progress when a subscription starts is delivered if it reaches a watched terminal state afterward. Prompt and other unrelated job edits do not move this boundary. Events captured for an enabled subscription remain pending while its destination is disabled, and are delivered after it is enabled again; removing the trigger or deleting the source run discards its pending event. Delivery retries are deduplicated by trigger and source run state. + For hosted jobs, connect the provider in [Settings](/integrations/oauth), select accessible resources in the browser editor, and verify a matching event with delivery tools. Factorize verifies provider signatures and manages OAuth subscriptions. Optional Cloudflare Tail triggers require your own source/relay integration; infrastructure setup belongs in [operations](/self-hosting/operations). Choose **Job lifecycle → Edited** and one or more source jobs to run a job when another job is saved (including enable/disable saves). Creation and run status changes do not produce edit events. Each successful save is an event, even if the submitted values are unchanged. Only enabled subscribers in the same tenant are matched; a job cannot subscribe to its own edits. diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index f95a3c12..cb3e44fa 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -329,6 +329,8 @@ Schedule config is `{cron, timezone}`. Webhook config supports `linear` (`projec Lifecycle config is `{sourceJobIds, states}`, where states are `succeeded`, `failed`, `stopped`, or `edited`. Triggers have stable server-generated slugs (`trigger-1`, `trigger-2`, …); use them in Mustache templates. Disabled triggers do not fire. +Terminal lifecycle events (`succeeded`, `failed`, and `stopped`) are recorded transactionally when a watched run changes into that state. Creating a subscription, enabling a disabled subscription, re-enabling it, or changing its watched jobs or states starts matching from subsequent terminal transitions; existing terminal runs are not replayed. A run already in progress when a subscription starts is delivered if it reaches a watched terminal state afterward. Prompt and other unrelated job edits do not move this boundary. Events captured for an enabled subscription remain pending while its destination is disabled, and are delivered after it is enabled again; removing the trigger or deleting the source run discards its pending event. Delivery retries are deduplicated by trigger and source run state. + For hosted jobs, connect the provider in [Settings](https://docs.factorize.sh/integrations/oauth), select accessible resources in the browser editor, and verify a matching event with delivery tools. Factorize verifies provider signatures and manages OAuth subscriptions. Optional Cloudflare Tail triggers require your own source/relay integration; infrastructure setup belongs in [operations](https://docs.factorize.sh/self-hosting/operations). Choose **Job lifecycle → Edited** and one or more source jobs to run a job when another job is saved (including enable/disable saves). Creation and run status changes do not produce edit events. Each successful save is an event, even if the submitted values are unchanged. Only enabled subscribers in the same tenant are matched; a job cannot subscribe to its own edits.