Skip to content

Declare Chronicle unique property constraints

A unique property constraint reserves a value for an event source so another source cannot claim it. Use it for a project name or email address that must stay unique even when different event types introduce or change the value. The owning source can claim its own value again without a violation.

In .NET, call builder.Unique(...) inside an IConstraint implementation. The client’s default artifact discovery finds these classes without separate registration. See Declarative constraints for client-specific API differences.

The following rule reserves a project’s name when it is created and releases it when the project is removed. Implement IConstraint and put the builder call in Define:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
[EventType]
public record ConstraintsUniqueProjectCreated(string Name);
[EventType]
public record ConstraintsUniqueProjectRemoved;
public class ConstraintsUniqueProjectName : IConstraint
{
public void Define(IConstraintBuilder builder) =>
builder.Unique(unique =>
unique
.On<ConstraintsUniqueProjectCreated>(e => e.Name)
.RemovedWith<ConstraintsUniqueProjectRemoved>());
}

View C# snippet source on GitHub

A second project cannot claim the same name while it is reserved. The rule applies within one namespace and one event sequence, not across tenants or sequences.

A unique property value belongs to an event source, not to a single append. The same event source may append its current value again without violating the constraint. If it claims a different value, the new value replaces its previous claim, freeing the old value for another event source.

Do not constrain a property containing the event source’s own id to prevent a second event on that source: it will re-claim its own value and pass. To allow an event type only once per event source, use a unique event type constraint instead.

When one event source accumulates many identifiers, call .WithMode(UniqueConstraintMode.PerValue) to keep all of them reserved. The default, PerEventSource, keeps only the source’s current value. The .NET API uses the enum shown below; Elixir declares this mode with mode: :per_value.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
[EventType]
public record MappingVersionRegistered(string VersionId);
[EventType]
public record MappingVersionRemoved(string VersionId);
[EventType]
public record MappingVersionsRemoved;
public class UniqueMappingVersionId : IConstraint
{
public void Define(IConstraintBuilder builder) =>
builder.Unique(unique => unique
.WithMode(UniqueConstraintMode.PerValue)
.On<MappingVersionRegistered>(e => e.VersionId)
.RemovedWith<MappingVersionRemoved>(e => e.VersionId)
.RemovedWith<MappingVersionsRemoved>());
}

View C# snippet source on GitHub

Each mapping version id remains unavailable to other event sources even after the project registers another version. The owning source may reclaim any of its values without a violation. .RemovedWith<MappingVersionRemoved>(e => e.VersionId) releases only the value carried by the removal event, provided that source owns it. .RemovedWith<MappingVersionsRemoved>() releases all values that source holds in the constraint’s scope.

For a composite value, pass removal-property expressions in the same order as the constrained properties. An event with no constrained properties present claims nothing and leaves earlier values reserved. .IgnoreCasing() applies to both claiming and releasing values.

Use multiple .On calls when different events introduce or change the same logical value. Here, Email on registration and NewEmail on an address change share one rule, so changing an address cannot claim one held by another user:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
[EventType]
public record ConstraintsUniqueUserRegistered(string Email);
[EventType]
public record ConstraintsUniqueUserEmailChanged(string NewEmail);
[EventType]
public record ConstraintsUniqueUserRemoved;
public class ConstraintsUniqueEmailAcrossEvents : IConstraint
{
public void Define(IConstraintBuilder builder) =>
builder.Unique(unique =>
unique
.WithName("UniqueEmail")
.On<ConstraintsUniqueUserRegistered>(e => e.Email)
.On<ConstraintsUniqueUserEmailChanged>(e => e.NewEmail)
.RemovedWith<ConstraintsUniqueUserRemoved>());
}

View C# snippet source on GitHub

Use .WithName(...) to give the constraint an explicit name. When not provided, Chronicle uses the class name of the IConstraint implementation:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
[EventType]
public record ConstraintsUniqueNamedUserRegistered(string Email);
public class ConstraintsUniqueNamedEmail : IConstraint
{
public void Define(IConstraintBuilder builder) =>
builder.Unique(unique =>
unique
.WithName("UniqueEmail")
.On<ConstraintsUniqueNamedUserRegistered>(e => e.Email));
}

View C# snippet source on GitHub

Call .RemovedWith<T>() when a lifecycle event should release the value held by that event source. In the default PerEventSource mode, the source’s current value then becomes available to another source:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
[EventType]
public record ConstraintsUniqueOrderPlaced(string Reference);
[EventType]
public record ConstraintsUniqueOrderCancelled;
public class ConstraintsUniqueOrderReference : IConstraint
{
public void Define(IConstraintBuilder builder) =>
builder.Unique(unique =>
unique
.On<ConstraintsUniqueOrderPlaced>(e => e.Reference)
.RemovedWith<ConstraintsUniqueOrderCancelled>());
}

View C# snippet source on GitHub

An invitation may end by acceptance, revocation, or expiry. Call .RemovedWith<T>() once for each event that should release the value. Every declaration applies independently; adding a second does not replace the first:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
[EventType]
public record ConstraintsUniqueSeveralInvitationSent(string EmailAddress);
[EventType]
public record ConstraintsUniqueSeveralInvitationAccepted;
[EventType]
public record ConstraintsUniqueSeveralInvitationRevoked;
[EventType]
public record ConstraintsUniqueSeveralInvitationExpired;
public class ConstraintsUniqueSeveralInvitedAddress : IConstraint
{
public void Define(IConstraintBuilder builder) =>
builder.Unique(unique =>
unique
.On<ConstraintsUniqueSeveralInvitationSent>(e => e.EmailAddress)
.RemovedWith<ConstraintsUniqueSeveralInvitationAccepted>()
.RemovedWith<ConstraintsUniqueSeveralInvitationRevoked>()
.RemovedWith<ConstraintsUniqueSeveralInvitationExpired>());
}

View C# snippet source on GitHub

By default, a constraint applies to every event sequence its event types are appended to. Each sequence keeps a separate index of claims. If you forward a constrained event to the outbox, that copy claims the value in the outbox too; a removal event in the event log does not release the outbox claim.

Call .ForEventLog() when only the event log should enforce the rule, or .ForEventSequences(...) to select other sequences. The kernel neither validates nor indexes the constraint for a sequence outside that selection:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
[EventType]
public record ConstraintsUniqueEventLogInvitationSent(string Email);
[EventType]
public record ConstraintsUniqueEventLogInvitationRevoked;
public class ConstraintsUniqueEventLogInvitationEmail : IConstraint
{
// InvitationSent is also forwarded to the outbox. Scope the constraint to the event log
// so the forwarded copy does not claim the email in the outbox's own index.
public void Define(IConstraintBuilder builder) =>
builder
.ForEventLog()
.Unique(unique =>
unique
.On<ConstraintsUniqueEventLogInvitationSent>(e => e.Email)
.RemovedWith<ConstraintsUniqueEventLogInvitationRevoked>());
}

View C# snippet source on GitHub

In the .NET builder, this selection covers every constraint defined on that builder, wherever in the chain you make the call. Calling .ForEventSequences(...) again adds to the sequences already named. Without either call, the builder’s constraints apply to every event sequence.

Changing the sequences takes effect when the client next registers its constraints. The kernel then rebuilds, in every namespace, the index of each sequence the constraint now applies to but did not before, from the events already in that sequence. A sequence the constraint no longer applies to stops validating it, and its index is no longer read until the constraint applies there again, when it is rebuilt.

Call .IgnoreCasing() to make the uniqueness check case-insensitive:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
[EventType]
public record ConstraintsUniqueCasingUserRegistered(string Email);
public class ConstraintsUniqueCasingEmail : IConstraint
{
public void Define(IConstraintBuilder builder) =>
builder.Unique(unique =>
unique
.On<ConstraintsUniqueCasingUserRegistered>(e => e.Email)
.IgnoreCasing());
}

View C# snippet source on GitHub

Call .WithMessage(...) to provide a custom message when the constraint is violated:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
[EventType]
public record ConstraintsUniqueMessageProjectCreated(string Name);
public class ConstraintsUniqueMessageProjectName : IConstraint
{
public void Define(IConstraintBuilder builder) =>
builder.Unique(unique =>
unique
.On<ConstraintsUniqueMessageProjectCreated>(e => e.Name)
.WithMessage("A project with this name already exists."));
}

View C# snippet source on GitHub

Use a callback to compose the message dynamically from violation context:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
[EventType]
public record ConstraintsUniqueMessageCallbackProjectCreated(string Name);
public class ConstraintsUniqueMessageCallbackProjectName : IConstraint
{
public void Define(IConstraintBuilder builder) =>
builder.Unique(unique =>
unique
.On<ConstraintsUniqueMessageCallbackProjectCreated>(e => e.Name)
.WithMessage(violation => $"A project named '{violation.Details[WellKnownConstraintDetailKeys.PropertyValue]}' already exists."));
}

View C# snippet source on GitHub

The Chronicle Kernel uses an index of claimed values to check the registered rule during append, regardless of which client writes the event. Event storage and the claim update are not crash-atomic. If an update cannot complete, the kernel marks the affected index as pending and refuses governed appends while it catches up. See Constraint or decision read for the enforcement limits.

A governed append refused with ConstraintIndexUnavailable has written none of that attempt’s new events. In .NET, its append result exposes IsRetryable as true and RetryAfter as a suggested delay of one second. Wait before retrying the unchanged request; for keyed appends, keep the same idempotency keys. A successful durable-key replay is not a refusal, even while an index is pending.

Retry metadata does not turn a uniqueness or concurrency violation into a transient failure. Older kernels that omit it yield IsRetryable == false and RetryAfter == null in the .NET client. The client does not automatically retry these refusals.

Before upgrading to Chronicle 19.112.0 or later, back up every namespace database. The startup patch permanently deletes unique-constraint claim rows whose stored value is not exactly 64 lowercase hexadecimal characters (^[0-9a-f]{64}$). The comparison is case-sensitive even on SQL Server databases with case-insensitive collations, so uppercase values are deleted.

Cleanup covers current per-event-source claims and retained per-value claims across all event sequences and scopes. A legacy raw value already matching the exact hash shape is indistinguishable from a hash and remains unchanged. MongoDB uses the same case-sensitive rule; in-memory storage has no persisted legacy claims to clean.

After cleanup, SQL value columns and indexes are repaired directly, even if a running kernel node cached an earlier skipped migration. Duplicate hash-shaped claims remain intact, with the existing non-unique-index fallback and a warning. A cleanup or schema-update failure stops the patch without recording completion; retrying is safe.

Downgrading does not undo the deletion. To roll back, stop the kernels and restore the backup taken before upgrading. Reindexing rebuilds claims using current hashes; it does not restore the deleted legacy rows.

To rebuild an existing declaration without changing it, use the operator Rebuild a constraint index command. Select its registered name, namespace, and event sequence, then follow the returned job identifier.

When a change to a property constraint requires reindexing, Chronicle rebuilds its index from the event sequence in log order. It clears all claims in each scope before replaying that scope’s first event, so stale claims do not block historical values.

While an index rebuild is running, Chronicle refuses appends governed by that index with ConstraintIndexUnavailable in the append result’s errors. Nothing is stored, so retry the unchanged append after a delay. Appends not governed by a rebuilding index continue normally. Governed appends resume once the rebuild handover and any pending repair finish.

If the rebuild step cannot hand over to the event sequence, Chronicle keeps refusing governed appends rather than accept duplicates against an incomplete index. The Kernel logs a warning starting with Constraint index rebuild terminal handoff failed or Constraint index rebuild cancellation handoff failed.

About every 30 seconds, Chronicle checks the constraint’s reindex job step. Once the step has ended (failed, stopped, completed, or removed), Chronicle releases the rebuild and catches the index up from the event sequence before accepting governed appends again. While the rebuild is held, the Kernel logs Constraint rebuild … is still holding … every 5 minutes. The gauge chronicle-event-sequences-constraint-indexes-rebuilding remains non-zero.

Restart the Kernel only when that message says the job step cannot be read (unreadable) or has no job, for example a step started by an earlier Kernel version. Restarting is safe: Chronicle catches the index up from the event sequence before accepting governed appends again.

If the store rejects a duplicate claim during the rebuild, Chronicle logs a warning, skips that claim, and continues. The first historical claimant keeps the value until an event releases or replaces it. The step persists skipped-claim counts per constraint and reports them in its completion progress message, for example Skipped 3 duplicate claims: UniqueEmail=2, UniqueName=1. The report contains constraint names and counts only, not claimant identities, values, or hashes; collision-free rebuilds leave the progress message unchanged.

Revising an event moves the claims it made: Chronicle releases the value the old content held and refolds the index from the revised position before the next governed append. Revisions made before this behavior shipped left stale claims behind. If you revised events of a constrained type before upgrading, rebuild that constraint’s index once so the stale claims are released.