Guard decisions with Cratis Chronicle decision reads
Use a Cratis Chronicle decision read when a command must check state and reject its append if another writer changes that state. The read folds events, applying them in order to compute a read model, and supplies a concurrency guard for the append. A matching event appended after the read’s boundary makes the guarded append report a concurrency violation and write nothing.
A plain read can tell you that a workshop has one place left. A decision read also lets the append detect another booking made while your command was deciding. It uses optimistic concurrency: read and decide first, then check for competing writes when appending.
| The guard | What it does |
|---|---|
| Notes the log position before it folds | Events appended while you decide are caught |
| Watches the key and the model’s event types | An unrelated append does not conflict with that guard; combined reads can widen it |
| Guards an absent model too | A concurrent creation conflicts |
| Is optimistic concurrency | Nothing is retried for you and nothing is locked |
For a unique value or a create-once rule, use a constraint to check the rule on every append. A plain read through IReadModels or an injected read model guards nothing, even when it is passive. Choosing how a rule holds compares the options, and Scenarios shows each as code.
If a decision read fits your rule, continue here for the read and commit lifecycle. How guards are derived explains its exact scope, and What a decision read costs covers the replay work.
Your first decision read
Section titled “Your first decision read”A workshop has a fixed number of places. Read the workshop, check the rule, and append with the read as the guard.
using Cratis.Chronicle;using Cratis.Chronicle.Events;using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.Projections.ModelBound;using Cratis.Chronicle.ReadModels;
public record WorkshopId(string Value) : EventSourceId(Value);
[EventType]public record WorkshopOpened(int Places);
[EventType]public record PlaceBooked(string Attendee);
[EventType]public record PlaceCancelled(string Attendee);
// The decision model: a flat projection with an Id, keyed by the event source.[FromEvent<WorkshopOpened>]public record WorkshopPlaces( string Id, [SetFrom<WorkshopOpened>(nameof(WorkshopOpened.Places))] int Total, [Increment<PlaceBooked>] [Decrement<PlaceCancelled>] int Booked);
public static class BookPlace{ public static async Task<bool> Handle(IEventStore eventStore, WorkshopId workshop, string attendee) { // 1. The read notes the log position, then folds the workshop's events. var read = await eventStore.GetDecisionReads().GetDetached<WorkshopPlaces>(new ReadModelKey(workshop.Value)); if (read.Instance is not { } places || places.Booked >= places.Total) { return false; }
// 2. The append carries the read as its guard. A later PlaceBooked, PlaceCancelled or // WorkshopOpened for this workshop rejects it and nothing is written. var result = await eventStore.EventLog.AppendMany( [new EventForEventSourceId(workshop, new PlaceBooked(attendee))], guardedBy: [read]);
return result.IsSuccess; }}defmodule MyApp.Events.DecisionReadsWorkshopOpened do use Chronicle.Events.EventType, id: "decision-reads-workshop-opened"
defstruct [:places]end
defmodule MyApp.Events.DecisionReadsPlaceBooked do use Chronicle.Events.EventType, id: "decision-reads-place-booked"
defstruct [:attendee]end
defmodule MyApp.Events.DecisionReadsPlaceCancelled do use Chronicle.Events.EventType, id: "decision-reads-place-cancelled"
defstruct [:attendee]end
# The decision model: a flat projection keyed by the event source.defmodule MyApp.ReadModels.DecisionReadsWorkshopPlaces do use Chronicle.ReadModels.ReadModel
defstruct id: nil, total: 0, booked: 0
from MyApp.Events.DecisionReadsWorkshopOpened, set: [id: :event_source_id, total: :places] from MyApp.Events.DecisionReadsPlaceBooked, add: [booked: 1] from MyApp.Events.DecisionReadsPlaceCancelled, subtract: [booked: 1]end
defmodule MyApp.DecisionReadsBookPlace do alias Chronicle.EventSequences.EventLog alias Chronicle.ReadModels.{DecisionConflict, DecisionReads} alias MyApp.Events.DecisionReadsPlaceBooked alias MyApp.ReadModels.DecisionReadsWorkshopPlaces
def handle(workshop_id, attendee) do result = Chronicle.decide(fn _unit_of_work -> # 1. The read notes the log position, folds the workshop's events and enrolls # itself as the guard of the unit of work. {:ok, read} = DecisionReads.get(DecisionReadsWorkshopPlaces, workshop_id)
case read.instance do %DecisionReadsWorkshopPlaces{total: total, booked: booked} when booked < total -> # 2. The append is buffered and committed with the guard. A later booking, # cancellation or opening for this workshop rejects the whole commit. :ok = EventLog.append(workshop_id, %DecisionReadsPlaceBooked{attendee: attendee}) :booked
_ -> :full end end)
case result do {:ok, :booked} -> true {:ok, :full} -> false {:error, %DecisionConflict{}} -> false {:error, _reason} -> false end endendWorkshopPlaces.Id identifies the workshop, so the fold and the guard refer to the same event source. Chronicle refuses projection shapes it cannot guard; see Admitted projections.
GetDetached returns both state and a guard. Pass that read to the append through guardedBy; reading alone does not protect anything. Instance is null when no event has created the model, and the guard covers that absent state too.
An append conflict is returned in the result rather than thrown as an exception. Read again and re-evaluate the rule before trying a new append. To distinguish a decision conflict from a constraint violation or another append failure, inspect the conflicts and check IsSuccess separately.
using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.ReadModels;
var read = await eventStore.GetDecisionReads().GetDetached<OrderEligibility>(orderId);if (!read.Exists){ // Decide whether creation is allowed, including the absent case.}
var result = await eventStore.EventLog.AppendMany( [new EventForEventSourceId(orderId, new OrderPlaced())], guardedBy: [read]);var conflicts = result.GetDecisionConflicts([read]);if (conflicts.Any()){ // The decision must be read again and resubmitted; no sequence numbers are exposed.}// Check result.IsSuccess separately for constraint violations and other append failures.Get<T>(key) enrolls the read in the unit of work instead of returning a detached guard. The next section covers that.
A decision read is Chronicle’s form of a Dynamic Consistency Boundary (DCB) decision model and append condition, within its one-event-source-per-event model. Dynamic Consistency Boundary in Chronicle says what maps and what does not, and DCB examples in Chronicle shows the canonical examples. To scope a read to one stream and append through an event source definition, see Event sources and the Dynamic Consistency Boundary.
Unit-of-work lifecycle
Section titled “Unit-of-work lifecycle”Use Get<T>(key) when the command runs in an ambient unit of work, the unit collecting its events for commit. It enrolls the read so that commit carries the guard. GetFor<T>(unit, key) does the same for the unit you pass, before returning the value.
GetDetached<T>(key) leaves you responsible for choosing the append that carries the guard. You can also enroll a detached read explicitly with IUnitOfWork.AddDecisionRead.
| Topic | Behavior |
|---|---|
| Detached reads under read protection | GetDetached is refused with DetachedReadWhileReadsAreProtected unless an advisory read allowance is open. A detached read is meant for a chosen append, and enrolling it silently would change which commit it guards |
| Who completes a protected unit | Its owner: UnitOfWork.ClaimDecisionReadCommitOwnership, then CommitAsOwner or RollbackAsOwner. Calling Commit() from application code after enrollment is rejected |
| Rollback and dispose | Once a claimed unit has enrolled a decision read, public Rollback() and Dispose() on an open unit are refused: only the owner can roll it back. During a pending commit, public and owner rollback throw UnitOfWorkIsCompleting in both Compatibility and Strict modes and keep the staged events. Disposal stays a no-op. A claim alone does not change rollback or disposal of a unit without enrolled reads, but owner rollback during a pending commit is still refused |
| Commit with no events | A protected commit with no events still validates the guard. A kernel too old to allow validate-only returns DecisionReadValidateOnlyNotSupported, never success |
| Staging after commit began | Units without decision reads keep their previous behavior by default: a late AddEvent or AddEvents stages events that cannot be appended, and each attempt logs an error with the correlation id and no event content. Protected units refuse late events in every mode |
| Strict policy | Set ChronicleOptions.UnitOfWorkLifecyclePolicy = UnitOfWorkLifecyclePolicy.Strict (also available through client and ASP.NET Core options) to reject staging as soon as commit begins, after commit failure, rollback or disposal. Strict rejection throws UnitOfWorkIsCompleted before it enumerates input or changes staged events |
In an ASP.NET Core request
Section titled “In an ASP.NET Core request”The Chronicle.AspNetCore middleware owns the request’s unit and normally completes it after the response has been written, so a conflict is reported too late to change the response. To respond to the outcome, ask the middleware’s owner to commit early with HttpContext.Features.Get<IUnitOfWorkCompletionFeature>() (in Cratis.Chronicle.AspNetCore.Transactions):
using Cratis.Chronicle.AspNetCore.Transactions;using Microsoft.AspNetCore.Http;
var completed = await HttpContext.Features.Get<IUnitOfWorkCompletionFeature>()!.CommitAsync();if (completed.GetDecisionConflicts().Any()){ return Conflict(); // Re-read and retry the decision in a new request.}if (!completed.IsSuccess){ // Handle constraint violations and other append failures before writing the response.}defmodule MyApp.Events.DecisionReadsEarlyOrderPlaced do use Chronicle.Events.EventType, id: "decision-reads-early-order-placed"
defstruct []end
defmodule MyApp.ReadModels.DecisionReadsEarlyOrderEligibility do use Chronicle.ReadModels.ReadModel
defstruct id: nil, placed: 0
from MyApp.Events.DecisionReadsEarlyOrderPlaced, set: [id: :event_source_id], add: [placed: 1]end
defmodule MyApp.DecisionReadsEarlyCommit do alias Chronicle.EventSequences.EventLog alias Chronicle.ReadModels.{DecisionConflict, DecisionReads} alias MyApp.Events.DecisionReadsEarlyOrderPlaced alias MyApp.ReadModels.DecisionReadsEarlyOrderEligibility
# Chronicle.decide/2 commits as soon as the function returns, so the outcome is known # while you can still choose the response. def place(order_id) do outcome = Chronicle.decide(fn _unit_of_work -> {:ok, read} = DecisionReads.get(DecisionReadsEarlyOrderEligibility, order_id)
if read.instance == nil do :ok = EventLog.append(order_id, %DecisionReadsEarlyOrderPlaced{}) end end)
case outcome do {:ok, _} -> :no_content
# Re-read and retry the decision in a new request. {:error, %DecisionConflict{}} -> :conflict
# Constraint violations and other append failures. {:error, _reason} -> :unprocessable_entity end endendThe middleware will not commit the completed unit again.
Inspecting the outcome
Section titled “Inspecting the outcome”IUnitOfWork.GetDecisionConflicts()maps violated labels toDecisionConflictvalues. Each names the read model (ReadModelType, and its identifier asReadModel) and the key. When the kernel reports it, it also names the first event that matched the decision’s guard after the read:ConflictingEventTypeIdandConflictingEventSequenceNumber. Reads that share a guard are merged, so that event can belong to another read under the same guard. Both are null with a kernel that does not report them.- A
DecisionConflictserializes with System.Text.Json as the read model identifier, the key and the conflicting event, without the CLR type. You can return it as a response body, for exampleResults.Conflict(unitOfWork.GetDecisionConflicts()). IUnitOfWork.HasEnrolledDecisionReadssays that at least one decision read was enrolled, including through a directAddDecisionReadcall. On Chronicle’s unit of work it stays true after commit, rollback or disposal. Custom implementations default tofalsefor compatibility, so afalsefrom one of those is not proof that it cannot enroll protected reads. The property does not grant permission to commit a protected unit without its owner capability.
Admitted projections
Section titled “Admitted projections”For a whole-source projection read, Chronicle admits a single event-log projection keyed directly by event source ID, with a nonempty finite set of event types, including removal types. The client must be able to identify the events that affect the decision. Joins, including variants, children, nested projections, derivatives, event-property routing, all-event subscriptions and projections on other sequences are refused. Routing keys must be empty or $eventSourceId. Reducers have separate admission rules; stream-scoped projections are covered below.
Use a string key without a converting format, or a GUID key in lowercase canonical D form. GUID concepts follow the same rule. Every writer of source IDs for a GUID-keyed model must use that form: an alternate casing or format is outside the guarantee even when the read key is canonical. Numeric and other converting key types, and models without a key property, are refused.
Empty keys, *, keys containing #, leading or trailing whitespace, and event type IDs containing commas are refused. IDecisionReads.Admit<T>() checks the projection shape without I/O; Get also validates the key. An unsafe shape or key throws DecisionReadRefused with a typed reason before reading.
The client captures the unfiltered event-log boundary before folding and uses it for the guard. It also checks a filtered tail to detect a fold that missed matching events; an incomplete fold detected by that probe refuses with FoldIncomplete.
The .NET client’s first-use comparison checks listed client and kernel definitions. A missing read-model or projection definition refuses with DefinitionMissing; a different or ambiguous definition refuses with DefinitionMismatch. The message names the missing definition or differing part, such as observer identity, generation delivery, event types or key routing, without dumping definition values.
These checks are diagnostics, not proof that every executing projection has the expected definition and initialization state. Stop protected commands while deploying definition changes, including while caches across silos converge, and resume only once execution agrees with the client’s definition.
Multiple reads of one key merge their event types and use their earliest boundary. An explicit competing scope on that key is refused; a decision scope replaces an ordinary append-time default scope. Each guard must target the same event store, namespace and event-log sequence as its append.
Definition agreement and reconnects
Section titled “Definition agreement and reconnects”The .NET client caches successful agreement checks per model and read scope, not refusals. A missing or mismatched definition is checked once more before the read refuses. A later read checks again, so a temporary disagreement during kernel startup does not require restarting the application. No fold or guard is returned while the listed definitions disagree.
Connecting, disconnecting, and successful projection registration clear the agreement cache. Successful checks otherwise stay cached between reads. A kernel restart that the connection does not observe cannot invalidate a successful cached check; this diagnostic still does not certify the executing projection’s definition.
For DefinitionMissing, ensure artifact registration has completed on the kernel before retrying. For DefinitionMismatch, inspect the named differences and align the definitions. Do not repeatedly re-register projections as a retry mechanism: full-set registration can trigger evolution, replay and retirement.
Reducers
Section titled “Reducers”A reducer or self-reducing read model can be read as a decision read, with or without read protection. Chronicle does not use a projection session for it. The client fetches every event of the handled types for the source from the event log, runs the reducer over them, and checks that the fold reached everything it should have. The guard uses the source ID and the reducer’s event types, as a whole-source projection guard does. The read can take up to three attempts.
Admit<T>() and Describe<T>() assess a reducer without I/O. A reducer that cannot be guarded exactly is refused with a typed reason before it runs:
| Reason | Why the reducer is refused | Fix |
|---|---|---|
NotEventLog |
The reducer observes an event sequence other than the event log | Read a model on the event log |
ReducerFilters |
The reducer filters its events by tag, event source type or event stream type, and a decision read cannot reproduce the filter exactly | Remove the filter, or use a projection |
ReducerDependencies |
A classic reducer has a constructor parameter other than ILogger<T>. Self-reducing read models are not subject to this rule |
Remove the dependency, or record what the fold needs in the event |
NoEventTypes |
The reducer handles no event types | Add a handler |
UnsupportedEventTypeId |
A handled event type ID contains a comma | Rename the event type |
ReducerGeneration |
A handled event type is registered with more than one generation, the generation a handler declares is unavailable, or an event was revised to another generation | Handle one generation per event type, and register the generation |
ReducerDispatchIncomplete |
The reducer did not receive every fetched event of its handled types | Check the reducer’s handlers for every handled event type |
InvalidKey |
The key is not a single event source ID | Pass the raw event source ID |
StreamScopeNotSupported |
A stream-scoped read was requested | Read the whole source |
FoldIncomplete |
After three attempts the fold had not reached the latest matching event | Try again |
Reducer |
The reducer cannot be resolved for the read model | Register the reducer |
A reducer that throws is not a refusal: the read fails with an InvalidOperationException that carries the reducer’s messages. Reducer code runs with read allowances suspended, so a reducer that calls Chronicle reads inside a protected invocation is refused by the guards.
Like a projection decision read, a reducer decision read processes the source’s history of handled event types on each attempt. Its cost grows with that history and with the reducer’s own work.
Pinned generation delivery
Section titled “Pinned generation delivery”Pinned generation delivery asks a projection to receive particular event generations. A decision fold runs with Compatibility delivery instead, so it cannot honor that choice. While read protection is active, Chronicle refuses the decision read with GenerationDeliveryNotSupported rather than silently using different generations.
The refusal applies when a protected frame is active or the receiving unit enforces read protection. Outside that protection, the read is not refused for this reason. Check Describe<T>().UsesPinnedGenerationDelivery before reading. Use Compatibility delivery for a protected decision read, or use a plain read when you do not need an append guard.
Scoped to one event stream
Section titled “Scoped to one event stream”When a decision concerns one stream within an event source, pass the source ID, stream type and stream ID to Get<T> or GetDetached<T>. The fold and its append guard use the same stream filters, so an append on another stream does not invalidate that guard. An optional event source type narrows both further. Additional enrolled reads or declared concurrency can widen the combined guard.
using Cratis.Chronicle;using Cratis.Chronicle.Events;using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.Projections.ModelBound;using Cratis.Chronicle.ReadModels;
[EventType]public record StreamOrderPlaced(string Status);
[Passive][FromEvent<StreamOrderPlaced>]public record StreamOrderEligibility(string Id, string Status);
public static class StreamDecisionExample{ public static async Task<AppendManyResult> PlaceOrder( IEventStore eventStore, EventSourceId orderId) { var read = await eventStore.GetDecisionReads().GetDetached<StreamOrderEligibility>( orderId, eventStreamType: "orders", eventStreamId: "checkout"); // Make the decision using read.Instance, including the absent case. return await eventStore.EventLog.AppendMany( [new EventForEventSourceId(orderId, new StreamOrderPlaced("placed")) { EventStreamType = "orders", EventStreamId = "checkout" }], guardedBy: [read]); // The caller checks IsSuccess and handles conflicts before resubmitting. }}defmodule MyApp.Events.StreamOrderPlaced do use Chronicle.Events.EventType, id: "stream-order-placed"
defstruct [:status]end
defmodule MyApp.ReadModels.StreamOrderEligibility do use Chronicle.ReadModels.ReadModel, passive: true
defstruct id: nil, status: nil
from MyApp.Events.StreamOrderPlaced, set: [id: :event_source_id, status: :status]end
defmodule MyApp.StreamDecisionExample do alias Chronicle.EventSequences.EventLog alias Chronicle.ReadModels.DecisionReads alias MyApp.Events.StreamOrderPlaced alias MyApp.ReadModels.StreamOrderEligibility
def place_order(order_id) do Chronicle.decide(fn _unit_of_work -> # Folds and guards only the "orders" / "checkout" stream of this event source. {:ok, read} = DecisionReads.get(StreamOrderEligibility, order_id, "orders", "checkout")
# Make the decision using read.instance, including the absent case. if read.instance == nil do EventLog.append(order_id, %StreamOrderPlaced{status: "placed"}, event_stream_type: "orders", event_stream_id: "checkout" ) end end) endendThe stream type and stream id are strings here. With an event source definition you can take them from the definition, so the read and the append use the same values. See Event sources and the Dynamic Consistency Boundary.
AdmitForStream<T>() admits the same finite, flat event-log projections as Admit<T>(). It also admits projections consistently keyed by $eventContext(eventStreamId) across their creation, update and removal events.
A source-keyed projection keeps the source ID as its model key but folds only the selected stream. A stream-keyed projection uses the stream ID as its model key; its concurrency label still identifies the source. For a GUID-keyed stream projection, use lowercase canonical D form for stream IDs on every append and read, just as source-keyed GUID projections require it for source IDs.
Reading a stream-keyed projection without stream scope refuses with StreamKeyRequiresStreamScope. The kernel must acknowledge stream scoping; an older kernel refuses with StreamScopeNotSupported rather than silently folding the whole source. A stream-scoped reducer read also refuses with StreamScopeNotSupported, because reducer decision reads fold the whole source.
The stream-scoped overload requires a specific stream type: EventStreamType.All refuses with AllStreamsNotSupported.
For an event-source-keyed projection, EventStreamId.Default is allowed with a specific stream type, including types that use only the default ID. Here, default means no stream-ID restriction: the fold and guard cover every ID within that source and stream type. A stream-keyed projection needs an explicit stream ID instead. Passing default refuses with StreamKeyRequiresExplicitStreamId because it could fold several instance keys together.
Reads of the same source merge into one guard, and reads of different streams widen it. How guards are derived has the merge rules.
A materialized projection keyed only by stream ID can collide when two event sources use the same stream ID. Prefer a passive projection ([Passive]) for these decision folds, or use a composite key for materialization. Composite-key projections are not admitted for protected decision reads. Command-property binding belongs to Arc; Chronicle supplies the explicit read API.
Declaring a per-stream read model
Section titled “Declaring a per-stream read model”Use [EventStream<TSource>(stream)] from Cratis.Chronicle.ReadModels when a model always represents one stream declared by an IEventSource. The model stays keyed by event source ID, but its fold is scoped to the stream. The attribute implies passive for model-bound and fluent projections, so no stored instance mixes months.
Key-only Get, GetFor and GetDetached refuse with ReadModelRequiresStreamScope. Use the stream overload and pass the declaration’s event source type as well as its stream type; an omitted or different source type, or a different stream type, refuses with StreamScopeDoesNotMatchReadModel. AdmitForStream<T>() assesses the stream shape; key-only Admit<T>() reports the required scope. Reducers, stream-keyed models, undeclared streams and All are invalid declarations.
The plain instance read, the route every writer must use and a worked monthly limit are on Read models scoped to one event stream. Existing models without this attribute retain their current key-only and stream-scoped behavior.
Limits and assumptions
Section titled “Limits and assumptions”The guard relies on a single ordered event-log writer, ordered primary storage reads, stable projection execution, and literal identity between source IDs and keys. It detects matching appends after its boundary regardless of which writer appended them. But it protects only decisions that carry a guard: an unguarded writer can still break the rule. Every writer deciding on that rule must participate, or the rule must be a constraint checked by the kernel on every append.
Revision and redaction change existing history without advancing the append tail. The .NET client captures the kernel’s mutation epoch, a sequence-wide marker, before folding when the kernel reports one. A changed or in-progress epoch rejects the guard. That can cause a conflict even when the mutation concerns another source or stream. Without the marker, those history changes are not detected by an append-tail guard. Migration generation replacement can bypass the grain and remains outside this protection, as do external data, clock values, other event sequences and definition changes.
A removal followed by recreation with nonempty defaults can fold differently from materialization even though the append guard still works. Check that the on-demand result represents the state your rule needs.
Each projection attempt makes two tail remote calls, activates a fresh session, folds the key’s relevant history and requests that the session be released. A read may take up to three attempts. The .NET client’s first read of each model type and read scope after a cache reset also makes two definition-listing calls; a missing or mismatched definition causes one more pair before refusal. Allow for that work when choosing the history a decision model will read.
The minimum supported kernel is Chronicle 19.0.0 with ExpectsNoMatchingEvent scope validation, introduced in 16.34. Older kernels can silently skip an empty-log guard.
When the kernel renumbers an append after a duplicate-sequence collision, it validates the scopes again before writing, as of Chronicle 19.40.1, so a decision read’s guard still applies on that path. Constraints are not run again there. Older kernels renumbered without validating again, so on those a duplicate grain activation or an unresolved earlier storage outcome could defeat this and existing concurrency scopes. Quiesce such writers when you must support a kernel older than 19.40.1. Writes that bypass the kernel’s append path are never guarded.