Decider Platform
The decider platform is this workspace's event-sourcing runtime: a Decider trait for domain decision logic, a native execution boundary that replays and appends JetStream streams, a WASM host that runs the exact same decision logic compiled to a component, and shared testing/observability tooling so both paths stay provably in sync. This is the guide to read first; it links out to the ADRs and per-crate READMEs for anything it only summarizes.
State replay and command decisions
Every decider is a plain Rust type implementing trogon_decider::Decider (crates/decider/trogon-decider/src/lib.rs):
pub trait Decider: Sized {
type StreamId: ?Sized;
type State: DeciderState<Self::Event>;
type Event;
type DecideError: std::error::Error;
const WRITE_PRECONDITION: WritePrecondition;
const SNAPSHOT_CADENCE: SnapshotCadence = SnapshotCadence::Never;
fn stream_id(&self) -> &Self::StreamId;
fn decide(state: &Self::State, command: &Self) -> Result<Decision<Self>, Self::DecideError>;
}
pub trait Evolve<Event>: Sized {
type Error: std::error::Error;
fn evolve(self, event: &Event) -> Result<Self, Self::Error>;
}
pub trait DeciderState<Event>: Default + Evolve<Event> {}
impl<T, Event> DeciderState<Event> for T where T: Default + Evolve<Event> {}DeciderState<Event> names the shared state contract. Its blanket implementation means state types only implement Default and Evolve<Event>.
The state's Default seeds state with no events applied. Its Evolve<Event> folds one stored event into state and is the only place state changes. decide evaluates a command against the current state and returns a Decision, never mutating anything itself. When a rejection crosses the WASM boundary, the bridge surfaces it with the constant "rejected" code on the WIT domain-error and carries the typed error's causal chain in its details pairs.
A generated protobuf message's Default may differ from the state before any events are applied. For example, CredentialStateSnapshot::default() has state: None, while credential replay starts with CredentialMissingState. A local #[repr(transparent)] wrapper can supply that semantic Default and implement Evolve in the domain crate, as permitted by ADR#0045. It contains only the generated message. StateSnapshot::Payload names that message for snapshot storage, with From and AsRef providing the consuming and borrowed conversions. Loading an existing snapshot preserves its fields; only replay without a snapshot starts from Default.
WRITE_PRECONDITION (crates/decider/trogon-decider/src/write_precondition.rs) is the concurrency guard applied when the decided events are appended. It is a total enum with no Option wrapper and no "unspecified" variant, so every decider states its intent:
pub enum WritePrecondition {
StreamUnchanged, // append only if the stream is still as replay observed it
NoStream, // append only if the stream is empty (first writer wins)
StreamExists, // append only if the stream already has events
Any, // append regardless of current stream state
}StreamUnchanged is the common optimistic-concurrency choice that commands declare explicitly. It names an intent rather than a revision because a compile-time const cannot carry one: the storage layer's StreamWritePrecondition (crates/decider/trogon-decider-runtime/src/stream/append_stream.rs) has a fourth variant the domain enum cannot express, At(StreamPosition), an OCC guard over an observed stream position rather than a revision count, enforced server-side via the expected-last-subject-sequence guard and tracked as at in the write_precondition telemetry attribute. Only the execution, which has already read the stream, can supply that position.
resolve_write_precondition(declared, expected_revision, observed) (crates/decider/trogon-decider-runtime/src/execution.rs) is the single shared function both the native and the WASM path call to turn the declared intent into a storage guard. Without a caller-supplied expected revision, each variant maps to its storage counterpart, and StreamUnchanged becomes At(observed) when the stream has events or NoStream when it does not. A caller-supplied revision strengthens the guard to exactly At(expected) rather than replacing it, and two combinations are rejected outright rather than silently reinterpreted: NoStream with any expected revision fails as PreconditionConflictError::CreateWithRevision (a command that can only create a stream cannot also assert the stream reached a revision), and a revision ahead of what the stream can prove fails as PreconditionConflictError::RevisionAheadOfStream. ADR#0035 rejects adding a trait-level At(N) variant to WritePrecondition for exactly this reason: it could only let a decider weaken the default guard, never strengthen it.
Decision::Events vs Decision::Act
decide returns a Decision<C> (crates/decider/trogon-decider/src/decision.rs):
#[non_exhaustive]
pub enum Decision<C> where C: Decider {
Events(Events<C::Event>),
Act(Act<C>),
}Decision::events(...) (or the single-event Decision::event(...)) is the common case: a flat, already-final batch of events. Decision::act() starts an ActBuilder<C> instead, for decisions that need to observe the state produced by an earlier step before deciding the next one:
Decision::act()
.execute(|state, command| { /* returns Decision<C> or Result<Decision<C>, C::DecideError> */ })
.execute(|state, command| { /* sees the state the previous step's events would produce */ })Each .execute call returns a new typestate ActChain<C, S> (S: Steps<C>, built from First/Then link types); these link types and ActChain/ActRun/Steps are #[doc(hidden)] implementation detail. Converting the finished chain into a Result<Decision<C>, C::DecideError> boxes the whole plan exactly once into an Act<C>, so Decision can hold either form as one uniform type. evaluate_decision (crates/decider/trogon-decider/src/decision.rs, #[doc(hidden)]) is the shared entry point both the native runtime and the WASM guest bridge call: C::decide then, for an Act, runs each step in turn, folding that step's events via C::evolve before handing the resulting state to the next step. This is why Decision::Act behaves identically on both paths: neither path reimplements the stepping logic.
The native path: CommandExecution
trogon-decider-runtime's CommandExecution<'a, E, C, S, G, A = WithoutAdmission, Auth = WithoutAuthorization> (crates/decider/trogon-decider-runtime/src/execution.rs) is the runtime boundary that applies one command to one stream: authorize, read, replay, decide, append. Both defaults are the absence of a policy, so an execution that configures neither behaves exactly as it did before either seam existed: whoever can construct a CommandExecution can apply any command the decider accepts, unless the host configures an authorizer (see Authorization below).
Build one with CommandExecution::new and configure it with builder methods before calling execute:
CommandExecution::new(&event_store, &command)
.with_expected_revision(revision) // strengthens C::WRITE_PRECONDITION to At(revision)
.with_headers(headers)
.with_command_id(command_id) // derives deterministic event ids for a redelivery
.with_event_id_generator(generator)
.with_replay_limit(limit) // optional cap on replayed events per command
.with_replay_chunk_size(chunk_size) // optional bound on how much of it is resident at once
.with_conflict_retry(retry_limit) // optional in-place OCC retry, off by default
.with_admission(&limiter) // optional concurrency gate, off by default
.with_principal(principal) // who is submitting; None unless the caller sets it
.with_authorizer(&authorizer) // optional authorization gate, off by default
.with_snapshot(snapshot_store) // moves to the snapshot-enabled type state
.with_task_runtime(scheduler)
.with_snapshot_failure_policy(policy)
.execute()
.awaitThere is one execute. Whether .with_snapshot(...) was called is a type state (S, either WithoutSnapshots or Snapshots), and the difference between the two is confined to the ExecutionSnapshots<C> trait that type state implements: it owns loading the replay context and storing a new snapshot, and execute calls it the same way either way. The trait is public because it appears in execute's signature, but it is sealed, so the two shipped type states are the only implementations. The phases are:
- Load. If the effective write precondition is
NoStream, neither the snapshot store nor the stream is read and the command is decided straight againstC::State::default(): any history at all would already violate the guard the append is about to use. OtherwiseWithoutSnapshotsreads the stream from the beginning (ReadFrom::Beginning), whileSnapshotsreads a snapshot first and then reads only the stream events after the snapshot's position (ReadFrom::after(position)). - Recover. On a snapshot the configured
SnapshotFailurePolicycannot trust, either because reading it failed or because it claims a position ahead of the stream, the policy decidesFailorDiscardAndReplay; a discarded snapshot falls back to a full replay from the beginning. - Decide and append, guarded by the resolved
StreamWritePrecondition. - Snapshot. After decide and append succeed, a snapshot write is scheduled: always, if a bad snapshot was just discarded and overwritten with a trustworthy one; otherwise only when the configured
SnapshotPolicy::decide_snapshotreturnsSnapshotDecision::Take.
with_replay_limit (ReplayLimit, a non-zero event count) bounds how much history one command execution may replay. Once a limit is configured, the read itself is capped to one more than the limit through StreamRead::read_stream_bounded (a default method that falls back to the unbounded read_stream for implementations that have not opted into a real bound; trogon-decider-nats has). If the capped read comes back with more events than the limit, the command fails with CommandError::ReplayLimitExceeded before any folding happens, so a decider that forgets or misconfigures snapshotting fails loudly instead of silently growing per-command latency with the stream. A discard-and-replay snapshot recovery is bounded by the same limit: its full replay from the beginning is otherwise a deliberate one-off that ends by overwriting the discarded snapshot, but a stream that has grown far beyond the configured limit still fails loudly instead of replaying without bound.
What the limit bounds depends on the store. The loud failure and the skipped fold hold for every StreamRead implementation. The I/O and memory bound holds only for implementations that override read_stream_bounded with a real capped fetch: a store still on the default fallback reads the whole stream first and only then discovers it exceeded the limit, so ReplayLimitExceeded protects folding time but not wire traffic or peak memory there. Nothing forces the override when a limit is configured, so "a stream far past the limit is never read in full" is a property of the store, not of ReplayLimit. The default is unlimited.
Chunked replay
with_replay_chunk_size (ReplayChunkSize, a non-zero event count) answers a different question than ReplayLimit does, which is why the two are separate value objects and either can be set alone. The limit is a correctness tripwire: past it, replaying is the wrong thing to do at all. The chunk size says nothing about how much history is acceptable, only how much of it may be resident at one time. A chunked replay reads the stream in steps of at most that many events, folding each step before reading the next, so peak memory is the chunk rather than the stream. When both are set, each read is bounded by whichever is tighter, and the limit still fails the command the moment the fold passes it. The default is a single read.
The walk is pinned to the tail the first read observed. Reads happen one after another, so the stream can grow between them; folding whatever a later read happens to return would build state from history the append is not guarded against, and the write precondition would then assert a position the decision never saw. Every chunk is therefore cut off at the first read's current_position, and events past it are left for the next execution, exactly as an unchunked replay leaves them.
One behavior does change with chunking, and only in the failure case: an unchunked replay rejects an over-limit stream before folding anything, while a chunked one has already folded the earlier chunks by the time the limit is reached. The command still fails with CommandError::ReplayLimitExceeded and still appends nothing, so nothing observable outside the execution differs.
CommandError<DecideError, EvolveError, ReadSnapshotError, ReadStreamError, AppendStreamError, EventTypeError, PayloadEncodeError, DecodeError> normalizes failures by phase (Decide, Evolve, ReadSnapshot, ReadStream, Append, EventType, EventEncode, DecodeEvent, SnapshotAheadOfStream, ReadAfterOverflow, ReplayLimitExceeded, PreconditionConflict, Overloaded) while preserving each phase's concrete source error type.
Conflict retry
An optimistic-concurrency conflict is not a failure of the command. It says the state the decision was made from is no longer the state the append would land on, and the only thing that can be done about it is to read the stream again and decide again. By default that round is the caller's to run: the conflict surfaces as CommandError::Append carrying the store's own error and the command is over. with_conflict_retry(ConflictRetryLimit) runs it in place instead, up to that many extra attempts, and the caller only sees a conflict that outlived all of them. The limit counts retries rather than attempts, and it is a NonZeroU32 value object, because "no retries" is the absence of a limit rather than a limit of none.
A retry needs three things to be true at once, and the default of every one of them is "do not retry":
- The store says so.
StreamAppend::classify_append_failuremaps a store's own error toAppendFailure::WriteConflictorAppendFailure::Fatal. Only the store knows which of its errors mean "the stream moved", so naming it there keeps the distinction typed rather than inferred from an error message. The default isFatal, so a store that has not classified its errors never has a command retried behind its back.InMemoryStoreandJetStreamStoreboth override it. - The decider declared
StreamUnchanged. Every other precondition asserts something a re-read cannot change:NoStreamconflicts because the stream now exists,StreamExistsbecause it does not, andAnynever conflicts at all. - No caller-supplied expected revision. A revision is the caller's own assertion about what they read. Re-reading past it would substitute the runtime's judgment for theirs.
A retry repeats the whole round, snapshot read included, so a stale snapshot cannot pin successive attempts to the same state. Each attempt is counted by decider.command.conflict_retries, so contention that is being absorbed is still visible rather than hidden by the loop.
Admission control
Per ADR#0028, with_admission gates an execution on a CommandAdmission limiter (crates/decider/trogon-decider-runtime/src/admission.rs). The permit is acquired before the first read and held until the execution ends, so one slot covers the reads, the decide, and the append rather than only the moment of admission; dropping the permit releases the slot, so a failing or panicking execution cannot leak one.
This is a seam, not a policy. The crate owns the trait, the AdmissionLimit value object, the OverloadedError rejection, and one semaphore-shaped implementation (ConcurrencyAdmission, whose clones share a single budget so several consumers in a process can be bounded together). It owns no bound: the number worth choosing is a limit against a specific host's memory budget, which is a deployment fact rather than a property of any decider. The type parameter therefore defaults to WithoutAdmission, which admits unconditionally, and a host that never configures a limiter behaves exactly as it did before admission control existed.
admit is synchronous. An admission decision that can await is a queue, and an unbounded queue relocates the memory pressure a limiter exists to bound while hiding it behind latency instead of surfacing it as a distinguishable error. A shed command fails with CommandError::Overloaded before any work begins and is recorded as decision_outcome=shed, distinct from both a domain rejection and a fault. A host that wants a bounded wait before shedding owns that wait in its own dispatch loop, before it builds the execution.
Authorization
Per ADR#0026, with_principal names who is submitting a command and with_authorizer gates the execution on a CommandAuthorizer (crates/decider/trogon-decider-runtime/src/authorization.rs). The check runs immediately after the admission permit and before the first snapshot read, stream read, decide, or append, and it runs outside the conflict-retry loop, so a denied command costs one call and a command that conflicts three times still answers to one authorization decision.
Like admission control this is a seam and not a policy. The crate owns the trait, the CommandPrincipal value object and the PrincipalKind, PrincipalId, PrincipalClaim, and PrincipalClaims pieces it is built from, the AuthorizationDeniedError and UnauthorizedError rejections, and nothing else. It ships no rule and no claim vocabulary: which claim a command requires is an application fact. The type parameter defaults to WithoutAuthorization, named for the absence of a decision rather than for a permissive one, so an unconfigured execution carries that absence in its own type.
The trait has two methods and implementations write only one. An implementation writes authorize(&self, principal: &CommandPrincipal, command: &C); the runtime calls authorize_execution(&self, principal: Option<&CommandPrincipal>, command: &C), whose default refuses an absent principal with UnauthorizedError::MissingPrincipal before authorize is consulted. Fail-closed is therefore what an implementation gets by writing nothing. A refused command fails with CommandError::Unauthorized (WasmCommandError::Unauthorized on the WASM path) and is recorded as decision_outcome=denied, distinct from a shed command, a domain rejection, and a fault.
C is a plain generic parameter rather than a Decider bound, which is what lets one trait cover both dispatch paths: the WASM path's command is a CommandEnvelope, not a Decider. The cost of checking this early is that an authorizer sees the principal and the command and nothing else, never the target stream or its replayed state. That is deliberate: a policy that must read stream state to decide is expressing a domain rule, and a domain rule belongs in decide.
The runtime ships only the seam; the NATS host is where a principal comes from. Per ADR#0082, trogon-decider-nats-server subscribes on {prefix}.*.*.DeciderService.Decide and reads the principal from the {kind}.{id} tokens of the subject the server delivered, before it decodes the request. A pair of tokens that names no principal is refused with UNAUTHENTICATED and PRINCIPAL_MISSING, and a subject without those tokens matches no subscription at all, so no header or payload field can stand in for them. The derived principal carries no claims and no directed principal, because the subject has no position for either. A client acting for a principal configures a PrincipalPrefix, the host's prefix followed by that principal's tokens. An id that cannot be one subject token travels in the hashed form every edge maps it to, and that hashed token is the id the host derives and an authorizer sees.
A host serves one tenant account until decider state is scoped by tenant. The derived principal carries no tenant, and every command a host runs shares its one events stream and snapshot bucket, so a host serving several tenants would let one tenant's commands replay and append to another tenant's streams. DeciderHost::start therefore refuses DECIDER_TENANT_POSITION=wildcard before it fetches or provisions anything, and nothing overrides that refusal.
Every execution the host runs is built with with_principal and with_authorizer. A host given no policy of its own authorizes with AdmitAnyPrincipal, which admits any derived principal and, through the trait's default, refuses an execution that has none; DeciderHost::with_authorizer replaces it, and a denial answers PERMISSION_DENIED with PRINCIPAL_UNAUTHORIZED. Execution paths the host does not serve still populate no principal on their own.
Snapshot policy and failure recovery
SnapshotPolicy<C> decides whether to take a snapshot after a successful append (decide_snapshot(context: DecideSnapshot<'_, C>) -> SnapshotDecision). Two implementations ship: NoSnapshot (never) and FrequencySnapshot (takes one once at least frequency events have been read or appended since the last snapshot). CommandSnapshotPolicy: Decider lets a decider declare its own default policy via an associated SNAPSHOT_POLICY const, so callers build a configured Snapshots without repeating the policy at every call site.
SnapshotFailurePolicy<C, ReadSnapshotError> decides how to react to a snapshot execution cannot trust: FailOnSnapshotFailure (the default, fails the command) or DiscardAndReplaySnapshotFailure (discards the bad snapshot and replays from the beginning of the stream instead of failing).
Scheduled snapshot writes run through a SnapshotTaskScheduler (fn schedule, plus a drain future that defaults to resolving immediately). TokioSnapshotTaskScheduler is fire-and-forget: its drain never actually waits. DrainableSnapshotTaskScheduler tracks in-flight writes so a host can drain().await outstanding snapshot writes before shutdown.
Command-level idempotency
with_command_id takes a CommandId, the stable identity of the command across every delivery of it. Every event the execution appends then derives its EventId from that identity (CommandId::event_id(index), a UUIDv5 over the command id and the event's big-endian position in the decided batch), so a redelivered command produces byte-identical ids in the same order. That is what lets a storage adapter recognize a retry: trogon-decider-nats publishes event.id as the JetStream Nats-Msg-Id, so its deduplication window collapses the second append instead of duplicating the events under fresh ids. Without a command id, ids come from the configured generator and every at-least-once redelivery looks like new history.
The id has to come from the transport. A value the execution generated would be as fresh on the retry as the UUIDv7 it replaces. A delivery that carries no id of its own but does carry a key the sender cannot vary between attempts can use CommandId::derive(namespace, key), as the scheduler's timer wakeups do, naming the occurrence they fire for. Distinct kinds of key need distinct namespaces, or two unrelated commands whose keys render alike collapse onto one identity.
Headers
Event headers are operational metadata (correlation, tenancy, causation, transport routing), distinct from event payloads, which are the canonical domain facts. The runtime does not derive required headers from commands or events through a generic callback; callers set headers explicitly via CommandExecution::with_headers. See Event Metadata for the full policy, and ADR#0013 for the one reserved header name this repository defines today, Trogon-Origin-Stream-Sequence, used only for provenance when an application appends a historical event into a different stream from the one where it originally lived. Native JetStream source, mirror, RePublish, and snapshot-restore operations use NATS-owned provenance or preserve the stored stream instead. The application header is never used for checkpoints, positions, or concurrency; those always use the stream's current sequence.
JetStream storage layer (trogon-decider-nats)
trogon-decider-nats implements the native runtime's storage traits (stream read/append, snapshot read/write) against NATS JetStream. Per ADR#0002, this crate is the adapter layer: it knows how to store and replay a stream, not how to decide/evolve.
One physical stream, subject per logical stream
Every decider's events live in one physical JetStream stream. A caller-supplied StreamSubjectResolver<StreamId> maps a domain stream identifier to the subject that stores it (resolve_subject_state, returning a SubjectState { subject, current_position }), so each logical stream gets its own subject within that one physical stream:
physical JetStream stream "orders-events"
├─ subject "orders.events.order-1" (logical stream "order-1")
├─ subject "orders.events.order-2" (logical stream "order-2")
└─ subject "orders.events.order-3" (logical stream "order-3")ensure_stream/ensure_bucket (provision.rs) idempotently create-or-open the physical stream and the KV bucket used for snapshots: a create that fails because the resource already exists resolves via a get instead of surfacing an error, so concurrent callers racing to provision the same resource both succeed.
Atomic multi-event append
append_stream (stream_store.rs) publishes a batch of events to one subject atomically using three headers on the underlying JetStream messages: Nats-Batch-Id and Nats-Batch-Sequence on every message in the batch, Nats-Batch-Commit on the final message, and (when appending is conditional) the expected-last-subject-sequence guard on the first message. The final message's stream sequence becomes the returned StreamPosition. User-supplied event headers are validated against NATS's own header-name and header-value rules before publishing; a name NATS would reject (for example one containing :, a space, or a non-ASCII character) fails the append with a typed PublishStreamError instead of panicking inside the NATS client.
Ordered, subject-filtered replay
Replay (stream_store/replay.rs) uses an ordered JetStream consumer scoped with filter_subject and DeliverPolicy::ByStartSequence { start_sequence }, reading only the target logical stream's own messages in order rather than scanning every physical sequence. The consumer is self-healing for most disconnects; residual failure kinds are retried by recreating the consumer from the last successfully processed sequence, bounded by ReplayRetryPolicy: 5 attempts, 100ms base delay, 5s max delay, exponential backoff between attempts. replay_ordered_range also takes an optional max_events, which stops the replay once that many events have been fetched even if the target sequence has not been reached yet; JetStreamStore::read_stream_bounded uses it to give CommandExecution's ReplayLimit a real bound on the wire, not just on the folded result.
KV-backed snapshots
Snapshot storage (snapshot_store.rs) is a set of free functions generic over a JetStream KV bucket (read_snapshot, write_snapshot, read_checkpoint, write_checkpoint, maybe_advance_checkpoint, persist_snapshot_change), not a dedicated struct. NatsSnapshotConfig carries the checkpoint key name; SnapshotChange<T> is either an Upsert or a Delete mutation applied atomically alongside the checkpoint update.
Retention watermarks
retention.rs answers the question snapshots make answerable: which events is nobody going to read again? Replay resumes from ReadFrom::after(snapshot.position), so the oldest outstanding snapshot for a stream is the boundary below which its history is dead weight. RetentionWatermarksBuilder folds one snapshot type's read_snapshot_map result at a time, plus any CheckpointSequence tracking progress over the same physical stream, into a RetentionWatermarks report keyed by snapshot id (which both execution paths set to the stream id).
The watermark itself is total: RetainAll or DiscardBelow(StreamPosition), ordered so that RetainAll is the least element and combining constraints is min. Every case the fold cannot justify a boundary for resolves to RetainAll -- a stream nobody snapshotted, a checkpoint at NONE, a stream one observed snapshot type covers and another does not -- so an incomplete picture over-retains rather than over-deletes. The one thing it cannot defend against is a marker it was never shown: a snapshot type or checkpoint left out of the fold produces a watermark that is too high, which is why the aggregate over a physical stream is only sound when every stream id on it is declared.
Nothing here purges. Per ADR#0029 the store never truncates as a side effect of a read, append, or snapshot write; the watermark is a read-only query an operator or scheduled job consumes, and that job is not part of this crate family. Watermarks are physical JetStream sequences, never Trogon-Origin-Stream-Sequence.
Read-side primitives: Projector and Processor
trogon-decider-nats also ships two generic read-side primitives, so consumers of decider streams don't hand-roll catch-up or redelivery logic:
Projector<Checkpoint>drives catch-up for one subject-filtered projection: given aProjectionCheckpointStore(load/save aCheckpointSequence) and aProjectionApply(apply one event, return the checkpoint to record for it),catch_upreplays events in stream order up to the tail observed when the call started, saving the checkpoint after each one. UseProjectorwhen you're building a read model or side-effect projection that needs to resume from wherever it last left off.Processor<Handler>drives a durable pull consumer's message loop for oneMessageHandler(handlereturns aHandlerVerdict:Ack,Retry, orPoison).RedeliveryPolicybounds retries (default: 5 max deliveries, 200ms base delay, 30s max delay, exponential backoff) before a message is poisoned andon_poisonis called with aPoisonReason(Verdict,RedeliveryExhausted,HandlerError, orPanic). UseProcessorwhen you need at-least-once, ack/nak/term message processing against a durable consumer, not a resumable full-stream projection.
CheckpointSequence wraps the underlying u64 stream sequence; CheckpointSequence::NONE (value 0) means no event has been applied yet, distinct from having processed sequence 1. next_from_sequence() returns the sequence a catch-up should resume from (the checkpoint's sequence plus one).
The WASM path
The same Decider logic can be compiled to a WASM component and executed by trogon-decider-wasm-runtime instead of running natively. Both paths share the same decide/evolve semantics (via evaluate_decision) and the same event codec, so a decider behaves identically whether it runs natively or as a guest.
export_decider! and the WIT contract
export_decider! (trogon-decider-guest-macros) generates the component glue for one or more commands that share a Decider::State and Decider::Event:
export_decider!(
CreateSchedule {
type_url = CREATE_SCHEDULE_TYPE_URL,
proto = v1::CreateSchedule,
module = "scheduler.schedules",
version = "0.1.0",
state_schema_version = SCHEDULES_STATE_SCHEMA_VERSION,
},
);Neither the write precondition nor the snapshot cadence is restated here. The macro reads both off the Decider itself, C::WRITE_PRECONDITION and C::SNAPSHOT_CADENCE, and emits them into the descriptor, so a decider declares each policy once and keeps it across both execution paths instead of having a wasm-only copy that can drift from the native one.
It expands to a hidden module containing wit_bindgen::generate! bindings, a Component unit struct implementing the WIT Guest trait (descriptor(), stream_id(command)), and a Session struct (RefCell<State>) implementing GuestSession: new loads a snapshot or builds initial state, evolve folds events and mutates the RefCell, decide only borrows state (it does not fold its own output back in), and snapshot encodes current state. The macro resolves the WIT contract via trogon_decider_wit::WIT_DIR, an absolute path baked into trogon-decider-wit at that crate's own compile time, so a component crate can live at any directory depth relative to it.
The contract itself lives in trogon-decider-wit's wit/world.wit (package trogon:decider@0.3.0, world decider, interface handler): descriptor() returns a module-descriptor { name, version, commands }, where each command-spec carries the command's write-precondition and its snapshot-policy, both total variants with no option<> wrapper so a module states each policy rather than leaving the host to infer one; stream-id(command) resolves a command-envelope to its target stream; the session resource exposes evolve(events), decide(command) -> result<list<any-envelope>, decide-error>, and snapshot() -> option<list<u8>>. A successful decide must return a non-empty event list; WIT cannot express that constraint, so the guest SDK preserves it by construction (Events has no empty form) and the host rejects a violating guest with WasmCommandError::EmptyDecision before the decision can be folded, snapshotted, or appended. domain-error { code, message, details } carries a stable code, a human-readable message, and the error's source chain as ordered key/value pairs, so detail that a single Display line would otherwise erase survives the WIT boundary. trogon-decider-wit compiles this contract for both sides: guest (feature guest, via wit_bindgen::generate!, for wasm32 components) and host (feature host, via wasmtime::component::bindgen!, for non-wasm32 runtimes), re-exporting the same WIT-derived types from both.
Engine budgets and deadlines
WasmDeciderEngine/WasmEngineConfig (trogon-decider-wasm-runtime/src/engine.rs) configure a shared wasmtime Engine with fuel metering, epoch-based interruption, the pooling allocator, and per-store resource limits, built once per process and shared across every loaded module:
| Budget | Default | Purpose |
|---|---|---|
fuel_per_call | 10,000,000 | Instructions a single decide/evolve/snapshot call may execute before trapping OutOfFuel. |
max_memory_bytes | 64 MiB | Ceiling on a store's linear-memory growth. |
max_table_elements | 8,192 | Ceiling on any table a session's store may create. |
max_instances_per_session | 8 | Ceiling on core module instantiations per session's store. |
max_tables_per_session | 6 | Ceiling on tables per session's store. |
max_memories_per_session | 4 | Ceiling on memories per session's store. |
max_concurrent_sessions | 256 | Pooling-allocator warm-slot ceiling. |
epoch_tick_interval | 50ms | Cadence of the engine's background epoch ticker. |
epoch_ticks_per_call | 40 | Ticks a call may run before being interrupted, i.e. a 2 second wall-clock budget per call at the default cadence. |
Fuel bounds instructions, not time; the epoch ticker is the wall-clock backstop for a guest that is still executing but too slowly. A WasmDeciderModule is loaded once (load), which compiles the component, structurally enforces zero imports by instantiating it against an empty wasmtime::component::Linker (the same requirement trogon-decider-sim's assert_zero_imports checks for, via wasm-tools instead), caches the resulting DeciderPre for cheap per-command instantiation, and probes the guest's descriptor() export once.
Execution ordering: decide, fold, then snapshot
WasmCommandExecution<'a, E, Snapshots, G, A = WithoutAdmission, Auth = WithoutAuthorization> mirrors the native CommandExecution boundary against the WIT session resource. Guest calls run via spawn_guest, which wraps tokio::task::spawn_blocking so a guest's fuel- and epoch-bounded call never occupies the async executor for its duration. Like the native path it has one execute, with the snapshot-store type state confined behind its own sealed trait, WasmExecutionSnapshots. The seam is per-crate rather than shared: a single session abstraction spanning both paths would have to split the wasm path's guest calls into separately awaited phases and pay a thread hop for each, so the two crates keep parallel skeletons that are verified against each other by tests rather than one skeleton reused. The crates do share the pieces that carry no session state: resolve_write_precondition, read_stream_for_execution, ensure_replay_within_limit, and the ReplayBounds and ReplayCursor that drive a chunked replay.
Before loading state, execution resolves the command descriptor's write precondition through the same shared resolve_write_precondition the native path uses, so a caller's expected revision strengthens the module's declared guard by exactly the rules described above. An effective NoStream precondition starts the guest from initial state without reading a snapshot or stream history. The same resolved value is later used for append, so replay planning and optimistic concurrency cannot disagree about precedence.
with_replay_limit, with_replay_chunk_size, with_conflict_retry, with_admission, with_principal, and with_authorizer mirror their native counterparts, including the bounded read: a configured ReplayLimit caps the read at one past the limit through StreamRead::read_stream_bounded on both the store-less and the snapshot-resumed path, and a ReplayLimitExceeded command fails before any of that history reaches the guest. A limiter that cannot admit fails the command with WasmCommandError::Overloaded before a wasm store exists at all, which is what makes limit x max_memory_bytes a real bound on the host's worst-case guest memory rather than an estimate. An authorizer that refuses fails the command with WasmCommandError::Unauthorized at the same point, before any guest is instantiated and therefore before the stream id the guest would compute exists, which is why an authorizer on this path is handed the CommandEnvelope and nothing else. A retried conflict costs a fresh guest session, a fresh replay, and a fresh decide, which is why it is bounded by the same ConflictRetryLimit and refused under the same three conditions as on the native path.
A chunk size buys the guest path one thing more than it buys the native one. An unchunked replay hands the whole stream to a single evolve call, whose fuel and epoch budget is therefore scaled by the stream's length; a long enough stream is one guest call that has to be allowed to run for a proportionally long time. A chunked replay folds each chunk in its own evolve call, so the budget is per chunk, and the session crosses the blocking boundary between chunks while the next read happens on the async executor. The session's destructor is owed either way: a fold that fails runs it before returning, and so does a read between two chunks that fails.
The guest's generated decide export only reads session state; it never folds its own newly decided events back into it (evolve mutates the session's RefCell<State>, decide only borrows it). A snapshot taken immediately after decide would therefore silently drop that command's own events. The snapshot-enabled execution path calls decide, then fold_decided_events (which replays those events into the session via evolve), then take_snapshot, in that order, so a session resumed from that snapshot ends up in the same state a full replay would produce. The no-snapshot path skips the fold entirely: no snapshot will observe that session again, so folding would only burn guest fuel for nothing.
Once the command's outcome is determined, whether it decided events, rejected, or faulted, the session is dropped, which runs the guest's session resource destructor, real guest code: it is armed with its own fresh fuel and epoch budget rather than whatever the preceding guest call left behind. A trap in it is counted in decider.wasm.traps under the drop guest phase and logged, but never fails the command. The only path that skips the destructor is a guest that already trapped: a trapped component instance cannot be reentered, so attempting it would re-count the same trap.
WasmCommandError distinguishes a guest call that trapped for any other reason (Trap) from one that exceeded its wall-clock epoch deadline (DeadlineExceeded), classified by downcasting the trap to wasmtime::Trap::Interrupt.
Snapshot failure recovery mirrors the native path
WasmCommandExecution::with_snapshot_failure_policy mirrors native's SnapshotFailurePolicy: a snapshot the host cannot trust, either because reading it failed or because it claims a position ahead of the stream, is routed through a WasmSnapshotFailurePolicy<ReadSnapshotError> before either failure is allowed to fail the command. FailOnSnapshotFailure (the default) keeps today's behavior; DiscardAndReplaySnapshotFailure discards the untrusted snapshot and replays the stream from the beginning instead, exactly as CommandExecution does natively. Both policy types are reused directly from trogon-decider-runtime, since neither carries any decider-specific state.
The WASM boundary has no typed Decider, so the policy's input is a WasmSnapshotFailureContext carrying whatever identity the execution actually has in hand at that point instead of a command reference: the module's name and version, the command's wire type URL, the resolved stream id, and the failure itself (reused as native's SnapshotFailure).
Native forces the post-append snapshot write unconditionally when a bad snapshot was just discarded, so a SnapshotPolicy that would otherwise skip cannot let the bad snapshot linger. The WASM path needs no equivalent branch: it has no host-side SnapshotPolicy to skip with in the first place, since a snapshot is written whenever the guest's snapshot() export returns one at all.
Registry rollout: swapping modules without a restart
DeciderRegistry routes command types to the WasmDeciderModule that declared them, built once via DeciderRegistryBuilder (which rejects command-type collisions across modules). DeciderRegistryHandle wraps a DeciderRegistry behind a RwLock<Arc<DeciderRegistry>> so it can be updated while command executions are in flight:
┌──────────────────────────┐
readers ────► │ RwLock<Arc<DeciderRegistry>> │ ◄──── activate(module) / retire(command_type)
└──────────────────────────┘activate(module) routes every command type the module declares to it, replacing whatever module previously owned each route; retire(command_type) removes one route. Both compute the entire next routing table first and take the write lock only long enough to install it with one assignment, so a module declaring more than one command type is activated or retired as a unit: a reader never observes some of its command types on the new module while a sibling command type from the same module is still on the old one. A caller resolves a module once per command dispatch and keeps using that resolved Arc; a later activate or retire never reaches back into an execution already running against a module it resolved earlier.
WasmSnapshotId folds a module's identity into every snapshot id it produces. It builds the collision-free logical identity {module_name}@{module_version}/{stream_id}, then encodes that complete value as unpadded base64url with a v1_ format prefix so it remains a valid NATS Key/Value key when a stream id contains characters outside the NATS key alphabet. Routing a command type from module version v1 to v2 via activate does not migrate or invalidate v1's snapshots: v2's snapshot id for a given stream is simply a different string, so v2's first command against a stream v1 had already snapshotted finds nothing under v2's id and falls back to a full replay from the beginning, the same fallback taken for a stream that was never snapshotted at all. That replay reconstructs the same guest state a snapshot would have, just without resuming from a saved position. No explicit migration or invalidation step is needed; the version bump folded into the snapshot id is enough on its own.
The v1_ representation replaces the earlier raw logical identity. NATS could not persist that legacy form because @ is outside its Key/Value key alphabet. A non-NATS store that persisted the legacy id needs replayable history for one cold rebuild or an explicit key migration before adopting the encoded format.
Testing story
Four layers, from unit-level to conformance-level:
TestCase(trogon-decider/src/testing.rs) is a given/when/then typestate builder for unit-testing a nativeDeciderdirectly: seed aHistory<C::Event>, issue a command, assert the resultingDecisionvia aThen-style expectation (exact event equality via.then(...), or the exact expectedDecideErrorvalue via.then_error(...)), and optionally assert the post-decision state.trogon-decider-simis the native-vs-wasm parity harness.SimHost/SimInstance(host.rs) load a compiled component and run every guest call against the same resource budgetWasmDeciderEngineapplies in production, so a decider that would trap in production traps the same way in tests instead of running unbounded.ScenarioIr/WireEnvelope(ir.rs) express a decider-agnostic given/when/then scenario in wire form (type URL plus encoded payload) that both a wasm run (ScenarioIr::run_wasm) and a native run (native.rs'srun_native, reusing the exacttrogon-decider-guest-sdkcodec functions the guest bridge expands into) can execute.SimScenario(scenario.rs) is the fluent given/when/then builder used directly against aSimInstance, supporting multiple chained steps against one open session.assert_parity(parity.rs) runs one scenario through both runners and returns an error on the first divergence between their resolved stream ids or their step outcomes, including a domain error'sdetailscausal chain, catching codec, codegen, or WIT-level drift that each runner's own pass/fail would miss.SimFixture(fixture.rs, featuretest-support) holds checked-in compiled.wasmfixtures for integration tests.decider-testCLI (cli/trogon-decider-test) runs a YAML conformance suite against a compiled component with no Rust required. ASuitedeclares scenarios (Scenario, each either a legacy singlewhen/thenpair or an orderedsteps: Vec<Step>list run against one session) and the event type URLs the decider is declared to produce. Strict mode (default on, disabled with--no-strict) fails the run if any declared command or event type has zero coverage across every scenario'sgiven/when/then.events; detection and reporting always run,--no-strictonly downgrades the failure to a stderr warning.assert_zero_imports(trogon-decider-sim/src/import_check.rs) checks a compiled component declares no imports viawasm-tools component wit, the same zero-import requirementWasmDeciderModule::loadenforces structurally at load time with an emptyLinker.
Observability
Per ADR#0008, the decider platform is instrumented against otel/semconv/registry/decider.yaml's registry.trogonai.decider attribute group. All decider telemetry is stability: development.
Attributes: command_type, module_name, module_version, write_precondition (any/stream_exists/no_stream/at), decision_outcome (decided/rejected/faulted/shed/denied), snapshot_outcome (hit/miss/discarded_read_failure/discarded_ahead_of_stream/failed), snapshot_write_success, guest_phase (instantiate/replay/decide/snapshot/drop), and trap_classification (deadline_exceeded/trap). stream_id is defined once in scheduler.yaml and reused here.
Spans: decider.execute_command, decider.read_snapshot, decider.write_snapshot, decider.append_stream, decider.replay_stream, decider.wasm.instantiate, decider.wasm.replay, decider.wasm.decide, decider.wasm.snapshot.
Metrics: decider.replay.events (counter), decider.snapshot.reads (counter, by snapshot_outcome), decider.snapshot.writes (counter, by snapshot_write_success), decider.snapshot.kv_read_failures / decider.snapshot.kv_write_failures (counters), decider.append.duration (histogram), decider.append.conflicts (counter), decider.replay.duration (histogram), decider.replay.retries (counter), decider.command.conflict_retries (counter), decider.wasm.execution.duration (histogram, by guest_phase), decider.wasm.fuel.consumed (histogram, by guest_phase), decider.wasm.traps (counter, by trap_classification).
Related ADRs
Accepted and reflected in the platform as built:
- ADR#0002: Rust Crate Boundaries: the domain/runtime/adapter split this document follows (
trogon-decider/trogon-decider-runtime/trogon-decider-nats). - ADR#0008: OpenTelemetry Observability: the vocabulary requirement behind the Observability section above.
- ADR#0013: Origin Stream Sequence Header: the
Trogon-Origin-Stream-Sequenceheader described under Headers above. - ADR#0026: Command Authorization Principal: the
CommandAuthorizerseam described under Authorization above. The NATS host derives the principal from the subject, per ADR#0082 below; on every other execution path no principal reaches an execution unless a caller puts one there. - ADR#0028: Decider Admission Control and Backpressure: the
CommandAdmissionseam described under Admission control above. The shared crates own the seam and one implementation; no bound is chosen anywhere in the decider stack, so a host that configures no limiter is exactly as unprotected as it was before. - ADR#0029: Snapshot-Derived Retention Watermark for Decider Streams: the read-only watermark described under Retention watermarks above. The purge that would consume it is an explicit Non-Goal there and does not exist; no code in this crate family truncates anything.
- ADR#0082: Inside the Bus the Principal Is Derived from the Subject, and Proof of Possession Is Enforced Only at the External Edge: the decider host's half, described under Authorization above. The host reads the principal from the subject and authorizes every execution it runs. The edge that verifies proof of possession and the grants that confine a caller to its own principal tokens live outside this crate family.
Draft, not yet implemented; do not treat these as current behavior:
