State language for dialect authors
Use a (state …) clause in a dialect definition to calculate values from accepted acts.
For example, a state field can count approvals or record the value when a chair closes a request.
Start with the approval example below. Use the rule table to find the arguments for each field. The grammar gives the syntax. After parsing, the installer checks names, types, protocols, and lattice rules. Use the CBCL parser to check a dialect definition before installation.
On this page
- A complete example
- Names, arguments, and installation
- State rule keywords
- Read guarantees and more entries
- Thresholds
- Conditions over several sources
- Freezes
- Domains
- Context paths
- Finite lattices and contribution tables
- Resource options and bounds
- Root addresses and migration
- Contracts and implementation status
A complete example
(define approval-count (cbcl) @author
(:roles (chair (* reviewer)))
(extend open (to) :from chair :to reviewer (tell to))
(extend approve (to) :from reviewer :to chair (tell to))
(extend close (to) :from chair :to reviewer (tell to))
(protocol (then begin open) (then open (repeat 8 approve close)))
(state
(reviewers (context thread roles reviewer))
(approvals (count approve))
(threshold enough approvals (count 3))
(sealed-approvals (count approve))
(freeze sealed-approvals close supersede)))
The clause (threshold enough approvals (count 3)) declares a new result named enough. The author selects this name. The preceding clause defines its input, approvals.
Value of approvals | Value of enough |
|---|---|
| 0, 1, or 2 | {"status":"pending"} |
| 3 or more | {"element":{"count":3},"status":"reached"} |
The approvals field counts accepted approval acts. One reviewer can send three acts. Thus, a value of three does not establish approval by three people. The reviewers field gives the role roster. The author must specify how the application uses this roster.
The sealed-approvals field counts the acts in the causal history of the closing act. Only the chair can send the closing act. If two earliest closing acts are concurrent, the field gives a fault.
Save the example as approval-count.cbcl in the repository root. Run this command.
cargo run -p cbcl-cli -- verify < approval-count.cbcl
Names, arguments, and installation
In these forms, name and source identify state fields. The symbol verb identifies a declared performative. The keyword :key identifies a message field. State field names and lattice names must match [a-z][a-z0-9-]{0,47}.
Use quotation marks for strings. Use signed 64-bit literals for integers. Use #t or #f for Boolean values. The values :target, target, and "target" have different atom types.
A data field can contain a finite binary64 literal such as 1.25 or 1e-3. Its shape type is float. An exact decimal such as 12.34m has the shape type decimal. Use a lowercase m suffix. Decimal literals cannot have an exponent.
The types integer and nonnegative accept only integers. The type number accepts all three numeric representations. A counter or sum must have a contract that accepts only integers. A named refinement can supply this contract. JSON preserves decimal precision with an object such as {"decimal":"12.34"}. See Text and values.
Use the form (name (rule arguments…)) for an ordinary field. Give each field a different name. Declare a source before a derived field or threshold that uses it. An unknown or forward reference causes installation to fail.
A freeze declaration applies to its source throughout the clause. This includes dependencies that precede the declaration. A domain declaration applies to each data rule for the specified verb. Its source must be an opener list field or a declared thread-role roster. The domain key must have type string.
The installer rejects unknown rule names, incorrect argument counts, invalid paths, and unsupported reads.
State rule keywords
Brackets in this table mean an optional argument, not literal CBCL brackets. Map arguments are key, value, then clock where applicable.
| Field rule | Observation |
|---|---|
(initial open :key) | Read the field from the only accepted opener. If there is no opener, the field is absent. Competing openers cause a fault. |
(exists verb) | Whether any eligible act of this verb exists. |
(count verb) | Number of different eligible act addresses. |
(set-union verb :key) | Distinct contributed values, without removal. |
(events verb :key) | Each event keeps its act identity, signer, and selected value. |
(values verb :key) | Distinct surviving values after explicit supersession. Alias: multi-value-register. |
(values-per-key verb :key :value [delete-verb]) | Surviving values grouped by key, with optional observed deletion. Alias: multi-value-map. |
(lww-register verb :value :clock) | Greatest eligible HLC/signer/address candidate. |
(lww-per-signer verb :value :clock) | Greatest surviving candidate for each signer. |
(lww-map verb :key :value :clock [delete-verb]) | Greatest surviving candidate for each key, with optional observed deletion. |
(observed-set add-verb remove-verb :key) | Values from the remaining additions. A removal cites the additions that it observed. |
(counter increment-verb decrement-verb :amount) | The sum of increments minus decrements. This rule does not authorize spending. |
(histogram source) | Count occurrences of values in an earlier supported map source. |
(sum source) | Sum integer values in an earlier supported map source. |
(progress verb) | Greatest established occurrence in the installed finite protocol, rather than the number of acts. |
(bounded-counter options…) | Resource value and account budgets checked against causal evidence. See the resource options below. |
(context [path…]) | Read installed dialect, sealed thread, or current observation metadata. |
(lift verb (into lattice-name) (contribute rows…) [projection]) | Join the finite-lattice contributions. An optional projection gives the value of the resulting element. |
The installer rejects the retired heads last, latest-per-signer, latest-per-key, and register-per-key. Select initial, a multi-value rule, or a named lww-* rule. See Select a state rule for clock assumptions and replacement references.
The occurrences of a progress verb must have a causal order. See the bounded progress example.
Read guarantees and more entries
Equal accepted sets under the same installed interpretation give equal
observations. This does not make each observation final as history grows.
Ordinary displayed values are snapshots unless their schema identifies a
threshold, frozen read, or immutable context projection. Examine state_schema
for a field’s read classification.
Thresholds
(threshold name source element…)
The first argument declares the name of the result. The second argument identifies a source field that precedes the threshold. The remaining arguments specify the alternatives.
A threshold starts pending. It can reach an alternative or return a fault. After it reaches an alternative, it cannot return to pending or reach a different alternative. A subsequent conflict can cause a fault. A fault in the source takes precedence.
Specify one or more alternatives. Each alternative must have the correct type. Each pair must give different answers that cannot occur together without a conflict.
| Element syntax | Eligible source and meaning |
|---|---|
#t | exists: one or more eligible acts exist. |
(count n) | count: n or more different acts, with n ≥ 0. |
(member scalar) | set-union, events, or a sealed thread-role roster: the scalar is present. |
(sum n) | Numeric events with a mandatory nonnegative field in the writer shape. The sum must be n or more. |
(progress n) | progress: established position of n or more, with n ≥ 0. |
"element-name" | A finite lift: its carrier has reached that named non-top element or something above it. |
Integer or #t on a finite projection | A checked stable projection of uniform integer or boolean type: projected integer at or above the limit, or Boolean true. |
In a threshold or finite lattice, a scalar is a string, integer, or Boolean. These forms exclude float and decimal literals. A bare fault cannot be an alternative.
For example, a count of three satisfies the bounds (count 2) and (count 3). These bounds cannot be alternatives in one read. Signed counters, balances, removable sets, and displayed LWW winners do not generally supply stable threshold inputs.
A sum threshold tests the nonnegative contributions from its source. The credits alone cannot represent a signed balance.
A pending threshold gives {"status":"pending"}. A reached threshold gives {"element":…,"status":"reached"}. A fault gives {"evidence":[addresses],"reason":…,"status":"fault"}. An unsupported resource profile can give a fault with an empty evidence list.
Evidence for a finite-lattice fault includes the writer acts that contributed to the fault. It also includes the applicable domain initializers or sealed roster roots. These records give the context for replay. An initializer can supply domain membership when it is concurrent with the writer.
Conditions over several sources
(approvals (count approve))
(closed (exists close))
(threshold ready (and (read approvals (count 2)) (read closed #t)))
Each read uses the threshold checks of a source field that precedes it. An and must contain two or more children. Children can contain nested conditions or repeated leaves. A condition can combine compatible bounds such as (count 2) and (count 3). A repeated leaf adds no approvals. A condition cannot compare two independently changing fields.
The result stays pending until each leaf succeeds. It then gives {"status":"reached","element":true}. The condition form (threshold ready (read approvals (count 2))) gives Boolean true. The direct form (threshold ready approvals (count 2)) keeps its authored count element.
A fault takes precedence over a pending sibling. The runtime combines and sorts the evidence from all leaves that have a fault. Each leaf uses the freeze scope of its source. The condition does not introduce a common causal cut. A freeze cannot target the condition itself.
The installer rejects stable reads of a source with a supersede freeze. The position of the freeze declaration does not change this rule.
A read counts as one condition node. An and counts as one node plus its child nodes. The total must fit max-list. Each element must obey the installed scalar bounds.
The schema gives the Boolean threshold the type of: bool. Its condition tree contains read or and nodes. The native runtime evaluates these conditions. Work continues on the extended Lean model, live oracle coverage, and the complete v0.4 proof.
Freezes
(freeze source verb) ; default policy: supersede
(freeze source verb supersede)
(freeze source verb fault)
The freeze verb must declare a :from role. Before the runtime accepts this verb, the source gives its usual value. The earliest accepted freeze act selects a causal cut. The cut includes the freeze act itself. A subsequent freeze act on the same causal path cannot change the cut. Concurrent earliest freeze acts cause a fault with evidence.
The supersede policy excludes contributors beyond the cut. The fault policy gives a terminal fault for such contributors. These policies apply to observations. They do not change the admission verdict for an act.
The result has three fields. The frozen field gives the address of the freeze act. The superseded field identifies excluded contributors. The value field gives the frozen value for derived functions.
A threshold first checks for source errors. For a factored source, it then tests the current raw carrier. The installer rejects a threshold on a source with a supersede freeze. Use two fields as in the approval example. Alternatively, select the fault policy if a contribution beyond the cut must cause a fault.
For a field with a domain, the freeze also applies to the domain sources. These include all matching initializer acts and role-roster roots. The check includes malformed evidence and evidence that contributes no value.
If a domain source is beyond the cut, the fault policy reports its address and the freeze address. The supersede policy records the exclusion. For a complete frozen value, the freeze act must follow the domain evidence and the writers.
Domains
(allowed (initial open :targets))
(domain approve :target allowed)
The runtime checks each approve act against the list. If the list contains its :target, the act can contribute to the data fields for approve. This check affects the observation. It does not change the admission verdict. Conflicting initializers cause dependent observations to give a fault.
A domain can also use a field with the rule (context thread roles role-name). Progress and resource validators use the accepted causal history. The domain filter does not remove their dependencies.
Context paths
All path segments are unquoted symbols. The form (context) returns the complete map. The forms
(context dialect), (context thread), and (context observation) return its
three submaps. Supported deeper paths are:
| Prefix | Supported remainder | Meaning |
|---|---|---|
dialect | name, address, body-address, author | Installed identity metadata. |
dialect | roles or roles role-name | Declared roles and their singleton/indexed cardinality. |
dialect | bounds or bounds max-fields, bounds max-list, bounds max-number, or bounds max-string | Installed state bounds. Use one bound name in the path. |
thread | id, root, initiator, opener | Sealed thread identity and the accepted opener address when available. |
thread | roles or roles role-name | Authenticated sealed account rosters. |
observation | accepted-count, frontier | Current accepted-history size and unreferenced accepted addresses. |
A nested role path must name a declared role. A value can be absent if the receiver has incomplete thread evidence. Malformed casts, conflicting roots, or mixed-thread histories can cause faults. Conflicting openers can cause a fault for paths that depend on the opener. The receiver can read the role roster independently of opener uniqueness.
Dialect projections and supported sealed thread leaf paths give contextual values. The complete context map, thread map, and observation paths give snapshots. The map has no built-in quorum formula, authorization override, clock, or mutable host state.
Finite lattices and contribution tables
The author specifies the merge operation with finite data tables.
(lattice phase
(elements empty ready conflict)
(bottom empty)
(top conflict)
(join
(empty empty empty) (empty ready ready) (empty conflict conflict)
(ready empty ready) (ready ready ready) (ready conflict conflict)
(conflict empty conflict) (conflict ready conflict) (conflict conflict conflict)))
(stage (lift mark (into phase)
(contribute (:phase "ready" ready))
(project stable ((empty 0) (ready 1) (conflict 2)))))
(threshold ready-now stage "ready")
Put these entries in (state …). Declare the verb mark with a shape for :phase. Put elements, bottom, top, and join in this sequence. Supply one join row for each ordered pair of elements.
The installer checks closure, identity, absorption, associativity, commutativity, and idempotence. The bottom and top elements must differ. The carrier must obey the installed max-list bound. It cannot contain more than 64 elements.
The runtime joins the element from each matching contribute row. If no row matches, the act contributes the bottom element. A project table maps each element to one string, integer, or Boolean. If there is no table, the display shows the element name.
The stable option checks that the projection preserves order for integers or Booleans. This option lets a threshold use the corresponding scalar. The displayed value can continue to change. The top element always causes a fault.
Resource options and bounds
bounded-counter accepts the following option lists in any order. Unknown or
duplicate options reject installation.
| Option | Meaning |
|---|---|
(floor n) | Required lower bound. |
(initial-rights open :allocations) | Required account allocations from the opener. |
(issuers role) or (issuers ()) | Required minting role, or disable issuance. |
(increment verb :amount) | Required increment operation. |
(decrement verb :amount) | Required decrement operation. |
(transfer verb :recipient :amount) | Required account-rights transfer. |
(ceiling n) and (initial-headroom open :space) | Optional upper bound and account headroom. In account mode, supply the two options together. |
(transfer-headroom verb :recipient :amount) | Optional headroom transfer. A ceiling is necessary. |
(ownership account) | Default account ownership mode. |
(ownership collective) and (initial open :amount) | Collective scalar initialization. Use quorum-budget. Omit the account allocation and transfer options. |
(certification host-gate) | Default host issuance-gate profile. |
(certification quorum-budget (validators key…) (faults f)) | Explicit certificate-runtime profile. |
Use the certificate runtime to establish finality for a collective or quorum-budget profile. A plain fold gives no proof of finality. See the annotated coin dialect for its roles and operations.
The :state-bounds clause sets limits for a dialect. The default values are 2048 for max-string, 64 for max-list, 10^12 for max-number, and 32 for max-fields. For example, (:state-bounds (max-list 24)) changes only the list limit.
Each specified bound must be positive and no greater than its default. If a bound is absent, the installer uses the default. The installer rejects an unknown, duplicate, or out-of-range bound.
Root addresses and migration
For a root with a cast, the kernel hashes the outermost canonical with-roles subtree. This subtree includes the roster, inner wrappers, and inner message. Wrappers above this subtree do not contribute to the state identity.
For a root without a cast, the kernel uses the simple-message hash. It also uses this hash for an act with a predecessor address. In the reconstructed act, an absent cause, begin, or an empty predecessor vector identifies a root. The wire grammar rejects an empty predecessor list.
Equal sealed roots have the same address. To identify a new thread, put a new authenticated :thread value or nonce in the selected subtree.
The kernel does not add randomness or read a clock to generate identity.
This migration changes addresses for existing roots with a cast. Keep the historical signed records. Use a new history for replacement records.
- Identify each descendant that cites a changed address. Examine
:caused-by,:replaces,:escrow-prev, and:escrow-deps. - Replace the affected references in the new history.
- Sort each changed address set again.
- Reissue the descendant with its new address.
- Repeat the procedure for acts that cite this descendant.
- Calculate the expected intents again.
- Check admission for the new history.
- Check the resulting state. An address change can change the result of a tie.
The authors must authenticate the replacement records. They must also sign them.
The migration manifest lists the old and new addresses for the affected unsigned test records. The initial snapshot contains the inputs and state bytes before migration.
The tests check that the other histories stay the same. For a reissued history, they check its address mapping, admission verdicts, and exact state bytes.
To reproduce the fixture migration, run cargo test -p cbcl-parser --test state_corpus write_role_root_migration -- --ignored --exact.
Before you commit, check the manifest and the three changed vectors.
Contracts and implementation status
SPEC-019 specifies the base state contract. SPEC-035 specifies HLC registers. SPEC-038 specifies the Causal Lattice Observation Kernel (CLOK).
Version 0.4 of SPEC-038 is a draft. The native runtime implements sealed-root identity, its fixture migration, and authored product reads. Verification of these features continues. Extended condition proofs and oracle coverage are pending. The agreement proof for the earlier single-source inventory is complete.
A state-bearing message must use each data keyword only one time. The state-shape check rejects a duplicate keyword, including a duplicate with the same value. Thus the shape check and the state rules use the same field value.