Skip to content

Concepts

Lifecycle hooks

Run your own code before each attempt and after a run succeeds, fails or is cancelled, with Trigger.dev's onStartAttempt, onSuccess, onFailure, onComplete and onCancel. Failure hooks run even after a crash or a timeout.

On this page

Lifecycle hooks are functions Bok Joy calls around a run: before each attempt, and once the run has ended. They have Trigger.dev v4's names and parameters, on a task and, from init.ts, for every task.

Add hooks#

On a task#

Pass the hooks as options of task(), schemaTask() or schedules.task(), as in Trigger.dev:

src/trigger/invoices.ts
import { task } from '@bokjoy/sdk/trigger';import { db } from '../db'; export const parseInvoice = task({  id: 'invoice.parse',  retry: { maxAttempts: 3 },  run: async ({ invoiceId }) => {    // ...    return { lines: 42 };  },  onSuccess: async ({ payload, output }) => {    await db.invoices.update(payload.invoiceId, { status: 'parsed', lines: output.lines });  },  onFailure: async ({ payload, error }) => {    await db.invoices.update(payload.invoiceId, { status: 'failed', reason: error.message });  },});

For every task#

Register hooks with tasks.onFailure and the like, usually in the init file of a folder in build.dirs. They run for every task, before the task's own hooks:

src/trigger/init.ts
import { tasks } from '@bokjoy/sdk/trigger';import * as Sentry from '@sentry/node'; Sentry.init({ dsn: process.env.SENTRY_DSN }); tasks.onFailure('sentry', async ({ ctx, error }) => {  Sentry.captureException(error, { extra: { task: ctx.task.id, run: ctx.run.id } });  await Sentry.flush(2000);}); tasks.onComplete(async ({ ctx, result }) => {  if (result.ok) return;  console.error(`run ${ctx.run.id} failed: ${result.error.message}`);});

Each call takes a hook, or a name and a hook. Registering a name again replaces that hook. Hooks for every task run in the order they were registered.

When each hook runs#

HookWhen it runsWhereWhat it gets, besides ctx, payload, task and signal
onStartBefore attempt 1 only. Trigger.dev v4 keeps it for older code.In the attempt, before onStartAttemptNothing more.
onStartAttemptBefore every attempt: the first and each retry. Not when a workflow carries on after a wait.In the attempt, before run()Nothing more.
onSuccessThe run completed.In the attempt, after run() returns and before the result is recordedoutput
onFailureThe run failed for good: its last attempt failed, it threw AbortTaskRunError, it ran past maxDuration, its process crashed or ran out of memory, or its worker was lost.In a hook runerror
onCompleteAfter either: with onSuccess it gets result: {ok: true, data}, with onFailure it gets result: {ok: false, error}.Where onSuccess or onFailure runsresult
onCancelThe run was cancelled while an attempt of it was executing. A run cancelled while delayed, queued or waiting runs none.In a hook runrunPromise
  • Global hooks run first, then the task's own.
  • A failed attempt that is retried runs no hooks. onFailure runs once, after the run has failed for good.
  • A start hook that throws fails the attempt, as a throw in run() does, and the task's retry rules apply.
  • Any other hook that throws changes nothing. The run keeps its outcome, the hook is not retried, and the run's page shows the error.
  • signal never aborts. Bok Joy stops a process by ending it, so a hook cannot be told to wind down.
  • onCancel runs after the run has stopped. The run's process is ended when you cancel it, and onCancel runs afterwards in a hook run, so it can clean up but not stop work in progress. Its runPromise is already settled.
  • output is a copy. A hook that changes it does not change the run's result.
  • Success hooks run only for a result Bok Joy keeps. An output over 10 MiB, or with a NUL character or half of an emoji (a lone surrogate) in a string, fails the attempt before any success hook runs, and the task's retry rules apply. So does a workflow whose code completes without taking a step its earlier attempts took: Bok Joy fails that run, and only its failure hooks run.
  • A wait ends no run. In a task registered as a workflow, an attempt that stops at triggerAndWait or batchTriggerAndWait runs no onSuccess, onFailure, onComplete or onCancel. The attempt that carries on after the wait runs no start hooks. The end hooks run once, when the run ends.
  • A hook cannot wait. triggerAndWait, batchTriggerAndWait and Bok Joy's own steps fail inside a hook with an error that says to move them into run(). Use tasks.trigger to start a run from a hook.

The error a failure hook gets#

When the run's last attempt threw, error is that error, as Trigger.dev passes it. The hook runs in another process, so Bok Joy rebuilds it from what the attempt sent:

  • Its class and name. A TypeError, RangeError, SyntaxError, ReferenceError, EvalError or URIError is rebuilt as one, so instanceof TypeError holds. AbortTaskRunError passes instanceof AbortTaskRunError. Any other class, your own or a library's, arrives as an Error with its name, such as PrismaClientKnownRequestError: check error.name rather than instanceof.
  • Its message, the run's error text.
  • Its stack, from where it was thrown, up to 8 KiB.
  • Its codes and statuses: code, errno, status, statusCode, status_code, type, syscall, sqlstate and pgcode, when the error has them as a string, a number or a boolean. Nothing else of the error is kept, since an error's other fields can hold secrets and personal data: an HTTP client's error holds the request's headers, a database error the row's values. So Prisma's code arrives, and its meta does not.

When no error was thrown, error is an Error with the run's error text as its message, and a name that says how the run failed:

nameWhen
MaxDurationExceededErrorAn attempt ran past the task's maxDuration.
OutOfMemoryErrorThe last attempt ran out of memory: the kernel stopped it, or Node's heap reached its limit.
ErrorAnything else: a crash, a lost worker, a failed child of a workflow.

Its stack is then the name and message alone, with no frames.

Hook runs#

Bok Joy runs failure and cancel hooks in a hook run: a child of the run, shown under it in the console's trace. It starts within about a second of the run ending. It loads your deployment's code with the run's environment variables, as an attempt would, and calls only the hooks. It never calls run().

  • ctx and payload are the run's. ctx.run.id is the run's ID, ctx.attempt.number its last attempt, and ctx.run.parentTaskRunId and rootTaskRunId its place in its run tree. A schemaTask gets the payload parsed as run() got it, or as it was sent when it no longer parses.
  • It never waits for its task's queue. A task with a concurrency limit of 1 never holds its own hooks back. The hook run joins the line when it starts, behind runs already waiting.
  • An environment runs at most 16 hook runs at a time. The rest wait their turn, so a storm of failures in staging never holds back your production runs. A hook run waiting for compute does not count.
  • It makes up to 3 attempts, 1 second apart, when an attempt cannot finish: your code fails to load, or its process crashes, times out or loses its worker. A hook that throws is recorded, not run again.
  • Each attempt has the task's maxDuration, at most 5 minutes.
  • Cancelling the run, or a run above it, never cancels it. It runs because the run ended. To stop a hook run, cancel the hook run itself.
  • It cannot start tasks or set metadata. tasks.trigger throws and metadata changes are dropped. Do that work in run(), or in onSuccess, which runs in the attempt.
  • It has no hooks of its own, and it cannot be replayed or retried from failure. Replay its run instead.
  • A public access token reads no output for it. A browser that follows the run with a public access token reads the hook run's output as null, since it holds what the hooks threw.
  • It is not counted as a run of the task in the console's task list, metrics or errors. Its compute is part of the task's usage.

When the run's output would not fit beside its payload in what an attempt receives (16 MiB), a success hook run gets no output. That happens only when success hooks run in a hook run, below.

Success hooks run in the attempt, so they see the run's memory. Bok Joy runs a task's success hooks in a hook run only when it never learned that the attempt ran them.

Hooks run at least once#

A hook can run twice. A hook run whose worker is lost runs its hooks again, with the same event and the same error. A success hook runs again when the worker is lost after the hook ran and the run is then retried. Write hooks so a second call is harmless: key what they send with ctx.run.id, and set a row to a state rather than append to it.

When both onSuccess and onFailure run#

There is one case where a run's success and failure hooks both run. onSuccess and onComplete ran in the attempt, then its worker was lost before the result was recorded, on the run's last attempt. Bok Joy cannot know the outcome, so the run fails with an error such as execution outcome uncertain after confirmed cleanup, and onFailure and onComplete run too: onComplete runs twice, once with ok: true and once with ok: false. The Lifecycle hooks panel on the run's page shows both. With attempts left, the run is retried instead, and its success hooks run again if it succeeds.

How deploy finds hooks#

Deploy loads your init files and task files (Find tasks in folders) and records, on every task, the hooks that run after a run ends: the task's own, and every one registered with tasks.onX in any file. That is how Bok Joy knows to start a hook run once the run's process is gone. A task whose code never loads the file that registered a hook gets a hook run that runs nothing.

Deploy loads the files without your environment variables. A hook registered only when a variable is set is not found, so it does not run after a failure or cancel, and the run's attempts log:

Text
bokjoy: onFailure is registered but this deployment did not declare it, so it will not run after a failure or cancel; deploy again so discovery finds it

Register the hook every time, and check the variable inside it:

JavaScript
import { tasks } from '@bokjoy/sdk/trigger'; tasks.onFailure('alert', async ({ ctx, error }) => {  if (!process.env.ALERT_WEBHOOK_URL) return;  await fetch(process.env.ALERT_WEBHOOK_URL, {    method: 'POST',    body: JSON.stringify({ run: ctx.run.id, error: error.message }),  });});

Start hooks always run where they are registered, found or not.

Deploy refuses a project whose sdk folder is older than lifecycle hooks, whatever its tasks declare: an older copy cannot run hooks after a run ends, so its onFailure would never run. Copy the sdk folder from your Bok Joy version and deploy again.

Without Trigger.dev's names#

A task you write in the manifest is not found by deploy, so list its end hooks (onSuccess, onFailure, onComplete, onCancel) in its hooks. In Node, register hooks for every task with lifecycle, and give a handler its own with withHooks. Each hook gets Bok Joy's own context as ctx and the input as payload:

tasks/invoices.mjs
import { defineTask, lifecycle, withHooks } from '@bokjoy/sdk'; lifecycle.onFailure('log', async ({ ctx, error }) => {  console.error(`${ctx.task.id} failed: ${error.message}`);}); export const parseInvoice = withHooks(async (input, ctx) => ({ lines: 42 }), {  onSuccess: async ({ payload, output }) => { /* ... */ },}); export const definition = defineTask({  id: 'invoice.parse', runtime: 'node', kind: 'task',  entrypoint: 'tasks/invoices.mjs', handler: 'parseInvoice',  hooks: ['onSuccess', 'onFailure'],});

In Python, on_start_attempt, on_start, on_success, on_failure, on_complete and on_cancel register a hook for every task, called with a hook or a name and a hook, or as decorators. with_hooks gives a handler its own. A hook takes one argument with ctx, payload and task, plus output, error, result or run_promise, read as attributes or items. error is an exception of the type the task raised when that is a built-in one such as KeyError, and otherwise a new exception class with the same name, with the exception's own attributes set on it and its traceback text in error.stack. In place of signal it has cancelled, an asyncio.Event set when the process is told to stop:

Python
from bokjoy import define_task, on_failure, with_hooks  @on_failure("log")async def log_failure(params):    print(f"{params.task} failed: {params.error}")  async def parse(input, ctx):    return {"lines": 42}  parse_invoice = with_hooks(parse, on_success=lambda params: print(params.output)) definition = define_task(    id="invoice.parse", runtime="python", kind="task",    entrypoint="tasks/invoices.py", handler="parse_invoice",    hooks=["onSuccess", "onFailure"],)

See how hooks ran#

The run's page in the console has a Lifecycle hooks panel: each hook, whether it was registered for every task or is the task's own, and whether it ran or threw, with the error. Success hooks the attempt ran are listed under that attempt, and the hook run, if any, is linked and shown in the trace.

From the API, GET /v1/runs/{id} answers hooks: end, what the run's end ran (its event, the hooks, their state, the hook run's own status as hook_run_status, and each hook's outcome), and attempts, the success hooks each attempt ran in its own process. A hook run is a run of its own, with source hook.