Skip to content

Cratis Arc generated values for command handlers

Cratis Arc’s [GeneratedValue] parameters give a command handler server-owned values without adding them to the request contract. Arc generates and validates each value before calling Handle(), then captures the accepted value for specs. Use them when the server should choose an identifier, code, or secret and a spec needs to pin that choice.

For example, a registration command needs a new customer identity. Calling CustomerId.New() inside the handler hides the choice from the spec; adding a command property hands the choice to the client. A generated handler parameter keeps it server-owned and testable. The handler can return the identifier without appending an event or using Chronicle.

The examples follow the shop from the Generated values tutorial and Generated Values Shop sample. Start with the concept and handler below; the plain-Guid example then shows generation without an event-store dependency. For the underlying UUID, ULID, TypeID, NanoID, and bytes strategies, use Generating values in Fundamentals.

Define the strategy on the concept before marking a handler parameter. Here CustomerId is cus_ followed by a lowercase ULID. It implements IGeneratable<TSelf> from Cratis.Fundamentals 7.23.0 or later; its static New() method supplies the value:

Shop/Common/CustomerId.cs
using Cratis.Chronicle.Events;
using Cratis.Concepts;
namespace Shop.Common;
public record CustomerId(string Value) : EventSourceId<string>(Value), IGeneratable<CustomerId>
{
public static implicit operator CustomerId(string value) => new(value);
public static CustomerId New() => new($"cus_{GenerateValue.Ulid().ToLowerInvariant()}");
}

The command asks for it as a Handle() parameter. The request carries only the customer’s name:

Shop/Customers/Registration/RegisterCustomer.cs
using Cratis.Arc.Commands.ModelBound;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Concepts;
using Shop.Common;
namespace Shop.Customers.Registration;
public record CustomerName(string Value) : ConceptAs<string>(Value)
{
public static implicit operator CustomerName(string value) => new(value);
}
[Command]
public record RegisterCustomer(CustomerName Name)
{
public (CustomerId, EventForEventSourceId) Handle([GeneratedValue("customerId")] CustomerId customerId) =>
(customerId, new EventForEventSourceId(customerId, new CustomerRegistered(Name)));
}
[EventType]
public record CustomerRegistered(CustomerName Name);

Arc calls CustomerId.New() before invoking Handle(). Because customerId is a handler parameter rather than a command property, neither the request body nor the generated TypeScript proxy contains it. The proxy for RegisterCustomer has only the name property. The handler returns the allocated identifier as the response and appends CustomerRegistered to that identifier. Check the command’s final result before using its response; having generated an identifier does not mean execution succeeded.

This example uses Arc’s Chronicle integration for EventForEventSourceId. Generation does not depend on it: a handler without Chronicle can return the generated value alone.

An identifier that implements IGeneratable<TSelf> over a Guid follows the same shape. These declarations allocate an identifier; they do not persist a cart or append an event, and the migration guide reuses them:

Shop/Carts/Starting/CartId.cs and StartCart.cs
using System;
using Cratis.Arc.Commands.ModelBound;
using Cratis.Concepts;
public record CartId(Guid Value) : ConceptAs<Guid>(Value), IGeneratable<CartId>
{
public static CartId New() => new(GenerateValue.Uuid());
}
[Command]
public record AllocateCartId
{
public CartId Handle([GeneratedValue("cart")] CartId cartId) => cartId;
}

Only non-nullable types that implement IGeneratable<TSelf> or IGeneratableInContext<TSelf> for themselves are valid. A raw Guid, a nullable concept, duplicate names, or a generated parameter on Provide() fails at handler construction.

Generate with the command’s time and tenant

Section titled “Generate with the command’s time and tenant”

Use the context-aware contract when a strategy needs the command’s time or tenant. If OrderId.New() reads the clock itself, values created during one command can carry different times and a spec cannot pin the clock through Arc’s generation context. Implement IGeneratableInContext<TSelf> from Cratis.Fundamentals 7.24.0 or later to receive that context:

Shop/Orders/Placing/PlaceOrder.cs
using Cratis.Arc.Commands.ModelBound;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
using Cratis.Concepts;
using Shop.Common;
namespace Shop.Orders.Placing;
public record OrderId(string Value) : EventSourceId<string>(Value), IGeneratableInContext<OrderId>
{
public static OrderId New(GenerationContext context) => new(GenerateValue.TypeId("order", context));
}
[Command]
public record PlaceOrder(CustomerId CustomerId)
{
public (OrderId, EventForEventSourceId) Handle([GeneratedValue("orderId")] OrderId orderId) =>
(orderId, new EventForEventSourceId(orderId, new OrderPlaced(CustomerId)));
}
[EventType]
public record OrderPlaced(CustomerId CustomerId);

Arc passes CommandContext.ReceivedAt as GenerationContext.Now, giving context-aware strategies the command’s captured received time instead of requiring another clock read. It supplies the command’s tenant as GenerationContext.Tenant: TenantId.NotSet and TenantId.Default become GenerationContext.DefaultTenant (the zero-GUID string), and named tenants use their Value.

The shop’s OrderId takes its time from the command but contains no tenant. A TypeID has no tenant slot, and GenerateValue.TypeId("order", context) reads only context.Now. If your value must carry the tenant, declare a separate concept, such as a TenantOrderId built as $"{context.Tenant}-{GenerateValue.Ulid(context)}". See Context-dependent values for the contract.

When implementing that contract:

  • If a type implements both interfaces, Arc always calls the context form. Its plain New() is never selected by Arc, and ARC0027 warns about it.
  • A default ReceivedAt throws MissingGenerationTime, even when a custom strategy ignores time. A manually constructed command context must supply its received time; Arc never substitutes UtcNow.
  • Scenario pins bypass generation, but still pass through validation.

For the shop’s ApiKey, the strategy uses 32 random bytes. Consult Secrets and tokens before selecting or shortening Bytes(32). Generation chooses the secret; the following Chronicle-specific example addresses where the application sends it, which is a separate security concern.

Shop/Customers/ApiKeys/ApiKey.cs
using Cratis.Arc.Chronicle.Commands;
using Cratis.Concepts;
namespace Shop.Customers.ApiKeys;
[NotAudited]
public record ApiKey(string Value) : ConceptAs<string>(Value), IGeneratable<ApiKey>
{
public static ApiKey New() => new(GenerateValue.Bytes(32, ValueEncoding.Base64Url));
}

Chronicle records command property values in event causation, the context that links an event to the command that produced it. [NotAudited] on the concept leaves command properties of that type out of that context. It does not protect event payloads, command responses, or logs. IssueApiKey returns a generated key as its response. Its event goes to the customer, not to the key:

Shop/Customers/ApiKeys/IssueApiKey.cs
[Command]
public record IssueApiKey(CustomerId CustomerId)
{
public (ApiKey, EventForEventSourceId) Handle([GeneratedValue("apiKey")] ApiKey apiKey) =>
(apiKey, new EventForEventSourceId(CustomerId, new ApiKeyIssued()));
}
[EventType]
public record ApiKeyIssued;

This example returns the key in the response and omits it from ApiKeyIssued. It does not implement one-time retrieval, guarantee delivery, or prevent the caller from logging or retaining the response. The ApiKey is not an event source id: the event is appended to the CustomerId. Keep the key out of event payloads and logs in application code; use Chronicle compliance ([Encrypted] and friends) for data that must be stored.

[NotAudited] earns its place on commands that receive the key as input. The shop’s RevokeApiKey takes an ApiKey property, and a spec confirms its value does not appear on the causation of ApiKeyRevoked. A generated Handle parameter is not a command property, so it never reaches the causation chain in the first place.

Match the value to its job, then read the linked page before shortening anything:

Value Strategy Why
CustomerId, CartId Ulid() with a prefix, or Uuid() Identifier; plenty of random bits
OrderId TypeId("order", context) Names its type, sorts by the command’s time
InviteCode NanoId(10, "23456789ABCDEFGHJKLMNPQRSTUVWXYZ") People read it aloud; only 50 random bits, so it is a generated property, never an identifier; back it with a uniqueness check where collisions matter
ApiKey Bytes(32) Secret, 256 bits

The decision flow, collision tables and entropy guidance are in Choosing a strategy.

Use an explicit name when specs must survive a parameter rename. By default, [GeneratedValue] uses the C# parameter name; [GeneratedValue("cart")] fixes the name independently. Names are case-sensitive, non-empty, and unique within the command. Specs use that same name to pin a value.

Arc generates values only after Provide() control results allow the command to continue. A value returned by Provide(), or registered in dependency injection, never overrides a generated parameter. Unmarked parameters keep their normal Provide and dependency injection behavior.

The Arc source generator registers a typed factory for each accessible generatable type. Commands compiled without it can use a cached reflection fallback with just-in-time (JIT) compilation. When dynamic code is unavailable, a missing factory fails at handler construction with MissingGeneratedValueFactory, naming the command and parameter. This factory path alone does not make the whole application compatible with NativeAOT, .NET’s native ahead-of-time compilation.

A generated value must satisfy its concept rules before the handler receives it. Arc resolves the concept’s discoverable validator from the command’s scoped provider and runs it asynchronously with the command’s cancellation token. Any failing rule, including Warning or Information, rejects either a generated or fixture-pinned value with GeneratedValueRejected.

Caller severity thresholds cannot permit these failures. A server-selected value breaking a concept rule is a server defect, not invalid request input: the command result contains an exception rather than a 400 validation failure.

CommandContext.GeneratedValues exposes validated captures in parameter resolution order. Each entry has a zero-based Order, a Name, its declared Type, its Value, and the immutable Freshness policy. Get<CustomerId>("customerId") retrieves the latest matching capture and fails if none exists. Context copies retain the same captures.

Keep caller-selected references on command properties. The customer to update or order to cancel identifies existing state; generating a replacement would not preserve the caller’s choice. Services and read models also remain ordinary Handle() dependencies.

Generation does not make a command idempotent: a repeated invocation can choose a different value. Retrying a successful registration may create another customer, depending on the handler and storage. Accept and enforce a client-supplied idempotency key when retries must not repeat the change.

Random and time-ordered identifiers are not consecutive numbers. If invoice numbers must have no gaps, use a coordinated counter rather than a generation strategy. Enforce storage uniqueness wherever the operation requires it; generation does not prove a value is absent from storage. Time-ordered values, UUIDv7 included, reveal their creation time and are not monotonic within a millisecond.

Generated values are unavailable to the command’s earlier authorization and input-validation filters. They cannot supply evidence for those decisions. A short code such as InviteCode is not proof of identity either; pair it with an expiry and a check.

With Arc’s Chronicle integration, GeneratedValueFreshness.Guarded is the default. Returned events and aggregate mutations targeting a generated identifier require the whole event source to be empty, regardless of stream or event type. Occupancy produces ConcurrencyViolation with ReasonDetail = "GeneratedIdentifierCollision"; Arc does not rerun Handle().

[GeneratedValue(Freshness = GeneratedValueFreshness.Unguarded)] opts out while keeping generation and validation. Values used only in a response or payload add no scope. Direct unit-of-work and transactional append calls receive the guard when they use the command’s actual unit of work, not an arbitrary new unit or external store. See Fresh identifiers for supported paths, explicit-scope merging, and version requirements.

Arc checks generated declarations in the IDE and at compile time: ARC0022 rejects invalid or nullable types, ARC0023 rejects attributes outside command Handle parameters, ARC0024 rejects empty or duplicate names, and ARC0025 warns when Provide() supplies a generated type. ARC0027 warns about dual generation interfaces, and ARC0028 offers migration from inline generation to a parameter. Startup validation remains in place for commands compiled without the analyzers.

If you are recovering a Screenplay model from your C# application, check whether its factories can be represented in the executable semantic model (ESM). A factory that works at runtime is not necessarily recoverable as model behavior. You do not need model recovery to use generated handler parameters.

Arc executes your concept’s generation contract at runtime; Screenplay recovery recognizes only the documented factory forms. A custom helper or external dependency can be valid Arc code without a recoverable Screenplay strategy. Self-contained String factory bodies, including multi-statement factories using context.Now, tenant formatting and GenerateValue.*(context), recover as inline generate rule bodies in ESM v21. The Cratis C# target binds ValueGeneration to Fundamentals’ Cratis.Concepts.GenerationContext; passing that context to a Fundamentals API is target-bound, not a promise of portability to other providers. Rule bodies never become generated identifiers because their entropy is unknown. Literal GenerateValue.Pattern calls and signed GenerateValue.Integer ranges also recover in v21; an int factory needs one in-range cast, and unsigned backings are refused. SP0073 names that limitation; it does not change your runtime factory or make the value caller-supplied.

The generated model keeps independent parameters and behavior. It withholds a whole event production when a required payload member or explicit destination depends on the opaque value; an optional payload dependency removes only that mapping. Dependent responses and operations stay in code too. When no event production remains, the model keeps a handler file reference, which is not executable Screenplay behavior. Enabling authoring-only constructs or raising the executable version cap does not recover an unknown factory. Keep the original handler and use the diagnostics to identify what the partial model cannot run.

Validated generation in a Screenplay model

Section titled “Validated generation in a Screenplay model”

A concept validator does not by itself prevent recovery. An empty validator keeps the existing generation contract; a String-backed concept with completely recoverable rules can carry both generate and validate in ESM v20. Screenplay checks that the strategy and rules agree. Proven rules are admitted; non-opaque unproven rules stay in the model with Information SP0078 (PLAY0689). Refuted rules withhold generation and dependent claims with SP0073 and the PLAY0688 witness, while preserving validation.

Unreadable, conditional or opaque validation stays outside executable generation. UUID validator rules such as Guid NotEmpty also remain outside Screenplay’s declarative algebra: recovery preserves the original validator through a source attachment rather than pretending UUID is text. This does not change Arc’s runtime validation behavior. A cap below ESM v20 withholds validated generation, not its rules, in both output modes. ESM v21 additionally recovers unconditional String Must(v => GenerateValue.HasValidChecksum(v, Checksum.Luhn)) rules, with Mod11 and Mod97 supported too. None and conditional checksum predicates are not recovered. Below v21, generation and its dependents are withheld while the checksum validator remains source-backed; rules are never stripped to fit an older cap. See Validated generation for the admission and fallback details.