> ## 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.

# Series and timelines

> Valid time: samples that hold at an instant, and facts that hold over a period.

A fact has two times. **Valid time** is when it holds in the business: a
price from 1 June, a meter reading at 09:00. **System time** is the version
in which Bijection committed it. You write valid time; you never write system
time.

| Question | How you ask |
| - | - |
| What holds now? | `ctx.get(tariffs(sku))` |
| What held on 15 October, as known today? | `ctx.get(tariffs(sku).at(oct15))` |
| What did we know at the version we decided on? | `ctx.get(tariffs(sku).at(oct15).in(version))` |

Two declarations have valid time. Both require `key`.

| Declaration | A fact holds | Read with |
| - | - | - |
| `series(fields, { key })` | Only at its instant | `.at(instant)`, `.over({ from, to })`: samples with `at` |
| `timeline(fields, { key })` | From `from` until `to` | `.at(instant)`, `.over({ from, to })`: segments with `from` and `to` |

A series written twice at the same key and instant keeps the later commit's sample.
The clock may report the same instant for several commits.

Use a timeline for state that holds over a period: a price, a contract, a
certification. Use a series for measurements at instants. Keep an event, such
as a decision or a receipt, in an ordinary [table](https://docs.bijection.com/database/tables.md).

## Timelines

```ts bijection/tariffs.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { mutation, query, role, t, timeline } from "@bijectionhq/bijection";

export const tariffs = timeline({ sku: t.string, amount: t.decimal, currency: t.string }, { key: ["sku"] });

/** The tariff in force at the frame's valid instant. */
export const current = query({ allow: [role.signedIn], args: { sku: t.string } }, (ctx, { sku }) =>
  ctx.get(tariffs(sku)),
);

/** Set a tariff from an instant on, replacing every later plan for the key. */
export const plan = mutation(
  { allow: [role.signedIn], args: { sku: t.string, amount: t.decimal, starts: t.instant } },
  async (ctx, { sku, amount, starts }) => {
    await ctx.put(tariffs(sku).over({ from: starts, to: null }), { amount, currency: "EUR" });
  },
);
```

### Write a period

`ctx.put(point.over({ from, to }), fact)` makes the fact hold throughout the
half-open period `[from, to)`. `ctx.retract(point.over({ from, to }))` makes
nothing hold throughout it. Both keep what stands outside the period. `null`
is unbounded: `to: null` replaces every later plan for the key.

Write several periods with one call each, in order. A later call wins where it
overlaps an earlier one.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
await ctx.put(tariffs(sku).over({ from: nov1, to: null }), planning);
await ctx.put(tariffs(sku).over({ from: nov10, to: nov20 }), sale);
```

A period whose `to` is at or before its `from` is refused.

A bound may be the commit's stamp: `frame.now.add({ seconds: 0 })`, or `frame.now.add(d)` for
the stamp plus an exact duration. The host places it when the commit lands,
so a period that starts when the write lands, or lasts an hour from then,
never starts at the entry instant `ctx.frame.now.entry`:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
await ctx.put(tariffs(sku).over({ from: ctx.frame.now.add({ seconds: 0 }), to: ctx.frame.now.add({ hours: 1 }) }), sale);
```

Only `ctx.put` and `ctx.retract` take a bound at `frame.now.add({ seconds: 0 })`: a read or an
assumption cannot see the stamp (`ClockTermBlind`).

### Read what is in force

A timeline point without `.at` is in force at the frame's `at`, which is now
unless the caller chose another instant. `.over` reads the segments over a
period, each with its `from` and `to`, clipped to the period.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const now = await ctx.get(tariffs(sku));
const then = await ctx.get(tariffs(sku).at(oct15));
const october = await ctx.page(tariffs(sku).over({ from: oct1, to: nov1 }), { size: 20, cursor: null });
```

## Series

A series holds one sample per key and instant. `key` names the fields of a
series, one to four of them; every other field is a value. Declare no time
field: the instant is the sample's place, written with `.at(instant)` and
read as `at`.

```ts bijection/readings.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { mutation, query, role, series, t, table } from "@bijectionhq/bijection";

export const producer = role();
export const operator = role();
export const machines = table({ name: t.string });
export const readings = series(
  { site: t.string, machine: t.key(machines), celsius: t.number, rpm: t.number },
  { key: ["site", "machine"], lifetime: { days: 90 } },
);

export const record = mutation(
  {
    allow: [producer],
    args: { site: t.string, machine: t.key(machines), at: t.instant, celsius: t.number, rpm: t.number },
  },
  (ctx, { site, machine, at, celsius, rpm }) => ctx.put(readings({ site, machine }).at(at), { celsius, rpm }),
);

/** One hour of samples, each with its `at`. */
export const hour = query(
  { allow: [operator], args: { site: t.string, machine: t.key(machines), starts: t.instant, cursor: t.cursor } },
  (ctx, { site, machine, starts, cursor }) =>
    ctx.page(readings({ site, machine }).over({ from: starts, to: starts.add({ hours: 1 }) }), { size: 500, cursor }),
);
```

A series takes `key`, `label` (a label or a family), `lifetime` (how long a
sample is kept after it is written), `history` and `mark`. It takes no
`total`, `machine`, `pin` or `erasable`. See
[Table options](https://docs.bijection.com/reference/configuration/tables).

### Write, correct and retract

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
await ctx.put(readings({ site, machine }).at(ctx.frame.now.add({ seconds: 0 })), { celsius, rpm });       // at the commit's stamp
await ctx.retract(readings({ site, machine }).at(at));                            // one sample
await ctx.retract(readings({ site, machine }).over({ from, to }));                // every sample in [from, to)
```

* `ctx.put` and `ctx.retract` read nothing, so they never refuse and a
  retry is harmless. A reader sees them exactly: one conflicts only when it
  changes what that reader read.
* Putting the same key at the same instant again replaces the sample. That
  is how you correct one. Two puts of one key at one instant in one
  transaction write one sample.
* `.over({ from, to })` is half-open; a `null` bound leaves that end open.
* No write is refused by the clock: a sample in the future or far in the
  past is accepted. A series that must refuse late or future samples is a
  [strict series](#the-strict-layer).
* `ctx.insert`, `ctx.replace`, `ctx.patch` and `ctx.delete` take the same
  points, and assume the sample absent or present as they do on any table.

### Read samples

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const exact = await ctx.get(readings({ site, machine }).at(at));                       // the sample at `at`, or null
const day = await ctx.list(readings({ site, machine }).over({ from: dayStart, to: dayEnd }).first(2000));
const newest = await ctx.list(readings({ site, machine }).over({ from: null, to: null }).descending().first(10));
const everyMachine = await ctx.list(readings.where({ at: { from, to } }).by("at").first(500));
```

* A sample reads as its fields and `at`, a `Temporal.Instant`.
* `.over` answers oldest first, and `.descending()` newest first.
  `ctx.page` answers `{ facts, next }`; pass `next` back as `cursor`.
* `readings.where({ at: { from, to } })` selects every key's samples in an
  interval, ordered by `at` then the key. No index needs declaring: every series
  is ordered by valid time across its keys.
* The last sample at or before an instant `t` is
  `ctx.list(readings(k).over({ from: null, to: t.add({ microseconds: 1 }) }).descending().first(1))`:
  `.over` is half-open and instants are whole microseconds, so the bound one
  microsecond past `t` includes a sample at `t`. `.at(t)` keeps its one
  meaning, the sample exactly at `t`.

A series or timeline declared with `mark` keeps the valid-time buckets each
write touched: see [Marks](https://docs.bijection.com/database/capabilities.md#marks).

State that holds between changes (a setpoint, a status, a price) is not a
series: declare a [timeline](#timelines). Use
[windowed derivations](https://docs.bijection.com/objects/windowed-derivations.md) to publish an aligned
result series from several series and timeline inputs.

## The valid instant of a call

A function's valid instant is `ctx.frame.at`, or `null` at the present. A
caller sets it for one call with `client.at(instant)`, and nested calls
inherit it; `ctx.call(fn, args, { at })` sets it for one inner call. A read at
the present answers what is valid when the transaction commits: if the next
boundary it read passes first, the host runs the transaction again. A watched
query re-runs when its reads change, and when the next valid boundary it read
passes.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { api } from "@bijectionhq/bijection/client";
const asAt = await client.at(Temporal.Instant.from("2026-10-15T00:00:00Z")).query(api().tariffs.current, { sku });
```

## Earlier versions

"What did we know then" is the same read in an earlier version. Store the
version a decision read, `ctx.frame.version`, with the decision, and read in it
later with `.in(version)` or `client.in(version)`. A version stays readable
for the table's `history`, or while a pin holds it. See
[History and lifetime](https://docs.bijection.com/database/history-and-lifetime.md).

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
await ctx.insert(approvals, { shipment, version: ctx.frame.version, approved: ctx.frame.now.entry });
// later:
const believed = await ctx.get(tariffs(sku).at(oct15).in(fact.version));
```

Access is judged as of now: today's grants decide what a read in an earlier
version may see.

## The series library

`@bijectionhq/library-series` builds on series tables: rollups that stay
exact under late writes, retention per tier, frames for dense telemetry, read
helpers and a strict layer. Each instance is a subtree you place in the app
tree.

| Word | Meaning |
| - | - |
| **Series** | One key of a series table, for example one machine |
| **Sample** | One value of a series at one instant: its fields and `at` |
| **Rollup tier** | A table of per-bucket aggregates (`"1m"`, `"1h"`) the library keeps |
| **Frame** | One fact holding many samples of one series, for dense telemetry |
| **Strict series** | A closed series that admits points with source receipts and refuses conflicts |

### Declare a library series

`series({ by, values, … })` from `@bijectionhq/library-series` declares a
series table of its own (its `points`) and everything it derives, and
returns a subtree:

```ts bijection/app.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { app, label, role, t, table } from "@bijectionhq/bijection";
import { series } from "@bijectionhq/library-series";

export const operator = role({});
export const producer = role({});
export const maintainer = role({});
export const machines = table({ name: t.string });

export const readings = series({
  by: { site: t.string, machine: t.key(machines) },
  values: { celsius: t.number, rpm: t.number },
  label: label.public,
  roles: { read: [operator], write: [producer], maintain: [maintainer] },
  lateness: { minutes: 15 },
  rollups: { "1m": { minutes: 1 }, "1h": { hours: 1 }, "1d": { days: 1 } },
  retention: { "1m": { days: 730 } },
  lifetime: { days: 90 },
});

export default app({ operator, producer, maintainer, machines, readings });
```

| Option | Meaning |
| - | - |
| `by` | One to four key fields: `t.string`, `t.key(table)`, `t.number` or `t.boolean` |
| `values` | The value fields; a rolled field is `t.number` or `t.maybe(t.number)` |
| `label` | Required. The label of every table of the series: a label, or a family (each function then runs under the caller's member). Name `label.public` to place it in public |
| `roles` | `{ read, write, maintain }`: who may call the readers and writers, and the roles the maintenance reactions hold |
| `every` | Expected time between samples; checks the finest rollup tier |
| `lateness` | How long after a bucket's end the roller waits, and a value every reader answers. Default 0 |
| `rollups` | Tier name to bucket width, finest first, at most four |
| `retention` | How long each tier's facts are kept, by tier name, in whole days. Unlisted: kept forever |
| `lifetime` | How long raw points are kept, in whole days |
| `frames` | `{ span, dt }` for a [frames series](#frames-for-dense-telemetry) |

The subtree:

| Path | What |
| - | - |
| `points` | The series table; with rollups it declares `mark`, so `points.marks` holds the touched buckets |
| `rollups.<tier>` | One table per tier (`"15m"` is `minutes15`), kept by `retention` |
| `dirty.<tier>` | Buckets of a coarser tier to fold again |
| `jobs`, `roll`, `roller` | The roller's record, its clock reaction and its reconciler |
| `tendTurn` | The per-key maintenance task of a family series |
| `describe`, `range`, `last`, `window` | Exposed with `roles.read` |
| `write`, `retract` | Exposed with `roles.write` |

Any function of the app may write the points directly:
`ctx.put(readings.points({ site, machine }).at(at), { celsius, rpm })`. The
in-transaction helpers are on `readings.helpers`:

* `write(ctx, facts)` takes facts `{ ...by, ...values, at }`, writes them and
  answers `{ written, late }`.
* `retract(ctx, by, at)` removes one instant, and
  `retract(ctx, by, { from, to })` an interval, up to 4,000 samples per
  transaction, finishing the rest in the background.
* `range`, `last` and `window` are the readers below. `readings.args` holds
  their value types for your own functions.

A put into a marked table writes the sample and its mark. One transaction
makes at most 16,000 writes; the helpers refuse beyond it.

### Readers and rollups

The readers answer columns. `range` answers one page of `[from, to)`:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const raw = query(
  { allow: [operator], args: { ...readings.args.by, ...readings.args.range } },
  (ctx, { site, machine, ...range }) => readings.helpers.range(ctx, { site, machine }, range),
);
// → { at: [Instant, …], celsius: [70.9, 71.2], rpm: [1480, 1481], next: null, lateness: Duration }
```

* A value missing from a sample is `null` in its column.
* `size` is 1 to 8,192 samples (default 2,000), and `order` is
  `"ascending"` or `"descending"`. `next` is the cursor of the following page.
* `readings.helpers.last(ctx, by, { at, within })` is the last sample at or
  before `at` (default now), or `null`; with `within`, `null` when it is that
  old or older.

`window` reads aggregate buckets. A tier keeps, per bucket and per rolled
value, the count, sum, minimum, maximum, first and last:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const chart = query(
  { allow: [operator], args: { ...readings.args.by, ...readings.args.window } },
  (ctx, { site, machine, from, to, every }) =>
    readings.helpers.window(ctx, { site, machine }, { from, to }, every, { celsius: ["mean", "max"] }),
);
// → { at: [...], count: [...], celsius: { mean: [...], max: [...] }, next: null, lateness }
```

The measures are `count`, `sum`, `mean`, `min`, `max`, `first`, `last` and
`rms`. `from` and `to` must be multiples of `every`, and a window answers
every bucket, empty ones included.

**The read rule.** With rollups, the points declare `mark` at the finest
tier's width, so the host records every bucket a write touches, and a range
retraction records its span in `points.spans`. A window reads the coarsest
tier whose width divides `every`, and refolds from a finer tier or from the
samples any bucket that is still marked or overlapped by a dirty span. A
window is therefore exact at its version whatever the roller's lag: a late
sample or a correction shows up in the next read. A window that would fold
more than 16,000 facts is refused with `SeriesNeedsRollup`, which names the
tier to declare. A window answers at most 8,192 buckets.

The roller folds marked buckets once they are older than the tier width plus
`lateness`. A tier is named by a count and a unit (`"15m"`, `"1h"`, `"1d"`)
that spells its width. Declare tiers finest first, each a multiple of the one
before. Readers answer the declared `lateness`, so a chart can draw a line at
now minus `lateness`.

To pivot samples you read yourself, use `columns(facts, fields)`:

```ts bijection/reading-columns.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { query, t } from "@bijectionhq/bijection";
import { columns } from "@bijectionhq/library-series";
import { machines, operator, readings } from "./readings";

export const temperatureColumns = query({
  allow: [operator],
  args: { site: t.string, machine: t.key(machines), from: t.instant, to: t.instant, cursor: t.cursor },
}, async (ctx, { site, machine, from, to, cursor }) => {
  const page = await ctx.page(readings({ site, machine }).over({ from, to }), { size: 2_000, cursor });
  return { columns: columns(page.facts, ["celsius"]), next: page.next };
});
```

### Retention

The table's `lifetime` erases each raw sample that long after it was written.
`retention: { "1m": { days: 730 } }` keeps minute rollups for two years, as
the tier table's `lifetime`. A tier may outlive its samples. See
[History and lifetime](https://docs.bijection.com/database/history-and-lifetime.md).

### Frames for dense telemetry

Above about one sample per second per series, store frames: one fact holds up
to 8,192 samples.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const vibration = series({
  by: { machine: t.key(machines), axis: t.string },
  values: { g: t.number },
  label: label.public,
  frames: { span: { seconds: 1 }, dt: { milliseconds: 1 } },
  rollups: { "1s": { seconds: 1 } },
});

await vibration.helpers.writeFrame(ctx, { machine, axis: "x", at: t0, g: samples });
const page = await vibration.helpers.range(ctx, { machine, axis: "x" }, { from, to, every: null, cursor: null, size: 2000, order: "ascending" });
```

* A frame's instant is its first sample's. `span` is the longest one frame
  covers, at most the finest tier's width. `dt` is the interval between
  samples; without it, each frame carries `offsets` from `at`.
* Readers answer flat sample columns, so a chart does not know the series is
  framed.
* Sending the same frame again changes nothing; sending it changed corrects
  the whole frame. Frames of one series should not overlap.

### A series per member

Give the series a family label, and every sample, mark and rollup fact takes
its member's label. Every function then runs under the caller's member
(`client.under(tenant.of("acme"))`).

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const tenant = label.family(t.string);
export const energy = series({
  by: { meter: t.string },
  values: { kwh: t.number },
  label: tenant,
  rollups: { "1m": { minutes: 1 }, "1h": { hours: 1 } },
});
```

Reads are exact without maintenance. Rolling and expiry run per series key,
never by listing members: `energy.helpers.write` arms each key it writes, and
a direct writer arms its key with `energy.helpers.tend(ctx, { meter })`. Each
active key has one pending `tendTurn` task.

## Ingest connector records

Mount the [Streams app](https://docs.bijection.com/integrations/native-kafka.md) to acquire topic records.
A reaction on its committed records (`on: records.changes`) writes the series
with `ctx.put`. A producer that writes over HTTP calls the series' `write`
function, or a [route reaction](https://docs.bijection.com/functions/reactions.md) of your own.

## Live charts

Use `useWatch` with a query that returns a bounded window of series buckets.
The chart chooses the time bounds and bucket width. A watch answers
`undefined` while loading, then the query’s `Result` as its buckets change.
Use aligned bounds when the query requires a whole number of buckets.

## Query with SQL

The points table and every tier are ordinary tables to [SQL](https://docs.bijection.com/sql), which
sees their stored facts. A sample's instant is the column `at`. A tier table
holds, per rolled value `f`, the columns `f_n`, `f_sum`, `f_sumsq`, `f_min`,
`f_max`, `f_first` and `f_last`, plus `count`. SQL does not apply the read
rule: a marked bucket has a stale fact or none. Use `window` when you need
exact buckets.

## The strict layer

Use a strict series when the clock is not enough evidence: when you need to
know which source delivered what, refuse contradictory or late deliveries, or
state that a range is complete.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { label, role, t } from "@bijectionhq/bijection";
import { strict } from "@bijectionhq/library-series/strict";

export const temperatureData = label();
export const operator = role({ clear: [temperatureData] });
export const producer = role({ clear: [temperatureData] });

export const temperatures = strict(
  {
    label: temperatureData,
    by: { machine: t.key(machines) },
    values: { celsius: t.number },
    future: { seconds: 2 },
    lateness: { minutes: 15 },
    late: "accept",
    rollups: { "1m": { minutes: 1 }, "1h": { hours: 1 } },
    lifetime: { days: 365 },
  },
  {
    roles: { admit: [operator, producer], read: [operator], retract: [operator], settle: [producer] },
    claimers: { source: true },
  },
);
```

Every point enters through admission: `temperatures.admission.admit`,
`produce` (a producer's route under a source it opened) and `retract`, with
the in-transaction helpers on `temperatures.strict`. A guard the subtree
declares refuses any write to its points whose writer is not one of its own
functions.

* An observation may carry an `order`. A higher order corrects, an equal
  order with other content is refused, and a lower one is superseded.
  Replaying a delivery is an inert duplicate.
* `future` refuses a point too far ahead of the clock, and `late: "refuse"`
  refuses one older than `lateness`. These two rules exist only here.
* A source settles how far its deliveries are complete, and the series'
  frontier answers how far the series is complete.
* Monitors keep episodes of a condition over the values and journal each
  transition. A transition reaches your mutation (`onTransition`) as a task
  whose `once` names the transition.

Admission reads the point it writes, so two producers of the same instant
conflict; appends to different instants still do not. One batch holds at
most 2,000 observations. A strict series takes one static label.

## Watches over a series

`watches({...})` from `@bijectionhq/library-watches` keeps alert episodes
over a condition, evaluated on a clock or on a strict series' monitor
transitions. It returns a subtree with `watches` (`insert`, `edit`, `pause`,
`delete`, `evaluate`, `list`, `get`) and `alerts` (`list`, `get`,
`acknowledge`, `assign`, `snooze`, `resolve`, `note`), exposed to its
`operators`, `responders` and `viewers`.

## From the command line

The exposed functions are ordinary queries and mutations, so
`bijection query` and `bijection mutate` call them by path
(`readings.range`, `readings.write`).

## Limits

| Limit | Value |
| - | - |
| Key fields | 4 |
| Samples in one page | 8,192 (default 2,000 for `range`) |
| Facts in one write call | 8,192 |
| Writes in one transaction, marks included | 16,000 |
| Facts one window folds | 16,000 |
| Buckets one window answers | 8,192 |
| Rollup tiers | 4 |
| Samples in one frame | 8,192 |
| Samples one retraction removes per transaction | 4,000 |

## Not supported yet

* A span retraction made outside the library on a family series arms no
  tend turn. Readers honour its dirty span at once, and the key's next tend
  turn rolls it.
* Tier retention runs from when a tier fact was last written, not from its
  bucket's start.
* Frames in a strict series, and a family label on a strict series.


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