> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Pipelines

> Declare derived datasets, run them on your compute and publish complete output groups.

A pipeline declares how input datasets become output datasets. Bijection keeps
the input versions, the run and the accepted outputs; the computation runs on your
warehouse or worker, which Bijection reaches through a receiver. The
`@bijectionhq/library-pipelines` library is a subtree you place in your tree beside a
[Datasets](https://docs.bijection.com/datasets) installation, which stamps each candidate's input versions, lineage
and label and owns which version is current.

An output group's value is `F(In@c)` for one version `c` of its inputs: one
version per input, consistent together. An
incremental run is a refinement of that value, admitted only when Datasets
accepts its hint.

## Declare a pipeline

```ts bijection/app.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { app, http, label, role, secret, t, target } from "@bijectionhq/bijection";
import { datasets } from "@bijectionhq/datasets-app";
import { dataset, pipeline, pipelines, runReplyFields, runRequestFields } from "@bijectionhq/library-pipelines";
import { arg } from "@bijectionhq/library-relations";
import { candidatePassed } from "./gates";

export const analyst = role({});
export const lake = datasets({
  admit: candidatePassed,
  // The pipelines run as the analysts: they pin cuts, run producers and
  // read the ledger, the Datasets exports these groups admit.
  publishers: [analyst],
  readers: [analyst],
});

// Your compute: a warehouse or launcher that runs installed programs.
export const warehouseToken = secret();
export const warehouse = target({
  label: label.public,
  via: http("https://compute.example.com/bijection/pipelines/run", { bearer: warehouseToken }),
  args: runRequestFields,
  returns: runReplyFields,
  within: { minutes: 30 },
});
const contacts = dataset("contacts", { fields: { id: t.string, region: t.string, level: t.int }, key: ["id"] });

export const regionCounts = pipeline({
  run: warehouse,
  dialect: "sqlSnowflake",
  outputs: {
    region_counts: contacts
      .where((c) => c.level.greaterOrEqual(arg("level", t.int)))
      .group(["region"]).pick((g) => ({ n: g.count() })),
  },
  args: { level: 2 },
  refresh: { when: "inputsChange", minInterval: { minutes: 5 } },
  freshness: { maxAge: { hours: 1 }, grace: { days: 1 } },
});

export default app({
  candidatePassed, analyst, lake, warehouseToken, warehouse,
  etl: pipelines({ owner: "pipelines", datasets: lake, operators: [analyst], pipelines: { regionCounts } }),
});
```

Set the warehouse credential with `bijection secret set warehouseToken`.
Several pipelines in the same installation can share a run target. Pass
`run` to `pipelines({ … })` and omit it from each `pipeline({ … })` that uses
that target. A pipeline can also supply its own run target. For native Trino
SQL, import `sql` from `@bijectionhq/library-pipelines` and use `sql.trino`
or `sql.trino.file`. These programs carry the `sqlTrino` dialect.

Each output is a [typed relation](https://docs.bijection.com/sql/relations.md) built with
`@bijectionhq/library-relations` over typed dataset sources. Nobody writes the
inputs, the columns, a plan or a digest: `bijection check` compiles the
relation's rebuild, step and shadow programs in the run target's dialect
module, derives the change class (`linear`, `group`, `bilinear`, `keyed(…)` or
`opaque`), and writes the programs' digests to the lock. An `arg(name, t.x)`
bind takes its value from the pipeline's `args`; an argument value with no
bind refuses `InputUnused`. Use `sql("sqlSnowflake")` for native SQL, or call
`sql("sqlSnowflake").file(path, { inputs, args, fields, key })` for a file.
Use `program(path, { run, runtime, inputs })` for an opaque program. These rebuild on every run
unless a contracted `step:` folds changes forward. Every `inputs` entry is a
typed dataset handle, `dataset(name, { fields, key })`, and a name the text
never uses refuses `InputUnused`. Check reads a file path relative to the
project, inside the application, and refuses `CREATE FUNCTION` in SQL program
text (`FunctionRefused`): Bijection never installs a function in a warehouse.

Declare the native rebuild's `fields` in its SQL options. `bijection check`
compares the declaration with the types and nullability it can derive.
`bijection check --fix` updates the rebuild's `fields` object in the source
for either an inline template or `.sql.file`. Declare any output whose type
check cannot derive. A contracted SQL step inherits the contract of its
single native rebuild output. Use an opaque step for a group of outputs.

## Publish a view relation

Put a view's typed relation in the pipeline's `outputs`. The output name is
an ordinary Datasets dataset. The run target or its placement supplies the
engine. Put each local contributor's mirror in `viewInputs`, keyed by the
source table's path in the app tree.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const ordersMirror = dataset("orders_mirror", {
  fields: { id: t.string, total: t.int },
  columns: { id: "_id" },
  key: ["id"],
});

export const publishOrders = pipeline({
  outputs: { order_totals: orderView.relation({ pick: ["total"] }) },
  viewInputs: { orders: ordersMirror },
});
```

The mirror must have a complete main publication of the contributing table
or the cut refuses `MirrorMissing`. All mirrors in the cut cover one
Bijection version. The output includes the picked fields and either
`key` for a scalar identity or one `key_<member>` column per compound
key member. Bind the successor table's mirror when the identity has a
retirement predicate. Its key columns must be available to exclude retired
identities at the cut.

Pick source values and use relational `derive` for computed fields.
A TypeScript derive closure, a cross-app object point or a field that
depends on External state refuses during check. The maintained compiler
lowers division for DataFusion and Trino and applies local `first(n)`
per group before aggregation. An oversized `atMost(n)` group refuses.
Using this lowering requires the matching compiler guest and runtime.

For a warehouse contributor, bind its virtual-table path to
`{ scan, export, statements }` in `viewInputs`. Use a public warehouse and
virtual table. The scan is a typed handle for the dedicated export dataset.
The installed target uses `warehouseExportArgs` and `warehouseExportReply`
from `@bijectionhq/app-sql`. Supply the reviewed digest for each SQL read
port under `statements`, as `{ dated: digest }` for a travelling port or
`{ current: digest }` otherwise.

Pipelines submits the export at the cut and charges one bulk statement per
port against the SQL receiver and table budgets. Travelling ports use a
common cut offset by the largest applicable skew. A port without travel
requires explicit `cut: { coherence: "mixed" }` and reports its snapshot's
source instant. The export target publishes the complete source snapshot
before replying. Pipelines verifies the exact returned publication.
`viewLineage` records the view definition, executed program, Bijection
version, mirror versions, and each port's statement and observation.

The managed SQL bulk export receiver is designed, not implemented. Install an export target for this route.

Warehouse view outputs use sealed subject buckets. See
[view dataset erasure](https://docs.bijection.com/datasets#view-dataset-erasure) for file limits and
the erasure scope reported by check.

## Use the installation's Lake SQL

Declare the typed outputs. A pipeline named `regionCounts` in the `etl` mount
has a batch slot at `etl.regionCounts`. A portable pipeline runs on
DataFusion unless it names another engine. Each
pipeline has its own binding, and the managed workers are pooled in the cell.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const outputs = {
  region_counts: contacts.group(["region"]).pick((g) => ({ n: g.count() })),
};
const regionCounts = pipeline({ outputs });
```

The engine is code, because DataFusion, Trino and Spark can answer the same
query differently. Name it on the pipeline; its slot then `needs` that engine.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const regionCounts = pipeline({ outputs, engine: "trino" });
```

The installation's bindings file chooses only who runs the slot. Unbound, it
is the host's managed Lake SQL offer, which must serve the engine. An
installation can bind the slot to its own HTTPS runner instead:

```ts ops/bindings/production.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { placement } from "@bijectionhq/bijection";
import app from "../../bijection/app";

export default placement.bindings([
  placement.bind(app.etl.regionCounts, placement.endpoint({ url: "https://sql.acme.example", credential: "sql.token" })),
]);
```

`bijection check --write-lock` shows the installed engine variants. Deployment
requires a program for the declared engine and checks the offer or endpoint
probe for that engine and its reviewed compiler revisions. Spark's portable profile supports grouped row counts
on string, int64 and boolean keys. Native SQL such as `sql.trino` declares a
fixed engine. Opaque programs declare their runtime and ordinary target with
`program(path, { runtime, run, inputs })`. Streaming windows use the Flink slot.

## Use your own DataFusion

Keep the engine in code: a portable pipeline runs on DataFusion unless it
names another engine. Bind only the slot's provider, in the installation's
bindings file, with `placement.bind(app.etl.regionCounts, placement.endpoint({ url, hosts, credential }))`.
A binding never names an engine; deploy refuses one. Use the receiver's HTTPS
origin as the binding URL. The slot calls
`/health` during deploy and `/bijection/pipelines/run` for executions. Set the
binding's credential to the receiver's `BIJECTION_LAKE_SQL_BEARER` value. The receiver
opens exact Lake gateway reads and stages through the Lake Writer under the
run's own Datasets lease, which arrives with each run, names its outputs and
ends with it. The receiver holds no standing writer session. A placement move affects future submissions.
Work already submitted settles through its original generation.

## Use your own Trino or Spark

Declare `pipeline({ outputs, engine: "trino" })` or `engine: "spark"` in code and bind
the slot to the same `placement.endpoint(...)` provider.
The [Lake SQL receiver guide](https://github.com/bijectionhq/bijection/tree/main/npm-packages/libraries/pipelines/python#use-your-own-trino-or-spark)
explains the Trino catalog, Spark Connect endpoint, and Lake Writer session.
Use `bijection query etl.status pipeline=regionCounts` to inspect the effective
engine and operator, the selected output group, and the attempt that produced it.

## Use Flink for event-time windows

Use one capture mount per Kafka partition. Publish their histories and
extents as a single Dataset release with `kafkaHistorySync`. The same
declaration gives the window relation its exact input names.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { app, t } from "@bijectionhq/bijection";
import streams from "@bijectionhq/app-streams";
import { pipeline, pipelines, stream } from "@bijectionhq/library-pipelines";
import { kafkaHistorySync, transfer } from "@bijectionhq/library-transfer";
import { data, exporter, lake, operator } from "./lake";
import { decodePayment } from "./decode-payment";

const capture = {
  revision: "payments-v1",
  watermarkLagMicros: 120_000_000n,
  admissionClock: "payments-store",
  decode: decodePayment,
};
const payments0 = streams({ data, kafkaPush: capture });
const payments1 = streams({ data, kafkaPush: capture });
const history = kafkaHistorySync("payments", {
  catalog: "lake",
  partitions: { "0": payments0, "1": payments1 },
});
const payments = stream("payments", {
  ...history.source,
  changes: "append",
  key: ["id"],
  eventTime: "paidAt",
  decimalScales: { amount: 2 },
  fields: { id: t.string, merchant: t.string, paidAt: t.instant, amount: t.decimal },
});
const minute = payments.window({
  every: { minutes: 1 },
  emit: "onClose",
  corrections: { within: { minutes: 10 }, after: "discard" },
});
const revenue = pipeline({
  inputLease: "required",
  outputs: {
    revenue_by_minute: minute.group(["merchant", "windowStart"])
      .pick((group) => ({ revenue: group.amount.sum({ scale: 2 }) })),
    payment_counts_by_minute: minute.group(["merchant", "windowStart"])
      .pick((group) => ({ count: group.count() })),
  },
});

export default app({
  data, exporter, lake, operator, payments0, payments1,
  transfers: transfer({
    label: data, operators: [operator], exporters: [exporter], datasets: lake,
    syncs: { payments: history.sync },
  }),
  etl: pipelines({ owner: "etl", datasets: lake, operators: [operator], pipelines: { revenue } }),
});
```

The source decoder supplies the event's exact instant and decimal text for
`amount`. Give the Kafka gateways one signed ingress each at `payments0`
and `payments1`. Declare the named catalog on the Datasets mount
([catalogs](https://docs.bijection.com/datasets/catalogs.md#declare-catalogs)); Transfer enrolls the Lake
Writer and attaches the sync on its clock.
The sync publishes all four input Datasets together at a one-minute
cadence. [Kafka capture](../../../npm-packages/apps/streams/README.md#record-event-time-history) · [Lake Writer setup](https://docs.bijection.com/datasets/publish-a-table.md)

Place both output Datasets in a sealed catalog to use window steps.
A catalog declared with `referenceFence: "datasets"` lets the Lake Writer
reclaim abandoned private candidates through Datasets inventory. Deploy
starts the window pipeline. Input selection wakes
it to read the latest complete cut, with a periodic poll for reconciliation.
Use `refresh.when: "manual"` for explicit runs or set `refresh.minInterval`
to refresh on a fixed polling interval. Stopping the pipeline lets the
current run settle and suspends new admissions until it is started again.
A watermark makes each window visible at its end. Events
recorded before the correction deadline can change a visible window. Replay
opens the original cut so the same events and watermark decisions apply.

The stream orders the captured records by committed admission time,
partition number, and journal position. Event time assigns windows. The
minimum of the recorded partition watermarks controls visibility and the
correction deadline. A recorded gap blocks the cut with `SourceGap` until
the inputs move or an operator requests a refresh. Idle partitions keep
their previous watermark.

When supplying your own input Dataset names, set `finality: "capturedCut"`
to apply the correction deadline to the named
cut. A later release can
include a record from a lagging capture that sorts before the previous
deadline. It can change a window even if the previous release's watermark
had reached that deadline. Replay uses the original capture vector and
reproduces its decisions.

For finality across successive appends, `kafkaHistorySync` supplies
`finality: "admissionFrontier"` for a source with multiple partitions.
Each capture extent must carry its commit instant and name the same
`admissionClock`. The runner evaluates records strictly before the earliest
extent commit across the partitions. Records at that instant wait until
every partition moves past it. Status shows the exclusive frontier
alongside the captured Kafka offsets and each partition's extent commit
instant. A partition at the earliest commit instant holds the frontier.
Clock-configured captures continue
to stamp the same offset during quiet periods. The event-time watermark
stays at its last recorded value until the source advances it.
[Kafka capture setup](../../../npm-packages/apps/streams/README.md#record-event-time-history)

For read-only Flink SQL, use `sql.flink` or
`sql.flink.file(path, { inputs, fields, key })` as the output expression.
Both forms can read a typed Dataset or a window relation. A mixed
cut keeps each window's history and extent together and pins other
Datasets in the same admission transaction.
Each Flink pipeline is its own slot at `<mount>.<pipeline>`: a batch pipeline
speaks `flink-batch@1` and a streaming one `flink-stream@1`, both managed
Flink unless you bind them elsewhere. A windowed stream is `running` state:
when you move its slot, the old run stops at a checkpoint the installation records and the
new provider resumes from it. The pipeline
status includes progress for the selected release and any active candidate
that reported its result. Admission failures distinguish an unavailable
cut, a changed predecessor, exhausted read capacity, and the sealed
custody limit.

### Use your own Flink

Keep `inputLease: "required"` and bind the pipeline's slot, here a pipeline
named `clicks`, to your HTTPS endpoint:

```ts ops/bindings/production.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { placement } from "@bijectionhq/bijection";
import app from "../../bijection/app";
const { bind, endpoint, env, bindings } = placement;

export default bindings([
  bind(app.etl.clicks, endpoint({
    url: env("FLINK_URL"), hosts: ["flink.example.com"], credential: "etl.clicks.token",
  })),
]);
```

Set `FLINK_URL` to `https://flink.example.com/bijection/pipelines/run` and
`etl.clicks.token` to the receiver's bearer secret. The bounded
receiver uses a reachable Lakehouse read gateway and a Datasets session with
`lake.roles.pipelineRunner`. Bind each precreated sealed output's UUID and
storage root with `lake.catalogs.bindOutput`. The same program can then
resume a checkpoint, read an admitted Kafka suffix, and publish both
outputs together. [Runner configuration](../../../npm-packages/libraries/pipelines/python/README.md#use-your-own-flink)

### Inspect a first release and a correction

After deploying, inspect the source cuts and the pipeline's selected release.

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection query payments0.kafkaPush.source.progress
bijection query payments1.kafkaPush.source.progress
bijection query etl.status pipeline=revenue
bijection query etl.list pipeline=revenue count:=5
```

Both output heads should name the same release. After the first rebuild,
send a late payment to a closed window within its correction horizon and
allow both capture extents to advance. The selected run's window progress
shows the capture offsets, common frontier, and affected windows. Replay
that run's retained cut to compare it with a rebuild while the current
release keeps serving.

## Review and deploy the programs

`bijection check --write-lock` writes the lock's `pipeline`, `program` and
`producer` lines and commits each program under
`bijection.statements/<owner>/<pipeline>/`: `<role>.sql` to read and
`<role>.program.json`, the exact bytes the run target installs, for the
`rebuild`, `step` and `shadow` roles. Plain `bijection check` refuses a
committed file that differs from what the source compiles, and deploy
refuses one that does not hash to its lock digest (`StatementStale`), or a
compiler revision the release's gateway lacks (`CompilerMissing`). A run
target accepts a run only for a digest installed for it
(`DigestUninstalled`). Under `access.mode: "trustedWorker"` a program's
inputs stay trusted rather than leased, and the lock says so.

`owner` is the stable name Datasets knows the library by: the issuer of its
producers and the owner of its cuts and run read grants. Each pipeline
enrolls itself with the Datasets mount as the producer `<owner>/<pipeline>`;
two producers for one dataset refuse `ProducerConflict`.

## Run and inspect it

The library's functions are at the subtree's paths (`etl.start`, …), each
exposed with `allow` to `operators` or `readers`:

| Entry | Who | What it does |
| - | - | - |
| `start` | operators | Start a pipeline's controller (idempotent) |
| `refresh` | operators | Request a refresh and return its receipt. Set `rebuild: true` to require a rebuild without a hint |
| `refreshReceipt` | operators | Observe a refresh receipt until it records a selected release or a refusal |
| `replay` | operators | Rebuild at a prior run's exact input cut for review, `{ run, meaning }` |
| `replace` | operators | Supersede one in-flight attempt at the same input versions, `{ run, generation }` |
| `acceptEvidence` | operators | Offer a certificate, reproduction or approval for a run awaiting evidence |
| `stop` | operators | Stop admissions; a run already in flight still ends |
| `select` | operators | Select retained candidates, one per output, all at the same input versions (`expected`: reviewed revisions or null); refuses `UnknownPipeline` or `InvalidGroup` |
| `status` | readers, operators | Report the current release, each output's served version and selection revision, freshness, demand, and installed program digests |
| `list` | readers, operators | The newest runs, `{ pipeline, count }` (count null: 20), each with its state and `message` |
| `publication` | readers, operators | The exact release a run served, with member versions, snapshots and digests |

From your own code, `etl.demand(ctx, "regionCounts", { rebuild: false })`
demands a refresh without a role check. A scheduler is an ordinary caller: it calls
`refresh` through a generated client, and a retry of the same call finds the
same receipt.

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection call etl.refresh regionCounts --wait
bijection call etl.refresh regionCounts --rebuild --wait --timeout 20m
bijection call etl.status regionCounts --watch
bijection call etl.list regionCounts --count 5
```

Each receipt records the input cut seen when the refresh was requested.
A completed receipt names a selected release that covers that cut. When
a release already covers it, a normal refresh can finish by reusing the
release. A forced refresh waits for a rebuild admitted for that request.
The CLI prints a receipt before waiting. Use `bijection wait <receipt>`
to resume on the same installation. A TypeScript client can wait with
`client.wait(started.value)` after `client.mutate(app.etl.refresh, args)`
succeeds. The CLI and SDK accept the same saved receipt.

### Replay a retained cut

Read the installed `meaning` from `status` and the original run ID from
`list`. Pass both to `replay` to check the reviewed program and reopen the
original input versions with fresh holds. The cut keeps its original time.
Read the resulting candidate versions in `list`, then use `select` to make
the complete group current. Replay refuses when the original input
inventory or authority is unavailable. Forward-only lookups continue
their selected checkpoints, which record the dimension version of every
advance.

Set `sourceBarrier: { kind: "currentRelease" }` when all inputs must come
from one selected release, such as an event history and its extent. Each
admission pins that exact release. Replay uses the recorded release even
after the input heads advance.

Automatic selection checks the output revisions recorded at run admission.
If an operator changes the selection while the worker runs, its result
stays a retained candidate. Use the output revisions reported by
`status` as `expected` when reviewing a manual selection.

## How a refresh runs

1. **Versions.** When the controller is due (there is demand, or `inputsChange`
   finds a new input version), it calls `cuts.take` on Datasets, which pins
   and holds one version per input in one transaction: by default the greatest
   consistent basis among retained, selected versions.
2. **Hint.** Any published, non-diverged candidate of the same meaning whose
   input versions precede the new ones may be the hint. A candidate at exactly
   the new input versions is reused without compute.
3. **Run.** One task goes to the pipeline's `run` target, `{ digest, mode, pins, binds }`:
   the installed program's digest, a `rebuild` or a `step` from the hint's
   outputs and input versions, and the arguments. One run is in flight per pipeline.
   The worker reads its inputs through short-lived leases (`runFileRequest` for
   the lake gateway) and echoes the request's `pins.inputDigest` with its output
   snapshots and digests.
4. **Publish.** Each output is a task of the Datasets `publication` target with
   `select: false`. A refused hint (a `Refused` message starting `hint:`)
   rebuilds at the same input versions (`onGap: "rebuild"`) or blocks once (`onGap: "block"`).
5. **Select.** A task of the Datasets `selection` target makes the whole group
   current in one catalog transaction. Automatic selection only moves forward
   in the input versions.
6. **Verify.** Shadow rebuilds at a step's input versions run for every `contracted` step,
   for the first step of a new meaning, and then for the first step at least a
   day after the last shadow (`pipeline({ shadow: { every } })` may only
   shorten it). They never block selection; a differing step becomes
   `diverged` and, if served, is replaced, and the meaning runs as rebuilds
   until it changes.

Datasets admits a hint only when it is published and not redacted, retired or
diverged, has the same meaning, its input versions precede the new ones over the same
inputs, every input outside `changes` is unchanged, its label flows to the new
label, its before-images are retained, no erasure falls in the range and the
range spans at most 64 versions per input. Otherwise the run rebuilds.

## Read what a run published

Pass a run's `id` from `list` to `publication({ run })` to recover the group it
served, even after another run became current. The query answers `null` when
the run has no release or Datasets can no longer admit it. Use the returned
release as `barrier: { kind: "release", release }` in a Datasets `cuts.take`,
or as a downstream pipeline's `sourceBarrier`, when downstream inputs must
match that whole group. Current access and retention still govern every read
of its versions: open them with a [read lease](https://docs.bijection.com/datasets/exact-reads.md), or
publish a [view](https://docs.bijection.com/datasets/consumer-views.md) for warehouse readers.

## Erasure and labels

`lake.versions.erased({ dataset, number, message })` redacts every retained
version older than the erasure and every version computed from one of them,
including a served one. The next refresh finds no admissible hint and
rebuilds.

A candidate's label is the join of its inputs' labels at those versions, the output
dataset's own label and the pipeline's `label`. A label that rises keeps the
hint; one that falls or moves sideways forces a rebuild.

## Keep results in a warehouse

A warehouse project (Snowflake, Databricks, BigQuery) is the pipeline's `run`
target: its receiver runs the program and answers the output snapshots. The
[Snowflake pipeline example](https://github.com/bijectionhq/bijection/tree/main/examples/snowflake-pipeline)
shows the installation, the warehouse run target and the typed pipelines. For small,
dated answers per key without versioning, declare a
[virtual table](https://docs.bijection.com/sql/application-api.md) instead.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.