Build self-reducing read models in Cratis Chronicle
A self-reducing read model in Cratis Chronicle keeps its state and transitions on the same .NET type.
Declare public static Reduce methods when the next state depends on the previous state and a
separate reducer class adds no useful separation. Each method is a fold: it combines an event with
current state to produce the next state. Start with this form for new reducer code.
If a fold needs injected services or the model is a shared contract that must stay separate, use
IReducerFor<T> instead. Choose how to build a read model
compares both forms with projection mappings. Self reducers use the same storage, filtering, and
replay pipeline as instance reducers; their discovery and invocation differ.
Declare the transitions
Section titled “Declare the transitions”Start with the state your caller needs, then declare public static Reduce methods on that concrete,
non-generic model. Each method receives an event and nullable current state and returns the next
state. No marker attribute or parameterless constructor is required:
using Cratis.Chronicle.Events;
[EventType]public record SelfBalanceAdded(decimal Amount);
[EventType]public record SelfBalanceCleared;
public record SelfAccountBalance(decimal Balance){ public static SelfAccountBalance Reduce(SelfBalanceAdded @event, SelfAccountBalance? current) => new((current?.Balance ?? 0m) + @event.Amount);
public static SelfAccountBalance? Reduce(SelfBalanceCleared @event, SelfAccountBalance? current) => null;}Kotlin does not support this workflow yet.Track self-reducing read model support: https://github.com/Cratis/Chronicle/issues/4851Java does not support this workflow yet.Track self-reducing read model support: https://github.com/Cratis/Chronicle/issues/4851This Chronicle client does not support this workflow yet.Track https://github.com/Cratis/Chronicle/issues/4851 before using self-reducing read models from Elixir.TypeScript does not support this workflow yet.Track https://github.com/Cratis/Chronicle/issues/4851 before using this API from this language.The balance example adds an amount to the previous balance, starting from zero if no state exists.
Clearing returns null. In any self reducer, returning a new model creates or updates the instance;
returning current ignores the event; returning null leaves it absent or removes existing state.
An event after removal receives null and can recreate the model.
| Part | Supported shape |
|---|---|
| Declaration | Public static, non-generic method named Reduce |
| Parameters | (event, current) or (event, current, EventContext) |
| Event | Non-object class or interface dispatch target |
| Current | Exactly the containing model type, nullable or declared without nullable annotations |
| Result | The model or Task of the model, including nullable results |
Chronicle awaits an asynchronous result before applying the next event. Plain Task, ValueTask,
and Task<object> are not state results. By-ref, optional, params, extra service, and reordered
arguments are not supported. The current parameter must allow null because state can be absent;
a non-nullable declaration is an almost-correct signature, not a promise Chronicle can satisfy.
Discovery and upgrades
Section titled “Discovery and upgrades”A method named Reduce is not enough on its own: discovery requires the complete static shape.
Other shapes remain helpers, except that a static near miss whose current or result refers to its
model logs a warning and is skipped. Explicit registration rejects that near miss with
InvalidSelfReducerSignature. Fix the signature before relying on the model’s transitions.
Once a type has a valid self-reduction method, invalid sibling Reduce declarations and malformed
replay hooks fail validation. A valid method still needs a matching event in that client’s registry
before it creates an observer subscription. A type’s presence in an assembly does not register it as
an event; use [EventType] or explicit event registration.
Types implementing IReducer or IReducerFor<T> always remain classic, even with a self-shaped static helper. Their instance activation, dispatch and plain-Task behavior are unchanged.
Arc query endpoints
Section titled “Arc query endpoints”In an Arc application, keep [ReadModel], the static Reduce methods, and query methods on the same
record. Arc’s current automatic query discovery excludes methods taking the read model itself, so
a reducer method is not exposed as a query.
For an older Arc version without that exclusion, use [ReadModel(RequireQueryAttribute = true)] and
mark intended queries [Query]. Chronicle’s discovery does not change an older Arc version’s endpoint
discovery.
See Arc’s model-bound read models and queries for the query contract.
Register the model
Section titled “Register the model”Default discovery recognizes a valid self reducer in your application’s artifact catalog. With
manual or explicit artifact registration, nominate the model before creating the store. Use the
existing generic or Type RegisterReducer APIs, and include the events it handles:
using Cratis.Chronicle;
// These excerpts reuse SelfAccountBalance from the basic example.public static class SelfBalanceRegistrations{ public static void ConfigureGeneric(ChronicleOptions options) => options.ExplicitArtifacts.RegisterReducer<SelfAccountBalance>("account-balances");
public static void ConfigureRuntimeType(ChronicleOptions options) => options.ExplicitArtifacts.RegisterReducer(typeof(SelfAccountBalance), "account-balances");}Kotlin does not support this workflow yet.Track self-reducing read model support: https://github.com/Cratis/Chronicle/issues/4851Java does not support this workflow yet.Track self-reducing read model support: https://github.com/Cratis/Chronicle/issues/4851This Chronicle client does not support this workflow yet.Track https://github.com/Cratis/Chronicle/issues/4851 before explicitly registering self-reducing read models from Elixir.TypeScript does not support this workflow yet.Track https://github.com/Cratis/Chronicle/issues/4851 before using this API from this language.There is no separate self-reducer registration API. Matching explicit and discovered declarations are combined; incompatible identities fail. For when a store captures its artifact catalog and what happens on reconnect, follow explicit artifact registration.
Remove a previous builder before switching a model to self reduction. In the same client catalog,
AmbiguousReadModelBuilder rejects another reducer, a fluent projection, or model-bound projection
mappings that also maintain the model. Configuration such as [Passive], [Reducer], sequence
selection, and filters does not by itself count as a projection builder.
Test the transitions
Section titled “Test the transitions”Use ReadModelScenario to fold the same events through the registered self reducer. This example checks accumulation, removal, and creation after removal:
using Cratis.Chronicle.Testing.ReadModels;using Cratis.Specifications;using Xunit;
// Uses SelfAccountBalance, SelfBalanceAdded, and SelfBalanceCleared declared above.public class when_recreating_a_self_reduced_balance : Specification{ readonly ReadModelScenario<SelfAccountBalance> _scenario = new();
SelfAccountBalance? _beforeRemoval; SelfAccountBalance? _afterRemoval;
async Task Because() { await _scenario.Given.ForEventSource("account-42").Events(new SelfBalanceAdded(10m), new SelfBalanceAdded(5m)); _beforeRemoval = _scenario.Instance; await _scenario.Given.ForEventSource("account-42").Events(new SelfBalanceCleared()); _afterRemoval = _scenario.Instance; await _scenario.Given.ForEventSource("account-42").Events(new SelfBalanceAdded(2m)); }
[Fact] void should_accumulate_the_additions() => _beforeRemoval!.Balance.ShouldEqual(15m); [Fact] void should_remove_the_instance() => _afterRemoval!.ShouldBeNull(); [Fact] void should_start_a_new_balance_after_removal() => _scenario.Instance!.Balance.ShouldEqual(2m);}Kotlin does not support this workflow yet.Track self-reducing read model support: https://github.com/Cratis/Chronicle/issues/4851Java does not support this workflow yet.Track self-reducing read model support: https://github.com/Cratis/Chronicle/issues/4851This Chronicle client does not support this workflow yet.Track https://github.com/Cratis/Chronicle/issues/4851 before testing self-reducing read models from Elixir.TypeScript does not support this workflow yet.Track https://github.com/Cratis/Chronicle/issues/4851 before using this API from this language.The model is absent after SelfBalanceCleared; the next addition receives null current and starts a
new balance. Also cover an empty history and each event that can arrive without prior state. A
scenario checks the fold, not the complete running system: it substitutes compliance and storage.
Configure observation and reads
Section titled “Configure observation and reads”Place reducer configuration on the model itself: [Reducer] controls identity, sequence, and activity.
Sequence, event-store, descriptive tag, and metadata-filter attributes keep their existing purposes.
using Cratis.Chronicle.Events;using Cratis.Chronicle.Reducers;
[EventType]public record ConfiguredBalanceAdded(decimal Amount);
[Reducer("verified-balances", eventSequence: "account-events")][FilterEventsByTag("verified")][EventSourceType("Account")][EventStreamType("Payments")][Tag("finance")]public record ConfiguredSelfBalance(decimal Balance){ public static ConfiguredSelfBalance Reduce(ConfiguredBalanceAdded @event, ConfiguredSelfBalance? current) => new((current?.Balance ?? 0m) + @event.Amount);}Kotlin does not support this workflow yet.Track self-reducing read model support: https://github.com/Cratis/Chronicle/issues/4851Java does not support this workflow yet.Track self-reducing read model support: https://github.com/Cratis/Chronicle/issues/4851This Chronicle client does not support this workflow yet.Track https://github.com/Cratis/Chronicle/issues/4851 before configuring self-reducing read models from Elixir.TypeScript does not support this workflow yet.Track https://github.com/Cratis/Chronicle/issues/4851 before using this API from this language.Read an instance with eventStore.ReadModels.GetInstanceById<SelfAccountBalance>(eventSourceId).
Materialized reads use the stored state. Put [Passive] on the model for on-demand by-ID folding;
[Reducer(isActive: false)] only stops active maintenance and does not make reads passive. Compare
passive reducers before changing the read behavior.
Handler selection
Section titled “Handler selection”Dispatch considers only concrete events registered in the owning client:
- An exact event parameter wins.
- Otherwise the nearest base-class handler wins over interface handlers.
- Otherwise the uniquely most-derived matching interface wins.
Equally specific handlers throw AmbiguousSelfReducerMethod. This includes two handlers for the same parameter with and without context. Declaration order and method names do not break ties. Separate clients can select different event sets without sharing registry-dependent dispatch or fingerprints.
The implementation fingerprint includes selected handlers and replay hooks, including inherited bodies and async state machines, together with the registry’s selected identities and generations. Existing kernel replay policy determines how changed implementations rebuild state.
Optional replay hooks
Section titled “Optional replay hooks”Use replay hooks for work tied to replay notifications, not for computing each event’s next state.
Each hook is optional and must be public static, non-generic, and return exactly Task. Global hooks
accept service arguments only; partition hooks require Partition first:
using Cratis.Chronicle.Observation;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;
public record SelfReplayBalance(decimal Balance){ public static SelfReplayBalance Reduce(SelfBalanceAdded @event, SelfReplayBalance? current) => new((current?.Balance ?? 0m) + @event.Amount);
public static Task BeginReplay(BalanceReplayAudit audit) => audit.Write("begin"); public static Task EndReplay(BalanceReplayAudit audit) => audit.Write("end"); public static Task BeginReplayPartition(Partition partition, BalanceReplayAudit audit) => audit.Write($"begin partition {partition.Value}"); public static Task EndReplayPartition(Partition partition, BalanceReplayAudit audit) => audit.Write($"end partition {partition.Value}");}
public sealed class BalanceReplayAudit(ILogger<BalanceReplayAudit> logger) : IAsyncDisposable{ public Task Write(string phase) { logger.LogInformation("Replay phase: {Phase}", phase); return Task.CompletedTask; }
public ValueTask DisposeAsync() { logger.LogInformation("Replay notification scope disposed"); return ValueTask.CompletedTask; }}
public static class BalanceReplayServices{ public static void Configure(IServiceCollection services) => services.AddScoped<BalanceReplayAudit>();}Kotlin does not support this workflow yet.Track self-reducing read model support: https://github.com/Cratis/Chronicle/issues/4851Java does not support this workflow yet.Track self-reducing read model support: https://github.com/Cratis/Chronicle/issues/4851This Chronicle client does not support this workflow yet.Track https://github.com/Cratis/Chronicle/issues/4851 before adding replay hooks to self-reducing read models from Elixir.TypeScript does not support this workflow yet.Track https://github.com/Cratis/Chronicle/issues/4851 before using this API from this language.Chronicle resolves trailing class or interface service arguments through dependency injection in an
asynchronous scope for that notification. Events, EventContext, the model, and extra partition
arguments are not hook services. Missing service registrations fail. Chronicle awaits the hook and
scope disposal before later notifications; an absent hook creates no scope, and hooks do not require
activating a model instance.
Hooks follow the existing notification stream. A full replay sends global begin/end notifications; do not assume it also sends partition notifications. Failure does not guarantee a later end notification. Replay and delivery are not exactly-once operations.
Reads, filters and preserved limits
Section titled “Reads, filters and preserved limits”Choose passive reducers for on-demand reads, not for historical snapshots.
GetSnapshotsById returns no reducer history; a materialized snapshot is the current stored state.
A bounded GetInstances(eventCount) takes a prefix of event-type-selected events before metadata
filtering, not the first N accepted events. Empty or all-rejected histories produce no instance.
Passive reads and reducer scenarios use the same filters as active delivery: an event must match any
configured tag and each configured source/stream category. Tag/Tags label observers; they do not
filter events. There is no stream-ID subscription filter. Inbox forwarding preserves append tags and
source/stream routes for both classic and self reducers, but upgrading does not restore tags dropped
by an earlier release.
Watch supports reducers; GetWatcherFor remains projection-only. Failed folds do not notify
watchers, even if part of the batch succeeded. Successful folds notify them, including removal when
the result is null, but a notification does not prove that persistence succeeded.
A self reducer can participate in a decision read if it
meets the admission rules, including observing the event log without metadata filters and handling
one generation per event type. An ordinary passive or materialized read does not guard a later append.
Container names follow the existing naming policy; there is no reducer ContainerName override.
Generation delivery, revisions, and personally identifiable information (PII) use the shared reducer engine. Passive/history queries retain instance reducers’ query-generation behavior; they do not gain the generation-pinning guarantees of observer delivery. Use ReadModelScenario for transitions and metadata filters, and real-kernel specifications for encryption, erasure, storage, replay, and transport behavior.
Diagnostics
Section titled “Diagnostics”If discovery misses a method, check CHR0058 for an almost-correct signature and
CHR0065 for event folds with the wrong name or a missing static
declaration. CHR0059 reports malformed hooks; CHR0060 reports definite handler ties.
CHR0061 reports definite builder conflicts within one type and warns about possible conflicts with
another builder. The runtime client’s event registry, plugins, and artifact catalog determine which
builders and events actually participate; compile-time diagnostics cannot decide that membership.
The model holds the fold’s result, not mutable reducer-service state.