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

# Table capabilities

> Presence labels, maintained totals, state machines, marks, writers and private tables: table options the host enforces.

These options add behaviour the host maintains on every write of a table.
[Pins](https://docs.bijection.com/database/history-and-lifetime.md#pins) and
[shared erasure fields](https://docs.bijection.com/database/history-and-lifetime.md#shared-erasure-fields)
are described with retention.

## Presence

`presence: { label, field, release }` states a label below the fact's label at
which a fact's existence is known: its key and the listed fields. `ctx.has`
reads at it, so a frame that clears the presence label but not the fact's
label learns whether the fact exists, and nothing else.

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

export const staff = label();
export const hr = label();
export const rosterRelease = release({ from: hr, to: staff, message: "Staff see who is on the roster, not the file." });

export const files = table(
  { person: t.string, team: t.string, notes: t.string },
  { key: ["person"], label: hr, presence: { label: staff, field: ["team"], release: rosterRelease } },
);
```

`release` is the standing [release](https://docs.bijection.com/access/disclosure.md) the listed fields
stand under. An index whose fields are all known at the presence label serves
selections from frames that clear only that label. A labelled table is
[protected](https://docs.bijection.com/database/protected-tables.md), so that index keeps tokens of its
fields at the store: it answers exact lookups, and other shapes through
`ctx.list(selection.atMost(n))`. A reviewed store exposure lets the store serve ordered shapes on that index.

## Totals

`total: [{ group, sum, erased }]` declares counts, and exact sums, that the
host maintains for each group of the `group` fields (one to four) on every
write. Totals are unnamed and matched by structure, like indexes.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const orders = table(
  { customer: t.string, region: t.string, amount: t.decimal, quantity: t.int },
  { total: [{ group: ["region", "customer"], sum: { amount: 2, quantity: 0 } }] },
);

// The groups whose `group` starts with the where fields:
const totals = await ctx.get(orders.where({ region: "emea" }).total());
// [{ key: { region, customer }, count, sum: { amount, quantity } }, …]
```

`sum` names each summed field with its fixed scale: a `t.decimal` at the given
number of places, or a `t.int` at scale `0`. `erased: true` keeps erased facts
in the count, and then sums nothing. A `.total()` no declared total serves is
refused with `TotalMissing` and the entry to add.

`ctx.count(selection)` is the exact count of any served selection, maintained
or not. On a [protected table](https://docs.bijection.com/database/protected-tables.md) it counts only a
selection that fixes every field of an index by equality, a minted table
whole, or an exposed store order; count anything else with a total. A total
is cheaper for a figure read often over many facts.

Maintained totals need disjoint contributions and bounded closure evidence.
For example, put an operations ledger at one fixed `operations` label and
declare `total: [{ group: ["status"] }]` on it. A query under
`operations` can read `ctx.get(ledger.where({ status: "open" }).total())`.
A family-member total that needs to enumerate covered sources refuses.
An ordinary Root row count can combine overlapping covers for a complete
equality selection when the cover has a bounded source population without
erasable or expiring rows. The read counts each admitted identity once.
Collections that need source closure or range evidence use a disjoint path
or a separately published figure.

To publish a lower-audience figure, have a high-side app compute the approved
figure at a declared cut and write it to an `operations.seal(t.int)` field.
A mutation with the reviewed Release can use
`ctx.open(report.openCount, { release: publishCount })` and write the number
to its audience's report table. Give that Release a fixed output shape,
cadence, and erasure policy. Review the effect of repeated exact counts or
adaptive filters as part of the same disclosure.
[Disclosure](https://docs.bijection.com/access/disclosure.md)

## State machines

`machine: { field, initial, edge, undeclared, history }` states the values one
field may hold and the named edges along which it may change. The host
enforces it on every write.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const invoices = table(
  { state: t.one("draft", "sent", "paid", "void"), amount: t.decimal },
  {
    machine: {
      field: "state",
      initial: "draft",
      edge: {
        send: { from: "draft", to: "sent" },
        pay: { from: "sent", to: "paid" },
        annul: { from: ["draft", "sent"], to: "void" },
      },
    },
  },
);
```

* `initial` is the state or states a fact may be born in.
* `edge` names each allowed change. An edge's `due` names a field holding the
  instant the edge falls due: while the fact is in `from` and the field holds
  an instant, the fact moves to `to` at it. Nothing runs at the instant; every
  write that leaves the fact in `from` decides the edge again, and taking
  another edge, clearing the field or deleting the fact ends it.
* `undeclared` says what any other change does: `refuse` (the default),
  `keep` (commit and record it) or `drop` (commit nothing for that fact).
* `history` keeps the fact's superseded machine versions readable for that
  long.

A [guard](https://docs.bijection.com/access/guards.md) can refuse an edge by role or condition; the
machine says which edges exist at all.

## Marks

`mark` on a series or timeline is the width of the valid-time buckets the
host marks on every write. A rollup reads which buckets changed, instead of
scanning the series.

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

export const readings = series({ meter: t.string, kwh: t.decimal }, { key: ["meter"], mark: { minutes: 5 } });

// The buckets a write touched, as a series keyed by the meter:
const touched = await ctx.page(readings.marks(meter).over({ from, to }), { size: 100, cursor: null });
```

Only the host puts a mark; `ctx.retract` on a mark clears it once the rollup
has handled the bucket. A marked series also keeps `readings.spans`: the spans
a range retraction dirtied, as a table of `{ meter, at, dirtyEnd, dirtyTier,
dirtyAfter }` facts that a rollup reads, patches and deletes.

## Writers

`writers: () => [...]` restricts which mutations or subtrees in the app tree
may write to the table. Each entry is a placed mutation (exact path) or a
placed subtree (any function under that path). `app()` resolves the thunk once
the tree is placed and lowers the list onto the table; the host compiles it
into a write guard on `act.write(table)` that refuses any other application
writer with `Forbidden` (with `guard` set to the table's path).

A direct operator write has no writer function. The guard refuses it.

To prevent writes at compile time as well, expose the table through
`table.readOnly(t)`. Callers receive a `ReadOnlyTable` handle that keeps point
reads and selections but rejects `insert`, `patch`, `replace`, `put`, `delete`
and `retract` at type-check time (`NotWriter`).

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const landing = {
  apply: mutation({ args: { id: t.string, total: t.decimal } }, async (ctx, fact) => {
    await ctx.put(orders(fact.id), { total: fact.total });
  }),
};

const orders = table(
  { id: t.string, total: t.decimal },
  { key: ["id"], writers: () => [landing] },
);

export const catalog = {
  orders: table.readOnly(orders),
  landing,
};
```

## Private tables

`private: true` keeps a table to the subtree that holds it: `vault.secrets`
belongs to `vault`. Only functions placed under that subtree read or write
the table, including the ones another function reaches with `ctx.call`.
Every other function is refused, whoever calls it: a read with
`LibraryTableReaderRequired`, a write at commit by the table's write guard
(`LibraryTableWriterRequired` in its message). A library uses it for facts
the app must not touch directly, such as credentials, while the app still
places the tables by placing the library. The installation itself (the
operator and the `/test` harness's `k.get` and `k.list`) still reads them.

A private table is never placed at the root (`PrivateAtRoot`). With
`writers`, every writer stays inside the subtree (`PrivateWriters`).

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

function vault() {
  const secrets = table({ code: t.string }, { private: true });
  const keep = mutation({ allow: [role.signedIn], args: { code: t.string } }, async (ctx, { code }) => {
    await ctx.insert(secrets, { code });
  });
  const count = query({ allow: [role.signedIn] }, async (ctx) => (await ctx.list(secrets.first(100))).length);
  return { secrets, keep, count };
}

// The app places vault.secrets, but only vault.keep and vault.count read or write it.
export default app({ vault: vault() });
```


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