Metakit / What a proof of one step cannot check

Refuse a store that cannot hold a rule

A store here is whatever persists your state: Postgres, SQLite, a table in memory. Describe it with a name and three facts about how it runs writes, defined just below. The values here are Postgres as it comes: its default level is read committed, it runs a transaction of several statements as one unit, and nothing locks a parent row unless your writes do.

ts
import * as Store from '@doeixd/metakit/store'

const postgres: Store.StoreCapabilities = {
  name: 'Postgres',
  isolation: 'read-committed',
  isolates: 'transaction',
  parentRowLock: false,
}

isolation is how the store runs writes that overlap in time. 'serializable' means the result is as if they ran one at a time. 'read-committed' means each statement sees what has been committed so far, so two writers can both read a value that one of them is about to change. 'eventual' means copies of the data accept writes separately and merge them later. isolates says how far that reaches: 'transaction' when a read and a write made later in the same transaction are one unit, 'statement' when only one statement, or one batch that cannot branch on what it read, is (Cloudflare D1 is such a store). A store that leaves it out is taken to isolate one statement. parentRowLock says whether a write locks the row that a group of rows belongs to (the account, for its ledger entries) until it commits.

Now declare the rules. A transition is one change to one record, with an optional condition (when) that must hold for it to apply. A machine is a record's Schema with its named transitions. An aggregate is a value computed over many rows, such as the sum of an account's entries.

ts
import { Schema } from 'effect'
import { Expr, Num, Transition } from '@doeixd/metakit'
import * as Rows from '@doeixd/metakit/aggregates'
import * as Machine from '@doeixd/metakit/machine'
import * as Temporal from '@doeixd/metakit/temporal'

const Account = Schema.Struct({ balance: Schema.Int }).pipe(
  Expr.refine($ => Num.gte($.balance, 0)),
)
const Amount = Schema.Struct({ amount: Schema.Int.pipe(Expr.refine($ => Num.gt($, 0))) })

const Bank = Machine.make({
  state: Account,
  transitions: {
    Deposit: Transition.make({
      state: Account,
      input: Amount,
      apply: ({ state, input }) => [
        Transition.set(state.balance, Num.add(state.balance, input.amount)),
      ],
    }),
    Withdraw: Transition.make({
      state: Account,
      input: Amount,
      when: ({ state, input }) => Num.lte(input.amount, state.balance),
      apply: ({ state, input }) => [
        Transition.set(state.balance, Num.sub(state.balance, input.amount)),
      ],
    }),
  },
})

const Entry = Schema.Struct({ account: Schema.String, delta: Schema.Int })
const aggregates = { balanceIsItsEntries: Rows.sum(Entry, $ => $.delta) }

const needed = Temporal.requirements({ machine: Bank, aggregates })
// [
//   { rule: 'Deposit', needs: 'row-atomic', because: 'it writes from the state it read' },
//   { rule: 'Withdraw', needs: 'row-atomic', because: 'it writes from the state it read' },
//   { rule: 'balanceIsItsEntries', needs: 'parent-serialized',
//     because: 'it reads every row under one parent' },
// ]

Temporal.requirements reads what each rule needs from the declarations. A transition that reads the record it writes needs row-atomic: its guard and its writes must apply to the row as one step. An aggregate needs parent-serialized: writers of the rows under one parent must run one at a time, which a 'serializable' store gives, and a 'read-committed' one gives only with parentRowLock. Each rule is typed as a key of what you declared.

Whether a store gives either also depends on where your writer checks the rule. Unless a requirement says otherwise, it is taken to be checked from a read made before the write, which at read committed may be stale by the time the write lands.

Call Store.mount where the server sets the store up:

ts
const mounting = () => Store.mount(postgres, needed)
// throws StoreRefused:
// [metakit] store "Postgres" (read-committed per transaction, does not lock the parent row) cannot hold:
//   - "Deposit" needs row-atomic (a guard and its writes apply to one row as one step),
//     judged from a read before the write: it writes from the state it read
//   - "Withdraw" needs row-atomic (…), judged from a read before the write: it writes from the state it read
//   - "balanceIsItsEntries" needs parent-serialized (writers of the rows under one parent
//     run one at a time), judged from a read before the write: it reads every row under one parent

It throws StoreRefused, an error, for a store that cannot hold one of the rules, and returns nothing for one that can. Store.refused(postgres, needed) gives the same list without throwing.

If your writer checks a transition's when inside the UPDATE that writes the row, say so with judged: 'in-statement'. The statement re-reads the row it writes, so the transitions hold at read committed; the aggregate does not, since its rows are other rows:

ts
const checkedInUpdate = needed.map(rule =>
  rule.needs === 'row-atomic' ? { ...rule, judged: 'in-statement' as const } : rule,
)
const stillRefused = Store.refused(postgres, checkedInUpdate).map(({ rule }) => rule)
// ['balanceIsItsEntries']

To get past the refusal, change what is true of the database and then what you declare: run it at the serializable level (isolation: 'serializable'), or have every write of an entry lock its account row first (select … for update) and declare parentRowLock: true. Store.mount believes the facts; it does not inspect the database.

A store that isolates one statement

On D1 a writer cannot read in one round trip and write in the next as one unit, so a rule judged from a read before the write is refused there even though D1 runs one write at a time. A rule your writer judges inside the statement that writes (an aggregate's rows read by a subquery of the UPDATE) holds:

ts
const d1: Store.StoreCapabilities = {
  name: 'D1',
  isolation: 'serializable',
  isolates: 'statement',
  parentRowLock: false,
}
const readFirst = () => Store.mount(d1, needed)
// throws StoreRefused: every rule, each judged from a read before the write
const inStatement = needed.map(rule => ({ ...rule, judged: 'in-statement' as const }))
Store.mount(d1, inStatement)
// returns: the rules are judged where D1 runs them as one step

Judging an aggregate in the statement does not make up for a weaker isolation: on the read-committed Postgres above, the subquery reads what had committed when the statement began, and its refusal stands.

A rule the database enforces itself

A foreign key is a rule the database keeps on its own: no row may point at a row that is not there, and a delete of the row pointed at waits for, or refuses, a write linking to it, at any isolation. Where a foreign key holds your rule, say so with judged: 'constraint'. It holds on any store but an eventual one, whose copies each check the key against their own rows:

ts
const linked: Store.Requirement = {
  rule: 'Entry.account',
  needs: 'parent-serialized',
  because: 'an entry may be written while its account is deleted',
  judged: 'constraint',
}
Store.mount(postgres, [linked])
// returns: the foreign key holds it on the read-committed Postgres above