RIDDL Language Guide¶
Overview¶
RIDDL (Reactive Interface to Domain Definition Language) is a domain-specific language designed for modeling reactive systems using Domain-Driven Design (DDD) principles. It bridges the gap between business domain experts and software engineers by providing a language that's both expressive for domain modeling and precise enough for implementation. This language was also designed to provide an AI model with sufficient context to generate code accurately from the specification.
Language Design Emphasis¶
RIDDL emphasizes:
- Declarative syntax with natural language readability
- Hierarchical structure with domains, (bounded) contexts, entities, processors, repositories, projectors, adaptors, and other definitions that specify the behavior of a system
- Event-driven and reactive design patterns
- State-based entity modeling with explicit state transitions
- Streaming of data between components from outlet to inlet via connectors
- Clear separation of commands, events, queries and results
- Saga-based coordination of complex atomic processes, possibly distributed
- Comprehensive domain modeling through DDD concepts
- Asynchronous, non-blocking communications (implied)
Language Structure¶
Definitions¶
Everything that has a name and can have metadata is known as a Definition in RIDDL.
Branches¶
Branch definitions are containers that hold other definitions. They form the hierarchical structure of a RIDDL model:
- Root: The implicit top-level container (not explicitly defined)
- Module: A flat, named collection of any top-level definition
- Domain: Contains bounded contexts and domain-wide definitions
- Context: Contains entities, repositories, sagas, and other processors
- Entity: Contains states, handlers, functions, and message types
- Epic: Contains use cases describing user interactions
- Saga: Contains steps for multi-step processes with compensation
Processors¶
A processor is any definition that can receive and process messages, and that may declare ports. Processors are the active components of a RIDDL model.
RIDDL has one unified processor model. Every processor kind — Context, Entity,
Adaptor, Projector, Repository, and the generic processor — may declare
inlets and outlets, and may carry an ascribed streaming shape:
- Entity: Stateful processor with commands, events, states, and handlers. Entities are the primary business objects that maintain state and respond to commands.
- Adaptor: Translates messages between two contexts. Defined with a
direction (
fromorto) relative to a context. - Repository: Handles persistence of data. Contains schemas and handlers for storage operations.
- Projector: Projects events to a repository, often transforming or aggregating data for read models (CQRS pattern). Projectors handle events only, and may declare correlations that join several events into one command.
- Processor: The generic streaming processor, declared with the
processorkeyword and an optionalas <shape>ascription. - Context: A bounded context is itself a processor, so it may hold handlers and ports of its own.
A Saga orchestrates multi-step processes with compensation logic for failure recovery. A Function defines a pure, reusable computation. Neither is a processor — both extend the vital-definition base — so neither takes a version or a copyright. A Saga does nonetheless bear inlets and outlets, being a coordinator with messages to receive and emit; a Function does not.
All processors can contain handlers, functions, types, constants, invariants, ports, and other processor-specific definitions.
Streaming Shapes¶
A processor's shape describes its streaming arity. It is normally derived
from the number of ports the processor declares, and may optionally be
ascribed with as <shape> to state the intent explicitly:
| Shape | Description | Inlets | Outlets | Synonym |
|---|---|---|---|---|
source |
Produces data from external sources | 0 | 1+ | |
sink |
Consumes data to external destinations | 1+ | 0 | |
flow |
Transforms data passing through | 1 | 1 | cascade |
merge |
Combines multiple streams into one | 2+ | 1 | fanin |
split |
Divides one stream into multiple | 1 | 2+ | broadcast, fanout |
router |
Routes messages based on content | 1 | 2+ | |
void |
Declares no ports at all | 0 | 0 |
streamlet OrderEnricher as flow is {
inlet RawOrders is event OrderEvent
outlet EnrichedOrders is event EnrichedOrderEvent
}
If an ascribed shape contradicts the declared arity, that is an Error. If a processor declares at least one port but ascribes no shape, that is a suppressible StyleWarning nudging you to say what you meant.
Deprecated shape keywords
The dedicated keywords source, sink, flow, merge, split and
router still parse but emit a [deprecated] message (shape-keyword).
Write streamlet <id> as <shape> instead; riddlc prettify does it for
you. They are slated for removal in 3.0.
Referring to a streamlet¶
A reference to a streamlet, such as the target of a tell or a use-case
step, is keyword-led like every processor reference. Any of these keywords
works: streamlet, or any shape keyword (source, sink, flow, merge,
split, router, void). The deprecated processor also still works. So
tell … to streamlet OrderEnricher and tell … to flow OrderEnricher name the
same thing. flow, router, streamlet and processor became reference
keywords in 2.7.0. Before that, a flow or router streamlet could not be
referred to at all.
The keyword is checked against the kind it resolves to (since 2.8.0):
tell … to repository F, where F is a streamlet, is the Error
ref-wrong-keyword. For a streamlet, streamlet, processor and every shape
keyword are all accepted — the shape keyword is not compared with the
streamlet's actual shape, so source F on a flow draws nothing. streamlet is
the spelling that is always right.
flow X in a use-case step is a group
flow is also an alias for a UI group. In the
positions where a use-case step names who acts (send … from, for,
refuses, and both ends of an arbitrary step), flow X is parsed as a
group reference. To name a flow-shaped streamlet there, write
streamlet X.
Domain Hierarchy¶
RIDDL models are organized hierarchically:
- Root: The top-level container for the entire system. Roots are not declared; they consist of the top-level definitions in a file. A Root may contain Modules, Domains, Authors, Versions, Copyrights and Comments.
- Module: A named, flat collection of any top-level definition, in any
order, with no hierarchy enforced at its own top level. The internal rules of
each contained definition still apply. Modules are the unit of reuse and of
compiled (
.bast) output. - Domain: A container for the specification of some knowledge domain.
- Context: Bounded context containing related entities and components.
- Entity: Stateful business objects with commands, events, and handlers.
- Repository: Persistent storage. May live in a Context or, when it synthesizes data across several contexts, directly in a Domain.
- Projector: A component that projects events to a repository for later retrieval, possibly transforming the data or merging multiple event streams.
- Saga: The orchestration of a multi-step atomic process with compensating actions to undo the process when errors arise.
- Epic: A collection of use cases showing an expected usage pattern.
- Case: A specific user interaction flow.
Nebula is deprecated
Earlier releases had an anonymous top-level scratch pad called a nebula.
A Module now does everything a nebula did and has a name. An anonymous
whole-file sequence of definitions still parses, but emits one
[deprecated] message and yields a Module with the synthetic id nebula.
Wrap your definitions in module <Name> is { … } instead.
Data Types¶
RIDDL has a rich type system supporting both simple and complex data structures.
Predefined Types:
- Strings:
String,String(min,max)with length constraints - Numbers:
Integer,Natural,Whole,Real,Number,Decimal(w,f) - Boolean:
Boolean - Temporal:
Date,Time,DateTime,TimeStamp,Duration,ZonedDateTime(zone) - Identifiers:
UUID,UserId,Id(entity path) - Other:
URL,URL(scheme),Currency(code),Location,Nothing,Anything - Physical:
Length,Mass,Current,Temperature,Luminosity,Mole
Anything is the dual of Nothing: a type assignment-compatible with every
other type in both directions. A port typed Anything is compatible with any
port it is connected to.
Abstract is deprecated
Abstract was renamed to Anything. The old spelling still parses to the
same node and emits a [deprecated] message.
Pattern Types:
Pattern("regex")— String matching a regular expression
Compound Types:
- Aggregation:
{ field1 is Type1, field2 is Type2 }— Named field collections - Alternation:
one of { TypeA, TypeB, TypeC }— Union/sum types. An alternation must offer a real choice: zero alternatives is an Error, exactly one draws a[deprecated]message, two or more is clean, andone of { ??? }remains the way to say "not decided yet". May also be written with bars:TypeA | TypeB | TypeCis the identical type.prettifyrewrites bars back toone of { ... }, which stays the canonical spelling. Predefined types are not valid alternatives either way. - Enumeration:
any of { Value1, Value2, Value3 }— Enumerated values
Aggregate Use Cases:
The keyword that introduces an aggregate says what kind of thing it is:
type, command, query, event, result, record, graph, table.
- Graph:
graph— models graph-structured data - Table:
table— models tabular data
Collection Types:
- Sequence:
sequence of Typeormany Type - Set:
set of Type - Mapping:
mapping from KeyType to ValueType - Optional:
optional TypeorType?
Special Types:
- Unique ID:
Id(<kind> Path)— runtime identity of one instance of a processor. Not entity-only; see Instance Identity. This is the canonical way to type a reference to an entity instance:Id(entity Order) - Entity Reference (deprecated):
reference to entity Path, and the shorterreference Path/reference to Path. All of these produce the sameUniqueIdthatId(entity Path)does — they are one construct with five spellings, not two constructs — and they drawtype-reference-to-is-id. WriteId(entity Path); the older forms go on parsing so existing models keep working
Messages and Records¶
There are exactly four messages: command, query, event and result.
Only a message can be sent, told, yielded, or handled by an on clause.
A record is data, not a message. A record can never be sent or handled. It
types an entity's state and supplies the payload of a morph.
Record is no longer a message
In RIDDL 1.x a record reference was accepted wherever a message reference
was. It no longer is. send, tell, yield and on <ref> accept the four
real messages only; state … of and morph … with accept a record.
Basic Syntax Elements¶
-
Readability Words: Optional words that improve human readability of a model.
- The complete list is:
and,are,as,at,by,for,from,in,is,of,so,that,to. - A synonym for
isis:,=, orare. - These words are accepted by the grammar but not required.
- The complete list is:
-
Definition Structure:
- The
[kind]indicates the kind of definition (domain, context, entity, etc.). - The
[name]is the identifier for this definition, which must be unique amongst its peers. - The "definition contents" depend on the
[kind]of definition. - The metadata section must always come after the closing brace of the definition, not within it.
- The
-
Type References: Always specify the kind of reference.
entity Productcommand CreateCartevent OrderCreatedrecord ProductDatauser Customer
Naming Rules¶
How a path identifier resolves¶
Every reference names its target with a path identifier: one or more
identifiers separated by dots, such as Tax.TaxIn or Outer.Deep.Leaf. A
single name and a dotted path resolve by different rules, so they are worth
taking separately.
A single name searches the whole model¶
One identifier with no dots is looked up in the symbol table — a dictionary of every name defined anywhere in the model. If exactly one definition carries that name, that is the answer, wherever it lives. If more than one does, the reference is an ambiguity error listing the candidates; if none does, it is a not-found error.
This is why a bare name can reach a definition in a sibling context without naming it, and why adding a definition elsewhere in the model can turn a working bare reference into an ambiguous one. To make a reference immune to that, qualify it.
A dotted path anchors, then walks down¶
A path of two or more names is resolved in two phases.
Phase 1 — anchor on the first name, tried in this order:
- The literal name
Rootanchors at the root of the model, which makes the rest of the path absolute. - Otherwise, if the name matches one of the ancestors of the place the reference is written, that ancestor is the anchor. The ancestor closest to the reference wins.
- Otherwise the name is looked up in the symbol table, exactly as a single name is: unique anchors the path, ambiguous is an error, absent is an error.
Steps 1 and 2 are the guaranteed forms — they depend only on where the reference is written, so they cannot be broken by a definition added elsewhere. Step 3 is the convenient one, and carries the same ambiguity risk as any bare name.
Phase 2 — walk down, one name at a time. Each remaining name must be found
among the contents of the definition named before it. There is no scope-popping
after the anchor: Tax.TaxIn means "anchor Tax, then look for TaxIn inside
it", and if Tax has no TaxIn the path fails there, even when a TaxIn
exists elsewhere in the model.
context Tax is {
record TaxIn is { subtotal is Natural }
}
context Billing is {
// `Tax` anchors via the symbol table, then `TaxIn` is
// sought among Tax's own contents.
record Invoice is { amount is Tax.TaxIn }
}
What counts as "inside" depends on the kind¶
For most definitions the contents are just the definitions written inside the braces. Several kinds contribute something else, so that paths follow the model rather than the syntax:
| Anchoring definition | What the next name may match |
|---|---|
| State | its own contents (handlers, invariants) first, then the fields of the record it is of — so a handler shadows a same-named field |
| on-clause | the fields of the message being handled |
| Field, Constant, Type | the members of its type expression |
| Inlet, Outlet | the members of the type it carries |
| Function | its own definitions, plus the fields of a deprecated inline requires/returns aggregation |
| Include | the definitions the included file contributes, as though written in place |
Because a State's own contents are searched before the record's fields, a handler named the same as a field is reached by a path, and the field is not. The nearer declaration wins.
Sibling names must be unique, regardless of kind¶
This rule exists because of how paths resolve. Each step of a dotted path picks a definition out of a container by name alone — the kind is never part of the choice — so two definitions sharing a name in one container would leave the step with nothing to decide on.
Uniqueness among siblings is what makes that step well-defined. It does not make a bare name unambiguous, since a bare name is looked up across the whole model: two definitions of the same name in different containers are perfectly legal, and a bare reference to that name is then an ambiguity error at the point of use rather than at either definition.
Two definitions in the same container may not share a name, even when they are different kinds of thing:
context Catalog is {
type Thing is String
entity Thing is { ??? } // Error: 'Thing' is already taken
}
Changed in RIDDL 2.0
Uniqueness used to be checked per kind, so type Thing beside
entity Thing passed with zero errors. It is now an Error.
This is the rule behind a class of confusing failures: with both defined,
a reference such as Id(Thing) had two plausible referents, and which one
it found was not something the model stated.
A definition keyword may not be a bare identifier¶
Eleven keywords introduce a definition, and none may be used as a bare name:
domain, context, entity, adaptor, saga, epic, projector,
repository, streamlet, handler, function
Two escapes, both legal:
handler 'projector' is { ??? } // quoted identifier
handler Projector is { ??? } // the check is case-sensitive
Nothing is wrong with the names — the point is that two introducing keywords in a row leave a reader, and any tool, guessing which word is the keyword. The quoted form says which.
This is deliberately not all 156 keywords. version and copyright, in
particular, remain usable as field and type names; that was a compatibility
decision when they were added, and it stands. The ambiguity only bites where a
word would otherwise start a definition, so that is where the rule bites.
Containment Rules¶
RIDDL follows strict containment rules that define what elements can be defined within other elements.
Root¶
A Root can contain Domains, Modules, Authors, Versions, Copyrights,
Comments, include directives, and import directives.
Module¶
A Module is flat: it can contain any top-level definition, in any order —
types and the four message kinds, constants, invariants, users, contexts,
entities, adaptors, functions, projectors, repositories, streamlets, sagas,
epics, connectors, relationships, authors, versions, copyrights, nested
modules, include and import.
Domain¶
A Domain can contain:
- Types
- Authors
- Contexts (bounded contexts)
- Domains (nested subdomains)
- Users (actors who interact with the system)
- Epics (user stories with use cases)
- Sagas (multi-step processes)
- Repositories (when they synthesize across several contexts)
- Connectors (when they join ports across contexts)
- Versions and Copyrights
- Imports (from
.bastfiles) - Includes (file inclusion)
Context¶
A Context (bounded context) can contain:
- Everything in processor definition contents (below)
- Entities
- Repositories
- Projectors
- Sagas
- Adaptors (message translation between contexts)
- Streamlets and generic processors
- Connectors (linking outlets and inlets)
- Groups (UI components, also called page, pane, dialog, etc.)
- Imports and Includes
Entity¶
An Entity can contain:
- Everything in processor definition contents
- States (with their own handlers and invariants)
- Includes
Processor Definition Contents¶
Every processor — Context, Entity, Adaptor, Projector, Repository, Streamlet — can contain:
- Types
- Constants
- Invariants
- Functions
- Handlers
- Inlets and Outlets
- Nested processors, streamlets, connectors and relationships
- Versions and Copyrights
- Comments and Includes
Leaf Definitions¶
Authors, Users, Terms, Constants, Versions and Copyrights contain only their metadata and cannot contain other RIDDL definitions.
Type System¶
Basic Types¶
UUID,String(min, max),Integer,Decimal(whole, fractional)Boolean,Pattern("regex"),Real,Natural, etc.
Numeric arguments accept a sign: range(-5, 5) and Decimal(-3, 2) mean what
they say.
The three integer types differ by range¶
| Type | Range | Use it for |
|---|---|---|
Integer |
any whole number, signed — … -2, -1, 0, 1, 2 … |
a quantity that may go negative: a delta, a balance, a temperature |
Whole |
non-negative — 0, 1, 2 … |
the counting type: how many, where none is a legitimate answer |
Natural |
positive — 1, 2 …, excluding zero |
the ordinal type: a position, or a quantity for which zero is meaningless |
type Delta is Integer // may be negative
type ItemCount is Whole // zero items is a real answer
type LineNumber is Natural // there is no line zero
The distinction is enforced, not merely conventional: a numeric literal
assigned to one of these is range-checked, so constant N: Natural = 0 is an
Error. A reference is not range-checked — only literals are, because only a
literal has a value the compiler can see.
Natural excludes zero
This catches people out. If zero is a legitimate value — an empty cart, a
balance paid off, a retry count before the first retry — the type you want
is Whole.
Number and Real are separate: Number is the unconstrained numeric type
and Real is floating-point. Neither participates in this ranking.
Complex Types¶
- Record Types: Named collections of fields
record Address is {
street1 is String
city is String
state is String
zipCode is String
country is String
} with {
briefly as "Physical mailing address"
described by {
| Represents a physical address with standard components
| used for shipping and billing purposes.
}
}
- Enumerations:
- Collections:
The yields and replies Clauses¶
A command or query may declare the response it produces. This makes the request/response pairing declarative, so generators can emit precise signatures. RIDDL has two such pairings, and each has its own keyword:
command PlaceOrder yields event OrderPlaced is {
cartId is CartId
}
query GetOrder replies result OrderInfo is {
orderId is OrderId
}
A command yields an event; a query replies a result. The two are
genuinely different acts — emitting an event as a consequence of a command is
not the same thing as answering a question — and a generator lowers them
differently. Crossing them is an Error: yields on a query, replies on a
command, or either naming a type of the wrong kind.
Changed in RIDDL 2.0
Before 2.0 both were spelled yields, and the reply statement was a
deprecated synonym for yield that parsed to the same node. They are now
distinct, and the switch is hard: yields result is an Error
immediately, with no transitional period.
The declaration side was effectively empty in practice — commands widely
declared yields event, while almost no query declared its result — so
replies fills a gap rather than breaking established models.
Both are optional. When declared, the handler for that message must respond
with exactly that message; when not declared, a handler may respond as it
likes. The one place replies is required is a query that something
asks — an ask takes the answer's type from the query's replies, so
there is nothing to read without it.
Type Validation
Errors:
- Defining a type whose name exactly matches a predefined type name
(e.g.,
type Currency is Decimal(10,2)) — this shadows the built-in type and is not allowed yieldsorreplieson a type that is not a command or query- A command whose
yieldsnames a non-event, or a query whoserepliesnames a non-result - Pairing the wrong keyword with the use case:
yieldson a query, orreplieson a command - A
Pattern("…")whose regular expression does not compile (type-pattern-invalid-regex; RIDDL uses Java regex syntax)
Style Warnings:
- Defining a type whose name is a case-variant of a predefined type
(e.g.,
type timestamp is TimeStamp) - A field, method or method argument whose name does not begin with a
lower-case letter (
field-should-be-lowercase,field-method-should-be-lowercase,field-method-arg-should-be-lowercase)
Completeness Warnings:
- Command types with no fields (excluding
???placeholders) - Event types not produced by any handler
- Query types without corresponding result types (and vice versa)
Contexts and Intentions¶
A context may declare its intention — what kind of bounded context it is — with a keyword prefix:
type Request is String
application context Storefront is { ??? }
external context StripePayments is { ??? }
// gateway and service carry SHAPE requirements -- see below
gateway context PublicApi is {
inlet fromWeb is type Request
inlet fromMobile is type Request
outlet inbound is type Request
}
service context Pricing is {
inlet request is type Request
outlet response is type Request
}
| Intention | Meaning |
|---|---|
application |
Presents a user interface. The only place UI may be modeled. |
external |
A third-party system the model does not own. |
gateway |
An entry point that adapts the outside world to the inside. |
service |
An internal service with no user interface. |
The intention is optional; a plain context declares no intention and is
subject to no intention rules.
Intention Validation
Errors:
- A context that contains a
group(or any of its UI aliases) but is not anapplicationcontext. UI belongs at the application boundary. - A
gatewaycontext that is not a merge — it must have 2 or more inlets and exactly 1 outlet. A gateway funnels several outside channels into one inside path, so a portlessgateway context G is { ??? }is an Error: "Gateway context 'G' must have a merge shape (>=2 inlets, 1 outlet) but is void". - A
servicecontext that is not a flow — exactly 1 inlet and 1 outlet. A service takes a request and returns a response. - An
externalcontext modeling persistence it cannot own
application and external carry no shape requirement, so a
placeholder application context A is { ??? } is fine. gateway and
service cannot be stubbed that way: declaring the intention commits you
to the ports.
The gateway, service, external and wrapper options are deprecated
These were previously spelled as options in the with { } block. Use the
intention prefix instead. The options still parse and emit a
[deprecated] message.
Entities and States¶
Entities are stateful objects with explicit states. Each state references a record that defines its data structure, and can optionally contain handlers and invariants that apply while the entity is in that state:
entity Product is {
handler ProductLifecycle is {
on init(start: ProductRecord) is { morph entity Product to state ProductData with start }
}
state ProductData of record ProductRecord is {
invariant PriceIsPositive is price > MinimumPrice
handler ProductHandler is {
on cmd: command UpdatePrice {
set field ProductRecord.price to cmd.newPrice
yield event PriceUpdated(productId = cmd.productId,
newPrice = cmd.newPrice)
}
}
} with {
briefly as "Product state with update handling"
}
} with {
briefly as "Represents a purchasable item"
}
States can also be defined without a body when handlers are defined at the entity level instead:
entity SimpleProduct is {
state ProductData of record ProductRecord
handler ProductHandler is {
on init(start: ProductRecord) is { morph entity SimpleProduct to state ProductData with start }
}
}
Creation: on init chooses the starting state¶
An entity has no initial state (since 2.8.0). It is created without a
state, and its on init clause — the creation clause, run once by
create — morphs it into the state it
starts in. Because on init takes the creation arguments, the starting state
can be chosen from them:
type TableNumber is Integer
record TicketData is { table: TableNumber, note: String }
command Submit is { note: String }
entity KitchenOrder is {
inlet Orders is command Submit
handler Lifecycle is {
on init(atTable: TableNumber, rush: Boolean) is {
when rush then
morph entity KitchenOrder to state Submitted
with record TicketData(table = atTable, note = "rush")
else
morph entity KitchenOrder to state Draft
with record TicketData(table = atTable, note = "")
end
}
}
state Draft of record TicketData is {
handler DraftHandler is {
on s: command Submit {
morph entity KitchenOrder to state Submitted
with record TicketData(table = Draft.table, note = s.note)
}
}
}
state Submitted of record TicketData is {
handler SubmittedHandler is { ??? }
}
}
The rules:
- One
on initper entity, in an entity-level handler. It belongs to the entity, not to any state. - An entity with states must
morphinto one. A stateless entity has nothing to morph into and is exempt. - Declaration order means nothing. Which state is written first no longer
decides anything; the
morphdoes. - In an
event-sourcedentity, theon initinvocation is the first journal entry, and replay re-runs it with the same arguments. Soon initmaysetandmorphexactly as anon eventfold may, and — like a fold — it may not readsystem.noworsystem.random(entity-event-sourced-fold-nondeterministic). A creation timestamp arrives as anon initparameter, supplied by whoever creates the instance. The old idiom of yielding aCreatedevent fromon initonly so that a fold couldmorphis no longer needed.
The old forms are deprecated, and keep their meaning until 3.0
| Deprecated | Rule id | What it still means |
|---|---|---|
initial state X |
entity-initial-state-marker |
The entity starts in X |
An entity with states whose on init does not morph (or that has no on init) |
entity-init-no-morph |
It starts in the initial state, or the first one declared |
on init inside a state's handler |
entity-init-in-state |
It runs only if that is the starting state |
The fix for all three is the same: one entity-level on init that
morphs into the starting state. Two initial states remain an Error
(entity-multiple-initial-states).
Initial Handlers¶
A state may have several handlers, switched between with become. An optional
initial marker says which of them is live when the entity enters the
state:
entity Order is {
handler OrderLifecycle is {
on init(start: PendingData) is { morph entity Order to state Pending with start }
}
state Pending of record PendingData is {
initial handler PendingHandler is { ??? }
handler AuditHandler is { ??? }
}
state Active of record ActiveData is { ??? }
}
Without the marker the first handler declared is the initial one, so marking it
makes the model safe to reorder. More than one initial handler in a state is
an Error. The marker is about handlers only: on a state it is the
deprecated form above.
on entry: a state's entry action¶
Some things must happen whenever the entity enters a state, whichever clause
moved it there. Writing that into every clause that morphs into the state works
only until someone adds a clause and forgets. on entry states it once:
type TableNumber is Integer
record TicketData is { table: TableNumber, note: String }
command Submit is { note: String }
command Reopen is { note: String }
type TicketCommand is Submit | Reopen
event TicketOpened is { table: TableNumber }
entity KitchenTicket is {
inlet Requests is type TicketCommand
outlet Tickets is event TicketOpened
handler Lifecycle is {
on init(atTable: TableNumber) is {
morph entity KitchenTicket to state Draft
with record TicketData(table = atTable, note = "")
}
}
state Draft of record TicketData is {
handler DraftHandler is {
on s: command Submit {
morph entity KitchenTicket to state Submitted
with record TicketData(table = Draft.table, note = s.note)
}
}
}
state Submitted of record TicketData is {
handler SubmittedHandler is {
on entry is {
send event TicketOpened(table = Submitted.table) to outlet Tickets
}
on r: command Reopen {
morph entity KitchenTicket to state Draft
with record TicketData(table = Submitted.table, note = r.note)
}
}
}
}
on entry runs once, after the morph completes, each time a live
morph moves an entity that already has a state into this one. It does
not run:
- At creation. The
morphinsideon initplaces a new instance in its starting state; that is part of creating it, not an entry. Work the starting state needs at creation belongs inon init, which already knows which state it chose. - For a
morphinto the state the entity is already in. Nothing changed, so nothing was entered. The record is still replaced. riddlc warns where this is evident (stmt-morph-to-current-state). - On replay or recovery. In an event-sourced entity a fold's
morphis re-run to rebuild state, and that re-run is not an entry. For the same reasonon entrymay notsetormorphthere (entity-event-sourced-mutation-scope): nothing it changed would be reproduced by replay. - On rehydration. An instance re-entering memory runs
on activate, noton entry. - In a chain.
on entrymay notmorph(entity-entry-morphs): an entry that moved on at once would run the next state's entry, and so on, with nothing to stop it.
It belongs in the handler that is live when the state is entered — the state's
initial handler. Anywhere else it never runs, and is an Error
(entity-entry-misplaced): in an entity-level handler there is no state to
enter, and a state's other handlers are reached only by a later become.
Outside an entity it does not parse. Unlike on activate it is an effect
block: it may send and tell.
Finite State Machines¶
When an entity has multiple states with their own handlers, it models a finite
state machine — each state responds to messages differently, and the morph
statement transitions between states:
entity Order is {
handler OrderLifecycle is {
on init(start: PendingOrderData) is { morph entity Order to state PendingOrder with start }
}
state PendingOrder of record PendingOrderData is {
handler PendingHandler is {
on command ConfirmOrder {
morph entity Order to state Order.ActiveOrder
with record ActiveOrderData()
}
}
}
state ActiveOrder of record ActiveOrderData is {
handler ActiveHandler is {
on command ShipOrder {
morph entity Order to state Order.ShippedOrder
with record ShippedOrderData()
}
}
}
state ShippedOrder of record ShippedOrderData is {
handler ShippedHandler is { ??? }
}
} with {
option is finite-state-machine
}
Entity Validation
Errors:
- More than one
initialstate (entity-multiple-initial-states), or more than oneinitialhandler in a state on entryanywhere but a state's initial handler (entity-entry-misplaced), or anon entrythatmorphs (entity-entry-morphs)- Defining a type whose name exactly matches a predefined type
- An entity with
option finite-state-machineand fewer than two states (entity-fsm-too-few-states)
Deprecations (until 3.0): initial state
(entity-initial-state-marker), an entity with states but no on init
that morphs (entity-init-no-morph), and on init inside a state
(entity-init-in-state). See
Creation.
Warnings:
- Entity Id type defined inside the entity body instead of the containing context (move it to the context level)
- Entity Id type defined at domain level or beyond (scope too broad)
- Entity Id type not defined at all
- An entity whose handlers are all empty (
entity-empty-handlers, a missing-content warning) - A
morphinto the state the clause is already in (stmt-morph-to-current-state): it changes no state, so noon entryruns
Completeness Warnings:
- Command handlers that neither
sendnoryieldan event, and do not refuse. A clause that refuses witherrororrequirehas processed the command — it decided, it declined, and there is nothing to record — so it discharges the obligation. Previously this flagged the honest refusal-only clause, and was silenced by adding asendafter the refusal, which the refusals-before-effects rule makes unreachable: it rewarded exactly the dead code a modeller should avoid. - Query handlers that don't
yieldorsenda result - Entities without any
on queryclause - Entities with no handlers at all (
entity-no-handlers). Since 2.8.0 this is reported once, here; theentity-no-handlers-or-statesError is no longer emitted - A state with no handler, where the entity declares none to cover it
either (
entity-state-no-handlers), reported only when some other state does have one - FSM entities (2+ states) without
morphorbecomestatements (entity-fsm-no-transitions, which replacedentity-fsm-single-statein 2.8.0 and now sees amorphinside a state's handler) - Empty handlers (no statements or only
???) - Handlers containing only
dostatements - Empty
on otherclauses (silently discards messages)
Commands and Events¶
Commands represent requests to change state:
command UpdatePrice yields event PriceUpdated is {
productId is ProductId
newPrice is Price
} with {
briefly as "Command to change a product's price"
}
Events represent state changes that have occurred:
event PriceUpdated is {
productId is ProductId
oldPrice is Price
newPrice is Price
} with {
briefly as "Event indicating a product price change"
}
Command-Event Relationship¶
Commands should always result in one or more events being emitted. This follows the reactive principles of RIDDL:
handler ProductCommandHandler is {
on cmd: command UpdatePrice {
when cmd.newPrice > MinimumPrice then
yield event PriceUpdated(productId = cmd.productId,
newPrice = cmd.newPrice)
else
error "Price must exceed the minimum"
end
}
}
Handlers¶
Handlers define how processors respond to messages. They contain on clauses
that match specific message kinds and execute statements.
On Clause Types¶
| Clause | Purpose | Example |
|---|---|---|
on command X |
Handle a specific command | on command CreateOrder { ... } |
on event X |
Handle a specific event | on event OrderCreated { ... } |
on query X |
Handle a query and yield a result | on query GetOrder { ... } |
on result X |
Handle a result | on result OrderInfo { ... } |
on init |
Create the instance; an entity morphs into its starting state |
on init(n: String) { ... } |
on term |
Execute when the processor terminates | on term { ... } |
on activate |
Execute when an entity is rehydrated | on activate { ... } |
on passivate |
Execute when an entity is evicted | on passivate { ... } |
on entry |
Execute when a morph moves the entity into this state |
on entry { ... } |
on quiescence <window> |
Execute when nothing arrived for the window | on quiescence "PT30M" { ... } |
on other |
Handle any unmatched message | on other { ... } |
A handler takes at most one each of on init, on term, on activate,
on passivate and on other; a second is the Error
handler-duplicate-special-clause. Branch inside the one clause instead.
on init and on term are once-ever lifecycle events. on activate and
on passivate fire on every rehydration and eviction, are entity-only, and
must be side-effect free: send, tell, yield, morph and become are
rejected inside them at parse time.
Creation runs on init, never on activate. A
create puts the new instance in
memory, but that is not an activation: on activate runs only when an
instance that already exists re-enters memory after a passivation. Nor does
a message addressed to an instance that was never created bring one into
being — activation recovers an instance, it never makes one.
on quiescence <window>¶
Fires when the processor instance has handled no message for the whole
window. The clock restarts on every handled message; inside a state's
handler the clause is armed only while that state is active.
handler CartHandler is {
on command ExampleEntityCommand { do "add the item" }
on quiescence "PT30M" { do "treat the cart as abandoned" }
}
The window is a duration literal or a bare path to a Duration-typed constant,
state field or message field — not a let, which is clause-local while the
window sits in the clause header. Validated as a correlation timeout is:
"banana" and "0s" are Errors, and so is a non-Duration path
(handler-quiescence-window-not-duration).
Legal on any handler-bearing processor. At most one per handler
(handler-quiescence-duplicate) and never inside a correlation
(handler-quiescence-in-correlation), which bounds itself with
times out after.
Unlike on activate / on passivate it is an effect block: yield,
tell, send, terminate, morph and create are all legal. In an
event-sourced entity the usual rule holds — change state only through a
yielded event, which is also what keeps replay from re-firing the timer.
quiescence remains a legal identifier; it is recognised only after on.
on every <period>¶
Fires once per period, whatever else happens (since 2.8.0):
handler MeteringBoundary is {
on command ExampleEntityCommand { do "count the usage" }
on every 30 days is { do "roll this period's usage up" }
on every month on last day at 23:00 is { do "close the month" }
}
The difference from on quiescence is the point: handling a message does
not reset it. It is legal wherever on quiescence is, a handler may hold
several, and it is an effect block with the same event-sourcing rule — change
state only through a yielded event. The period is any of the shapes in
Periods and Calendar Schedules; a plain
Duration is a fixed span, so on every 30 days is not "monthly".
Lifecycle clauses take parameters¶
on init and on term may declare a parameter list. Neither is required to.
In an entity with states, on init's parameters are what it chooses the
starting state from — see
Creation. A processor with no
states takes them just as well:
streamlet Meter as source is {
outlet Readings is event RawEvent
handler Lifecycle is {
on init(sensorName: String) is { do "open the sensor named by sensorName" }
}
}
on init's parameters are how a business key — an order number, an email —
reaches an instance whose Id is opaque and
system-generated. on term's parameters are pure payload: a clause needing
the instance it is ending reads self.id, which is in scope for the whole body
and stays live to its very end.
on other can bind the envelope¶
on other may bind the residual message's envelope — not a message, since
what arrived did not match any clause:
This is legal only where an option message_envelope(...) is in scope: without
one there is no envelope type, and envelope would have nothing to be. RIDDL's
predefined Riddl.Envelope carries the CloudEvents v1.0 context attributes —
note its id field is spelled messageId. The option is scope-inherited, so
declaring it on a context covers everything within.
Reading a field through the binding¶
m.<field> resolves in two steps: the envelope's own fields first, then a
field common to every message that could still reach this clause. What can
reach an on other is the processor's dataflow-inlet types — alternations
expanded — minus whatever the sibling on <message> clauses already take,
since on other is the case _ of the handler.
"Common" is strict: every remaining member must carry that field, at the same
type. Where only some do, or they disagree on the type, the reference is the
Error handler-on-other-field-not-common — the clause would otherwise read a
field that half its possible inputs do not have. A processor with no inlets,
or one where no message is left over, behaves as it always did.
Naming the Handled Message¶
An on clause may bind a local name to the message it is handling, using
ordinary type ascription. Within the body the name denotes the whole message:
handler H is {
on ord: command PlaceOrder {
yield event OrderPlaced(id = ord.id, total = ord.total)
}
}
The binding is optional, so every existing model parses unchanged. A local name that shadows an outer definition is legal but draws a Warning; a name that does not begin with a lowercase letter draws a StyleWarning.
Message Origins¶
An on clause may name where the message came from:
Basic Handler Example¶
handler ProductCommandHandler is {
on upd: command UpdatePrice {
when upd.newPrice > Zero then
set field ProductRecord.price to upd.newPrice
yield event PriceUpdated(productId = upd.productId, newPrice = upd.newPrice)
else
error "Price must be greater than zero"
end
}
on query GetProduct {
reply result ProductInfo(ProductRecord.id, ProductRecord.price)
}
} with {
briefly as "Processes commands for product management"
}
Handler Locations¶
Handlers can be defined at multiple levels:
- Entity handlers: Default message handling for the entity
- State handlers: Message handling specific to a state
- Context handlers: API-level handlers for the bounded context
- Processor handlers: Handlers in Repository, Projector, Adaptor, etc.
An entity-scope handler may be marked initial, which makes it the initial
handler for every state that does not define one of its own — a default
across the whole state machine rather than a per-state choice. Where no marker
appears, an entity-scope handler is defaulted to initial only when the entity
has exactly one state.
Declaring more than one initial handler at entity scope is an Error,
regardless of how many states the entity has. Verified against
2.0.0-rc.9-54.
Handler Kind Rules
Errors, enforced at parse time where possible:
- A projector is event-only:
on command,on queryandon recordare rejected.on eventandon resultare valid. requireanderrorare forbidden inon event— an event has already happened and must always be accepted.on activate/on passivateoutside an entity, or containing an effect statement.- An adaptor handler with no
on otherclause. An adaptor must say explicitly what it does with messages it does not recognize.
Style Warnings:
- Two
onclauses in one handler that handle the same message. The later clause is unreachable.
Invariants¶
An invariant is a named boolean rule. Its full form is:
Implicit Application¶
An invariant applies to every clause of its declaring scope, checked as a precondition before any effect in that clause. No statement at the point of use is needed.
Changed in RIDDL 2.0
Previously an invariant did nothing unless a clause named it in require
invariant X, which made it easy to carry a constraint that read as enforced
and was inert. Every invariant now applies — including ones you also
require explicitly, because otherwise adding a single require would
silently narrow a rule from enforced-everywhere to enforced-there.
Condition Forms¶
invariant Legacy is "the account must be in good standing"
invariant InStock is quantity >= Zero
invariant CanCoverFee is {
let available = call function Available(held = holdAmount, total = balance)
available >= minimumFee
}
A condition takes a full expression
Arithmetic, counts and quantifiers are all available inside a condition —
balance - holdAmount >= minimumFee is a legal invariant, and so is
count of items > MinimumOrder.
Two restrictions that used to apply are gone: the boolean sub-language now
has a numeric literal atom (so amount >= 0 parses), and a let may bind
an expression rather than only a reference or a call. A literal operand
is legal but draws a style warning,
value-literal-comparison-style — a named constant says what the
threshold means, so quantity >= MinimumStock reads better than
quantity >= 3. Zero is exempt (since 2.8.2): quantity >= 0 needs no
name, because zero means itself.
A literal string is an AI-fill site. A boolean expression or a block already is the predicate. The block form admits the statements a pure function may contain, ending in the boolean that is the predicate.
Scope and Readable Fields¶
The declaration decides both — never the call site:
| Declaration | Applies to | May read |
|---|---|---|
in an entity, no requires |
every clause of that entity, including its states' handlers | fields present in every state record |
| inside a state S | that state's handlers only | S's record fields |
in an entity, requires state S |
that entity's clauses while in state S | S's record fields |
requires <type T> |
nothing implicitly — explicit only | the value handed to it |
| on a context or other stateless processor | nothing implicitly — explicit only | the value handed to it |
The intersection rule. An entity-level invariant reading balance forces
every state record of that entity to have a balance field. Referencing a field
absent from any state record is an Error.
A stateless processor has no ambient data for an implicit predicate to read, so an invariant declared on one must name what it needs and be invoked explicitly:
record Limits is { ceiling: Integer, used: Integer }
invariant UnderLimit requires record Limits is used <= ceiling
The clause then hands it the value:
A nested function is private¶
A path identifier may descend into a function to reach a definition nested inside it — the path grammar is generic and needs no special case.
But a function nested inside another function is that function's private implementation. Calling it from outside its parent draws a StyleWarning: the nesting is how a model says "this is an internal step", and reaching past it ignores what the author said.
Purity¶
An invariant block may contain only the statements a pure function may contain:
no state writes, no send/tell, no morph/become/yield/reply. An
invariant may not send even a read-only query — doing so would make the
predicate asynchronous, fallible, non-deterministic and no longer structurally
terminating. The clause gathers; the invariant receives.
A function may read no entity state at all; an invariant may read the state its declaration names. That asymmetry is deliberate — an invariant is a predicate over state, evaluated inside the entity's single-writer window, with its readable fields bounded by its declaration.
Failure Modes¶
| Applied | Failure is a | Result |
|---|---|---|
explicitly, at require invariant X |
refusal | modeled outcome — an error result naming the rule |
| implicitly | fault | exception plus rollback; does not widen the clause's result type |
Invariants in scope are checked in declaration order; the first failure is reported.
Implicit invariants are skipped in on init — that clause is where state
comes into existence. They apply in on term, and they apply in on
event clauses. The last is not a contradiction of the rule forbidding
authored require/error in on event: that rule bars refusing an event,
and an implicit violation faults and rolls back rather than refusing, so the
event remains a fact.
Diagnostics¶
- An invariant declaring
requires <type T>that norequire invariant X with <expr>ever invokes draws a warning — it is inert. - An entity-level invariant referencing a field absent from any state record is an Error.
See the Invariant concept page for the reasoning behind these rules.
Value Expressions¶
RIDDL 2.0 introduces a real value-expression system. Wherever a statement needs a value, it accepts any of these forms:
| Form | Syntax | Meaning |
|---|---|---|
| Literal | "some text" |
Opaque pseudo-code or a literal constant |
| Empty | empty, none, empty Tags |
The minimum-cardinality inhabitant of a type; typed by its position, or by an ascription that names a type |
| Value reference | order.total |
A named field, state field, function input, or let local |
| Constructor | OrderPlaced(total, id = x) |
Builds a message or record |
| Get | get from input SignupForm |
Reads a UI input or an entity state |
| Call | call function Pricing.Total(a, b) |
Invokes a pure function for its result |
| Prompt | prompt("compute the discount") [as <type>] |
A value computed by AI at generation time; the optional ascription states its type |
| Boolean | a > b and not c |
A structured boolean expression |
| Arithmetic | subtotal + amount * rate |
+ - * / on numbers, + on strings, a timestamp ± a duration |
| Duration literal | 30 days, 1.50 hours |
A duration value written in units rather than as a string |
| Constant reference | constant MaxItems |
A named constant's value; the bare name works too |
| Collection predicate | all of items as i where i.quantity > Zero |
all of / any of / none of — a boolean |
| Filter | items as i where i.quantity > Zero |
The matching elements — not a boolean |
| Count | count of items |
How many elements, as a Whole |
| Map | each of items as i yielding i.sku |
A new collection, one projected value per element; optional where filter (2.8.3) |
| Membership | tags contains "urgent" |
Whether the collection holds that value |
| Sum | sum of lines as l by l.quantity |
The total, of the elements or of a per-element product |
| One of | one of lines as l where l.sku == s |
The matching element, or empty |
| Default | nick otherwise "guest" |
The left side unless it is empty |
| Conditional | when c then a else b end |
One of two values; only the chosen one is evaluated |
| Duration units | minutes of grace |
A Duration as a whole number of units |
| Query | query one reservations where id == q.id |
Reads stored rows; legal only in a repository |
A Literal Is Held to Its Position's Type¶
A written number or string has a type its text decides, and since 2.8.0 it
must fit the position it is written in — a field, a constructor or call
argument, a let with a declared type:
record Booking is {
guests: Natural, vip: Boolean, onDate: Date, startsAt: DateTime, madeAt: TimeStamp
}
command Book is { name: String }
event Booked is { booking: Booking }
entity Reservation is {
inlet Requests is command Book
outlet Bookings is event Booked
handler Desk is {
on command Book {
send event Booked(booking = record Booking(
guests = 4, vip = 0, onDate = "2026-11-18",
startsAt = "2026-11-18T19:30", madeAt = system.now
)) to outlet Bookings
}
}
}
| Position | Accepts | Refused (an Error) |
|---|---|---|
| A number of a constrained range | a number in range | -3 for a Natural (value-not-natural) |
Boolean |
true, false, and the integers 0 and 1 |
any other number (value-type-mismatch) |
Integer |
a number, or a Boolean (true = 1, false = 0) |
a string |
String, Currency, a record |
a value of that type | a number (value-type-mismatch) |
Date |
"2026-11-18" |
any other string shape (value-time-literal-not-iso8601) |
DateTime, TimeStamp |
"2026-11-18T10:30", optionally with :ss, a fraction, and Z or ±hh:mm |
a date alone, or anything not ISO-8601 |
Three details:
- No literal fills a
Currency. A number,"1.00"and"USD 1.00"are all refused; pass aCurrency-typed reference, such as the handled command's own amount. - A String-typed reference is still accepted for a time field. Its value is invisible to the validator, so only a written string is checked.
TimeStamp→DateandTimeStamp→DateTimeare intended conversions.onDate = system.nowis correct: the generator takes the date part, or keeps the instant.
An optional value where one is required is an Advisory
Supplying a T?, T* or T{0,n} value where the position's minimum is
one is legal, and draws the Advisory value-optional-for-required:
whether the value is empty is a run-time fact, so the generator decides
how the empty case is handled. A guard the model states settles it —
inside when x != empty then, the else of x == empty, each conjunct
of an and, and everything after require x != empty or after a
when x == empty then error … end, the value is proven present and draws
nothing. x otherwise y supplies the
default inline instead.
Arithmetic¶
+ - * / apply to numbers; + also concatenates two strings; and a timestamp
takes a duration added or subtracted. There is no power, root or math function —
those remain a prompt("…"), because RIDDL specifies what is computed and a
model that needs a logarithm is describing an implementation.
set field grandTotal to subtotal + amount * rate
set field balance to balance - amount
log "order " + orderId
The result type is the smallest constrained numeric type that contains both operands and the result:
| Operands | Result | Why |
|---|---|---|
Natural + Natural |
Natural |
a sum of non-negatives cannot go below zero |
Natural - Natural |
Integer |
a difference can |
Integer / Integer |
Integer |
truncating — RIDDL does not silently widen to a fraction |
Integer + Real |
Real |
|
Decimal + Decimal |
Decimal |
|
Real + Decimal |
Number |
no constrained type contains both faithfully |
Mixing what cannot be combined is the Error
value-arithmetic-operand-mismatch, which names both types — a String plus a
Natural, for instance.
Durations¶
A duration may be written in units rather than as a string: 30 days,
1.50 hours, 250 milliseconds. The unit is a word, singular or plural, from
nanoseconds up to weeks. Abbreviations (30d) and ISO-8601 (PT30M) are not
accepted here.
Two places keep their string durations, because they are clause headers
rather than value positions: the on quiescence "<window>" window and a
correlation's times out after "<duration>".
system.now is the only spelling of the current instant. Added to or
subtracted from a duration it gives another instant, which is what makes
send … at system.now + 30 days work.
Periods and Calendar Schedules¶
A period says how often something recurs. It is what follows every, in
both recurring forms — a timer clause and a
recurring send — and since 2.8.0 it
takes one of three shapes:
| Shape | Examples | Means |
|---|---|---|
A positive Duration |
30 days, 1 hour, "PT15M", "30 minutes", a Duration constant or field |
A fixed span: every 30 days, not "monthly" |
| A calendar schedule | month on day 1, weekday at 08:30 |
A calendar cadence, read in local time |
| A cron text | cron "0 9 1 * *" |
Exactly the standard five-field cron, for what the words cannot say |
The calendar cadences:
on every month on day 1 at 09:00 in "America/Toronto" is { do "open the billing cycle" }
on every month on last day is { do "close the books" }
on every month on the third wednesday at 10:00 is { do "hold the review" }
on every 3 months on day 1 is { do "report the quarter" }
on every year on march 31 at 17:00 is { do "close the fiscal year" }
on every year on the first monday of september is { do "start the season" }
on every day at 06:00 is { do "open the kitchen" }
on every weekday at 08:30 is { do "send the stand-up digest" }
on every monday, wednesday and friday is { do "restock" }
on every cron "0 9 1 * *" in "UTC" is { do "the same as the first line, in UTC" }
at HH:MM[:SS]is optional, and defaults to midnight.in "<zone>"is optional, and defaults to UTC. The schedule is read in that zone's local time, soday at 06:00 in "Europe/Paris"stays at six in the morning across a daylight-saving change. A zone is an IANA zone id that exists, such as"America/Toronto", or an offset such as"+05:30". Anything else,"Mars/Olympus"included, is the Errorvalue-time-zone-malformed.- A day a month lacks is skipped, not moved.
on day 31fires in seven months a year andfebruary 29only in leap years. riddlc gives the Advisoryvalue-schedule-day-skips-monthsand recommendson last day, the month-end idiom. - None of the words is reserved. A whole schedule wins over a value of
the same name (
every dayis daily even beside a constantday), butevery monthwith noon …anchor still names a value.
Schedule validation
Each is an Error: a non-positive Duration
(value-non-positive-duration), or a Duration with no unit
(value-vague-duration); a period that is not a Duration at all
(handler-every-not-duration in on every, stmt-send-every-not-duration
in a send); a day of the month outside 1–31
(value-schedule-day-out-of-range); a date no year has, such as
february 30 (value-schedule-date-never-exists); an interval of zero
(value-schedule-interval-not-positive); a weekday named twice
(value-schedule-duplicate-weekday); a time past 23:59:59
(value-schedule-time-out-of-range); a cron text without exactly five
fields (value-cron-malformed); and a malformed zone
(value-time-zone-malformed).
Calendar periods in arithmetic¶
1 month and 2 years are calendar periods, not Durations — a month has
no fixed length. They are legal only added to or subtracted from a Date,
DateTime, ZonedDateTime or TimeStamp, and the result keeps the operand's
type:
Month-end clamps: January 31 + 1 month is the last day of February, and
February 29 + 1 year is February 28. TimeStamp arithmetic is in UTC, a
ZonedDateTime's in its own zone. Note the contrast with a schedule: a
schedule skips a missing day, while arithmetic clamps to the month's
last day. A period anywhere else — count + 1 month — is
value-arithmetic-operand-mismatch.
Constants¶
A constant's value may be an expression, so long as every operand is itself fixed — a literal, a duration literal, or another constant:
constant PointsPerDollar is Natural = 5
constant Bonus is Natural = PointsPerDollar * 2
constant Window is Duration = 30 days
is, : and = are interchangeable as the readability word, so
constant Bonus: Natural = PointsPerDollar * 2 says the same thing.
An operand that is not fixed is the Error constant-operand-not-constant — a
field or a let cannot appear here, because a constant is resolved once, before
anything runs. A value that does not fit the declared type is
constant-expression-type-mismatch.
In an expression a constant may be named plainly (MaxItems) or explicitly
(constant MaxItems); both resolve to the same thing.
Empty and None¶
empty is the minimum-cardinality inhabitant of a type — no value at all.
none is a synonym producing the identical AST; prettify converges both on
empty.
set field nickname to empty
set field tags to none
let noTags = empty Tags
when tags == empty then ??? end
Every value in RIDDL is typed, and empty is one of only two values whose
spelling does not say which type (the other is prompt(…)). So it gets its type
one of two ways:
- From its position. A bare
emptytakes the type of whatever it fills: the field it is assigned to, a constructor or call argument, alet's declared type (let t: Tags = empty), an output, a function'sreturns, a stored row, or the operand opposite it in a comparison — which is what makestags == emptylegal. - From an ascription, where no position supplies one.
empty Tnames the type, andTis a type NAME, never a type expression. Declaretype Tags is String*and writeempty Tags;empty String*is the Errorvalue-ascription-not-a-name. A bareemptywith no type anywhere isvalue-empty-untyped.
An ascription must be syntactically the position's declared type, or it is
value-empty-ascription-contradicts. A field declared inline (tags is
String*) has no name to restate, so it takes only a bare empty.
It is legal exactly where the minimum cardinality is zero — T?, T* or
T{0,n}, read through any type names. A bare T or a T+ demands at least one
value. Ascribing such a type is value-empty-needs-zero-cardinality; a bare
empty in such a position is value-empty-not-allowed.
A type name is a bare path and statements have no terminator, so the parser
stops an ascription at any word that can follow a value — a statement keyword,
a readability word such as to, in or where, or any reserved word that
cannot begin a type. That is why put empty to …, store empty in … and
update T set f = empty where … read as intended.
Constructors¶
A constructor builds a message or a record inline. Arguments are positional first, then named:
An empty argument list is an arity of zero and must match like any other,
so OrderPlaced() against a message that has fields is an Error.
Argument count, names, ordering and (best effort) types are all checked against the target's fields.
An operand may name a VALUE, not only a type
send, tell, yield, reply and morph all take an operand saying
which message or record is being delivered. That operand may be a bare
name already in hand — an on-clause binding, a state field, a let local,
or a function input:
Naming a message type says nothing about where the value comes from, which is most of what a generator needs to know. A bare type reference still parses and still means "some value of this type", but it draws a CompletenessWarning — and the intended end state is an Error, deferred only because the reference corpus holds over fourteen thousand of them.
morph gets the same freedom with a different rule: its operand is checked
for type-conformance against the target state's record, since the
message-operand test would reject every correct use.
Duplicates are Errors
A repeated field name in an aggregate — command C is { x is String, x
is Integer } — is an Error. A repeated name makes the aggregate's
shape ambiguous, so every consumer would have to pick one silently. Both
locations are named in the diagnostic, because the author is looking at one
and needs the other.
A repeated constructor argument — C(x = 1, x = 2) — is the same
mistake at the call site, and is likewise an Error.
Correlations¶
A correlation accumulates several events, keyed by one or more fields, into a
single command the repository handles. It is legal only inside a
projector.
correlation <Id> by <field> {, <field>} yields command <CmdRef> is {
handler <Id> is { <on-event clauses that set the command's fields> }
} times out after "<duration>" { <statements> }
correlation FulfillmentJoin by customerId, orderId
yields command RecordFulfillment is {
handler Collect is {
on event OrderPlaced { set field RecordFulfillment.total to "the total" }
on event PaymentTaken { set field RecordFulfillment.paidAmount to "paid" }
}
} times out after "30 days" {
tell command ReportStalled to entity Monitor
}
Four rules carry the meaning:
- Identity is the full key tuple, ordered as written and never canonicalized.
- Completion is derived from the target command's type — every required field set by some fold. Key fields are exempt, being filled from the key.
times out afteris mandatory, so an unbounded correlation cannot be written. Its duration is an ordinary string.- The target must be a command, because a repository is changed by handling
one;
yields record Ris deliberately not derivable.
Errors
- A required non-key field of the target that no fold sets — the correlation could never complete.
- Two folds setting the same field — the completed value would depend on arrival order, which across sources is not guaranteed.
Typed holes: prompt("…") as <type>¶
prompt(...) may carry an optional type ascription:
That is a typed hole, and it is the seam between RIDDL's two tiers: the type is known and checkable at compile time, while the computation that produces a value of that type is prose an AI fills in at generation time. The deterministic tier parses, validates and type-checks; the AI tier is the string inside the parentheses.
The ascription restates the position's type; it never overrides it. A
let takes its type from the ascription, but in a position that already
determines the type — a constructor argument, a field — the ascription must
agree with it. Writing one is opt-in: unascribed prompt(...) is unchanged and
still valid, and is the right form wherever the position already says enough.
When written, the ascription is a type NAME, exactly as for empty. A bare
predefined type — Real, Boolean, TimeStamp, String — is a name;
String(1,30) and Recipe* are type expressions, and ascribing one is the
Error value-ascription-not-a-name. Declare the type and name it.
Get¶
get from reads a value from a UI input or an entity state:
record HamperData is { total is Natural }
command AddItem is { sku is String }
entity Hamper is {
handler HamperLifecycle is {
on init(start: HamperData) is { morph entity Hamper to state Collecting with start }
}
state Collecting of record HamperData is {
handler HamperHandler is {
on command AddItem {
let current = get from state Collecting
}
}
}
}
The two forms cannot share a clause. An input exists only inside an
application context, and state may be read only inside the entity that
owns it — reading another definition's state is an Error.
Call¶
call invokes a function — and only a function, because functions are the
only pure definitions — and produces its result:
Calling something with no declared returns is an Error.
Boolean Expressions¶
Boolean expressions have the usual precedence, with the two arithmetic levels sitting between a comparison and its atoms:
* and / bind tighter than + and -, all four fold left, and parentheses
group. count of binds tighter than arithmetic, so count of items + 1 is
"one more than the number of items".
Binary minus wants whitespace on its left
a - 3 subtracts; a-3 is a single identifier, because a hyphen is a
legal character in a RIDDL name. This bites only the minus: a+3 and
a*3 are unambiguous. Write spaces around every operator and the question
never arises.
An invariant takes one too, though it is a definition rather than a statement:
and, or, not, true and false are context-sensitive: they are
recognized only inside a boolean expression, so they remain legal identifiers
everywhere else.
! is another spelling of not¶
! is a prefix operator and a plain alternative spelling of not, legal
wherever a boolean expression is — a when condition, a require, a let
initializer, inside parentheses, and applied before a comparison:
when !order.isPaid then error "not paid" end
require !order.isCancelled
let stillOpen = !(order.isPaid and order.isCancelled)
when !!order.isPaid then ??? end
The two are fully interchangeable. There is no difference in meaning, precedence or associativity, and both produce the identical AST node — there is no hidden "which spelling was written" flag a generator could observe.
The pretty-printer emits not. A model written with ! converges to not
on output, the same way A | B converges to one of { A or B }: RIDDL is meant
to stay readable by people who are not computer scientists.
! and != are unrelated
a != b is the ordinary "not equal" comparison operator. The ! in it
is part of one two-character token — it is not the negation operator being
applied to = b. !x and x != y share a character and nothing else.
Comparisons are type-checked, not syntactically restricted
Either operand may be any expression — a reference, a literal, a
get from, a constant, arithmetic, a count of. What may sensibly be
compared is validation's question, not the grammar's, so a nonsense
comparison is reported by the validator rather than refused by the parser:
count > "5" is the Error value-ordering-needs-numeric, naming the types
it got.
== and != require operands of the same category; <, >, <= and
>= require an ordered type — numeric, timestamp or duration — on both
sides.
A literal operand is legal and draws the style warning
value-literal-comparison-style, except zero, which is exempt (2.8.2).
Naming the value is still better style, because the name records the
intent:
constant MaxItems is Natural = 100
// ...
when cart.itemCount > MaxItems then error "too many items" end
(This reverses an earlier rule. Through 2.2 both operands had to be typed references and every literal failed at parse time; 2.3.0 lifted that.)
Quantifying over a collection¶
all of, any of and none of turn a collection and a predicate into a
boolean. The element binding is explicit and scoped to the predicate:
when all of order.items as line where line.quantity > Zero then ??? end
when any of cart.tags as tag where tag == "urgent" then ??? end
when none of order.items as line where line.sku == "" then ??? end
when count of order.items > MinimumOrder then ??? end
when cart.tags contains "urgent" then ??? end
On an empty collection, all of is true and any of is false —
the usual reading of "every element satisfies it" when there are no elements.
none of is likewise true.
Every one of these forms — the quantifiers, a filter, count of and
contains — needs a collection: a T* or T+ field, a set of,
sequence of, mapping or table. Anything else, such as a String, is the
Error value-not-a-collection. The value contains tests must be of the
element type: tags contains 5 on a String* is the Error
value-membership-type-mismatch.
Dropping the quantifier gives a filter, whose value is the matching elements rather than a boolean:
A filter is not a boolean, so when order.items as line where … does not
parse. Pass it to count of, bind it with let, or quantify it.
Mapping a collection¶
Since 2.8.3, each of … yielding turns every element of a collection into a
new value, optionally filtering first:
let skus = each of order.items as line yielding line.sku
let bigOnes = each of order.items as line where line.quantity > Zero yielding line.sku
let lines = count of (each of order.items as line yielding line.sku)
The element binding — line here — is in scope only in the where
filter and the yielding projection. The projection may be any value
expression.
The result is a collection of the projection's type, and its cardinality follows the source:
| Source | Filter? | Result |
|---|---|---|
T+ |
no | U+ — mapping a non-empty collection cannot empty it |
T*, a set of, anything else |
no | U* |
| any | yes | U* — a filter may remove every element |
So a filtered map passed where a U+ is required draws the
value-optional-for-required Advisory: the
model asks for at least one element and the filter may leave none. A
projection of the wrong type is the usual value-type-mismatch Error at the
position that receives it.
Parenthesize the map when it is an operand
The projection is a full value, so it runs to the end of whatever follows
yielding. As an operand of any operator, write the map in parentheses:
count of (each of xs as x yielding x.sku) > Limit— without the parentheses,> Limitbelongs to the projection and the line does not parse.(each of xs as x yielding x.sku) otherwise fallback— without them this parses and validates silently with a different meaning: theotherwiseapplies to each element'sx.sku, not to the collection.
A map that is the whole operand of count of or the whole right-hand side
of a let needs none.
each and yielding are not reserved words; they remain legal identifiers.
riddlc find -type collection-map lists every map in a model.
Why this took until 2.8.3
Until 2.8.3 this section said there was deliberately no map, because a
transformation would build a collection whose shape is declared nowhere.
The typing rule above answers that: the result's element type is the
projection's type, which the model does declare, and its cardinality is
derived from the source. Nothing about the shape is invented.
Totals, matches, defaults and choices¶
Since 2.8.0 a value can also total a collection, pick one element of it, fall back when something is empty, and choose between two values:
let units = sum of order.lines as l by l.quantity
let line = one of order.lines as l where l.sku == note
let wanted = line.quantity otherwise 1
let greeting = cart.nickname otherwise "guest"
let size = when units > MinimumOrder then "large" else "small" end
let hoursLeft = hours of (order.dueAt - system.now)
| Form | Value | Type |
|---|---|---|
sum of xs |
The total of the elements; an empty collection sums to zero | The element's type; numbers, Duration and Currency add, and Natural sums to Whole |
sum of xs as e by <expr> |
The total of <expr> per element |
<expr>'s type, as above |
one of xs as e where p |
The element satisfying p — the first match in a sequence — or empty when none does |
The element type, made optional |
x otherwise y |
x, unless it is empty; then y, evaluated only in that case |
x's type, without the optionality |
when c then a else b end |
a if c holds, else b; only the chosen branch is evaluated |
The branches' common type |
minutes of d (any plural unit, nanoseconds … weeks) |
A Duration in whole units, truncated toward zero |
Integer |
Optional chaining. A path may pass through an optional field, and what it
reaches is optional: with line: Line?, line.quantity is an optional
quantity — which is how one of composes with the field after it. Collections
do not chain, and a foreach … in path through an optional is still refused.
Precedence. <unit> of d and sum of bind tighter than arithmetic, so
minutes of d + 1 is (minutes of d) + 1. The projection after by is a
product, so one that adds is parenthesized: by (e.a + e.b). otherwise is
the loosest value operator: a + b otherwise c is (a + b) otherwise c,
and its result is used in an expression only inside parentheses:
(x otherwise 0) + 1. Parentheses accept any value, not only a boolean.
A conditional value is closed by end, so it needs none; its else is
mandatory, and a multi-way choice nests another when in it.
None of the words is reserved. sum, count, hours and days remain
legal field names.
Validation
<unit> ofsomething that is not aDuration:value-duration-units-not-duration.sum ofelements that do not add (a record, a string):value-sum-not-summable.x otherwise ywhereycannot stand in forx:value-otherwise-mismatch. A literal default is checked like any literal, somaybeN otherwise "x"for an integer isvalue-type-mismatch.x otherwise ywherexcan never be empty draws the style warningvalue-otherwise-never-empty: the default is dead.- Conditional branches with no common type:
value-conditional-branch-mismatch. Numbers of different kinds join; a bareemptybranch makes the result optional.
otherwise: a default for empty¶
otherwise is also what the value-optional-for-required Advisory suggests
first, before a when x != empty guard: supplying an optional value where one
is required, with the default stated inline, settles what the empty case
means.
Statement Syntax¶
Morph Statement¶
Changes entity state. The payload is a record — a bare record reference or an inline constructor:
Send Statement¶
Emits a message on one of this processor's own outlets. A connector then routes it to a downstream inlet:
send event ItemAdded(sku = "the item") to outlet CartEvents
send command ProcessPayment(orderId) to outlet PaymentRequests
send … to inlet is deprecated
Sending directly into another processor's inlet bypasses the streaming
model — that is tell's job. outlet is the canonical send target. The
inlet form still parses and emits a [deprecated] message; it is slated
for removal in 3.0.
The portlet's type is a contract
A send naming a message the portlet's declared type does not admit is
an Error. The portlet's type is what the connector and every downstream
consumer are built on, so a consumer typed by it simply cannot receive the
value.
Sending the same value twice is two messages
One statement list that puts the same value onto the same outlet
twice draws a Warning (stmt-duplicate-send-same-outlet, since 2.5.0).
It counts send, forward, and a tell whose only route is that outlet.
Each transmission gets its own message id, so the receiver sees two
distinct deliveries and no downstream deduplication will recognise them as
one. If that is what you meant, the warning is harmless: it does not block
code generation, and a generator must deliver both.
Scheduling a delivery: send … at <instant>¶
An optional at clause states when the message should be delivered:
send event ItemAdded(sku = order.id) to outlet CartEvents at order.dueAt
send event ItemAdded(sku = order.id) to outlet CartEvents at system.now
send event ItemAdded(sku = order.id) to outlet CartEvents at system.now + 30 days
The instant must type as TimeStamp, DateTime or ZonedDateTime (through
aliases). It may be any expression of that type: a message or state field, a
constant, system.now, or — since 2.3.0 — a timestamp with a duration added
or subtracted, as the third line shows. A Date or a String is an Error —
stmt-send-at-not-instant, which names the type it got.
It states an instant, never a mechanism. Whether that becomes a timer, a scheduler entry, a delay queue or a poll is the generator's choice, and RIDDL deliberately does not say.
Two consequences worth planning around:
- A past instant is delivered immediately. There is no error and no discarding; "at" means "no earlier than".
- There is no cancellation construct. The idiom is to schedule to yourself and decide at fire time, so any receiver of a scheduled message must tolerate it arriving stale — the booking it refers to may already be cancelled.
send only. tell m to x at t already parses as something else, so tell
does not take at. Everything else about send is unchanged: it is a
transmission rather than a local state change, it does not discharge a
yields obligation, and outlet ownership and portlet typing apply exactly as
above.
Recurring delivery: send … every <period>¶
every in place of at makes a send recur (since 2.8.0):
command CloseMonth is { periodEnd: TimeStamp }
constant FirstClose: TimeStamp = "2026-12-01T00:00:00Z"
record MeterData is { count: Integer }
entity Meter is {
inlet Closes is command CloseMonth
outlet Clock is command CloseMonth
handler Lifecycle is {
on init is {
send command CloseMonth(periodEnd = system.now + 30 days) to outlet Clock
every 30 days starting at FirstClose
send command CloseMonth(periodEnd = system.now) to outlet Clock
every month on day 1 at 09:00
morph entity Meter to state Counting with record MeterData(count = 0)
}
}
state Counting of record MeterData is {
handler CountingHandler is {
on command CloseMonth { do "close the month" }
}
}
}
connector MonthClock is { from outlet Meter.Clock to inlet Meter.Closes }
send <msg> to <outlet> every <period> [starting [at] <instant>]:
- Only in
on init. Anywhere else it is an Error (stmt-send-every-not-in-init): every message the clause handled would register one more recurrence. - Without
starting, the first delivery is one period after thesendruns.startingis typed exactly asatis —TimeStamp,DateTimeorZonedDateTime— and with a calendar schedule it means the first occurrence at or after that instant. - The message is re-evaluated at every firing, so
system.nowin it is the time of each delivery. - There is no cancellation: it ends with the instance.
A rescheduling clause is not a loop
An on X clause that sends X again at <instant> + <duration> is a
recurrence, and stream-graph-cycle no longer reports it (2.8.0). Any
other instant still counts as a loop, since a past instant is delivered
immediately.
Both portlet kinds are checked, and both sides expand through alias chains. To carry more than one message on an outlet, declare its type as an alternation of everything that may travel on it:
The same rule applies to forward on its portlet
shape. tell is not checked this way — it names a processor, which has no
single declared type.
Tell Statement¶
Delivers a message directly to a processor:
tell command EscalateReview(orderId) to entity Review
tell command ProcessPayment(orderId) to entity PaymentService
tell may also address one instance rather than a statically named
processor, by naming a value typed Id(...):
The two forms are told apart by the keyword: every processor reference is
keyword-led (to entity Order, to streamlet Enricher; see
Referring to a streamlet), so a bare path is
unambiguously a value. The
instance is deliberately never resolved — a model cannot know which
Order an Id(entity Order) holds, that being a runtime value, and nothing
needs to: every question asked of a tell target is answered by the processor
kind, which the Id names structurally.
Unlike terminate, this is not entity-only. Only
an entity can be ended, but any processor can be addressed — a singleton's
Id denotes its singular deployment. send is untouched:
it takes a portlet, not a processor, so an Id cannot apply.
Validation
A tell whose target is not reachable through any modeled connector is an
Error (msg-tell-target-unreachable). A connector path is not enough,
either: the path must carry the told message. See
A route must carry the message below.
A tell whose target declares no clause receiving that message type
draws a CompletenessWarning — nothing would happen when it arrived. The
mirror check fires on the receiving end too: an inlet admitting a type the
processor handles nowhere is reported even if nothing sends to it. An
on other clause satisfies both, because stating a policy for anything
unmatched is saying what arriving means.
A route must carry the message¶
Since 2.5.0, tell routing is worked out by message type, not by connector
topology alone. A told message arrives only at an inlet whose type admits
it, and travels on through an intermediate processor only if that processor's
on clause for it sends it again. A processor with no clause for the
message passes nothing on. These are the same rules the infinite-message-loop
check (stream-graph-cycle) uses.
So connectors joining sender and target do not settle the question. When they
exist but no path can carry the type, the tell is an Error,
msg-tell-no-route-for-type, and the message names which of two causes
applies:
- None of the target's inlets admits the type. The usual case is telling an entity an event when its inlets admit only commands.
- Every path passes through a processor that drops it: one that does not admit the message, or that receives it without sending it on.
The remedy is one of three: remove a redundant tell, declare (and connect) an
inlet that admits the message, or tell a type the target already accepts. A
relay in the middle must pass the message on explicitly:
command ExampleRelayed is { note: String }
streamlet Relay is {
inlet incoming is command ExampleRelayed
outlet outgoing is command ExampleRelayed
handler Passing is {
// Without this `send`, the relay swallows the command and a `tell`
// routed through it is msg-tell-no-route-for-type.
on relayed: command ExampleRelayed { send relayed to outlet outgoing }
}
}
This is a different fault from msg-tell-target-unreachable, which means
there is no connector path at all. Both share the same exemptions:
predefined targets, ??? bodies, targets with no inlets, senders with no
outlets, and a processor telling itself.
The route must also be one route. If the message can reach the target
from more than one of the sender's own outlets, the model does not say which
channel the tell travels on, and that is a Warning,
msg-tell-route-ambiguous. Before routing followed message types, this
looked true of 1,821 tells in the riddl-models corpus; with type-aware
routing, none of them are ambiguous.
Addressing is structural¶
A tell names a processor type — but an entity has many instances, so
something must say which one. RIDDL takes that from the message itself:
the address is the message's field typed Id(target),
found without annotation.
type OrderRef is Id(entity Order)
// `orderId` is typed Id(entity Order), so it IS the address. Nothing
// needs to be declared, and nothing needs to be written at the call site.
command Reprice is { orderId: OrderRef, newTotal: Price }
tell … by <field> exists only to disambiguate when more than one field
qualifies:
tell command Reprice(orderId = prompt("the order to reprice"),
newTotal = cart.total) to entity Order by orderId
Two rules make this predictable:
- Candidates match by resolved identity, never by the path's last segment,
so two entities named
Orderin different contexts cannot collide. - The search follows alias chains but never nesting. A field typed
OrderId, wheretype OrderId is Id(Order), is an address — that alias is ordinary house style. A field whose nested record carries the id is not, because descending into an aggregate is an unbounded search with no principled place to stop. Renaming is followed; containment is not.
Zero candidates is a CompletenessWarning, and only when the target is an
entity — an entity is the only multiply-instantiated processor. It is not an
Error for a measured reason: the reference corpus held 7,556 tells against
7 Id-typed fields, so an Error would have condemned essentially every model
in existence. Ambiguity, by contrast, is an Error — it is a
contradiction rather than an omission.
Forward Statement¶
Passes the handled message on to somewhere else and discharges this clause's
response obligation, because whatever handles it downstream is what produces
the declared yields event or replies result.
It takes both transmission shapes — a portlet like send,
a processor like tell:
Without it, a boundary handler that merely passes a command along had nothing
it could say. yields is declared on the message, so every handler of a
command declaring yields event E owes an E — even one whose entire job is
delegation and which produces nothing itself.
Validation
forward is legal only in a clause handling a command that declares
yields or a query that declares
replies — anywhere else it is an Error, stmt-forward-wrong-clause,
because there is no obligation for it to discharge. You cannot forward an
event or a result: those record what happened and owe no answer.
A boundary handler that merely relays a message with no response owed
is not forwarding; write send <bound> to outlet X.
The operand's type must match the handled message. Values are not compared, so a handler may adjust field contents and still be forwarding the same message.
It is not terminal, but the response has been delegated — so a yield
or reply after it is an Error, since this clause cannot also produce
what it just handed away. A send or tell after it is legal and draws a
style warning.
On the portlet shape the outlet's declared type must
admit the message, exactly as for send.
What settles a path
Only yield/reply, error/require, and forward discharge a
response obligation. A send of the handled message does not — not
even to an outlet that admits it. Emitting some other message does not
either.
Yield and Reply Statements¶
These are the statement halves of the two pairings described under
yields and replies. Both produce a
declared response without the handler needing to know the sender's identity:
yield emits a command's declared event. reply answers a query with
its declared result. Each satisfies the completeness check for its own kind of
handler, and the wrong pairing — yield result or reply event — is an Error.
Changed in RIDDL 2.0
Until 2.0 reply was a deprecated synonym for yield, parsing to the
same node. That is now reversed: reply is a first-class statement with
its own meaning, and yield result no longer parses as valid. If you are
migrating a 1.x model, reply is a destination rather than something to
rewrite away.
A prompt(...) as a yield argument draws an Advisory
yield event Booked(at = prompt("the time it was booked") as TimeStamp)
draws stmt-yield-argument-prompt, an
Advisory. A prompt is the hole an AI fills worst, and a
yielded event's field is nearly always something the handler already has:
a message or state field, system.now, or an expression. If the value
really has to be computed, leave the field off the event and let the
on event fold compute it.
Where the answer goes¶
"Without knowing the sender" names the destination, not a hidden channel.
A yield or reply is published on every outlet of its processor whose
type admits it, and it reaches the sender only along the connectors the
model wires back to it. There is no separate, unwired return path, so nothing
arrives twice, and a sender with no wired path back receives nothing.
Two rules follow from that (2.8.3):
stmt-send-duplicates-yield(Style). Asendof the same value on an outlet theyieldalready publishes on is redundant, and the receiver gets it twice. Drop thesend.msg-answer-unreachable(Completeness). Asendortellof a command that declaresyields, or a query that declaresreplies, whose answer no route carries back to an inlet of the sender admitting it. The answer is lost. Give the sender an inlet for the answer and a connector from the responder's outlet to it.
Set Statement¶
Assigns a value to a field or a state:
set field status to "Active"
set field total to call function Pricing.Total(subtotal, tax)
set state ActiveOrder to record ActiveOrderData()
set requires something that OWNS state
set — and get from state — are legal only where the container actually
owns state: an Entity, which owns its State, or a Projector,
which owns the read-model record its folds build.
Everywhere else it is an Error: a Context (state lives in the
entities, repositories and projectors it contains, never in the context
itself), a Saga (whose state is housekeeping with no domain meaning), a
Repository, an Adaptor, and the streamlets. A Function is
rejected at the keyword — functions are pure, so the caller passes state in
through requires.
State is also readable only inside the entity that owns it. Reaching into another entity's state is not a scoping inconvenience; it is the thing entity boundaries exist to prevent.
Append and Remove Statements¶
Change a collection field of the entity's state by one element, in three forms:
record Line is { lineId: String, name: String }
event-sourced entity Basket is {
record BasketData is { basketId: String, lines: Line*, labels: String* }
event LineAdded is { line: Line }
event LineRemoved is { lineId: String }
event LabelDropped is { label: String }
state Live of record Basket.BasketData
handler Folds is {
on init(start: Basket.BasketData) is { morph entity Basket to state Live with start }
// append: the value goes on the END of the collection
on added: event Basket.LineAdded {
append added.line to field Basket.BasketData.lines
}
// keyed remove: EVERY element whose `lineId` equals the value
on removed: event Basket.LineRemoved {
remove from field Basket.BasketData.lines where lineId == removed.lineId
}
// by-value remove: EVERY element equal to the value
on dropped: event Basket.LabelDropped {
remove dropped.label from field Basket.BasketData.labels
}
}
}
They exist for event sourcing. An event-sourced entity's on event folds must
say how the event changes state, and until 2.2.0 a fold that added to or
removed from a list could only be written as
set field S.items to prompt("items with the new item appended") — which
riddlc now reports as an incomplete prose fold
(entity-event-sourced-prose-folds). These two statements give the common
cases a real spelling.
Arithmetic folds have a real spelling too, as of 2.3.0:
set field S.balance to S.balance + points. The older
set field S.balance to prompt("balance + points") still validates — it names
its target and its operands, so it counts as a stated, derived fold rather
than prose — but it is legacy, and the arithmetic form is what a generator can
act on without guessing.
Ordering is meaning for a sequence, so append always places at the end.
Both remove forms remove every matching element, not the first.
Validation
- The target must be a collection field of the entity's current
state: a type with
*,+or{n,m}cardinality, or asequence,setortableof. An optional (T?) is not a collection. Otherwisestmt-collection-field-not-collection. - The value must be assignment-compatible with the collection's
element type in the by-value forms, or with the key field's type
in the keyed form — the same typing
setapplies to its value, and the same rule id on a mismatch. - A keyed
removemust name a field of the element record. A scalar collection has none:stmt-collection-key-not-a-field. - Everything that binds
setbinds these: legal only in an Entity or Projector (state-set-not-allowedelsewhere); banned in a function body; an effect for refusals-first, so arequireorerrorafter one is an Error; and in an event-sourced entity legal only inside anon eventclause for one of the entity's own events (entity-event-sourced-mutation-scope). - Removing the last element of a
+collection violates its cardinality. That is a run-time refusal, not something riddlc can decide statically.
append, remove and where were already reserved words, so no existing
model changed meaning when the statements arrived.
Let Statement¶
Creates a local variable binding, with an optional type annotation. When no annotation is given, the type is inferred from the bound expression:
let totalPrice = subtotal + amount
let discount = totalPrice * rate
let ready = order.isPaid and not order.isCancelled
A let is lexically scoped and statement-ordered: it is visible only after its
declaration and is shadowed inside nested blocks.
A type annotation must be a type NAME
The annotation is a path, so it names a declared type: let discount: Price
works where type Price is Decimal(10, 2) is in scope. An inline
parameterised type does not parse — let discount: Decimal(10, 2) stops
at the ( — and a bare predefined Decimal does not resolve as a path
either. Name the type once and annotate with the name, or leave the
annotation off and let the expression's type stand.
Log Statement¶
log <value> records a value for a human reader:
It is deterministic — never an AI-fill site, unlike a bare string in a
do. It is not state, not a message, and it produces nothing a later statement
can read, so it is legal wherever a statement is, a function body
included: logging observes a value without being an effect on the model.
The common idiom is a journal sink for whatever a handler did not recognise:
+ concatenates strings, it does not stringify
log "count: " + count is the Error value-arithmetic-operand-mismatch
when count is numeric — + on a String needs a String on the other
side. Either log the value on its own line (log count) or concatenate
two strings. There is no implicit conversion, by design: RIDDL does not
choose a number's rendering for you.
Repository Statements¶
Four statements change stored data and one value reads it. All five are legal only inside a repository — a repository owns the storage, so nothing else may write it:
record StoredBooking is {
bookingId: String, guestName: String, assignedTable: String, partySize: Integer
}
command RecordBooking is { bookingId: String, guestName: String, partySize: Integer }
command SeatBooking is { bookingId: String, confirmedTable: String }
command CancelBooking is { bookingId: String }
query FindBooking replies result BookingFound is { bookingId: String }
result BookingFound is { guestName: String }
type BookingChange is RecordBooking | SeatBooking | CancelBooking
repository BookingStore is {
schema BookingSchema is relational
of bookings as record StoredBooking
key on field StoredBooking.bookingId
index on field StoredBooking.guestName
inlet Changes is type BookingChange
inlet Questions is query FindBooking
outlet Answers is result BookingFound
handler Storage is {
on add: command RecordBooking {
store record StoredBooking(
bookingId = add.bookingId, guestName = add.guestName,
assignedTable = "", partySize = add.partySize
) in BookingSchema.bookings
}
on seat: command SeatBooking {
// unqualified table name: this repository declares one schema
update bookings set assignedTable = seat.confirmedTable
where bookingId == seat.bookingId
}
on drop: command CancelBooking {
delete from BookingSchema.bookings where bookingId == drop.bookingId
}
on ask: query FindBooking {
let found = query one BookingSchema.bookings where bookingId == ask.bookingId
reply result BookingFound(guestName = found.guestName)
}
}
}
| Form | Meaning |
|---|---|
store <record> in <table> |
Adds a row |
upsert <record> in <table> |
Adds it, or replaces the row with the same key |
update <table> set f = v, … where <cond> |
Changes named fields of matching rows |
delete from <table> where <cond> |
Removes matching rows |
query [one] <table> [where <cond>] |
A value, not a statement: reads rows |
A table is named Schema.table, or by the bare table when the repository
declares exactly one schema, as the update above shows.
Inside where and set, a bare name is a ROW field
That is the whole point — these clauses talk about stored rows — but it
means a bare name shadows a same-named field of the handled message.
In the update above, bookingId is the row's column and
seat.bookingId is the command's field. Qualify the message field always;
the row field never needs it.
query without one reads every matching row, in unspecified order —
if order matters, the model must say so some other way, because a repository
makes no promise about it. query one reads the first match, or empty when
nothing matches.
upsert requires the schema to declare a key on a field of the stored
record: without a key there is no definition of "the same row", so there is
nothing for it to replace.
Validation
Each is an Error:
queryoutside a repository:value-query-outside-repository. Ask the repository instead (ask query … of repository …).- A table name that is not a data entry of a schema in scope:
repo-table-not-in-schema. storeorupsertof a value that is not the record the table stores:stmt-store-value-not-table-record.update … set f = vwherefis not a field of that record:stmt-update-field-not-in-row.upsertinto a table whose schema has nokey ona field of its record:stmt-upsert-needs-key.
Ask¶
ask states that two messages are two halves of one interaction: a query
sent to a processor, and the reply that answers it. It is a value, not a
statement, so it is used through let:
An ask states what it asks (since 2.8.0). It supplies the query's field
values exactly as a constructor does: named or positional
(positional first), every field supplied — an optional one too, as
empty if nothing — none twice, and each of its field's type. Inside a
foreach, an argument may name the element, so the model says which element
is being asked about. The bare ask query Q of P remains the spelling for a
query with no fields.
A bare ask of a query with fields is deprecated until 3.0
ask query GetProduct of entity Catalog, where GetProduct has fields,
says nothing about what is asked. It draws [deprecated]
[value-ask-bare-query] through 2.x and becomes an Error at 3.0 — the same
Error a bare send of such a message already is. --fix and prettify
do not migrate it, because only the author knows which values to supply.
Mistakes in the argument list draw the constructor's own rules:
value-constructor-missing-fields, value-argument-duplicated,
value-not-a-field, value-type-mismatch.
Before ask, a model could say a message was sent (tell) and what handling
one produces (yields/replies), but not that a caller awaits a particular
answer. yield names no destination and tell says nothing about a reply, so
a generator could not tell fire-and-forget from request/response.
ask declares that correlation and nothing else. It deliberately implies
no mechanism — not a future, a temporary actor, a correlation-id field, or a
blocking call. All four are lowerings a generator may choose, on the same
principle as message_envelope: RIDDL specifies meaning, generators choose
representation. Timeouts are likewise a generated-code concern, not language.
Queries only, structurally. The operand is a query reference, not a general message reference — a command, event, result or record is not answerable, so the restriction is in the shape of the syntax rather than in a validation rule.
The answer's type is always known: it is the query's declared
replies result X. This is the one place
replies is mandatory, which is why the requirement sits at the ask site
rather than on every query.
Errors
- Asking a query that declares no
replies— there is no type to give the answer. - Asking a processor that has no clause handling the query. An
on otherclause counts as handling everything, and an entity's handlers may live under a state. - Asking anywhere inside a saga step, including as a value nested in a larger expression. See below.
- No connector carries the query from the asker to the callee
(
msg-ask-target-unreachable), or none carries the answer back (msg-ask-reply-unreachable). See "Both legs must be wired" below.
An ask whose callee refuses is expected, not an error: recording a rejection settles the obligation, consistent with the discharge rule.
Both legs must be wired. An ask is two messages, and like a
tell each one needs a modelled channel. The query needs a
connector from an outlet the asker owns to the callee's inlet. The reply needs
one from the callee's outlet back to an inlet of the asker. A missing leg is an
Error, and each leg has its own rule, so a model missing both gets two
messages:
command CheckStock is { sku: String }
result StockLevel is { onHand: Whole }
query GetStock replies result StockLevel is { sku: String }
entity Storefront is {
inlet Orders is command CheckStock
inlet Answers is result StockLevel
outlet Questions is query GetStock
handler Shop is {
on c: command CheckStock {
let level = ask query GetStock(sku = c.sku) of entity Warehouse
do "decide what to show from level"
}
on result StockLevel { do "the answer arrives here" }
}
}
entity Warehouse is {
inlet Asked is query GetStock
outlet Told is result StockLevel
handler Stock is {
on query GetStock { reply result StockLevel(onHand = 0) }
}
}
connector Ask is { from outlet Storefront.Questions to inlet Warehouse.Asked }
connector Answer is { from outlet Warehouse.Told to inlet Storefront.Answers }
A saga may not ask
A saga must not depend on dynamic state, or the same inputs could yield different transaction results at different times. Compensation makes this sharper: if the forward action read a value that has since changed, the undo would be reversing something other than what happened.
The remedy is to acquire the value in a handler and pass it into the saga
through the saga's requires, so the saga is closed over its inputs and
compensation sees the same data the forward action saw.
The prohibition reaches every ask embedded in a value expression, at
any depth — it is not enough to keep ask off the right-hand side of a
let.
Instance Identity¶
RIDDL could describe processors but not instances of them. A model could
say what an Order entity does, and could not say which Order, could not
bring one into being, and could not name the one it is currently running as.
Four constructs close that gap.
Id(P) — the identity of one instance¶
Id names any processor, not only an entity: adaptor, context, entity,
projector, repository or streamlet. The keyword form is canonical and a bare
path is shorthand:
type OrderRef is Id(entity Order) // canonical
type PlainRef is Id(Order) // shorthand for the same thing
type CatalogRef is Id(entity Catalog)
The keyword is stored as written, so prettify is byte-exact — and
validation makes it tell the truth. A keyword contradicting the referent's
actual kind is an Error, because a wrong keyword is worse than none: a
reader believes it.
Why Id covers a singleton too
A context or repository has exactly one instance, so its Id may look
pointless. It is not: an Id is how you address something. For a
singleton it denotes the deployment, and addressing it means "select the
right shard and forward". Only entities may be created and ended, but
every processor may be named.
This is runtime identity, and it is not the definition's model-time
identity. Two Order instances share one definition but never share an
Id(Order). The value is opaque and system-generated, so a business key —
an order number, an email — belongs in state, supplied through on init.
self — the instance running right now¶
self's type is a synthesized record with id and version. That it is
an ordinary record is load-bearing: self.id resolves through the same path
walk as every other value, so no resolution rule anywhere has to know self
exists.
Two consequences follow from the type not being user-nameable — self.id is
Id(Order) inside an Order handler and Id(Shipping) inside a Shipping one:
let me: T = selfhas noTyou could write.selfis not assignable into a message field. Passself.id.
The field set is closed. Adding to it is a language change, and the test is
runtime-only: anything a generator can know statically it should inline,
which is why version qualifies and, say, cluster placement does not.
create — bring an instance into being¶
create is a value: it creates an instance of an entity, runs that
entity's on init clause, and yields the
new instance's Id, so it is used through let.
Arguments in parentheses are bound to on init's parameters, positionally or
by name — create entity Order("A-1001"), or
create entity Order(code = "A-1001"). Supplying a different number of
arguments than on init declares parameters is an Error
(handler-clause-wrong-arity).
Creation is instantiation: the instance is given a place for its values
and an Id. Initialization is the job of its on init clause, which
creation then runs — and only that clause; on activate is not run. It does
not add a second way for an instance to exist: construction completes only
when on init finishes. Without it, no Id(P) value could ever come into
being and the whole addressing story would be inert. A new instance has no
state until on init morphs it into one, so the arguments are what decide
where it starts.
create and terminate are entity-only, by an
explicit check rather than as a side effect of the type system — create of a
projector, repository or any other singleton is an Error
(stmt-not-instantiable). Both are effects, so both are banned in a
function body, in on activate / on passivate, and in a correlation fold.
Both are legal in a saga step. Binding the id and never using it is a warning
(stmt-initiate-id-unused — the code keeps its original spelling): the
instance was created and immediately made unreachable.
Spelled initiate before 2.7.0
initiate is the deprecated spelling of the same value and builds the
same AST. It draws [deprecated] [value-initiate-keyword], and
riddlc validate --fix rewrites it to create. It will be removed in
3.0.
The asymmetry is the design
create names a type and yields an id; terminate consumes an
id and yields nothing. So create is a value and terminate is a
statement, and on term needs no parameter naming the instance — self
is in scope for the whole body and stays live to its very end, so
self.id already says which one is ending.
Put Statement¶
Publishes a value to a UI output. Valid only in application and context handlers:
The value is checked against the output's declared type. ConfirmationPanel
is declared shows record ExampleOrder, so putting one field of that record is
a value-type-mismatch Error.
Return Statement¶
Returns a function's result. Valid only in a function body:
When Statement¶
Conditional logic. The end keyword is required:
A condition may be any of:
- A boolean expression:
when a > b and not c then - A bare boolean-typed reference, including a dotted path:
when order.isPaid then - A
letbinding, optionally negated:when authorized then,when !authorized then - An AI-evaluated prompt:
when prompt("the user is authenticated") then
A bare reference is resolved and checked to be Boolean-typed; a clearly non-Boolean condition is an Error.
A bare string condition is deprecated
when "the user is authenticated" then still parses but draws a
[deprecated] message (bare-string-condition). Write
when prompt("the user is authenticated") instead.
The reason is consistency: everywhere else in RIDDL a bare quoted string
denotes a literal value, while prompt(…) marks something an AI
decides. A natural-language condition is plainly the latter, so it should
say so rather than borrow the literal's spelling.
An else clause handles the false case:
let authorized = user.hasPermission
when authorized then {
send event ActionCompleted(note = "done") to outlet Events
} else {
error "User not authorized"
} end
Match Statement¶
Pattern matching over a typed subject. The subject is a value reference, a
get from, or a legacy pseudo-code literal:
match orderStatus {
case Pending {
tell command ProcessPayment(orderId) to entity PaymentService
}
case Shipped when order.isPaid {
tell command ConfirmOrder(orderId) to entity Order
}
default {
error "Unknown order state"
}
}
A comparison case needs a numeric subject, so it belongs to a different match than the one above — the subject's type decides which case forms are legal on it:
match order.total {
case >= HighValueThreshold {
tell command EscalateReview(orderId) to entity Review
}
default { do "no escalation needed" }
}
A case pattern is one of:
- Type case — a bare type reference matching an alternant, enumerator or
message subtype:
case Pending - Comparison — an operator and a comparand, with the subject as the
implicit left operand:
case >= HighValueThreshold - Literal — a legacy pseudo-code label:
case "pending"
Each case may carry an optional when <boolean> guard.
Naming an unknown type-case is an Error. For a closed subject — an
Enumeration or Alternation — a non-exhaustive match without a default draws a
StyleWarning.
Foreach Statement¶
RIDDL's safe, bounded loop. There is no unbounded iteration in the language:
foreach line in field order.lines {
send event LineShipped(sku = line.sku) to outlet Shipments
}
foreach item in myLocalCollection {
do "record the item"
}
The collection is a field reference or a let-bound local whose type resolves
to a collection — Sequence, Set, Graph, Table, Replica, Mapping, or a
cardinality wrapper such as many or optional. Any resolvable path that
lands on a collection is accepted; it need not be a direct field of the
enclosing state, which is why order.lines above works.
The element name is bound over the loop body and carries the element's
type, so line.sku resolves and line.nosuch is an Error. The binding ends at
the closing brace.
Destructuring a mapping¶
A mapping yields a key and a value, so iterating one binds two names:
Arity is a validation rule rather than a grammatical one — both shapes parse — and it is checked in both directions:
| Mistake | Message |
|---|---|
| one name over a mapping | binds a key AND a value, so it needs two names |
| two names over a non-mapping | binds a second name only over a mapping |
Require Statement¶
Asserts a precondition that must hold before proceeding:
require amount > Zero
require "the customer is in good standing"
require invariant BalanceNonNegative
require invariant UnderLimit with limits
The with <value> form hands a value to an invariant that declares
requires <type> — the one invariant form ambient scope cannot supply. See
Invariants.
In a when or match condition the same invariant needs no argument, and
the invariant keyword itself is optional there. The asymmetry is deliberate:
a condition asks whether the rule holds, while a require applies it and
so must be handed what the rule reads.
Naming an invariant does not switch it on
As of RIDDL 2.0 an invariant applies implicitly across its declaring
scope, whether or not any clause names it. A require invariant X is an
explicit restatement at a point you want the check called out — never what
activates it. The rule that an unreferenced invariant draws a UsageWarning
is withdrawn; the only inert form left is an invariant declaring
requires <type> that nothing ever invokes, and that still warns.
Error Statement¶
Refuses to proceed, with a reason:
error ends its statement list. It refuses unconditionally, so anything
written after it can never run, and a following statement is an Error. Use
require instead when the refusal is conditional —
require refuses only when its condition fails, so statements after it are
ordinary and reachable.
terminate ends a list the same way, for a different
reason: the instance is gone, so a later statement has nothing to act on. An
on term clause is unaffected — it is a separate statement list that runs
because of the termination, never after it.
Terminate Statement¶
Ends the life of the entity instance handling the message. It names the identity being terminated, and may carry closing values the way a constructor does:
on cmd: command ExampleCommand {
require cmd.amount > ExampleZero // refusals first
terminate self.id
}
Like error, terminate ends its statement list: the
instance no longer exists, so a statement written after it can never run and is
an Error. Unlike error, the way to react to it is not a conditional
refusal but an on term clause, which is a separate list
that runs because the instance ended.
terminate is an effect for the refusals-before-effects
rule — ending the instance is the most complete local state change there is.
Refusals Before Effects¶
Within any single linear statement list, every refusal (require, error)
must come before every effect — and for this rule an "effect" is a change to
this definition's own state: set, morph and terminate. Performing one
and then refusing would leave a partial change behind.
Each statement list is checked independently, so each branch of a when,
match or foreach body is its own list. A refusal after an effect in the same
list is an Error.
Why send, tell, yield, become and put are not effects here
This rule asks "would refusing now leave a partial change?", which is a narrower question than "is this pure?" — the one asked of functions.
send, tell and yield are transmissions: any state they cause is
somewhere else and later, which is a remote "maybe" a locally-refusing
statement can live with. become changes behaviour, not state. put
delivers to an output. None of them can leave this
definition half-changed, so none of them has to come after the refusals.
This matters in practice: "refuse and publish a rejection event" is a
common idiom, and it is expressible precisely because a send may sit
before an error.
A transmission issued before a refusal is delivered. The refusal does
not recall it. The refusal goes back to the refused message's sender, and
nothing is rolled back, because nothing local has changed yet. A generator
must not hold the earlier send until the clause completes. If it did, the
rejection event the refusal announces would never be published.
on cmd: command Withdraw {
require cmd.amount > Zero // refusals first
require balance >= cmd.amount
set field balance to "balance - amount" // then effects
yield event Withdrawn(amount = cmd.amount)
}
Do Statement¶
Describes an action in natural language for later implementation:
This is useful for describing business logic that will be implemented in target code. For several lines of guidance, brace a sequence of strings:
do {
"Apply the loyalty discount before any promotional discount."
"Round the result to the customer's currency."
}
The bare form takes exactly one string. The same block shape is what
prompt(...) accepts between its parentheses.
The prompt statement is deprecated
do is canonical. prompt "..." still builds the same node and emits a
[deprecated] message; prettified output normalizes it to do.
Do not confuse it with the prompt(...) value, which is a different
construct distinguished by its parentheses — it denotes a value computed by
AI rather than an action described for a human.
Validation in prose belongs in a type
do "validate b.partySize is between 1 and 20" draws the style warning
stmt-do-validates-a-range. A do that checks a field against a range,
a set or a bound is better said as the field's type: a range such as
Integer(1,20), an enumeration (any of { … }) or a pattern. Then the
constructor validates the field for free, and the prose can go. The rule
matches a do that begins with a verb (validate, check, ensure,
verify, require), then a field, then a bound such as is between,
one of or at least. A do that only mentions "between" in passing
is not flagged.
Code Statement¶
The code statement is RIDDL's deliberate escape hatch: an opaque
pass-through of raw target-language source, handed to the code generator
untouched.
It is written as a fenced block with a language tag:
The language tag must be one of exactly four: scala, java,
python, mojo.
RIDDL does not parse, check, or understand the contents. Everything between the fences is carried through verbatim.
Where it is allowed¶
Everywhere. Unlike every other statement, code is subject to none of the
scope rules:
| Rule | Applies to code? |
|---|---|
| Functions must be pure | No — code is legal in a function body |
on activate / on passivate must be side-effect free |
No — code is legal there |
| Refusals must precede effects | No — code is neither, so it never trips the check |
That is not an oversight. RIDDL cannot classify opaque source: it has no way to know whether a block of Scala writes state, sends a message, or computes a number, so it declines to guess rather than guessing wrong.
Using it opts out of the guarantees
Every rule above exists to give a model a property worth having — a
function that is provably pure, a lifecycle clause that provably does not
emit, a handler that provably refuses before it acts. A code block
suspends those guarantees for as long as it lasts, and it makes the model
specific to one target language.
That is a real trade and worth making deliberately. Prefer
do "..." to describe intent and let the generator
implement it; reach for code when a generator genuinely cannot express
what you need.
The tag is matched by prefix
The parser matches the four tags as prefixes, so javafoo and pythonic
are currently accepted, with the surplus text treated as part of the code
body. Do not rely on this — only the four tags above are supported, and
the leniency may be tightened.
Become Statement¶
Switches the live handler of an entity:
Functions¶
Functions define reusable, pure operations. A function's requires and
returns may name an existing type rather than spelling out an aggregation,
which makes unary and nullary functions natural:
function CalculateTotal is {
requires record TotalInputs
returns Price
return call function Tax.Apply(subtotal)
} with {
briefly as "Calculates the final cart total"
}
The inline aggregation form still parses, but it is deprecated
(func-inline-aggregation) and slated for removal in 3.0:
function CalculateTotal is {
requires { subtotal is Price, taxes is Price, shipping is Price }
returns { total is Price }
do "Add subtotal, taxes and shipping"
}
Functions must be pure
A function body may not write entity state (set, morph, become), nor
send, tell or yield. This is enforced at parse time, so an effect
statement can never enter a function's AST.
Refusals (require, error) and pure computation (let, when, match,
foreach, do, return, code blocks) remain legal.
The inline requires { … } form is deprecated
Naming a type is preferred. The inline aggregation emits a [deprecated]
message but continues to work.
Sagas¶
Sagas coordinate multi-step processes with compensation:
saga CheckoutProcess is {
requires record CheckoutInputs
returns record CheckoutOutcome
step TakePayment is {
tell command ProcessPayment(CheckoutInputs.orderId) to entity PaymentService
} reverted by {
tell command RefundPayment(CheckoutInputs.orderId) to entity PaymentService
} with {
briefly as "Processes payment for the order"
}
step ReserveStock is {
tell command ReserveItems(CheckoutInputs.orderId) to entity Inventory
} reverted by {
tell command ReleaseItems(CheckoutInputs.orderId) to entity Inventory
} with {
briefly as "Holds the items until payment settles"
}
} with {
option is timeout("PT5M")
briefly as "Orchestrates the checkout process steps"
}
Saga Options¶
| Option | Meaning |
|---|---|
parallel |
Start all steps at once; the coordinator gathers results asynchronously. Any one failure compensates in reverse order of the original sends. |
timeout("<duration>") |
How long the saga's run may take before compensation fires |
A saga is sequential by default, so there is no sequential option.
There is no compensate option
Compensation is not a switch. Every step must declare reverted by, and
on failure the saga runs the completed steps' undo blocks in reverse
order. That is what a saga is. An option compensate used to be
accepted, and a generator read it as a switch, so it abandoned completed
steps on failure unless the model carried it. It was removed before 2.0.
Writing it now draws opt-unrecognized.
What an absent timeout means¶
A saga's timeout bounds how long its run may take before compensation fires.
Absence does not mean "no bound". It means the bound is left to whatever executes the saga, and that executor's choice decides when compensation runs — so two conforming generators may compensate at different times for the same model.
That is why a saga with no timeout draws a CompletenessWarning
(saga-no-timeout) rather than an Error: the model is under-specified, not
self-contradictory. RIDDL specifies meaning, and an unstated bound is a meaning
the model declined to give. A saga whose body is ??? is exempt, under the
standing rule that a body declaring itself incomplete earns at most a Missing
warning.
saga Checkout is {
step ReserveStock is {
tell command ReserveItems(orderId = "o-1") to entity Inventory
} reverted by {
tell command ReleaseItems(orderId = "o-1") to entity Inventory
}
step ChargeCard is {
tell command ProcessPayment(orderId = "o-1") to entity PaymentService
} reverted by {
tell command RefundPayment(orderId = "o-1") to entity PaymentService
}
} with { option timeout("PT5M") }
Every step tells a command to something else. That is not a stylistic
choice: a step whose do-block tells no command effects nothing, and its
reverted by block then promises to compensate an action that never
happened. riddlc makes that an Error (saga-step-no-tell) rather than a
completeness warning, because it is a self-contradiction, not an omission —
the step claims to be one step of a distributed transaction while performing
none of it. A send does not satisfy the rule; a saga step drives a processor,
and tell is how a processor is driven.
Saga Validation
Errors:
- A saga step that references a definition owned by a different domain. A saga orchestrates a transaction within one bounded domain.
- A saga step whose do-block contains no
tell command(saga-step-no-tell). See above: the step effects nothing, so there is nothing for itsreverted byblock to compensate.
Warnings:
- A step's do-block containing more than one potential failure point
(
saga-step-too-many-fail-points). A step's do/undo is all-or-nothing, so it should have at most one place it can fail — split the step.send,tell,yieldandputcan fail, as can each embeddedcallorget. - A step whose undo block does not target everything its do block targets
(
saga-step-uncompensated, a style warning): something the step changed has no compensation. - A saga with no
timeoutoption (saga-no-timeout, a completeness warning) — see "What an absenttimeoutmeans" above.
Repositories¶
Repositories define persistence:
// `record Cart` here, not the page's `entity Cart`: a schema stores DATA.
record CartLine is { id: ProductId, quantity: Natural }
record Cart is { items: many CartLine }
command SaveCart is { cart: Cart }
repository CartRepository is {
// A link joins two STORED records' fields; it cannot reach inside a
// collection, so the lines are a table of their own.
schema CartData is relational
of cart as record Cart
of lines as record CartLine
link cartItems as field CartLine.id to field Product.id
inlet Saves is command SaveCart
handler CartRepositoryHandler is {
on save: command SaveCart {
store save.cart in CartData.cart
}
}
} with {
briefly as "Persistent storage for shopping cart data"
}
A repository is changed by commands and read by queries, never by events. An event that should be stored is first turned into a command by whatever handles it — usually a projector or an entity.
Validation
- Error (
repo-inlet-carries-event): an inlet whose type is, or includes, an event. - Warning (
handler-repository-handles-events): anon eventclause in a repository's handler. - Warning (
repo-no-commands-or-queries): handlers that take no command and no query at all. - Missing (
repo-no-handler): a repository with content but no handler.
Schema Clauses¶
A schema names its kind, then takes its clauses in a fixed order: of …,
link …, key on …, index on …, and finally its own with { … }.
| Clause | Says |
|---|---|
of <table> as <record> |
This table stores that record |
of <table> as <record> with history |
…and keep an append-only history of it |
link <name> as field A to field B |
A relationship between two stored fields |
key on field F |
F is a unique natural key |
index on field F |
F is expected to be searched on |
record Item is { itemId: String, ticketId: String, name: String }
repository TicketStore is {
schema TicketSchema is relational
of items as record Item with history
key on field Item.itemId
index on field Item.ticketId
}
A key is not an index. An index says a field will be searched on; a key
says no two stored rows may share its value, which is what gives upsert its
meaning of "the same row". A keyed schema counts as indexed on that field, so
there is no need to write both for one field. There are no composite keys:
a key names exactly one field of the stored record. A key on a field of some
record the schema does not store is the Error
repo-schema-key-not-stored-field. A link joins two fields of the same
type; linking an Integer to a String is the Error
repo-link-type-mismatch.
with history asks the generator for an append-only history of the table —
every version retained rather than each write overwriting the last. It states
the requirement, not the mechanism: whether that becomes a temporal table, an
audit sidecar or an event log is the generator's choice.
What riddlc checks about a schema's kind
The kind is suggestive, not a storage engine, but a few shapes contradict it. Each is a Warning:
| Kind | Warned when | Rule id |
|---|---|---|
flat |
more than one data entry | repo-flat-schema-many-nodes |
flat, document, columnar, vector |
any link |
repo-schema-should-not-have-links |
vector |
more than one data entry | repo-vector-many-nodes |
time-series |
no index on |
repo-time-series-no-indices |
relational |
several data entries, no links | repo-relational-no-links |
hierarchical |
several data entries, no links | repo-hierarchical-no-links |
star |
several data entries, no links | repo-star-no-links |
graphical |
data but no links | repo-graph-no-links |
Repositories at Domain Scope¶
A repository that synthesizes messages from entities across several contexts, and is queried by several contexts, may be declared directly in a Domain rather than in a Context.
Repository Scope Validation
A repository's reach is the set of contexts owning the messages its
on clauses handle.
- Error (
repo-domain-scope-misplaced): a domain-scoped repository reaching only ONE context. It is provably unnecessary at domain scope — move it into that context. - CompletenessWarning (
repo-handles-foreign-contexts): a context-scoped repository reaching another context. Consider promoting it to domain scope.
Adaptors¶
Adaptors translate messages between bounded contexts. They handle the transformation needed when one context communicates with another that uses different message formats or terminology.
Direction¶
Adaptors specify a direction relative to a context:
from context X: Receives messages from context X, translates for local useto context X: Sends messages to context X, translating from local format
Example¶
context OrderContext is {
event OrderPaymentReceived is { orderId is UUID }
adaptor PaymentIntegration from context PaymentContext is {
// The adaptor owns the outlet it publishes on. Naming the enclosing
// context's outlet is `stmt-outlet-not-owned`.
outlet OrderEvents is event OrderPaymentReceived
handler InboundPayments is {
on evt: event PaymentContext.PaymentCompleted {
let orderId = evt.reference
send event OrderPaymentReceived(orderId) to outlet OrderEvents
}
on other {
error "Unrecognized payment event"
}
}
} with {
briefly as "Translates payment events for order processing"
}
}
The Isolation Seam
An adaptor bridges exactly two contexts: its parent context and its referent context. It is the only sanctioned crossing point between contexts, so it must not traffic in a third context's messages.
A message whose owning context is neither the parent nor the referent is an Error. Types defined at domain or root level are shared vocabulary common to both sides and are never flagged.
Every adaptor handler must also have an on other clause.
Projectors¶
Projectors transform and aggregate events into read models. They are key to implementing CQRS, where the write model (entities) is separate from the read model (projections).
Purpose¶
- Project (transform) events from multiple sources into denormalized views
- Aggregate data for efficient querying
- Maintain materialized views updated by event streams
Example¶
context ReportingContext is {
projector SalesDashboard is {
record DailySales is { day is Date, total is Decimal(10, 2) }
updates repository SalesData
handler SalesEventHandler is {
on event OrderContext.OrderCompleted {
do "Update daily sales totals with order amount"
}
on event OrderContext.OrderRefunded {
do "Subtract refund amount from daily totals"
}
}
} with {
briefly as "Projects order events to sales dashboard"
}
}
Projectors are event-only
on command, on query and on record are rejected at parse time
inside a projector. Only on event and on result are valid.
Completeness Warnings:
- Projectors not referencing any repository
- Projector handlers not
telling to a repository - Declared repository references never used in
tell
Streaming Processors¶
Streaming processors define components for building data pipelines with typed input ports (inlets) and output ports (outlets).
Inlets and Outlets¶
- Inlet: A typed input port that receives messages
- Outlet: A typed output port that sends messages
Every processor kind may declare ports — not just streamlets. An entity may own an outlet; a projector may own an inlet. And every processor kind must declare the ports its handlers use: nothing is implied by the kind, the direction, or the shape, for an adaptor any more than for anything else.
A missing port is incomplete
A processor whose handler clauses receive messages but which declares
no inlet, or which send, tell, forward, yield, reply or ask
but declares no outlet, is incomplete in exactly the way a ??? body is —
and is reported the same way, as a Missing warning that names the
types so you know what to write:
Adaptor 'Bridge' is incomplete: it handles Event 'Happened' but declares
no inlet to receive them on
One rule, two id spellings, on purpose. An entity reports
entity-no-inlet / entity-no-outlet, because those ids were published
first and a published code keeps its meaning. Every other kind reports
stream-processor-no-inlet / stream-processor-no-outlet.
Until the port is declared, every rule that would read it abstains:
the shape ascription is not judged, a tell from a port-less sender is
not reported unreachable, and a far context's inbound adaptor with no
inlet neither admits nor refuses a message. One omission draws one
message. An error-sink inlet is infrastructure and does not count.
context DataPipeline is {
streamlet OrderEventSource as source is {
outlet OrderEvents is event OrderEvent
} with {
briefly as "Streams order events from the event store"
}
streamlet OrderEnricher as flow is {
inlet RawOrders is event OrderEvent
outlet EnrichedOrders is event EnrichedOrderEvent
handler EnrichmentHandler is {
on event OrderEvent {
do "Look up customer details and product information"
send event EnrichedOrderEvent(OrderEvent.orderId, region = "EU") to outlet EnrichedOrders
}
}
}
streamlet AnalyticsSink as sink is {
inlet AnalyticsEvents is event EnrichedOrderEvent
handler AnalyticsHandler is {
on event EnrichedOrderEvent {
do "Send event to analytics platform"
}
}
}
}
Portlet Options¶
| Option | Applies to | Meaning |
|---|---|---|
async |
Inlet, Outlet | A deliberate codegen async boundary; the generator inserts a real boundary here rather than fusing the stream |
ordered |
Connector, Inlet | Delivery preserves order |
unordered |
Connector, Inlet | Delivery order is not significant |
Streaming Validation
Errors:
- An ascribed shape that contradicts the declared port arity
- A port referenced by more than one connector (see below)
Style Warnings:
- A processor with at least one port and no
as <shape>ascription - A connected pipeline in which every portlet is
async. Nothing can be fused, so the stream pays message-passing overhead at every boundary and typically runs slower than a fused one.
Completeness Warnings:
- Isolated processors not connected to any connector
- Sources without a downstream path to a sink
- Sinks without an upstream path from a source
- Unattached inlets and outlets
- Flow/Split/Router handlers that don't send to outlets
Connectors¶
Connectors link an outlet to an inlet, defining how data flows between processors.
Syntax¶
Example¶
context DataPipeline is {
connector OrderFlow is
from outlet OrderEventSource.OrderEvents
to inlet OrderEnricher.RawOrders
with {
briefly as "Connects order source to enrichment"
}
}
Port Cardinality¶
Exactly one connector may attach to any given port. Fan-in and fan-out are
modeled by declaring multiple ports — a merge or split shape derives from
its arity — never by attaching several connectors to a single port.
More than one connector on a port is an Error.
Connector Scope¶
A connector may be declared in a Context or, when it joins ports in two different contexts, in the enclosing Domain.
Connector Placement Validation
- Error: the two ends resolve to different domains. A stream edge across a domain boundary is a failure of domain analysis.
- Error: a domain-scoped connector whose ends share one context (over-scoped) — move it into that context.
- Error: a context-scoped connector whose ends cross contexts (under-scoped) — promote it to domain scope.
- CompletenessWarning: a domain-scoped connector that crosses
between two different contexts without the
persistentoption. Durability at a context boundary can be model correctness, not merely deployment. A connector with both ends inside the same external context does not cross anything and is not asked for it. - Error: a cross-context connector that reaches past a context boundary. Each end must land on the context's own portlet — the source context's outlet, the target context's inlet — never on a portlet declared by something the context contains.
Why the boundary rule is an Error
A context publishes a public API — its message set — while its representations stay private. Wiring a cross-context connector to a contained entity's inlet binds a peer to that entity's existence and to its current command set, so the entity can no longer change without breaking a stranger. That contradicts the bounded context rather than under-stating it.
Inside one context the rule does not engage at all: any processor, streamlet or connector may talk to any other, and a connector may drive a contained entity's inlet directly.
Pipeline Pattern¶
context EventProcessing is {
streamlet Events as source is { outlet Raw is event RawEvent }
streamlet Validate as flow is {
inlet In is event RawEvent
outlet Out is event ValidatedEvent
}
streamlet Store as sink is { inlet In is event ValidatedEvent }
connector Step1 is from outlet Events.Raw to inlet Validate.In
connector Step2 is from outlet Validate.Out to inlet Store.In
}
The Standard Module¶
Every model has access to a predefined module named Riddl, with no import and
no author declaration required. It provides the two stream terminators that the
one-connector-per-port rule makes structurally necessary:
| Definition | Kind | Purpose |
|---|---|---|
BottomlessPit |
sink | Consumes everything delivered to its inlet hole and emits nothing |
ForeverEmpty |
source | Never produces anything on its outlet void |
Drain |
type | Anything, so one drain absorbs every message type |
Reaching BottomlessPit terminates a pipeline exactly as a modeled sink does,
and ForeverEmpty originates one, so neither draws reachability warnings. The
port-cardinality rule is waived for them: many connectors may share the
universal drain.
A model that ignores the standard module is completely unaffected by it — the module is never added to your model's contents.
UI Components¶
RIDDL supports UI modeling. UI may only be modeled inside an application
context.
application context Storefront is {
command PlaceOrder is { cartId is UUID }
record PaymentDetails is { cardToken is String, amount is Decimal(10, 2) }
page ProductDetails is { ??? } with {
briefly as "Page showing product information"
}
page ShoppingCart is {
button Checkout activates command PlaceOrder with {
briefly as "Checkout button to proceed to payment"
}
}
page Payment is {
form PaymentEntry submits record PaymentDetails
}
} with {
briefly as "User interface components for the system"
}
An input element always names a defined type — a command it triggers, or a
record it submits. A predefined type such as Boolean will not do: the
reference is resolved against the model, and predefined types are not
definitions in it.
Element Aliases¶
| Role | Keyword and aliases |
|---|---|
| Group | group, page, pane, dialog, menu, popup, frame, column, window, section, tab, flow, block, scene, space, zone |
| Output | output, document, list, table, graph, animation, picture, sound, speech, haptic |
| Input | input, form, text, button, picklist, selector, item, voice, gesture, gaze |
Interaction Verbs¶
- Presentation (outputs):
presents,shows,displays,writes,emits - Acquisition (inputs):
acquires,reads,takes,accepts,admits,enters,provides,selects,chooses,picks,initiates,submits,triggers,activates,starts
UI Validation
Errors:
- A
group(or alias) in a context that is not anapplicationcontext
Style Warnings:
- An input using a selection verb (
selects,chooses,picks) whose type is not a choice among options — that is, not an Enumeration or Alternation
Epics and Use Cases¶
Epics model user stories:
epic ShoppingCartEpic is {
user Customer wants to "add items to a shopping cart"
so that "they can purchase multiple items at once"
case AddingToCart is {
user Customer must "add products to cart"
so that "they can purchase them later"
step focus user Customer on page Storefront.ProductDetails
step take input Storefront.ProductDetails.AddToCartForm from user Customer
step send command AddToCart from context Storefront to entity Cart
step show output Storefront.ShoppingCart.CartSummary to user Customer
step entity Cart refuses user Customer "the item is out of stock"
} with {
briefly as "Adding products to the shopping cart"
}
}
Two rules shape those steps. Inputs and outputs are group contents, so a
step names the page that holds them, not the context directly. And a user may
only interact at the application boundary: the command travels from
context Storefront to the entity, not from the user to the entity. Routing a
user's command straight at an entity is an Error.
User Story Verbs¶
The user-story verb may be any of wants, must, shall, should, may,
will, can. All variants parse to the same structure — the modality is
vocabulary, not captured data.
Interaction Step Kinds¶
| Step | Syntax |
|---|---|
| Focus | step focus <user> on <group> |
| Direct | step direct <user> to <url> |
| Select | step <user> selects <input> |
| Take input | step take <input> from <user> |
| Show output | step show <output> to <user> |
| Refusal | step <source> refuses <user> "<reason>" or … invariant <ref> — the invariant form ties the step to the require that enforces it |
| Send message | step send <message> from <source> to <target> |
| Self-processing | step for <ref> is "<description>" |
| Arbitrary | step from <source> "<relationship>" to <target> |
| Vague | step is "<subject>" "<verb>" "<object>" |
The refusal step is new in 2.0. It models a system element declining a user's request, which previously had no way to be expressed except as free text:
The arbitrary and vague steps carry free prose rather than typed references, so they are the two that the AI-translatability check examines.
Steps may be grouped with sequence { … }, parallel { … } and
optional { … }.
Users interact only at the application boundary
A User may not reach past the application straight into the domain. For the
two untyped step kinds — arbitrary and send-message — when exactly one side
resolves to a User, the other side must be a UI element or a definition
whose enclosing context has the application intention. Otherwise it is an
Error.
Use Case Completeness
RIDDL analyzes whether each use-case step is witnessed by the model's structure, and whether the ordered sequence of steps is an admissible trace through the state machines of the entities it drives. Both emit CompletenessWarnings:
- A
sendstep whose receiver has no matchingonclause, or no reachable wiring from sender to receiver - A
show outputstep with no handler doingput … to <output> - A
take/select inputstep whose input type nothing consumes - A message delivered to an entity in a state that does not handle it
- A step whose free-text prose contains no word found in the in-scope
vocabulary, so it is unlikely to be AI-translatable into a test. Adding
termdefinitions and descriptions enlarges the vocabulary and quiets this.
Modules and Imports¶
A module is a named, flat collection of any top-level definition:
module Commerce is {
domain Shopping is { ??? }
type Money is Decimal(12, 2)
author Reid is { name is "Reid Spencer" email is "reid@ossuminc.com" }
}
Modules can be compiled to a binary .bast file and imported by other models.
Importing¶
The full form takes everything the file's root module holds:
The selective form takes exactly one named definition, optionally renamed:
An importable kind may be any of domain, context, entity, type, epic,
saga, adaptor, function, projector, repository, streamlet,
author, module, user, connector, constant, invariant.
An imported definition must be structurally legal where the directive sits, exactly as if it had been written there by hand. An illegal placement is an Error.
Import vs Include¶
include "file.riddl"splices source text; the parser rules are determined by the enclosing container.import "file.bast"loads compiled definitions from a binary module.
Include Hygiene
- StyleWarning: an included file whose path does not end in
.riddl - MissingWarning: an include that parsed but contributed no definitions
Version¶
A version declares a component of a scope's version coordinate. It is either a
name or a natural number, never both:
domain Garibaldi is {
version Garibaldi
context Ordering is {
version 4
command Reorder is { orderId is UUID }
record OrderState is { status is String }
entity Order is {
version 3
handler OrderLifecycle is {
on init(start: OrderState) is { morph entity Order to state Open with start }
}
state Open of record OrderState is {
handler OrderHandler is { on command Reorder { ??? } }
}
}
}
}
A definition's precise version is composed from every versioned ancestor,
root to leaf, joined with .. The Order entity above is Garibaldi.4.3. Only
scopes that actually bear a version contribute a component, so an unversioned
context would give Garibaldi.3 — which is what makes adoption incremental.
Versions may be declared at Root, Module, Domain, and all six processor kinds. Declaring more than one version in a single scope is an Error.
A version coordinate is not a semantic version
The composed form looks like semver but is a hierarchical coordinate.
Do not read compatibility into it: 3.1.6 → 3.2.1 says nothing about
breakage, and Garibaldi.4.3 is not orderable against Jellyfish.1.1 at
all. Its length varies with nesting depth, so comparison must be
component-wise. A generator targeting a semver-demanding ecosystem needs an
explicit mapping rule.
Copyright¶
A copyright is a named notice carried verbatim:
domain Shopping is {
copyright House is "© 2026 Ossum Inc."
external context StripePayments is {
copyright Stripe is "© 2026 Stripe, Inc."
}
}
The literal string is the notice in its entirety — symbol, year and holder — because notices vary by jurisdiction, holder and license.
Unlike version, a copyright does not compose. The applicable notice is the
one declared by the definition itself or, failing that, by the nearest
ancestor that declares one. That is the point of allowing it at inner scopes: a
vendored external context bearing a third party's notice must override its
enclosing domain's, not be appended to it.
Copyrights may be declared at the same nine scopes as versions. Declaring more than one in a single scope is an Error.
Metadata¶
Metadata goes in a with { } block after the closing brace of the
definition:
event-sourced entity Product is {
// Entity definition content
???
} with {
briefly as "Product available for purchase"
described by {
| Represents a product in the catalog that customers can purchase.
}
by author Reid
term SKU is {
| Stock Keeping Unit, the unique identifier for a variant
}
}
The available metadata kinds are briefly, described by/described at/
described in file, term, option, by author, figma, attachment and
comments.
Metadata Validation
Style Warnings:
- Repeating a single-valued metadata kind (
briefly,ulid). Only the first is used.author,see,term,option,commentanddescribedmay be repeated freely. - The same
termname defined at two scopes with different definition text. Identical redefinitions are fine.
Missing Warnings:
- A Domain that identifies no author, considering its own author references and defined authors as well as those of any enclosing domain
Figma References¶
A figma reference connects a model element to the exact frame in a Figma file
that depicts it:
application context Storefront is {
page Checkout is { ??? } with {
figma "aBcD1234" node "42:1337"
}
}
The two literal strings are the file key and the node id — exactly the two arguments the Figma REST API takes — so the reference resolves to one frame rather than a document a human must search.
It is metadata, not a definition: it has no identifier, nothing can
path-reference it, and it contributes nothing to the symbol table. It is
permitted on Input, Output, Group, and an application context — the
definitions that describe user interface.
Drift validation is opt-in and off by default
With --check-figma-drift and a FIGMA_TOKEN in the environment, a node
the API does not know about is an Error, and a frame whose name does not
correspond to the annotated definition's name is a Warning. Names are
compared on letters and digits only, so Payment Screen, PaymentScreen
and payment_screen all correspond.
An offline build cannot be affected: the flag is off by default, no token means no client, and every failure to reach or understand the API produces nothing at all. Only a successful API answer can produce a message.
Validation Message Severity¶
RIDDL's validator produces messages at the following severity levels (from lowest to highest):
| Severity | Kind | Description |
|---|---|---|
| 0 | Tip | Suggestions, shown with --provide-tips |
| 0 | Info | Informational notes |
| 1 | StyleWarning | Naming and style conventions |
| 1 | Advisory | A structural fact consistent with the model as written but unusual for what such a declaration normally means. Not a warning |
| 2 | MissingWarning | Missing optional content |
| 3 | UsageWarning | Unused definitions or unreferenced declarations |
| 3 | Deprecation | Use of a construct slated for removal |
| 4 | CompletenessWarning | Model is valid but incomplete for implementation |
| 5 | Warning | Likely mistakes or problematic patterns |
| 6 | Error | Invalid constructs that prevent compilation |
| 7 | SevereError | Fatal errors that halt processing |
Deprecation messages are rendered with their own [deprecated] label rather
than being folded in with ordinary warnings, so a model can be checked for zero
deprecations independently of zero warnings. They surface under every command —
parse, validate, stats, bastify and the prettify and generation
commands — not only validate.
Advisory (severity 1, since 2.2.0) is not a warning: --fail-on warning
does not trip on it, -w does not hide it, and it never blocks generation.
It has its own switch, --show-advisories (default true). The bar for one
is that a modeller may dismiss it by design, not only by editing — the rule
that made the kind necessary is adaptor-direction-advisory, which had been
a Warning and so blocked generation for a design choice the model is entitled
to make.
The other Advisories in 2.7.0 are the three journal counts on an entity
(entity-event-sourced-unread-history, entity-event-sourced-snapshot-events
and entity-crud-with-transitions-consumed; see
Does the journal earn its keep?),
and stmt-yield-argument-prompt (see
Yield and Reply Statements).
CompletenessWarning (severity 4) identifies models that parse and validate
correctly but are missing details needed for a complete, implementable
specification. They can be toggled with the -c /
--show-completeness-warnings CLI flag (default: true).
Messages at severity 4 and above are considered actionable — they should be addressed before considering a model ready for translation or code generation.
Best Practices¶
- Include Metadata: Add descriptions to all definitions in
withclauses after their closing braces. - Be Explicit: Always specify reference kinds (entity, command, event…).
- Ascribe Shapes: Write
as <shape>on any processor with ports, so the intent is stated rather than inferred. - Name Constants: a literal comparison operand is legal but draws a style
warning, so give thresholds names —
constant MaxItems is Natural = 100— rather than embedding magic numbers. The name records what the threshold means; the number alone does not. - Declare
yields: A command or query that declares its response gives generators a precise signature and lets the validator check conformance. - Start explicitly: Give each entity with states an entity-level
on initthatmorphs into its starting state, and mark a state'sinitialhandler when it has several. Neither depends on declaration order, so the model is safe to reorder. - Refuse First: Put every
requireanderrorahead of every effect. - End When Statements: Always terminate
whenwithend. - Use Match for Multiple Conditions: Prefer
matchover a chain ofwhenstatements. - Model Complete Flows: Include UI components and user interactions, and
keep all UI inside an
applicationcontext. - Follow Containment Rules: Only define elements within their appropriate containers.
- Terminate Every Stream: Every outlet needs a connector; route genuinely
unused output to
BottomlessPit.
Common Parse Errors¶
Some mistakes produce an error that does not point at the thing that is wrong. These are the ones worth recognising by their symptom.
Expected ("(") at a field, far from any obvious cause¶
You have named one of your own types after a parameterized predefined type. The parser reaches the reference, recognises the built-in name, and demands its argument list — so the error is reported at the use, which may be hundreds of lines from the declaration that caused it.
type Currency is any of { USD, EUR, GBP, JPY } // the actual cause
// ...
record Payment is {
amount: Currency // Expected ("(") reported HERE
}
The fix is to rename your type — CurrencyCode, say.
Predefined names whose parentheses are required produce this misleading
form: Currency, Decimal, Pattern, Id. Naming a type after a bare
predefined instead gives a clear, well-located error at the declaration —
"Type 'Location' redefines built-in type 'Location'" — so those are easy.
The full set of reserved type names:
| Group | Names |
|---|---|
| Text | String, Pattern, URL |
| Numeric | Boolean, Integer, Natural, Whole, Number, Real, Decimal |
| Physical | Current, Length, Luminosity, Mass, Mole, Temperature |
| Temporal | Date, Time, DateTime, TimeStamp, Duration, ZonedDate, ZonedDateTime |
| Identity | UUID, UserId, Id |
| Other | Currency, Location, Nothing, Anything, Abstract |
Grep a model for these before you start if you are hunting an error of this shape.
Expected one of ("*" | "+" | "," | …) after a collection field¶
You have written many of X. The collection prefix is many with no
of:
items: many ProductInfo // correct
items: ProductInfo* // equivalent
items: many of ProductInfo // does not parse
of does belong to the other collection forms — sequence of X, set of X,
graph of X, mapping from K to V — which is what makes many of such an
easy slip.
Expected one of ("(" | "yields") at the is of a message¶
The body is empty. RIDDL has no empty body; use the ??? placeholder:
The error lands on is rather than on the braces, because the parser is still
looking for what may follow the identifier.
A comment after ???¶
??? ends the body, so nothing may follow it inside the braces. A comment
may, however, come before it — that is the whole point of the
undefined = {comment} "???" production:
domain MyDomain is {
// Start building your domain model here
??? // fine -- the comment introduces the stub
}
domain MyDomain is {
???
// Start building your domain model here
// does not parse -- ??? already closed the body
}
Both parts survive a prettify round trip. The comment is kept as part of
the container's contents, and the ??? is re-emitted for a body that holds
nothing but comments — because the marker records deliberate intent ("not
specified yet") that a bare comment does not.
Undefined Bodies¶
??? is available wherever a body may be left unspecified, and the same rule
applies at each: an optional run of comments, then the marker. That covers
container bodies (domain, context, entity, processor, repository, adaptor,
projector, group, handler, author), type bodies (aggregate_definitions,
enumerators, alternation_contents), statement blocks, with { } metadata
blocks and doc blocks.
Common Syntax Issues¶
- Don't use
=to assign fields; useset field x to <value>.let x = …is valid for local bindings. - Don't forget
endafterwhenstatements. - Always include reference kinds before identifiers.
state … ofandmorph … withtake a record, not a message.sendtargets an outlet; usetellfor direct delivery to a processor.- A comparison operand may be any expression, literals included — but a bare literal draws a style warning, so name the value.
- Place comments only where definitions are allowed, not within clauses.
- Metadata blocks follow their definitions rather than being nested within them.
- Never place entity, type, or repository definitions directly within a domain — they belong in a context. (A repository is the exception, when it genuinely spans contexts.)
- Never place definitions inside an author — authors only contain metadata.
- Use
whenfor conditionals;ifis not supported. - Use
dofor describing implementation logic, not bare quoted strings. - Every adaptor handler needs an
on otherclause. - Attach at most one connector to any port.
Incomplete Definitions¶
??? means "known to be incomplete", and validation treats it as such: a
definition whose body is ??? earns at most a Missing warning saying the
body should be provided, and every other check is skipped for it —
structural requirements, completeness, wiring, cross-references. The author has
already said don't expect much, so the validator does not pile on.
That exemption is why ??? stubs are safe to use liberally while a model is
being drafted, and why a ??? entity is never reported as failing to receive a
message told to it.
Use ??? as a placeholder for incomplete definitions:
record PaymentDetails is { ??? } with {
briefly as "Record for payment information details"
}
page Checkout is { ??? } with {
briefly as "Checkout page for completing purchase"
}
Author Inheritance¶
Authors are defined once and inherited throughout the model hierarchy, but
cannot contain any definitions. An author definition may only appear in a
Module or a Domain body; everywhere else, reference one with by author Name in
the with { } block:
domain ShopifyCart is {
author Claude is {
name is "Anthropic Claude"
email is "support@anthropic.com"
} with {
briefly as "Model creator and maintainer"
}
context ShoppingContext is {
???
} with {
by author Claude
briefly as "Main shopping context containing commerce entities"
}
} with {
briefly as "Shopping cart domain model"
}
Deprecated Constructs¶
Everything below still parses in 2.x and emits a [deprecated] message. All of
it is slated for removal in 3.0.
| Deprecated | Write instead | Rule id | Fixed by |
|---|---|---|---|
processor P is { … } |
streamlet P is { … } |
stream-processor-keyword |
--fix, prettify |
source/sink/flow/merge/split/router as keywords |
streamlet <id> as <shape> |
shape-keyword |
prettify |
initiate entity E |
create entity E |
value-initiate-keyword |
--fix, prettify |
prompt "..." statement |
do "..." |
prompt-statement |
--fix, prettify |
Abstract |
Anything |
abstract-type |
--fix, prettify |
a quoted numeric constant, = "5" |
= 5 |
quoted-constant-literal |
--fix, prettify |
reference to entity E |
Id(entity E) |
type-reference-to-is-id |
--fix, prettify |
type C is command { … } (any message kind) |
command C is { … } |
type-first-aggregate |
prettify |
state X is record R, or no introducer |
state X of record R |
state-is-record |
prettify |
entity option is event-sourced/aggregate/transient/consistent/available |
that word before entity |
entity-option-to-intention |
prettify |
entity option is value |
persistent before entity (renamed) |
entity-option-to-intention |
prettify |
connector option persistent/at-least-once/at-most-once/exactly-once |
that word before connector |
connector-option-to-intention |
prettify |
context option is gateway/service/external |
that word before context |
opt-deprecated |
by hand |
context option is wrapper |
an adaptor | opt-deprecated |
by hand |
option is package |
option is namespace |
opt-deprecated |
by hand |
when "a natural-language condition" |
when prompt("…"), or a boolean expression |
bare-string-condition |
by hand |
send … to inlet X |
send … to outlet Y, or tell |
send-to-inlet |
by hand |
requires { … } / returns { … } inline aggregation |
requires <TypeRef> / returns <TypeRef> |
func-inline-aggregation |
by hand |
one of { A }, an alternation of one |
a second alternative, or A itself |
single-alternation |
by hand |
| an anonymous nebula (definitions with no wrapper) | module <Name> is { … } |
anonymous-nebula |
by hand |
initial state X |
an entity-level on init that morphs into X |
entity-initial-state-marker |
by hand |
ask query Q of P where Q has fields |
ask query Q(f = v, …) of P |
value-ask-bare-query |
by hand |
an entity with states whose on init does not morph, or that has none |
on init(…) is { morph entity E to state S with … } |
entity-init-no-morph |
by hand |
on init inside a state's handler |
the entity-level on init; a per-state action is on entry |
entity-init-in-state |
by hand |
Fixed by says what migrates it mechanically. --fix is riddlc validate --fix, which
rewrites the file in place; prettify is riddlc prettify, which writes a normalized copy.
"By hand" means neither does: the replacement needs a judgement the tool cannot make. Checked
against riddlc 2.7.0.