decisions

A decision point: a place in a system where a recommender proposes an output, a policy either proceeds or asks a person, the person approves, rejects or corrects, and the final output is released exactly once to a gated tool. Everything that happened is kept as an append-only record of entries, which is the data the system learns from.

This module holds the declaration (Point), the gated tool (Gated and Released), and the desk with its verbs. A Desk binds a point to its gated tool, its current policy and a storage port. It is a plain value: build one where you need it, and call its verbs inside your own transaction. Nothing here keeps global state, starts a process or performs I/O; the port does that, in the transaction you pass.

import decisions
import decisions/memory
import decisions/policy.{AnyoneHolding, Ask, Policy}
import decisions/vocabulary.{Approve}

let point = decisions.point("billing.fee_refund", refund_codec())
let desk =
  decisions.desk(
    point,
    drives: fn(_) { refund_fee() },
    under: fn(_) {
      Ok(Policy(version: 1, rules: [], otherwise: Ask(AnyoneHolding("finance"))))
    },
    over: memory.port(),
  )

// A request: the recommendation is recorded and waits for finance.
let assert Ok(waiting) = memory.transaction(store, decisions.recommend(desk, _, proposal))

// Another request: Bia opens the card and approves. The refund is
// released to the gated tool in her verdict's transaction.
let assert Ok(released) =
  memory.transaction(store, fn(tx) {
    use card <- result.try(decisions.open(desk, tx, waiting.id, by: bia, latest: unchanged))
    decisions.decide(desk, tx, card, Approve)
  })

The verbs, grouped by who calls them:

A record’s life, by the status of its head: pending (expected, or only failed attempts so far), then recommended, awaiting a person, accepted, possibly held for an undo window, and finally one of released, rejected, expired or withdrawn. happened ends every record of its subject that has not been released yet: a pending record is reported in not_begun and its later recommendation is refused with SupersededBefore (unless its own deadline had already passed: it then expires as deadline passed, and a later recommendation is recorded expired); an undecided or held one expires and nothing is released. Only a key never expected can still be recommended after the event that should have superseded it.

Every verb loads the occurrence first, which locks it, then reads the store’s clock, so entries are stored in time order. A verb that returns Error has written nothing the caller must keep: roll the transaction back. The two exceptions to “nothing is kept” are recorded on purpose by record_failure and record_refusal, each in a transaction of its own.

Target-independent: builds for Erlang and JavaScript.

Types

The only way to a verdict: an occurrence as it was shown to one validator. Only open and resume construct one. Its output type ties it to points of that output type at compile time; two points with one output type are told apart at run time, where a desk refuses another point’s occurrence with UnknownOccurrence.

pub opaque type Card(output)

What a policy’s Consult hands to the consulted decision point.

pub type Consultation(output) {
  Consultation(
    point: String,
    occurrence: String,
    subject: vocabulary.Subject,
    context: vocabulary.Manifest,
    recommendation: vocabulary.Recommendation(output),
  )
}

Constructors

A decision point bound to its gated tool, its current policy and a storage port. Build one per point wherever it is needed; it holds no state.

pub opaque type Desk(output, tx)

What a runtime that delivers wake-ups or notices may do after a refusal, without reading its text.

pub type Disposition {
  Transient
  Retry
  Poisoned
  Final
}

Constructors

  • Transient

    Contention, or a store whose outcome is unknown: deliver again soon, not counted. Nothing about the job is wrong.

  • Retry

    It may pass on another try, or may never pass: deliver again after a backoff, counted, and set the job aside when the attempts are used.

  • Poisoned

    It needs an operator, and the occurrence still waits for what the job was delivering: set the job aside, do not drop it.

  • Final

    The occurrence moved on, or the job can never apply to it: the job is done.

A gated tool: a guard, and an executor that accepts nothing but a released output. Its name is recorded on the release. The guard, the desk’s release check and the executor run in that order inside one savepoint (store.Port.atomically), so an executor that writes and then returns Error leaves nothing behind, and the release records the evidence of both the guard and the check. drives picks the tool from the output; see Guard for what a guard should and should not read.

pub type Gated(output, tx) {
  Gated(
    name: String,
    guard: fn(tx, vocabulary.Subject) -> Result(
      List(vocabulary.Ref),
      Stop,
    ),
    execute: fn(tx, Released(output)) -> Result(Nil, Stop),
  )
}

Constructors

A guard states facts about the world for a subject, such as “the service window is open”. Its parameters are the transaction and the subject. A check that needs the output, such as an amount against a balance, belongs in the release check (checking), where its evidence is recorded; a threshold on the output belongs in the policy. A guard built inside drives can close over the output, and nothing stops it; do not. It returns the evidence it relied on, which the release records, or a Stop.

pub type Guard(tx) =
  fn(tx, vocabulary.Subject) -> Result(List(vocabulary.Ref), Stop)

Why a handler the application wrote (a settlement follower, a wake-up or job handler) failed: one type both runtimes take.

pub type HandlerFailure {
  DeskRefused(refusal: Refusal)
  ApplicationFailed(reason: String)
}

Constructors

  • DeskRefused(refusal: Refusal)

    A verb of the desk refused; disposition classifies it.

  • ApplicationFailed(reason: String)

    The application’s own work failed, such as a call to another system.

What a runtime does with a job whose handler failed. A runtime decides everything from this value, without looking at the failure.

pub type Handling {
  Redeliver
  Backoff
  SetAside
  Drop
}

Constructors

  • Redeliver

    Deliver the job again soon, and do not count this failure: the store was contended, or its outcome is unknown. Nothing about the job is wrong.

  • Backoff

    Deliver the job again after a backoff, and count this failure toward setting the job aside: the application’s own work failed, or a desk refusal that may pass later or may never pass (Retry). When the runtime’s attempts are used, it sets the job aside as for SetAside.

  • SetAside

    Set the job aside now for an operator, without delivering it again: the record does not decode, and every delivery would fail the same way.

  • Drop

    The job is done; drop it. The desk refused for a reason another delivery will not change: the occurrence moved on, the job was not eligible, or the request was malformed.

A decision point’s declaration: its name, its output type, the verdicts it allows, the facts a policy may read, and its timing. It holds no condition for proceeding without a person; that is the policy’s.

pub opaque type Point(output)

What a recommender proposes, and about whom. Build one with proposal and add what applies with asked_by, hanging_from and valid_until.

pub opaque type Proposal(output)

What a key’s record holds: an occurrence, or a record that has not begun (expected, holding failed attempts, or superseded or lapsed at its own deadline before it began).

pub type Record(output) {
  Begun(occurrence: occurrence.Occurrence(output))
  NotBegun(pending: occurrence.Pending)
}

Constructors

Why a verb did not do what was asked. Every refusal leaves nothing the caller must keep: roll the transaction back.

Refusal may gain variants in a minor release; keep a _ branch.

pub type Refusal {
  UnknownOccurrence
  NotRecommended(attempts: List(occurrence.Attempt))
  NotAwaiting
  AlreadyDecided(by: String)
  NotEligible
  VerdictNotAllowed
  ReasonRequired
  NoteRequired
  NeverShown
  OutputChanged
  NotHeld
  NotTheDecider
  NotReleased
  NotSampled
  NotSettled
  NotConsulting
  InvalidFacts(faults: List(policy.Fault))
  ToolRefused(reason: String, rollback: Rollback)
  ToolUnsure(reason: String)
  ConsultFailed(point: String, reason: String)
  SupersededBefore(event: String)
  DeadlinePassedBefore(deadline: timestamp.Timestamp)
  KeyTaken(point: String)
  NoPolicy(reason: String)
  Unpublishable(faults: List(policy.Fault))
  Unreadable(reason: String)
  Unencodable(reason: String)
  StoreFailed(error: store.StoreError)
}

Constructors

  • UnknownOccurrence

    No occurrence of this point has this id.

  • NotRecommended(attempts: List(occurrence.Attempt))

    The key was tried and nothing was recommended yet; these are the failed attempts.

  • NotAwaiting

    The occurrence is not waiting for this: it settled, or its deadline passed, or it waits for a consulted point.

  • AlreadyDecided(by: String)

    The occurrence no longer waits because by’s verdict settled it: accepted it (held or released after) or rejected it. Only a verdict settles this way; an occurrence that expired, was withdrawn or was refused by the tool is NotAwaiting. The same verdict sent again on the same card or ticket is not refused: it returns the occurrence.

  • NotEligible

    This validator may not open or decide this occurrence.

  • VerdictNotAllowed

    The point’s declaration does not allow this verdict.

  • ReasonRequired

    A rejection or a correction needs a reason category.

  • NoteRequired

    A verdict for missing context needs a note saying what was missing.

  • NeverShown

    The card names no recorded showing of this occurrence to this validator: a ticket for someone else, or a card opened while the occurrence was not waiting for verdicts.

  • OutputChanged

    The output that stands was corrected after this card was shown. Open the card again to see the output the verdict would be about.

  • NotHeld

    The occurrence is not on hold, or its hold has already ended.

  • NotTheDecider

    Only whoever decided may withdraw.

  • NotReleased

    The occurrence has not been released, so nothing outside the database can have happened yet.

  • NotSampled

    The occurrence was not sampled for a review, or is not released yet.

  • NotSettled

    The occurrence has not settled, so there is no outcome to assess.

  • NotConsulting

    The occurrence is not waiting for an answer from this point.

  • InvalidFacts(faults: List(policy.Fault))

    A consulted point’s answer holds facts the point does not declare, or of the wrong type.

  • ToolRefused(reason: String, rollback: Rollback)

    The guard or the gated tool refused in the verdict’s own transaction. Roll the transaction back, then pass rollback to record_refusal in a transaction of its own to keep the attempt on the record.

  • ToolUnsure(reason: String)

    The guard, the release check or the tool could not tell (Unsure). Nothing was recorded; roll back and try again later.

  • ConsultFailed(point: String, reason: String)

    The handler wired with consulting failed to ask point.

  • SupersededBefore(event: String)

    A newer event, event, superseded this key before anything was recommended under it: the trigger’s work is moot. Nothing was written, shown or released. A runtime drops the job as done.

  • DeadlinePassedBefore(deadline: timestamp.Timestamp)

    The key’s own deadline (expect_until) passed by the store clock before anything was recommended under it: nothing can be decided any more. Nothing was written. expect, expect_until, record_failure, record_failure_with, read and every verb that needs an occurrence refuse such a key this way; recommend_once does not, it records the late recommendation expired. A runtime drops the job as done.

  • KeyTaken(point: String)

    recommend_once or record_failure was given a key that an occurrence of another point already holds. Keys are one namespace across every point of a store.

  • NoPolicy(reason: String)

    The policy could not be read.

  • Unpublishable(faults: List(policy.Fault))

    The policy read for this point fails publishable.

  • Unreadable(reason: String)

    The stored record does not decode with this point’s codec.

  • Unencodable(reason: String)

    The point’s codec cannot encode an output to be stored.

  • StoreFailed(error: store.StoreError)

    The store refused or failed.

A final output being released. Only the desk constructs one, for one release attempt, inside the savepoint, after the guard and the release check allowed it, and hands it to the gated tool’s executor alone. If the executor refuses, the attempt rolls back and no release happened: an executor must not keep the value or pass it on, because it names a release only within the call it was handed to. A gated tool’s executor accepts nothing else.

pub opaque type Released(output)

What a verdict refused at release leaves behind once its transaction rolled back: who gave it, on which showing, the verdict and why it was refused. Only the desk makes one, inside ToolRefused, and record_refusal accepts nothing else, so the record can only show a refusal that happened.

pub opaque type Rollback

Why a guard, a release check or an executor did not let a release happen.

pub type Stop {
  Refuse(reason: String)
  Unsure(reason: String)
}

Constructors

  • Refuse(reason: String)

    It refuses this release, for good. With a validator present the verdict rolls back (ToolRefused); with nobody waiting the occurrence ends Refused.

  • Unsure(reason: String)

    It could not tell: its database connection dropped, a provider timed out. Its savepoint rolls back, nothing is recorded as refused, and the verb fails with ToolUnsure, so the caller or the runtime tries again later (counted toward setting the job aside).

What happened did.

pub type Supersession(output) {
  Supersession(
    expired: List(occurrence.Occurrence(output)),
    not_begun: List(String),
    unreadable: List(#(String, Refusal)),
  )
}

Constructors

  • Supersession(
      expired: List(occurrence.Occurrence(output)),
      not_begun: List(String),
      unreadable: List(#(String, Refusal)),
    )

    Arguments

    expired

    The occurrences it expired: undecided or held ones, which had a recommendation.

    not_begun

    The keys of records it ended before they began: expected, or holding only failed attempts. Their recommend_once will be refused with SupersededBefore, except for a record whose own deadline had already passed: it expired as DeadlinePassed, and a later recommendation is recorded expired.

    unreadable

    The occurrences about the subject that could not be read, with why. The others were still superseded.

What a card is known by outside this process: the occurrence and the entry that showed it. A page or another system keeps this and nothing else, and gets the card back with resume.

pub type Ticket {
  Ticket(occurrence: String, seen: Int)
}

Constructors

  • Ticket(occurrence: String, seen: Int)

What the release check sees: the output about to be released, who it is about, the context it was recommended from, and the release’s key. It is a plain value; no executor accepts it.

pub type ToRelease(output) {
  ToRelease(
    output: output,
    subject: vocabulary.Subject,
    context: vocabulary.Manifest,
    key: String,
  )
}

Constructors

What a wake-up found.

It may gain variants in a minor release; keep a _ branch where a new one needs no decision of yours.

pub type Woken(output) {
  Woken(occurrence: occurrence.Occurrence(output))
  NotDue(until: timestamp.Timestamp)
  NothingDue
  LapsedBefore(pending: occurrence.Pending)
}

Constructors

  • Woken(occurrence: occurrence.Occurrence(output))

    Something was due and the occurrence moved.

  • NotDue(until: timestamp.Timestamp)

    Nothing is due before until. The wake-up arrived early, for one because the job queue’s clock is ahead of the store’s: deliver it again at until.

  • NothingDue

    Nothing is pending: the occurrence settled, or it waits for no time. A wake-up delivered again is harmless.

  • LapsedBefore(pending: occurrence.Pending)

    A record that had not begun reached its own deadline (expect_until) and expired with DeadlinePassed; this is the record now.

Values

pub fn allowed(card: Card(o)) -> vocabulary.Verdicts

The verdicts the card’s point allows.

pub fn allowing(
  point: Point(o),
  verdicts: vocabulary.Verdicts,
) -> Point(o)

The verdicts a validator may give.

pub fn asked_by(
  proposal: Proposal(o),
  requester: String,
) -> Proposal(o)

The person who asked. SomeoneElseHolding keeps them from approving it. A recommendation by Person(subject) is that person’s request without this.

pub fn assess(
  desk: Desk(o, tx),
  tx: tx,
  occurrence id: String,
  finding assessment: vocabulary.Assessment(o),
) -> Result(occurrence.Occurrence(o), Refusal)

What proved true later, about an occurrence that settled (released, rejected, expired, withdrawn or refused). It is appended and changes no verdict and no output. An occurrence that has not settled is refused with NotSettled: there is nothing final yet to judge. Each call appends one assessment; repeating it records the finding again.

pub fn checking(
  desk: Desk(o, tx),
  with check: fn(tx, ToRelease(o)) -> Result(
    List(vocabulary.Ref),
    Stop,
  ),
) -> Desk(o, tx)

A check the release makes with the output in hand, such as “the amount is covered by the balance”: it runs after the gated tool’s guard and before its executor, inside the same savepoint, and returns the evidence it relied on, which the release records beside the guard’s in relied, or a Stop. It sees a ToRelease, never a Released, so it cannot reach the executor. A threshold on the output alone belongs in the policy; this is for a fact of the world that must be compared with the output at release.

pub fn codec(point: Point(o)) -> wire.Codec(o)

The point’s output codec.

pub fn consulting(
  desk: Desk(o, tx),
  with consult: fn(tx, Consultation(o)) -> Result(Nil, String),
) -> Desk(o, tx)

How this desk reaches the points its policy may consult. The handler recommends at the consulted point, whose gated tool calls inform on this occurrence, in this transaction or a later one.

pub fn context_of(released: Released(o)) -> vocabulary.Manifest

The context the occurrence was recommended from: its references, never the output. A release check (checking) or an executor that must know which revision of the subject the occurrence is about reads it here.

pub fn decide(
  desk: Desk(o, tx),
  tx: tx,
  card: Card(o),
  verdict: vocabulary.Verdict(o),
) -> Result(occurrence.Occurrence(o), Refusal)

The verdict an occurrence waits for. An accepted output is held when the point has a hold, and released otherwise, in this transaction: the guard and the gated tool run here. A refusal at release is Error(ToolRefused(reason, rollback)): roll the transaction back, then keep the attempt with record_refusal(rollback).

The card must be a recorded showing to its holder (NeverShown), shown after the last correction by anyone else (OutputChanged), and the validity must not have passed (NotAwaiting), whether or not the wake-up that expires it was delivered.

The same verdict sent again on the same card returns the occurrence and runs nothing. Under Several, a validator gives one verdict per output that stands: after approving, they may not reject or correct the same output (NotEligible); after someone else corrects it, they decide again on the new output.

pub fn decider(released: Released(o)) -> occurrence.Decider

Who accepted the output: a policy version or a validator. An executor that attributes its writes uses this.

pub fn declared(point: Point(o)) -> List(#(String, fact.Kind))

Every fact a policy for this point may read, with its type.

pub fn describe(refusal: Refusal) -> String

A refusal as one line of text, for a person.

pub fn desk(
  point: Point(o),
  drives tool: fn(o) -> Gated(o, tx),
  under policy: fn(tx) -> Result(policy.Policy, String),
  over port: store.Port(tx),
) -> Desk(o, tx)

A desk for point. drives picks the gated tool for a final output, so a point whose output has several variants can drive one tool per variant. The tool it returns closes over that output, and so can its guard; a guard should read only its parameters, the transaction and the subject, and leave checks on the output to checking (where their evidence is recorded) and thresholds to the policy. under reads the current policy in the caller’s transaction, so publishing a version is a write. over is the storage port.

pub fn disposition(refusal: Refusal) -> Disposition

Classify a refusal. Every variant is named here, so a new one cannot be classified by accident.

RefusalDispositionWhy
StoreFailed(Contended), StoreFailed(Unavailable)TransientNothing written, or the outcome is unknown; another try is the remedy
StoreFailed(Conflict)RetryA rerun reloads the record, but a conflict that repeats is a second writer that needs looking at
NoPolicy, ConsultFailed, ToolUnsureRetryMay pass later (a policy published, a handler wired, a provider back), or may never
Unreadable, Unpublishable, InvalidFacts, Unencodable, KeyTakenPoisonedAn operator must fix the record, the policy, the answer, the codec or the key; the occurrence or its trigger still waits
every other refusalFinalThe occurrence moved on (settled, decided, expired, not waiting for this), or the request can never apply
pub fn expand(
  desk: Desk(o, tx),
  tx: tx,
  card: Card(o),
  read read: String,
  result captured: vocabulary.Ref,
) -> Result(Card(o), Refusal)

The validator opened more than the card showed. result is the captured evidence of what that read returned (see model.capture).

pub fn expect(
  desk: Desk(o, tx),
  tx: tx,
  key key: String,
  trigger trigger: vocabulary.Trigger,
  about subject: vocabulary.Subject,
) -> Result(Nil, Refusal)

Record, in the transaction that receives a trigger, that a recommendation is expected under key about subject. From then on the record holds the key, so happened for a newer event about the subject supersedes it like any waiting occurrence, and the recommend_once that follows for this key is refused with SupersededBefore. Call it in the same transaction as the happened that the trigger itself reports, after that happened, and in the transaction that admits the job that will recommend, so the expectation and the job exist together or not at all.

happened takes the subject lock and then the records’ locks; expect before happened would take a record’s lock first, which could deadlock with a transaction that keeps that order, and the happened would supersede the key just expected. expect takes no subject lock itself: what orders two admissions about one subject is the happened each runs first.

Safe to repeat: an expected key is recorded once. On a key that already holds a recommendation it does nothing; on a key another point holds it is refused with KeyTaken; on a key already superseded it is refused with SupersededBefore, and on one whose own deadline passed with DeadlinePassedBefore. An expectation made with expect has no deadline: a record that stays expected (its worker died for good) keeps the head status Pending and its arrival time, which a queue or an operator can ask for. To give it one, use expect_until.

pub fn expect_until(
  desk: Desk(o, tx),
  tx: tx,
  key key: String,
  trigger trigger: vocabulary.Trigger,
  about subject: vocabulary.Subject,
  valid_until deadline: timestamp.Timestamp,
) -> Result(Nil, Refusal)

expect, with the occurrence’s own deadline: an instant the application knows when it admits the trigger, such as the end of a service window. It is written on the expected entry, in whole milliseconds rounded down, and the record is due at it: its head’s due time is the deadline and a wake-up is scheduled for it.

At or after the deadline by the store clock the record is lapsed, whether or not that wake-up was delivered: wake expires it with DeadlinePassed and admits its settlement notice, and expect, expect_until, record_failure, record_failure_with, read and every verb that needs an occurrence are refused with DeadlinePassedBefore and write nothing. A recommendation that comes after is still recorded, and starts expired (recommend_once). The deadline the recommendation carries is the earliest of this one, the point’s validity and the proposal’s.

Repeated with an earlier deadline, it appends another expectation and the earliest counts; with an equal or later one it writes nothing: a deadline never moves later. On a key that already holds a recommendation it does nothing. When the deadline has already passed, the expectation is written with its expiry at once, so the transaction that received the trigger can still commit.

pub fn fact(
  point: Point(o),
  key: fact.Key(a),
  from: fn(o) -> a,
) -> Point(o)

Declare a fact of the output, such as an amount, that a policy may read. from computes it from the recommended output.

pub fn facts_of(
  point: Point(o),
  output: o,
) -> List(#(String, vocabulary.Fact))

The facts the point computes from an output.

pub fn handling(failure: HandlerFailure) -> Handling

What a runtime does with a handler’s failure. A desk refusal follows its disposition: Transient is Redeliver, Retry is Backoff, Poisoned is SetAside, Final is Drop. An application failure is Backoff.

pub fn hanging_from(
  proposal: Proposal(o),
  parent: vocabulary.Parent,
) -> Proposal(o)

What the occurrence hangs from, so settling it can start what follows.

pub fn happened(
  desk: Desk(o, tx),
  tx: tx,
  event: String,
  about subject: vocabulary.Subject,
) -> Result(Supersession(o), Refusal)

A world event happened to a subject. Every record of this point about that subject that has released nothing expires as superseded, when the point declares the event with superseded_by:

  • a record that has not begun (expected, or holding only failed attempts): its recommend_once is then refused, so the work in flight for an older trigger never shows or releases anything; one whose own deadline (expect_until) had already passed expires as DeadlinePassed instead, and its wake-up is cancelled;
  • an undecided occurrence; one whose validity had already passed expires as DeadlinePassed, which is what ended it;
  • a held occurrence: its hold’s wake-up is cancelled and its output is never released.

A released occurrence is untouched. A record that cannot be read is reported and does not stop the others. Each superseded record admits one settlement notice.

The subject lock. For an event the point declares, happened first loads subject_lock(point, subject) through the port, which locks that id for the rest of the transaction, and only then reads waiting. So two happened about one subject of one point run one after the other, and the second sees every record the first committed, including the key its transaction expected: two triggers about one subject admitted at the same moment cannot both miss each other. A transaction that calls only expect, recommend or recommend_once, without happened, takes no subject lock and is ordered by nothing here. An event the point does not declare takes no lock. A store error while waiting for the lock is StoreFailed (Contended after a long wait), so the delivery is tried again.

Locks are taken in one order: the subject lock, then the records in the order waiting returns. In a transaction that also expects a key, call happened before expect: the other order could deadlock with a transaction that follows this one, and would supersede the key just expected.

The superseding window. A worker that recommends from an older trigger and commits after happened would create an occurrence nothing supersedes. Call happened and then expect with that trigger’s key in the transaction that received it, and a later happened supersedes it before it begins; the window stays open only for a key that was not expected first.

pub fn holder(card: Card(o)) -> vocabulary.Validator

Who holds the card.

pub fn inform(
  desk: Desk(o, tx),
  tx: tx,
  occurrence id: String,
  from from: String,
  facts facts: List(#(String, vocabulary.Fact)),
) -> Result(occurrence.Occurrence(o), Refusal)

The consulted decision point from settled: its final output arrives as facts, and the policy current now is read again with them (so a version published while the consulted point worked applies).

Refused with NotConsulting unless the occurrence waits for exactly that point, with InvalidFacts when a fact is not declared by this point (signal) or has another type, and with NotAwaiting once the validity has passed.

pub fn key(released: Released(o)) -> String

A stable key for the outside effect: the idempotency key a provider is sent and the cause a command log cites. An uncertain outcome is settled by looking the effect up by this key.

pub const missing_context: String

The reason category that requires a note: the validator knows something the card does not show and must say what.

pub fn name(point: Point(o)) -> String

The point’s name.

pub fn note(
  desk: Desk(o, tx),
  tx: tx,
  card: Card(o),
  note: String,
) -> Result(Card(o), Refusal)

The validator enters what they know from outside the card.

pub fn occurrence_of(released: Released(o)) -> String

The id of the occurrence that was released.

pub fn open(
  desk: Desk(o, tx),
  tx: tx,
  occurrence id: String,
  by validator: vocabulary.Validator,
  latest latest: fn(vocabulary.Ref) -> String,
) -> Result(Card(o), Refusal)

Show an occurrence to a validator, and record the showing. Only an occurrence a verdict can be given on opens: one waiting for verdicts, to a holder of a set it waits for (NotEligible otherwise), or one released and sampled, for its review. Any other is refused with what a card would run into: AlreadyDecided(by) when someone’s verdict settled it, NotSampled when the policy released it unsampled, and NotAwaiting otherwise (waiting for a consulted point, expired, withdrawn, refused, or its validity has passed). A queue page read before the lock learns it here.

The showing records every input (a context reference or one of the model’s reads) whose latest revision differs from the one the model had. Drift says only that the content differs now: it cannot tell a change in the world from one the release itself caused (a read of “does the patient exist” differs once the release created them).

pub fn output(released: Released(o)) -> o

The released output.

pub fn parent(
  released: Released(o),
) -> option.Option(vocabulary.Parent)

What the occurrence hangs from: the run to follow on, or the occurrence that consulted this one.

pub fn point(
  name: String,
  output: wire.Codec(output),
) -> Point(output)

A point with this name and output codec. It allows approve and reject, declares no facts, has no hold and no validity, and nothing supersedes it. The name is stored on every occurrence: keep it stable.

pub fn point_of(desk: Desk(o, tx)) -> Point(o)

The desk’s point.

pub fn proposal(
  trigger trigger: vocabulary.Trigger,
  about subject: vocabulary.Subject,
  context context: vocabulary.Manifest,
  recommending recommendation: vocabulary.Recommendation(o),
) -> Proposal(o)

A proposal that hangs from nothing and that nobody asked for.

pub fn publishable(
  point: Point(o),
  policy: policy.Policy,
) -> Result(Nil, List(policy.Fault))

Whether a policy may be published for this point: it reads only facts the point declares, each as its declared type. Call it before storing a policy version. The desk checks it again each time it reads a policy.

pub fn read(
  desk: Desk(o, tx),
  tx: tx,
  occurrence id: String,
) -> Result(occurrence.Occurrence(o), Refusal)

The occurrence as the record holds it now. It writes nothing.

pub fn read_record(
  desk: Desk(o, tx),
  tx: tx,
  key key: String,
) -> Result(Record(o), Refusal)

The record under a key, whether or not it has begun. It writes nothing. UnknownOccurrence when the key holds nothing of this point.

pub fn recommend(
  desk: Desk(o, tx),
  tx: tx,
  proposal: Proposal(o),
) -> Result(occurrence.Occurrence(o), Refusal)

Record a recommendation under a new id and apply the policy. When the policy proceeds and the point has no hold, the gated tool runs here, once; when it refuses, the occurrence ends Refused. When the proposal’s own deadline (valid_until) has already passed, the recommendation is recorded and expires at once, and no policy runs.

pub fn recommend_once(
  desk: Desk(o, tx),
  tx: tx,
  key key: String,
  proposal proposal: Proposal(o),
) -> Result(occurrence.Occurrence(o), Refusal)

recommend, at most once per key, which becomes the occurrence’s id. A trigger delivered again finds the occurrence it already made and writes nothing. Safe under concurrent deliveries because the port locks a key that does not exist yet. Keys are one namespace across every point of a store: a key another point’s occurrence holds is refused with KeyTaken, so prefix keys with something the point owns.

An expectation (expect) and failed attempts recorded under the key stay at the start of the record. A key that a newer event superseded before it was recommended is refused with SupersededBefore(event), and nothing is written, shown or released: the work in flight is moot.

Deadlines. The deadline written on the recommendation is the earliest of the point’s validity counted from now, the deadline the key’s expectations carry (expect_until) and the proposal’s (valid_until). When the occurrence’s own deadline (the key’s or the proposal’s) has already passed by the store clock, the recommendation is recorded and the occurrence expires at once with DeadlinePassed: no policy runs and nothing is shown or released, and the expired occurrence is returned, so the late output stays on the record. That holds whether or not the wake-up that expires the key was delivered first; when it was not, the expiry is written before the recommendation, so the record has one shape either way.

The superseding window. happened supersedes what the record holds when it runs. Call expect with this key in the transaction that receives the trigger, and the record holds it while the model works; the window stays open only for a key that was not expected first.

pub fn record_failure(
  desk: Desk(o, tx),
  tx: tx,
  key key: String,
  trigger trigger: vocabulary.Trigger,
  about subject: vocabulary.Subject,
  failure failure: model.Failure,
) -> Result(List(occurrence.Attempt), Refusal)

Record that a recommender failed under key before anything was recommended. Call it in a transaction of its own, after the one the attempt ran in rolled back, so the record shows that the trigger was tried and why it failed. Returns every failed attempt so far, from which a caller decides on another try (see model.retryable). When the key already holds a recommendation, nothing is written. When a newer event superseded the key before it was recommended, nothing is written and the result is Error(SupersededBefore(event)): do not try again. When the key’s own deadline (expect_until) has passed by the store clock, nothing is written and the result is Error(DeadlinePassedBefore(deadline)): do not try again either.

Each call records one attempt, so repeating a call records the attempt again: two attempts that failed alike look the same, and the desk cannot tell a second attempt from a repeated call. After an Unavailable outcome, read the record first (read returns NotRecommended(attempts)) and call again only if the attempt is not there.

The record lives under whatever key you give, before any occurrence exists, so give the key recommend_once will use for the same trigger: then the attempts and the recommendation that follows share one record. A failure that carries evidence (model.with_evidence) is recorded with it.

pub fn record_failure_with(
  desk: Desk(o, tx),
  tx: tx,
  key key: String,
  trigger trigger: vocabulary.Trigger,
  about subject: vocabulary.Subject,
  failure failure: model.Failure,
  evidence evidence: List(vocabulary.Ref),
) -> Result(List(occurrence.Attempt), Refusal)

record_failure, pointing at evidence the application stored about the attempt, such as a provider exchange that did not decode. The evidence a failure carries itself (model.with_evidence) is added.

pub fn record_refusal(
  desk: Desk(o, tx),
  tx: tx,
  rollback: Rollback,
) -> Result(occurrence.Occurrence(o), Refusal)

Keep on the record a verdict whose release was refused. Call it in a transaction of its own, after decide returned ToolRefused(reason, rollback) and its transaction rolled back. It changes no status. Only the desk makes a Rollback, so nothing else can be recorded this way. It is safe to repeat: the token names one refused verdict (its validator, the verdict and the showing it was given on), and a second call with the same token appends nothing and returns the occurrence.

pub fn report(
  desk: Desk(o, tx),
  tx: tx,
  occurrence id: String,
  effect effect: vocabulary.Effect,
) -> Result(occurrence.Occurrence(o), Refusal)

What became of the release outside the database: performed with a receipt, not performed, or not yet known. Report again when a lookup settles an uncertain outcome; the latest report is the one that counts.

pub fn resume(
  desk: Desk(o, tx),
  tx: tx,
  ticket: Ticket,
  by validator: vocabulary.Validator,
) -> Result(Card(o), Refusal)

The card again, in a later request, from its ticket. It is the same showing, so nothing is recorded. A ticket that names no showing of this occurrence to this validator is refused with NeverShown; one shown before the output was corrected by someone else, with OutputChanged; one whose occurrence’s validity has passed, with NotAwaiting.

pub fn review(
  desk: Desk(o, tx),
  tx: tx,
  card: Card(o),
  verdict: vocabulary.Verdict(o),
) -> Result(occurrence.Occurrence(o), Refusal)

A verdict after the fact, on a sampled and released occurrence, given on a recorded showing (open records one). It changes no outcome and counts toward agreement. Each reviewer reviews once; whoever decided the occurrence, asked for it, or recommended it as their own act may not review it; and when the point names reviewers (reviewed_by), only holders of that set may (NotEligible).

pub fn reviewed_by(point: Point(o), set: String) -> Point(o)

Who may review a sampled occurrence after its release: holders of set. Without it anyone may, except the people review always excludes (whoever decided it, asked for it, or recommended it as their own act).

pub fn shown(card: Card(o)) -> occurrence.Occurrence(o)

The occurrence as the card shows it, with every entry recorded up to the card’s last action.

pub fn signal(point: Point(o), key: fact.Key(a)) -> Point(o)

Declare a fact that arrives beside the output, such as a model’s score in its signals or a consulted point’s answer, that a policy may read.

pub fn subject(released: Released(o)) -> vocabulary.Subject

Who the release is about.

pub fn subject_lock(
  point point: String,
  subject subject: vocabulary.Subject,
) -> String

The id happened loads, purely as a lock, before it reads which records of point about subject are waiting: subject_lock_prefix followed by the lowercase hex SHA-256 of the point name, the subject’s kind and the subject’s id, each written as its byte length, a colon and the text. The length prefixes keep the parts apart, so ("a", "b:c") and ("a:b", "c") give different ids, and the id is 87 bytes however long the parts are. No entry is ever stored under it.

A key of your own that equalled it would still be harmless: happened ignores what the load returns and only waits on the lock, so such a record would merely make happened about that subject wait for its transactions too. Matching 64 hex digits of a SHA-256 takes a choice, not an accident; the reserved prefix rules out the choice.

pub const subject_lock_prefix: String

The prefix of every subject lock id (subject_lock). It is reserved: do not use it for keys of your own.

pub fn superseded_by(point: Point(o), event: String) -> Point(o)

A world event that expires an occurrence about the same subject that has not been released, reported with happened: one still undecided, and one accepted and held, since nothing is released while it is held.

pub fn ticket(card: Card(o)) -> Ticket

The card’s ticket.

pub fn valid_for(
  point: Point(o),
  validity: duration.Duration,
) -> Point(o)

How long an occurrence may wait to be decided. After it, no verdict is accepted and the occurrence expires.

pub fn valid_until(
  proposal: Proposal(o),
  at deadline: timestamp.Timestamp,
) -> Proposal(o)

The occurrence’s own deadline, an instant the application knows, such as the end of a service window. The deadline written on the recommendation is the earliest of this, the point’s validity counted from the recommendation, and the deadline the key’s expectation carries (expect_until): a proposal brings a deadline earlier, never later. When it has already passed, the recommendation is recorded and expires at once. The instant is kept in whole milliseconds, rounded down.

pub fn verdicts(point: Point(o)) -> vocabulary.Verdicts

The verdicts the point allows.

pub fn wake(
  desk: Desk(o, tx),
  tx: tx,
  occurrence id: String,
) -> Result(Woken(o), Refusal)

A wake-up for an occurrence: a hold ended, the validity passed, or waiting changed what the policy says; or for a record not begun whose own deadline (expect_until) passed, which then expires (LapsedBefore). A release checks the guard, the release check and the tool again against the world as it is now; a Refuse ends the occurrence Refused, an Unsure fails the wake-up with ToolUnsure and records nothing, so it is delivered again.

Of the policy’s later answers whose time has passed, it applies, in order, the first that proceeds, consults a point not yet consulted, or asks for what the approvals given so far already meet, and otherwise the last. So a wake-up delivered late reaches the outcome one delivered on time would have. Each is applied as the first answer was: one that consults asks the consulted point, one that asks for what the standing approvals meet accepts. A wake-up that finds nothing due writes nothing and names the next time something is due, always in the future, or NothingDue.

pub fn waker(
  desk: Desk(o, tx),
) -> #(
  String,
  fn(tx, String) -> Result(
    option.Option(timestamp.Timestamp),
    Refusal,
  ),
)

The desk’s wake with its output type erased, so one job handler can serve every point by name: #(point name, handler). The handler returns None when the job is done, and Some(until) when it arrived early and must be delivered again at until.

pub fn with_hold(
  point: Point(o),
  hold: duration.Duration,
) -> Point(o)

A wait between every acceptance and its release, during which the decider, or a holder of the withdrawn_by set, may withdraw. A Proceed that declares its own hold takes the place of this one for the acceptances it makes; to hold only what the policy lets proceed, put the hold in the policy’s Proceed and not here. The guard and the tool run when it ends, at the wake-up: a refusal then ends the occurrence Refused, and never reaches the validator who approved, who has already been answered.

pub fn withdraw(
  desk: Desk(o, tx),
  tx: tx,
  occurrence id: String,
  by who: String,
) -> Result(occurrence.Occurrence(o), Refusal)

The decider takes a held output back before its hold ends. The decider is the validator whose verdict accepted it, or the person whose own act the policy let proceed. Once the hold has ended by the store’s clock it is refused with NotHeld, whether or not the wake-up that releases it was delivered.

pub fn withdraw_as(
  desk: Desk(o, tx),
  tx: tx,
  occurrence id: String,
  by validator: vocabulary.Validator,
) -> Result(occurrence.Occurrence(o), Refusal)

withdraw by a validator: the decider, or a holder of the set the point names with withdrawn_by. Refused with NotTheDecider for anyone else, and with NotHeld once the hold has ended.

pub fn withdrawn_by(point: Point(o), set: String) -> Point(o)

Who may withdraw a held occurrence besides its decider: holders of set, through withdraw_as. Without it only the decider may, which for an output the policy accepted from a model is nobody. Pair it with a Proceed that holds (an undo window the policy declares) or with with_hold.

✨ Search Document