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

# Transactions and conflicts

> A mutation is one serializable transaction. What it read, including its strict writes' assumptions, is validated at commit.

A mutation runs as one transaction under one label, its `under`. Its writes,
submits and grave acts commit together, or none does. A query reads one
consistent version and commits nothing.

## The read set

Everything a transaction relies on is in its **read set**:

* every read: `get`, `has`, `list`, `page` and `count`;
* the assumption of every strict write: `insert` assumes the fact is absent,
  and `replace`, `patch` and `delete` that it is present;
* the inputs of every access decision: the grants that admitted the call,
  the facts guards read, and the clock interval.

Blind writes, `put` and `retract`, read nothing and add nothing to it.

At commit, the host checks the read set against everything committed since the
transaction began. If none of it changed, the transaction commits, and
transactions are serializable: the result is as if they ran one at a time.

## When the world moved

If something the transaction read changed, the host runs the handler again on
the new state. Handlers are deterministic, and nothing a handler does leaves
the transaction before it commits, so a re-run is safe and needs no code of
yours. Write a mutation as if it ran alone.

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

export const accounts = table({ owner: t.string, balance: t.number });

/** Move money between two accounts. Two concurrent transfers that read the
 * same account commit one after the other, never interleaved. */
export const transfer = mutation(
  {
    allow: [role.signedIn],
    args: { payer: t.key(accounts), payee: t.key(accounts), amount: t.number },
    refuses: { Overdrawn: null },
  },
  async (ctx, { payer, payee, amount }) => {
    const paying = await ctx.get(accounts(payer));
    const paid = await ctx.get(accounts(payee));
    if (paying === null || paid === null) return ctx.refuse("Absent", "No such account.");
    if (paying.balance < amount) return ctx.refuse("Overdrawn", "The balance is too low.");
    await ctx.patch(accounts(payer), { balance: paying.balance - amount });
    await ctx.patch(accounts(payee), { balance: paid.balance + amount });
  },
);
```

`Conflict` is the host code for the case it cannot retry: a branch landing
whose `seen` the branch moved past, for example. See [Errors](https://docs.bijection.com/functions/errors.md).

## Hidden changes never conflict

Reads are validated by the values they revealed. A change to a fact or field
above the reader's label is invisible to the reader, so it never re-runs or
wakes that reader.

## Conflicts are exact

A write conflicts with a read, and wakes a live query, only when it changes
the read's answer: it moves a fact into, out of or within the selection,
changes a fact the read returned, or changes a ranked read's inputs. Blind
writes (`ctx.put`, `ctx.retract`) are judged exactly like strict ones, so
writing an unchanged fact, or one outside every selection you read, disturbs
no one. A `count` depends on its whole range. A `list` or `page` that fills
depends only on the range up to its last fact and on the facts it returned, so
a fact that sorts after the last one never conflicts with it. A page that is
not full depends on its whole range.

## Reading a queue that others keep filling

A mutation that counts or lists facts that other writers keep adding can lose
every retry to them when those writers run under labels yours does not
dominate: the host never makes them wait for you. Three shapes never starve.

* Page the queue oldest first by a `t.accepted()` field. The store fills it
  with the commit's own time, so every later arrival sorts after every fact
  you have seen. While your page is not full each arrival is a real change
  and conflicts with it; a full page stops conflicting with arrivals.
* Read fixed history with `.in(version)`: it conflicts only with an erasure
  in a table it read, and the mutation must commit while that version is
  still retained.
* Have the writers `submit` to a handler that runs `under` your label.

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

export const inbox = table({ body: t.string, at: t.accepted() }, { index: [["at"]] });
export const readInbox = query({ allow: [role.signedIn] }, async (ctx) => {
  const { facts } = await ctx.page(inbox.by("at"), { size: 100 });
  const seen = await ctx.count(inbox.in(ctx.frame.version));
  return { facts, seen };
});
```

## Decisions are reads

The grants and guard facts that admitted a call are in its read set. Revoking
a grant therefore conflicts with an in-flight transaction that relied on it:
that transaction runs again and is decided against the grants that remain.

## Expecting a version from the caller

A transaction protects what it read in this run. To protect what a person saw
before they pressed Save, compare it in the mutation.

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

export const notes = table({ text: t.string, generation: t.number });

export const save = mutation(
  { allow: [role.signedIn], args: { note: t.key(notes), generation: t.number, text: t.string }, refuses: { Edited: null } },
  async (ctx, { note, generation, text }) => {
    const fact = await ctx.get(notes(note));
    if (fact === null) return ctx.refuse("Absent", "The note no longer exists.");
    if (fact.generation !== generation) return ctx.refuse("Edited", "Someone else changed this note. Reload it first.");
    await ctx.replace(notes(note), { text, generation: generation + 1 });
  },
);
```

## Time budget

A transaction runs at `ctx.frame.now.entry` and commits at its stamp, before
`ctx.frame.now.entry` plus `ctx.frame.within`, or refuses `Expired`. A function whose
work does not fit belongs in a [task](https://docs.bijection.com/functions/effects.md).

What the host decides for the transaction still holds at the stamp: a grant's
`until`, a task's `due` and `until`, a budget window, and what a read at the
present returned. If the clock passes one of these before the commit lands,
the host runs the transaction again, as after a conflict, while its time
lasts.

Your own comparisons with `ctx.frame.now.entry` are judged at the entry instant and
bind nothing. To act only before `end`, read the clock:

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

export const checkOffer = mutation({ args: { end: t.instant }, refuses: { Closed: null } }, (ctx, { end }) => {
  if (!ctx.frame.now.before(end)) return ctx.refuse("Closed", "The offer has ended");
  return null;
});
```

`frame.now.before(end)` answers whether the commit lands before `end`, and the
host holds the commit to that answer. You can also keep `end` in valid time
and read it at the present.

To write the commit instant, place `frame.now.add({ seconds: 0 })`. `frame.now.add(d)` is the
stamp plus an exact duration, and `frame.now.subtract(d)` is before it. The
host writes the stamp plus `d` in a top-level field, at a series sample's
`.at`, or at a timeline write's `.at` or `.over` bound, never the entry
instant:

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

export const leases = table({ id: t.string, holder: t.string, expires: t.instant }, { key: ["id"] });
export const readings = series({ meter: t.string, kwh: t.number }, { key: ["meter"] });
export const tariffs = timeline({ meter: t.string, cents: t.number }, { key: ["meter"] });

export const stamp = mutation(
  { args: { id: t.string, holder: t.string, meter: t.string, kwh: t.number, cents: t.number } },
  async (ctx, { id, holder, meter, kwh, cents }) => {
    const now = ctx.frame.now;
    await ctx.put(leases(id), { holder, expires: now.add({ minutes: 5 }) });
    await ctx.put(readings(meter).at(now.add({ seconds: 0 })), { kwh });
    await ctx.put(tariffs(meter).over({ from: now.add({ seconds: 0 }), to: now.add({ hours: 24 }) }), { cents });
  },
);
```

No code reads the stamp, so only a blind write (`ctx.put`, `ctx.retract`)
takes a point or a span at `frame.now.add({ seconds: 0 })`. A read or an assumption there is
the type error `ClockTermBlind`: read the present without `.at`.

## Effects leave after commit

A transaction never calls the outside world. Work outside it is a task
submitted with `ctx.submit`, which commits with the transaction and runs after
it. See [Effects](https://docs.bijection.com/functions/effects.md).


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