Liking cljdoc? Tell your friends :D

Invariants

A guard is a Datalog query attached to an attribute. When a transaction touches that attribute, validators evaluate the guard. A metered change query rejects a transaction when it returns a row. A scalar predicate rejects an assertion when the predicate is false.

This is datopia's model: you install an attribute, and you install the invariant that guards it.

Metered guards on signed Datahike transactions

Install skuld.guard/schema at genesis. An account can install a guard directly on an existing attribute in its identity namespace, or attach a published revision as described below. Use (skuld.client/sign-guard signer chain nonce registration) to build the signed envelope, then submit it like an ordinary write. For example, protect the value 7 from being removed by any operation, including a map replacement:

{:guards (keyword sender "level")
 :reads []
 :query '[:find ?entity :in $before $after $delta
          :where [$delta ?entity _ ?value :retracted]
                 [(= ?value 7)]]}

The next ordinary transaction can include :fuel 32 alongside :tx-data. Sign (skuld.ledger.authz/tx-digest chain sender nonce tx-data 32). The four-argument signature is still valid for envelopes omitting :fuel; their guard budget is zero. A redundant assertion produces no change row.

Input or outcomeContract semantics
$deltaResolved changes across the envelope for declared reads and the directly guarded attribute. Rows are [entity attribute value :added] or [entity attribute value :retracted]. Both sides of a cardinality-one replacement are visible.
$beforeDatabase immediately before this envelope. Both snapshot sources use the same declared read attributes.
$afterCandidate post-state after applying the stamped user forms and before charging the account. Indexed reads are restricted to declared attributes in identity-owned namespaces, including those of other accounts.
ResultAny result row refuses the business writes. Empty results allow later checks to continue. Guard bindings are read from pre-state; an installation in an earlier envelope of the same block is already effective.
OrderingDiscover attachments in attribute order and execute each distinct revision once in digest order. Sort change rows by attribute, entity ID, operation and value. Every triggered guard draws from the same signed budget. Evaluation stops on the first refusal.
LimitsAt most 512 fuel per transaction, eight declared read attributes and 32 visible changes per invocation. Changes support long, resolved ref ID, string and keyword values. String and keyword spellings have the evaluator's 128-code-unit limit.
Fee and receiptReserve the priced write plus the signed guard limit. A successful write costs the ordinary transaction fee plus one unit per unit consumed. A guard refusal spends the nonce and charges the base fee plus consumed fuel. Receipts list guards, event counts for executed queries and total fuel. Later storage or trusted-invariant refusals retain the fuel charge. A block-capacity deferral charges zero and preserves the nonce.

Signed fuel covers each matched metered attachment and query execution. Skuld applies a separate transaction preparation limit while Datahike builds the candidate report before guard dispatch. The current profile exposes both snapshots from the same speculative transaction report and the resolved changes visible to the invocation. Trusted Kontor invariants have the four-source interface described below.

For example, to reject a new price on a booking that was already confirmed, install this guard on the price attribute. Here price and status are the actual namespaced attribute keywords.

{:guards price
 :reads [status]
 :query (conj '[:find ?booking :in $before $after $delta :where]
              ['$delta '?booking price '_ :added]
              ['$before '?booking status :confirmed])}

If one envelope sets the booking back to draft and changes its price, the guard sees the earlier confirmation and refuses both writes. A rule that also forbids removing the price should match the operation with a wildcard. A status-only update does not trigger a price guard. To enforce a constraint whenever either attribute changes, install guards on both attributes with their respective owners' authorization.

Sharing a row across accounts

Suppose a theatre writes capacity and an agency writes requested seats on the same performance entity. Both attribute schemas already exist. The agency can sign this registration using its own funded account. Here agency and theatre are the identity-derived namespace strings.

(def requested (keyword agency "requested"))
(def capacity (keyword theatre "capacity"))

(def capacity-guard
  {:guards requested
   :reads [capacity]
   :query (conj '[:find ?show :in $before $after $delta :where]
                ['$delta '?show requested '?qty :added]
                ['$after '?show capacity '?limit]
                '[(> ?qty ?limit)])})

With a published capacity of 10, an agency request for 9 passes and a request for 11 returns a violation. The join requires an existing capacity fact. A missing capacity yields no violation in this particular query. The theatre can subsequently lower capacity to 5. Its change touches only its own attribute and therefore does not run the agency's guard. An agreement that must hold in both directions needs a corresponding guard on the theatre's capacity, installed by the theatre. The ordinary transaction boundary enforces attribute ownership independently of both guards. Declaring a read grants no authority to change the theatre's capacity. Protocol attributes such as :urd.account/balance are outside the declared read set allowed by this profile.

Publishing and attaching contracts

Each map below is the registration argument to skuld.client/sign-guard. The publisher signs the first. Only the owner of the attribute can sign the second and third. Use the digest from the publication receipt.

{:contract (keyword publisher "booking-rule") :reads [price status] :query query}
{:guards price :attach digest}
{:guards price :detach digest}

Publication alone creates no triggers. A named contract can be revised with :replaces or frozen with :immutable?. An existing attachment continues to execute its exact approved revision until the attribute owner changes it. Attach only to an attribute included in that revision's reads. (skuld.client/active-guards db price) lists every active revision. Before signing, call (skuld.client/preview-guards db sender nonce forms fuel) to estimate ordinary write fees and inspect metered guard receipts on the finalized snapshot. Final admission also checks signatures, trusted invariants, storage collateral and block capacity. The publisher pays storage collateral for retained revisions. The attribute owner pays for the attachment. Registrations accept at most 256 input nodes, depth 16 and 8192 bytes of scalar input under the protocol size measure.

An attribute has four slots including its optional direct guard. A changed attribute is looked up in the pre-state attribute registry. Each matched metered attachment costs one discovery fuel, even when another attribute already triggered the revision. Successful queries charge their ordinary event schedule. A receipt includes total fuel, discovery fuel when spent, and the sorted triggering attributes for each executed revision. Scalar predicates occupy a slot and count toward the invocation limit under their existing fee.

The dispatch limits are 1024 report datoms, 64 distinct changed attributes, eight distinct triggered revisions and 512 signed fuel per envelope. A limit refusal discards the business writes. The report and attribute caps bound grouping and unsuccessful lookups even on zero-fuel writes. Query input is capped at 32 visible changes, including changes to readable attributes on other entities. Use a literal attribute in the leading delta pattern when only one type of change should produce a violation.

Run the dispatch benchmark from the repository root. It measures prepared reports on an in-memory store for zero matches, 1,000 unrelated revisions, four shared revisions and eight distinct revisions.

clojure -Sdeps '{:paths ["src" "dev"]}' -M -m skuld.guard-cost

Replacing or freezing a guard

The owner can replace the current guard by signing a complete registration with the expected current digest. Read the digest from the successful installation receipt (:guard-digest) or directly from the registry.

(def current (skuld.guard/binding-for db requested))
(def replacement (assoc capacity-guard
                        :replaces (:invariant/guard-digest current)
                        :immutable? true))
;; Sign (skuld.guard/registration-digest chain agency next-nonce replacement).
;; Submit replacement as the envelope's :registration.

Each successful install or replacement costs 10,000 units. The new program applies to later envelopes, including the next envelope in the same block. Existing business data is left in place. Reusing an obsolete digest gives :stale-guard. Omitting :replaces on an existing binding gives :already-guarded. These authenticated refusals spend the nonce and base fee.

Guards are replaceable by default. Setting :immutable? true on creation or replacement permanently freezes that revision, including for the owner. A replacement naming the frozen digest returns :immutable-guard. There is no unregister operation. The registry keeps every revision, even with Datahike history disabled. To audit it, look up [:invariant/guard-digest digest] and follow :invariant/previous-digest to the initial revision. The digest includes the target, program, freeze flag and predecessor. Each executed metered guard also reports its digest in the transaction receipt.

Scalar value guard

Start the beta chain with the same Skuld version on every validator and install skuld.guard/schema at genesis.

An account may bind one predicate to an existing :db.type/long attribute in its own identity namespace. For example, given the funded account namespace sender, build the registration as follows.

{:guards (keyword sender "level")
 :query  '[:find ?value . :in ?value :where [(> ?value 0)]]}

Sign (skuld.guard/registration-digest chain sender nonce registration) and put the registration in the envelope's :registration field. Ordinary signed transactions use :tx-data. Block order determines when a guard takes effect, including later writes in the same block. A successful installation costs 10,000 units. An authenticated duplicate at the next nonce costs the base fee and leaves the original binding intact.

The scalar grammar admits one comparison of ?value against a signed 64-bit integer literal. Operators are <, <=, =, >= and >. Each asserted value in the produced transaction datoms must satisfy the predicate. If any fails, the entire user write is refused with the ordinary refusal fee and nonce change. Retractions are permitted. Existing values are grandfathered. Installation time is independent of the attribute's existing data. Evaluation walks the produced datoms, sorts the distinct attributes for stable receipt ordering, and looks up each binding by its indexed attribute.

Certified change-guard demo

The current demo registers a metered guard that rejects negative assertions and all retractions. It checks success, both kinds of refusal, replay protection and the signed fuel receipts.

The devnet runs a fixed equal-weight committee in one JVM. The client pins the public roster supplied by the local launcher, verifies Ed25519 precommits on each proposal and re-executes every block in its own JVM. Account and storage state are disposable. The demo assumes an empty rewards commit map and a fixed logical time per block; it does not exercise staking economics. Run it with bin/check-guard-devnet. To inspect the requests and receipts yourself, start each role in its own terminal with the same fresh private directory. In the first terminal:

dir=$(mktemp -d)
echo "$dir"
clojure -M:guard-devnet validators "$dir"

In the second terminal, substitute the printed directory:

clojure -M:guard-devnet client /path/to/private-directory

The client waits for deployment finality before submitting the writes. receipt-1 and receipt-2 are EDN files containing the certified proposals from height zero, transaction outcomes and the account read. Only public key material is exchanged. A REPL client can use publish! to submit successive request-N files and receive! to read their receipts; the validator process exits on stop or after 90 seconds of inactivity. The socket demo accepts the funded account's registrations and writes to its level attribute. General ledger applications supply their own admission schema. The local directory acts as the trusted channel for the initial roster.

Trusted four-source guards

The remaining sections describe the earlier Kontor-compatible guard format. Trusted genesis code can install those guards directly. Their deployment helper and experimental rule-program metadata stay outside signed block registration. The live legacy evaluator reads the query and the four sources; it does not resolve stored rule programs as a fifth argument.

A signed posting can carry Datahike business valid time on its transaction entity via :db.valid/from and :db.valid/to. These describe the business interval; Datahike records transaction time in :db/txInstant. The integration test uses Kontor's posting builder and its shipped account-active invariant.

Four sources

Skuld passes Kontor the immutable transaction report and the transaction forms used to prepare it. Guard dispatch examines the resolved additions and retractions. Each triggered trusted query receives these four sources:

$beforethe database as it is
$afterthe database with the transaction applied
$empty+datomsan isolated database seeded for lookup refs and updated with the transaction forms
$datomsthe raw transaction operations

That is what lets a guard express a transition rather than a state — a zero-sum transfer needs before and after, and needs the delta separately to know what moved.

Dispatch is on produced datoms

Which guards run is decided by the attributes a transaction produces, not the ones it mentions.

The distinction is not academic. kontor schedules invariants by asking which attributes a transaction mentions, and for a destructive form the answer is nobody:

(defmethod get-attribute :db/retractEntity [_] nil)

Its reasoning is sound for kontor's use — "none asserts a new attribute value, so per-attribute invariants have nothing to schedule against". It is exactly wrong when the invariant is the access control, which is this model: a guard on an attribute must fire when that attribute's data is destroyed, or deletion is the way around every guard.

What actually happened was stranger than not firing. nil binds as unbound in the lookup query, so it matched every registered rule. Measured with a deny-all invariant on :guarded/value:

write :guarded/valueBLOCKED — correct
retractEntity a guarded entityBLOCKED
retractEntity an unrelated oneBLOCKED — wrong
write an unrelated attributeallowed — correct

Fail-closed, which is the lucky direction, and wrong twice: an unrelated invariant blocked unrelated deletions, and every retractEntity evaluated every invariant in the database — O(N) amplification from a three-token transaction, in a model where N grows with adoption because invariants are the contracts.

Same root cause, third occurrence. Submitted forms do not name what a transaction touches — it broke attribute scoping, it broke row ownership through the :db/isComponent cascade, and it broke invariant dispatch.

A guard that throws is a guard that failed, not one that passed. Treating a throw as a pass would make a malformed query the way past every invariant.

Registration

Registration was closed for a long time, because it is remote code execution if done naively: :invariant/query is read-string-ed and handed to d/q, which resolves namespaced function symbols.

Reopening it needs four checks:

PARSE — the query must parse under the real datalog parser, not a regex.

SOURCES — exactly the four inputs above, in order.

FUNCTIONS — every called function must be in datahike's built-ins. The allowlist is that narrow deliberately: datahike's filter-by-pred falls through built-ins, then all of clojure.core except eval, then resolve, then Java method resolution. A bare spit resolves.

Two independent passes find the calls — one semantic over the parse tree, one structural over the raw form — and their union is used. Deliberately over-broad; the syntax check is what stops it flagging every legitimate or.

SIZE — 4 KB of query, 8 KB of rules, 64 clauses, 8 rule sets.

The same validation re-runs on any query a transaction registers, which closes the hole that fixing the dispatch opened.

Content addressing

A guard is addressed by a hash over its read form, so whitespace and formatting do not fork the address, and two people registering the same guard get one row.

Rule sets are addressed the same way and are immutable. That is the supply chain argument: if a guard declares it uses rule set <digest> and somebody could edit that rule set, they could silently change what the guard means. They cannot change a hash.

Rule names are namespaced, so (alice/reach ?x) and (bob/reach ?x) coexist.

Pricing

A recursive guard is not statically boundable — transitive closure over a graph grows from 45 pairs at 9 edges to 3,160 at 79. And charging measured time would fork the chain, because a warm cache measures near zero and a cold one does not.

So: a flat, high fee for recursion, and a base plus per-byte fee otherwise.

base       10,000
per byte        2
recursive  500,000

You may guard attributes in your own namespace freely. Anything else is governance.

See also

Transactions for where guards run in admission · Ownership for what "your own namespace" means

Can you improve this documentation?Edit on GitHub

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close