---
url: https://kit.kambium.net/docs/tasks.md
---
# Task execution

Use tasks for work that needs persisted identity, retries or recovery after a
process stops. An engine declares the operation and its handler; the worker owns
claiming, concurrency, attempt timeouts and finalization.

## Declare and register operations

The application extends `TaskPayloadByOperation` through
`@kambium/kit/shared/types`. Handler payloads and `context.tasks.enqueue` then use
the same operation-to-payload relationship. The
[heartbeat guide](https://kit.kambium.net/docs/first-engine.md#_2-declare-your-task-operation) gives the complete
module augmentation and import pattern.

The declaration must be included in the application's TypeScript program. It does
not register an executable handler: the operation must also appear in the engine's
`tasks` definition or the server's platform tasks. Runtime registration validates
ownership before dispatch. Keep operation names unique across engines unless
sharing a payload contract and worker settings is intentional.

Operations are stored as text, so adding a name needs no migration. Payloads must
be persisted JSON values. Validate external inputs before enqueueing and handle
nullable payloads from stored rows; types do not validate either boundary.

## Enqueue work

After declaring the heartbeat operation from the guide, a hook can enqueue it:

```ts
await context.tasks.enqueue("heartbeat", {
  external_record_id: `heartbeat:${requestedAt}`,
  payload: { requestedAt },
  reuseExisting: true,
});
```

The current context supplies the engine identity. Do not add a separate `sync_id`
or construct another provider service to enqueue work. `external_record_id`
identifies the work within the engine/operation; choose it deliberately when
redelivery should reuse a task.

`reuseExisting: true` reuses stored task identity across insert races and retries
and wakes due pending work. It does not reset a broken task or execute future-dated
work immediately. Persisted identity reuse does not make an external side effect
idempotent by itself.

`run_at` schedules a task for later. `scheduleDelayedTaskWake` only arms a wake for
an already persisted task; it does not insert one. Scheduled recovery is disabled
by default in development/tests. The [optional local task check](#optional-local-task-check)
runs its task through the worker; do not infer production recovery from that
check alone.

## Complete or fail a task

A handler receives `{ context, task, run, signal }`. Await its work and propagate
failure. Call `run.success(message)` only after required writes/side effects
succeed; it records completion and a success event. The worker also owns automatic
success for a normally returned handler that has not finalized its run.

Useful `TaskRun` methods include:

| Method | Contract |
| --- | --- |
| `logMessage`, `warn` | Record progress without declaring completion |
| `success` | Mark done, clear the payload and record success |
| `skip` | Finish as done with a skipped final result |
| `reschedule(runAt)` | Return to pending for a later time without consuming the current attempt |
| `fail` | Apply retry/terminal classification and persist failure |

Throw an ordinary error when a later attempt may succeed. `PermanentError` and
`RetryClassifiedError` with `permanent: true` are terminal at the task boundary;
they become broken without retry. Exhausting attempts also breaks the task.
A configuration error that the same payload cannot fix should be classified
permanent. Do not catch failures and return normally unless the work truly
completed.

### Retry and recovery boundaries

Each task is a unit of retry and recovery. Database claiming gives one worker
ownership of a pending task at a time. After failure or interruption, a retry
invokes the handler again from the beginning. Progress events are logs with no
effect on where execution resumes.

Choose task boundaries around the work that should retry together. If one handler
performs A, B and C, a failure at C can repeat A and B. Split those operations into
separately persisted tasks in a chain when they need independent recovery.
Retrying a successor does not rerun a predecessor already recorded as done.

Task completion and an external provider write are separate operations. If a
provider accepts a write and the worker stops before recording success, recovery
can repeat that write, even with a single worker process. Use stable provider
identities or an engine-owned persistence strategy where repeated side effects
would be harmful. Smaller tasks narrow the work repeated; they do not remove
this external-write failure window.

Use the supplied abort signal for cancellable I/O. After a timeout or lease loss,
an earlier attempt's external request can still be in flight when another attempt
starts. Exclusive claiming cannot cancel that request. Cancellation or lease loss
must not be reported as successful completion.

## Optional local task check

After [registering the heartbeat engine](https://kit.kambium.net/docs/first-engine.md), use this optional
exercise to verify execution through the real worker and read back its saved
result. Run commands from the app directory, with Desktop's **Local Server**
switched off or `dev:local` stopped.

The generated app already supplies the authentication, workspace and local
operator infrastructure. The heartbeat-specific changes select the engine kind,
provide its task payload and assert the expected result.

Replace `local-check.ts` with the complete check below. It creates local test
records, runs the heartbeat through the real worker and checks the saved timestamp,
task status, attempt count and success event. It uses the generated app's local
operator and refuses a non-local Supabase endpoint.

::: details Complete heartbeat local-check.ts

```ts
import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import type { createServer } from "@kambium/kit/server";

// Run only via `kambium local check`, using the same configured app and worker.
export async function checkLocal(server: Awaited<ReturnType<typeof createServer>>) {
  assert.equal(process.env.KAMBIUM_LOCAL, "1");
  assert.equal(server.context.mode, "dev");
  const url = new URL(process.env.SUPABASE_URL!);
  assert.ok(["localhost", "127.0.0.1", "[::1]"].includes(url.hostname), "Local check requires local Supabase");
  const context = server.context;
  const supabase = context.supabaseMaster;
  const identityPath = ".local/kambium/operator.json";
  async function signIn() {
    return fetch(new URL("/auth/v1/token?grant_type=password", url), {
      method: "POST", headers: { apikey: process.env.SUPABASE_PUBLISHABLE_KEY!, "content-type": "application/json" },
      body: JSON.stringify({ email: process.env.KAMBIUM_LOCAL_OPERATOR_EMAIL, password: process.env.KAMBIUM_LOCAL_OPERATOR_PASSWORD }),
    });
  }
  let signed = await signIn();
  if (signed.status === 400) {
    const result = await supabase.auth.admin.createUser({
      email: process.env.KAMBIUM_LOCAL_OPERATOR_EMAIL,
      password: process.env.KAMBIUM_LOCAL_OPERATOR_PASSWORD, email_confirm: true,
    });
    if (result.error) throw result.error;
    signed = await signIn();
  }
  assert.equal(signed.status, 200, "Local operator sign-in failed");
  const identity: { user: { id: string }; access_token: string } = await signed.json();
  const userId = identity.user.id;
  try {
    const stored: { user_id: string } = JSON.parse(await readFile(identityPath, "utf8"));
    assert.equal(stored.user_id, userId, "Local operator identity changed");
  } catch (error) {
    if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
    await writeFile(identityPath, JSON.stringify({ user_id: userId }) + "\n", { mode: 0o600, flag: "wx" });
  }
  const headers = { authorization: `Bearer ${identity.access_token}` };
  const created = await server.inject({ method: "POST", url: "/ui/workspaces/create", headers,
    payload: { name: "Local example" } });
  assert.equal(created.statusCode, 201, created.body);
  const workspaceId: string = created.json().workspace.id;
  const engineId = randomUUID();
  const inserted = await supabase.from("syncs").insert({ id: engineId, user_id: userId,
    workspace_id: workspaceId, kind: "heartbeat", active: true, config: {} });
  if (inserted.error) throw inserted.error;
  // This exercises the real Redis-backed permission-cache invalidation path.
  await context.invalidateEngineAccess();
  const requestedAt = new Date().toISOString();
  const task = await context.repos.taskMasterRepo.insert({ sync_id: engineId,
    external_record_id: `local-check:${randomUUID()}`, operation: "heartbeat", payload: { requestedAt },
    status: "pending", run_at: new Date(Date.now() - 1000).toISOString() });
  if (!context.taskManager) throw new Error("App has no task manager");
  await context.taskManager.processNowAndWait({ tasks: [task] });
  const persisted = await context.repos.taskMasterRepo.findById(task.id);
  assert.equal(persisted.status, "done", persisted.last_error ?? "Local task did not complete");
  assert.equal(persisted.attempts, 1);
  const engine = await context.repos.syncMasterRepo.findById(engineId);
  assert.equal(engine.kind, "heartbeat");
  assert.equal(engine.last_active_at, requestedAt, "Heartbeat did not save its timestamp");
  const events = await context.repos.taskEventRepo.findByTaskId(task.id);
  assert.ok(
    events.some(event => event.status === "success" && event.message === "Heartbeat recorded"),
    "Heartbeat did not record its success event",
  );
  const result = { workspace_id: workspaceId, engine_id: engineId, task_id: task.id, status: persisted.status };
  await writeFile(".local/kambium/last-check.json", JSON.stringify(result, null, 2) + "\n", { mode: 0o600 });
  console.log("Local engine task passed:", result);
}
```

:::

Run from the app directory:

```sh
npm run local:check
```

Expect `Local engine task passed:` with `status: 'done'`. The command creates a
local test workspace and active heartbeat instance, persists a task, runs it
through the worker and reads back the engine and task events. Its IDs are saved
in `.local/kambium/last-check.json` for inspection.

To verify the check catches a regression, temporarily remove the timestamp
update from the handler and rerun `npm run local:check`. It should fail with
`Heartbeat did not save its timestamp`. Restore the update and rerun successfully.

This checks task execution and persistence. The test instance is inserted as
active; it does not exercise the lifecycle activation flow or provider OAuth.

## Recovery and advanced scheduling

Production jobs include pending/stale task recovery when enabled. Recovery,
lease handling and engine eligibility remain worker-owned. Engine-local task
writes reject another instance's rows. Installed backend handlers still have
privileged repository access; scoped helpers are an API contract, not isolation
from untrusted code.

Core 0.8.1 supports `keepLatest` for registered operations with Core database
schema 1.4.0 or newer. Declare it once per engine and operation in
`defineEngine({ taskScheduling })`. The key is scoped to that engine instance and
operation. New input replaces the pending successor while running attempts and
retries retain their identity. Registration rejects policies for
`airtable_webhook_drain`, operations without a registered handler, and duplicate policy
attachments. For Airtable record or schema tasks, remove the legacy
`enqueueDelayedTasks` hook before enabling scheduling. See [TaskScheduling](https://kit.kambium.net/docs/kit-api.md#taskscheduling).

::: details Worker ordering, startup and periodic recovery

Fast and background workers share process-local total, per-engine and
per-operation concurrency budgets. Within a lane, due tasks are ordered by
`run_at`, then `id`; handler registration order gives no priority. An engine runs
one operation type at a time within that lane. Saturated operations and engines
are filtered before applying the pending-query limit.

After the server listens successfully, startup triggers one pending-task replay,
even when cron jobs are disabled. It does not wait for task completion before
returning the listening address. Set `config.startupTaskRecovery: false` only
when the host owns that startup sequencing. Periodic recovery is separately
controlled by `jobsEnabled`.

With jobs enabled, pending recovery runs every minute and stale-processing
recovery every five minutes. Stale recovery uses a ten-minute threshold,
100-row pages and a five-attempt limit. Broken-task payload cleanup runs hourly
with a fourteen-day default retention. These are recovery defaults, not a promise
that an interrupted external side effect executes only once.

Shutdown stops new dispatch and cancels/requeues active attempts. Handlers must
honor the supplied signal and make repeated side effects safe.

:::

::: details Task chains and failure continuation

Task definitions can declare `failureContinuation` defaults or a callback that
reconstructs a successor for persisted engine work. An explicit payload policy
and successor take precedence. Lookup uses the owning engine definition; an
operation shared by several engines does not inherit another engine's defaults.

A successor must be persisted before the failed attempt is finalized. If that
write fails, the attempt remains recoverable. Inactive engines, reconnect
handling, shutdown and lease loss can suppress continuation. Reusing a stored
successor identity still requires idempotent external side effects.

:::

Optional source detail (repository access may be required):
[worker contracts](https://github.com/MartinMalinda/kambium/blob/main/packages/core/server/tasks/README.md), [engine task inputs](https://github.com/MartinMalinda/kambium/blob/main/packages/core/types.ts),
[TaskRun](https://github.com/MartinMalinda/kambium/blob/main/packages/core/tasks/run.ts) and
[task registration](https://github.com/MartinMalinda/kambium/blob/main/packages/core/server/tasks/registry.ts).
