> For the complete documentation index, see [llms.txt](https://www.health-samurai.io/docs/interbox/llms.txt).
> Use it to discover all available pages before guessing URLs.

---
# Step context

```ts
import { defineLookup, defineState, defineStep } from "@health-samurai/interbox/chain";
import type { Batch, RowContext, StepContext } from "@health-samurai/interbox/chain";
```

A step's function gets a `StepContext` as its second argument, and the function passed to a
row method gets a `RowContext`. The tables below list what each carries. The sections after
them cover state, unit reads, reference lookups, queued items, custom events, provenance and
terminology.

## `StepContext`

The second argument of a step, one per input before the store and one per take
after it.

| field | what it is |
|---|---|
| `signal` | an `AbortSignal` that fires at the work's deadline and when a stop's grace period ends. See [Deadlines](steps.md#deadlines) |
| `state(handle)` | the pipeline's state under a declared handle. See [State](#state-definestate-and-ctxstate) |
| `sender.queued(keys)` | the meta of the newest queued version of each key. See [`ctx.sender.queued`](#ctxsenderqueued) |
| `units` | reads the units of this pipeline. See [Reading units](#reading-units-ctxunits) |
| `lookup(handle)` | reads a reference table by key. See [Reference lookups](#reference-lookups-definelookup-and-ctxlookup) |
| `files.open(file)` | opens a file of a whole delivery as a stream. See [Whole deliveries](files.md#read-delivery) |
| `translate(map, code)` | a concept map lookup. See [Terminology](#terminology) |
| `translateFor(context, code)` | the same, through the map bound to a sender |
| `conceptMapFor(context)` | the name of the map bound to a sender |

## `RowContext`

The second argument of every function you pass to a row method (`map`,
`flatMap`, `filter`, `skip`, `notReady` and the four `with…` methods).

| field | before the store | after the store |
|---|---|---|
| `unit` | `undefined` | `{ id: bigint, attrs, createdAt: Date }` of the row's unit |
| `source` | `undefined` | `{ id, pipeline, receivedAt }`: the unit's id as a string, the pipeline, and the unit's creation time as ISO 8601 |
| `signal` | the input's signal | the take's signal |
| `units` | as on `StepContext` | as on `StepContext` |
| `lookup` | as on `StepContext` | as on `StepContext` |
| `files` | as on `StepContext` | as on `StepContext` |
| `translate`, `translateFor`, `conceptMapFor` | as on `StepContext` | as on `StepContext` |
| `webhook(event, payload)` | emits a custom event. See [`ctx.webhook`](#ctxwebhook) | the same |

A `RowContext` has no `state` and no `sender`. A row function that needs them
uses the step's own context:

```ts
const seen = defineState<{ at: string }>("lab.seen");

const markSeen = defineStep("mark-seen", (rows: Batch<LabResult>, ctx: StepContext) =>
  rows.map(async (row) => {
    ctx.state(seen).set(row.accession, { at: new Date().toISOString() });
    return row;
  }),
);
```

## State: `defineState` and `ctx.state`

```ts
function defineState<V>(namespace: string): StateHandle<V>;

interface State<V> {
  get(key: string): Promise<V | null>;
  get(keys: readonly string[]): Promise<Map<string, V>>;
  set(key: string, value: V): void;
  set(entries: Iterable<readonly [string, V]>): void;
  del(keys: string | readonly string[]): void;
}
```

State is a small durable key/value store, scoped to the pipeline: each pipeline
has its own copy of every namespace, and no pipeline reads another's. Declare a
handle once, at module level, and import it wherever a step needs it:

```ts
const lastSeen = defineState<{ orderAt: string }>("adt.last-seen");

const newerOnly = defineStep("newer-only", (msgs: Batch<Admit>, ctx: StepContext) =>
  msgs.skip(async (msg) => {
    const before = await ctx.state(lastSeen).get(msg.patientId);
    if (before !== null && before.orderAt >= msg.sentAt) return "older than what we have";
    ctx.state(lastSeen).set(msg.patientId, { orderAt: msg.sentAt });
    return undefined;
  }),
);
```

- **Namespace names.** They use lowercase Latin letters, digits, `-` and `.`,
  start with a letter, and are at most 46 characters. `defineState` throws on
  any other. The name is what the rows are stored under: renaming it leaves the old
  rows behind.
- **Reserved prefixes.** `filedrop.` and `aidbox.` are reserved for the state
  Interbox writes itself, and `defineState` throws on a name that begins with
  either. To read the Aidbox sender's state, use the
  [`fingerprints`](built-in-stages.md#fingerprints) handle.
- **Values.** They are JSON. A key holding the NUL character or a lone UTF-16
  surrogate, or a value JSON cannot hold, makes `set` or `del` throw.
- **Many-key `get`.** It is one query and answers a `Map` without the keys it
  did not find. Single-key `get`s made in the same tick are read together.
- **A `get` after a `set` or `del` in the same work reads the buffered write.**
  Other work sees only committed values.
- **No time to live.** A namespace that would grow forever is cleaned with
  `del`.

Writes are buffered and commit with the work they belong to:

| where | they commit | they are dropped when |
|---|---|---|
| a step before the store | with the input, when it commits | the input is refused |
| a step after the store | with the take's result, even when one of its units fails | the take passes its deadline, a stop ends it, or another worker took one of its units over. When Postgres refuses the values, their keys are deleted instead and the units' results still commit |

A `set` or `del` made after the step's work has finished, from a promise no one
awaited, is dropped without throwing, and the engine logs an error naming the
pipeline, the namespace and the key.

## Reading units: `ctx.units`

```ts
interface UnitsReader {
  count(filter?: UnitsFilter): Promise<number>;
  find(query?: UnitsQuery): Promise<UnitRow[]>;
}

interface UnitsFilter {
  readonly attrs?: Readonly<Record<string, string>>;
  readonly status?: UnitStatus | readonly UnitStatus[];
}

interface UnitsQuery extends UnitsFilter {
  readonly limit?: number;               // 1 to 1000; 100 by default
  readonly order?: "newest" | "oldest";  // by unit id; "newest" by default
}

interface UnitRow {
  readonly id: string;
  readonly status: UnitStatus;
  readonly attrs: Readonly<Record<string, unknown>>;
  readonly createdAt: string;            // ISO 8601
  readonly orderAt: string;              // ISO 8601
  readonly errorStep?: string;           // present only on a unit at "error"
  readonly errorKind?: string;
  readonly errorMessage?: string;
}

type UnitStatus = "received" | "processed" | "sent" | "skipped" | "error" | "deferred";
```

`ctx.units` reads the units of the step's own pipeline, and no other:

```ts
const priorResults = defineStep("prior-results", (msgs: Batch<Oru>, ctx: StepContext) =>
  msgs.withAttrs(async (msg) => ({
    prior: String(await ctx.units.count({ attrs: { patient_id: msg.patientId }, status: "sent" })),
  })),
);
```

- **Filters.** Each attr matches by equality on its text, `status` matches any
  one given, and every condition must hold. An attr value must be a string, and
  anything else throws.
- **Indexes.** A filter on an attr the store declares in `index` reads that
  index. Any other attr is a scan of the pipeline's units.
- **Limits.** `find` answers at most `limit` rows. A `limit` outside 1 to 1000,
  or an `order` other than the two, throws.
- **Before the store.** A call runs in the input's own transaction, so it sees
  the units that input has written so far.
- **After the store.** Each call is a short read-only query of its own, under a
  statement timeout of what is left of the take's deadline. Once `ctx.signal`
  has fired, a call throws.
- **No text search.** `ctx.units` does not read `search_text`.
- **A query per row adds up.** A `count` inside `map` is one query per unit.
  For a whole take, use `mapAll` and query once.
- **A Retry can see different units.** The answer depends on what is in the
  database when the step runs.

## Reference lookups: `defineLookup` and `ctx.lookup`

```ts
function defineLookup<Row = LookupRow>(name: string, spec: LookupSpec): LookupHandle<Row>;

interface LookupSpec {
  readonly table: string;               // read as reference.<table>
  readonly key: string;                 // a text column with a unique index of its own
  readonly columns: readonly string[];  // what each row answers; the key is not added
}

interface LookupReader<Row> {
  get(keys: readonly string[]): Promise<Map<string, Row>>;
}

type LookupRow = Readonly<Record<string, unknown>>;

class NotReady extends Error {
  constructor(message: string, afterMs?: number);
  readonly afterMs: number;
}

const MAX_NOT_READY_MS = 86_400_000;

function isNotReady(err: unknown): err is NotReady;
```

A lookup reads rows of a reference dataset, such as a provider registry or a
code table, by key. Declare a handle once, at module level, export it from the
workspace entry in `LookupRegistry`, and read through `ctx.lookup`:

```ts
const providers = defineLookup<{ name: string; taxonomy: string | null }>("providers", {
  table: "npi_registry",
  key: "npi",
  columns: ["name", "taxonomy"],
});

export const LookupRegistry = { providers };

const providerName = defineStep("provider-name", (claims: Batch<Claim>) =>
  claims.withAttrs(async (claim, ctx) => {
    const found = await ctx.lookup(providers).get([claim.npi]);
    return { provider: found.get(claim.npi)?.name ?? "unknown" };
  }),
);
```

- **Registered handles only.** The workspace entry, `src/index.ts`, exports
  `LookupRegistry` beside `ChainRegistry`: a plain object whose values are the
  handles its steps use, as `defineLookup` returned them. A `Map`, or a value
  that is not such a handle, fails the workspace load with an error naming the
  entry. A step may pass only a handle the registry holds, the very object,
  not another declared alike. Any other throws an error naming the handle and
  `LookupRegistry`.
- **The `reference` schema, and no other.** `table` always means
  `reference.<table>`, whatever the connection's `search_path`. The engine's
  own tables and the workspace's inbound tables hold the messages pipelines
  carry, and a lookup must not become a way to read them, so reference data has
  a schema of its own. Rows are read from `reference.<table>` alone, as
  `FROM ONLY` reads them, and never from a table that inherits from it in any
  schema. A partitioned table, whose rows live in its partitions, is therefore
  never ready. The engine does not create the schema or its tables: create
  and load them yourself, readable by the role the engine connects as.
- **Names.** The lookup's name, `table`, `key` and every column use lowercase
  Latin letters, digits and `_`, start with a letter or `_`, and are at most 63
  bytes, the most Postgres keeps of a name. `defineLookup` throws on any other.
  Names are always quoted, so a column called `order` is read as it is, and
  there is no `*`: a lookup reads the columns it lists.
- **Key.** A `text` column with a unique index on that column alone:
  valid, not partial, not on an expression, with no second key column, in the
  column's own collation and with the default operator class for `text`. A
  primary key on it is such an index. An index built `COLLATE "C"` or with
  `text_pattern_ops` on a column of another collation is not. `get(keys)`
  answers a `Map` holding only the keys found. A key given twice is answered
  once, a key holding the NUL character or a lone UTF-16 surrogate matches
  nothing, and a key that is not a string throws an error naming its index.
- **Any number of keys.** The engine reads them 1000 to a query and merges the
  answers. A call per row is a round trip per row: for a whole take, gather
  the keys in `mapAll` and call once.
- **Values.** They are JSON, as Postgres's `row_to_json` writes them: a `date` is its
  ISO string, a `timestamptz` an ISO string with the offset of the session's
  time zone, a `char(n)` is padded to n, a `text` comes back unchanged, and a
  `bigint` or `numeric` is a JavaScript number, a numeric `NaN` the string
  `"NaN"`. A number past 2^53, or one with more than 15 significant digits,
  can come back rounded, and nothing reports it. Keep identifiers, such as
  account or member numbers, in `text` columns.

### Where a lookup runs

- **After the store.** Each call is a read-only transaction of its own, under a
  statement timeout of what is left of the take's deadline and a lock timeout
  of 2 seconds. Once `ctx.signal` has fired, a call throws.
- **Before the store.** The same holds, under what is left of the input's
  deadline. The steps before the store run before the input's transaction
  opens, so a lookup never holds that transaction open or keeps the table
  locked.

### Not ready

A table is ready when `reference.<table>` exists, holds at least one row, has
its key as above, and has every listed column. Until then a call throws
`NotReady`, and so does a call that waits on a lock past its 2-second lock
timeout:

| where | a lookup that is not ready |
|---|---|
| after the store | leaves its unit at the store, taken again a second later, counting no attempt, however long the table takes to load |
| before the store | refuses the input with the code `not_ready`: MLLP answers `AE`, HTTP `500`, and the sending side retries |

No table is checked when the workspace loads, so a table not loaded yet never
stops the engine. The first call of a handle in each worker checks the
table, and a call checks it again whenever Postgres answers from a different
table under that name, as after a swap. Whether the table is empty is read on
every call.

A step may catch `NotReady` to go on without the rows. Tell it with
`isNotReady(error)`, not `instanceof`: the workspace bundle carries its own
copy of the class, and the error comes from the engine's. A step may also throw
a `NotReady` of its own, with a delay in milliseconds, and the engine treats it
the same way, waiting at least one second. The delay must be from 0 to
`MAX_NOT_READY_MS`, 24 hours: the constructor throws on any other.

### Loading a new version

Load it beside the table in use, then swap the two by rename:

```sql
CREATE TABLE reference.npi_registry__loading (LIKE reference.npi_registry INCLUDING ALL);
COPY reference.npi_registry__loading FROM STDIN;
ANALYZE reference.npi_registry__loading;
BEGIN;
ALTER TABLE reference.npi_registry RENAME TO npi_registry__old;
ALTER TABLE reference.npi_registry__loading RENAME TO npi_registry;
COMMIT;
DROP TABLE reference.npi_registry__old;
```

The load runs before the swap's transaction, so the renames hold their locks
only for a moment, and no lookup sees the table half-loaded or missing. A
lookup made during the swap waits for its commit and then reads the new table.
One that waits past its 2-second lock timeout is not ready: its unit waits, or
its input is refused.

## `ctx.sender.queued`

```ts
ctx.sender.queued(keys: readonly string[]): Promise<Map<string, Readonly<Record<string, unknown>>>>;
```

For each key that has items waiting in this pipeline's sender queue, the meta
of its newest queued version, newest by the items' `order_at`, then unit, then
item. A key with nothing queued is not in the map. `skipUnchanged()` uses it to
compare a resource with the version already waiting to go out.

## `ctx.webhook`

```ts
ctx.webhook(eventType: `custom:${string}`, payload: unknown): void;
```

On a row function's context. Emits a custom event to the pipeline's webhooks
that subscribe to it in `.webhook({ on })`. The payload must be JSON, or the
call throws.

- **Before the store.** The event is written with the input's commit.
- **After the store.** It is written with the unit's result when the unit
  closes `processed`, `sent` or `skipped`, and dropped when the unit fails or
  waits.

See [Webhooks](../guides/webhooks.md) for subscriptions and delivery.

## `ctx.source` and `provenanceId`

After the store, `ctx.source` names the unit a row belongs to:

```ts
interface RowSource {
  readonly id: string;          // the unit's id
  readonly pipeline: string;
  readonly receivedAt: string;  // the unit's creation time, ISO 8601
}
```

Prefer `receivedAt` or `ctx.unit.createdAt` over `new Date()` for anything you
put in an output. They do not move when the unit is retried, so a Retry
produces the same output, and `skipUnchanged()` can skip what is already
delivered.

To record in the destination which unit produced a set of resources, add a
`Provenance` whose id comes from the unit:

```ts
import { provenanceId } from "@health-samurai/interbox";

function provenanceOf(ctx: RowContext, targets: readonly Resource[]): Provenance {
  const unit = ctx.unit;
  if (unit === undefined) throw new Error("provenance is built after the store");
  return {
    resourceType: "Provenance",
    id: provenanceId(unit),
    recorded: unit.createdAt.toISOString(),
    agent: [{ who: { display: "Interbox" } }],
    target: targets.map((r) => ({ reference: `${r.resourceType}/${r.id}` })),
  };
}
```

`provenanceId(unit)` is `ib-<unit id>-<created time in base-36 milliseconds>`,
at most 32 characters. A Retry of the unit gives the same id, so its
Provenance is updated in place.

## Terminology

```ts
translate(map: string, code: string): Promise<ConceptMapMatch | undefined>;
translateFor(context: ConceptMapContext, code: string): Promise<ConceptMapMatch | undefined>;
conceptMapFor(context: ConceptMapContext): string;

interface ConceptMapContext {
  type: string;
  sendingApplication: string;
  sendingFacility: string;
}

interface ConceptMapMatch {
  targetCode?: string;      // absent when the equivalence is unmatched or disjoint
  targetDisplay?: string;
  targetSystem?: string;
  equivalence: string;
  sourceDisplay?: string;
}
```

The lookups read the concept maps under `src/terminology/concept-maps/` in the
workspace. `translate` looks a code up in the map with that id. `undefined`
means the map has no entry for the code, or there is no such map.
`translateFor` looks it up in the map bound to a sender's context, and
`conceptMapFor` names that map: the bound one, or, when none is bound, a name
derived from the context, `hl7v2-<application>-<facility>-<type>`. A lookup
that misses reads the map files again when they changed since they were last
loaded.

```ts
const loincOf = defineStep("loinc-of", (codes: Batch<string>) =>
  codes.withAttrs(async (code, ctx) => ({ loinc: (await ctx.translate("lab-codes", code))?.targetCode ?? null })),
);
```
