# Operations and durable work

Fellow runs background work on PostgreSQL: there is no broker to operate. Jobs, durable event deliveries,
workflows and schedules are rows in global tables (`fellow_jobs`, `fellow_events`, `fellow_workflows`,
`fellow_workflow_steps`), claimed by workers with `FOR UPDATE SKIP LOCKED`. Everything carries the
context envelope (tenant, subject, roles, request id, trace) of whoever started it, so a worker runs the work
in that tenant: `sql()` is scoped and row-level security applies, exactly as in the request.

## Jobs

Jobs live in `modules/<module>/jobs/` and are named `<module>.<...>` (FW-JOB-001). Create one with
`fellow make:job records.document.index`.

```ts
import { defineJob, dispatch, transaction, z } from '@fellowframework/core'

export const indexDocument = defineJob({
  name: 'records.document.index',
  payload: z.object({ id: z.uuid() }),
  maxAttempts: 5,          // then the job is dead (inspect, then `fellow queue:retry`)
  backoff: 5,              // seconds, doubled per attempt, up to maxBackoff
  timeout: 60,
  async handler({ id }, context) {
    // context.tenantId is the tenant of the dispatcher
  },
})

await transaction(async () => {
  await createDocument(input)
  await dispatch(indexDocument, { id })   // queued only if the transaction commits
})
await dispatch(indexDocument, { id }, { delay: 60, idempotencyKey: `index:${id}` })
```

- **Transactional.** `dispatch` writes in the current transaction: a rollback discards the job (outbox pattern).
- **At least once.** A crashed worker's lease expires and the job runs again. Make handlers idempotent; `once(key, fn)`
  runs a side effect at most once per key in the tenant.
- **Retries.** Errors retry with exponential backoff. A `FellowError` with a 4xx status (except 409 and 429) is
  permanent: retrying cannot help, so the job dies at once. Unexpected failures join the error groups.
- **Inactive modules.** Jobs of a module that is inactive for the tenant are skipped.

## Durable events

Listeners are inline by default. A durable consumer is recorded with the transaction and delivered by workers,
once per consumer, with retries:

```ts
import { onEvent, once } from '@fellowframework/core'
import { documentCreated } from '../events/document.created'

onEvent(documentCreated, async ({ id }) => {
  await once(`search:${id}`, () => indexInSearch(id))
}, { durable: 'records.search-index' })
```

`emitEvent` inside a transaction writes `fellow_events` and one delivery job per durable consumer; nothing is
delivered if the transaction rolls back. Deliveries go through the queue (`fellow.event.deliver`).

## Workflows

A workflow is a function whose steps survive restarts. Each `ctx.step` result is stored; after a suspension the
function is replayed from the start and completed steps return their stored result instead of running again.

```ts
import { defineWorkflow, startWorkflow, signalWorkflow, z } from '@fellowframework/core'

export const routing = defineWorkflow({
  name: 'records.document.routing',
  version: 1,
  input: z.object({ documentId: z.uuid() }),
  timeout: '30d',
  async run(ctx, { documentId }) {
    const sent = await ctx.step('send-to-review', () => moveDocument(documentId, 'in_review'), {
      compensate: (result) => moveDocument(documentId, result.from),   // undone if the workflow fails or is cancelled
    })
    const decision = await ctx.waitForSignal<{ approved: boolean }>('decision', { timeout: '7d' })
    if (!decision?.approved) throw new Error('Rejected')                 // compensations run in reverse order
    await ctx.sleep('cool-down', '1h')
    await ctx.step('archive', () => moveDocument(documentId, 'archived'))
    return { previous: sent.from }
  },
})

const { id } = await startWorkflow(routing, { documentId }, { idempotencyKey: `routing:${documentId}` })
await signalWorkflow(id, 'decision', { approved: true })
```

Rules that keep replay correct:

- Side effects (database writes, calls, emails) go inside `ctx.step`. Code outside steps runs again on every replay.
- Step names are stable identifiers. Changing the order or names of steps of running instances needs a new
  `version`; keep the old version deployed until its instances finish.
- A signal sent before the workflow reaches `waitForSignal` is kept and consumed when it gets there.
- A wait that times out returns `null`; a workflow past its `timeout` fails.
- Inside a tenant context, other tenants' workflows do not exist (`workflow.not_found`).

The example application routes documents this way: `examples/records/modules/records/workflows/document-routing.ts`.

## Schedules

```ts
import { defineSchedule } from '@fellowframework/core'
import reminder from '../jobs/routing-reminder'

export default defineSchedule({ name: 'records.routing-reminder', cron: '0 11 * * 1-5', job: reminder, payload: { days: 3 } })
```

Cron has five fields in UTC (or `@hourly`, `@daily`, `@weekly`, `@monthly`). With `tenants: 'each'` (default) the job
is queued once per active tenant where the module is active; `tenants: 'none'` queues one maintenance job.
Each run has an idempotency key per schedule, tenant and minute, so several workers never duplicate it.

## Workers

```bash
fellow work                      # default queue, 4 concurrent jobs, scheduler on
fellow work --queue mail,default --concurrency 8
fellow work --once               # drain what is ready and exit (cron-driven hosts, CI)
```

The worker boots the application (manifests, `app.ts`, listeners, jobs, workflows, schedules, channels), records a
heartbeat in `fellow_workers`, runs the scheduler once a minute and reschedules workflows whose wake-up job was
lost. `SIGTERM` stops claiming, waits for running jobs and exits. Deploy web and worker processes from the same
release: a delivery for a listener the worker does not have fails with a clear error.

## Idempotent routes

```ts
export default defineRoute({ ..., method: 'POST', idempotent: true })
```

A client retrying with the same `Idempotency-Key` header gets the first response (with `idempotent-replayed: true`)
instead of running the handler twice. The key is scoped to tenant, subject and route; reusing it with a different
body is refused (422 `idempotency.key_reused`), and a retry while the first request still runs gets 409
`idempotency.in_progress`. 5xx responses release the key so the client can retry. `idempotent: { required: true }`
makes the header mandatory; `ttlHours` sets how long responses are replayed (default 24).

## Real-time channels

```ts
// modules/records/channels/documents.ts
import { defineChannel } from '@fellowframework/core'
export default defineChannel({ name: 'records.documents', permission: 'records.document.read' })

// in a service
import { broadcast } from '@fellowframework/core'
await broadcast('records.documents', 'document.moved', { id, to: 'archived' })
```

```ts
// in a Vue page
import { subscribeChannel } from '@fellowframework/vue'
subscribeChannel('records.documents', (message) => reload(), { onReconnect: reload })
```

Browsers connect to `GET /__fellow/events?channel=...` (Server-Sent Events). The endpoint authenticates like any
route, checks the channel permission (and `authorize` with the `{param}` values of names such as
`records.document.{id}`) and only ever subscribes the caller's tenant. Inside a transaction a broadcast waits for
the commit (`afterCommit`), so clients never see rolled-back data. Broadcasts are notifications without delivery
guarantee: reload state on reconnect. With several instances, or workers in separate processes (broadcasts from jobs and workflows), set `FELLOW_BROADCAST=redis` (and `REDIS_URL`) in every process.

## Health

| Endpoint | Meaning |
|---|---|
| `GET /__fellow/health` | Liveness: the process answers. Never touches dependencies. |
| `GET /__fellow/ready` | Readiness: database (with a role subject to RLS) and cache answer. 503 while draining. |

Call `setDraining()` on shutdown so load balancers stop sending traffic before the process exits.

## Observability

Fellow instruments through the OpenTelemetry API: requests are server spans (with the incoming `traceparent`),
jobs, deliveries and workflow runs are spans linked to the request that started them, and metrics cover request
duration, jobs by outcome, query duration and emitted events. Without an SDK it is all a no-op. To export:

```bash
bun add @opentelemetry/sdk-node @opentelemetry/exporter-trace-otlp-http @opentelemetry/exporter-metrics-otlp-http @opentelemetry/sdk-metrics
```

```ts
// app.ts
import { startTelemetry } from '@fellowframework/core/otel'
export default defineApp({ boot: async () => void (await startTelemetry({ serviceName: 'records' })) })
```

Logs are JSON lines with `requestId`, `tenantId` and `subject`. Queries slower than `FELLOW_SLOW_QUERY_MS`
(default 500) log `db.slow_query` with the statement text, never its values.

## Diagnosing failures

Unexpected errors (HTTP 500 and dead jobs) are grouped by fingerprint: error type, message with ids and numbers
removed, the first frame in application code and the route.

```bash
fellow errors                   # groups, counts, last request id
fellow diagnose <id>            # request id, fingerprint, job id or workflow id
```

`fellow diagnose` gathers the error group, the jobs, events and audit entries of the same request, the workflow
history, the file and line that raised the error, the most relevant project code, known causes for the error
signature and the next steps. `fellow doctor` also reports ready jobs with no live worker, dead jobs, overdue
workflows and recent error groups.

## Backups

```bash
fellow backup                     # pg_dump custom format + manifest with SHA-256
fellow backup:verify backups/fellow-2026-12-03T02-00-00-000Z.dump
fellow restore backups/fellow-2026-12-03T02-00-00-000Z.dump   # needs: fellow approve backup.restore <file>
```

The application role is subject to row-level security and cannot read every tenant, so full backups use
`FELLOW_BACKUP_DATABASE_URL`: a role with `BYPASSRLS` used only for backups and restores, never by the
application (FW-BACKUP-001 otherwise; `--schema-only` works with the application role). Verify every backup
and rehearse restores in a separate database. Point-in-time recovery (WAL archiving) belongs to the database
platform and complements these logical backups.

## Retention

`fellow retention:run` also prunes completed and cancelled jobs and workflows and fully delivered events older
than `FELLOW_OPERATIONS_RETENTION_DAYS` (default 30), and expired idempotency keys. Dead jobs and failed workflows
are kept for inspection.
