Skip to content

Closing streams in Cratis Chronicle

Closing a stream in Cratis Chronicle tells the kernel to reject new events within a chosen scope, such as one invoice or one reporting period. Appends inside that scope fail with a StreamClosed constraint violation, regardless of which client sends them. Events already stored remain available to read and replay.

Use a closure when a business rule says no more events belong in that part of the history. Checking the rule only in command code leaves room for two requests to race or another client to bypass it; the kernel checks it before committing an append.

A closure is a record in the kernel’s constraint storage. It is not an event, and it does not change the events already in the log. Every append is checked against the closures of its event sequence and namespace before it is committed.

There are two ways to create a closure:

Way Written by Reopened by
Manual Your code calls CompleteStream Only the admin repair path, not a normal application flow
Event-driven The kernel, when it appends an event type declared with [ClosesStream] An event type you name in ReopenedBy

Choose an event-driven closure when a domain fact ends the scope: the event log then records the fact that caused the closure. The kernel writes the closure after storing that event, without allowing another append between them. These writes are not crash-atomic; see Guarantees and limits. Use a manual closure for an ad-hoc close that no domain event represents.

A scope selects which events a closure blocks. Build it from any non-empty combination of these four dimensions; leaving a dimension unset means it can match any value:

Dimension Matches
Event source id One event source, for example one invoice
Event source type Every event source of one type
Event stream type A kind of stream, for example monthly-report
Event stream id A stream id, for example 2026-04; combine it with a stream type to narrow the match

An append is refused when every dimension set in a closure equals the append’s value. Closing the stream monthly-report / 2026-04 of event source report-7 refuses only appends that carry all three values. Another report that uses the same stream type and id is unaffected.

Some examples:

Scope Refuses
Event source report-7, stream type monthly-report, stream id 2026-04 That one report’s April stream
Event source report-7 Every stream of report-7, including its default stream
Stream type monthly-report, stream id 2026-04 The April stream of every event source
Event source type Report Every event source of that type

Values are compared by exact spelling on every storage: letter case, character width, accents and trailing spaces all count, so a closure for Order-1 does not refuse an append for order-1. On SQL Server, closures stored before this behavior keep the spelling they were stored with; close any other spelling you need separately.

EventSourceId.Unspecified, EventSourceType.Unspecified and an empty stream type or stream id count as unset. EventStreamType.All and EventStreamId.Default are real values: the scope event source report-7 + All + Default closes exactly the default stream of report-7.

Scoped closing shows how to close each combination from code.

The two-argument call closes one stream type and stream id pair across every event source:

using Cratis.Chronicle.EventSequences;
public class ClosingStreamsInvoiceCloser(IEventLog eventLog)
{
public async Task CloseInvoiceStream(EventStreamId invoiceStreamId)
{
var result = await eventLog.CompleteStream(new EventStreamType("invoices"), invoiceStreamId);
result.Switch(
sequenceNumber => Console.WriteLine($"Stream closed at sequence number {sequenceNumber}"),
error => Console.WriteLine($"Failed to close stream: {error}"));
}
}

View C# snippet source on GitHub

An empty stream type means All and an empty stream id means Default, so ("", "") is the default stream and returns DefaultStreamCannotBeCompleted. The call returns Result<EventSequenceNumber, CompleteStreamError>. On success the number is the tail of the event sequence at the moment of closing.

To close anything narrower or broader than “one pair for every event source”, pass a ClosedStreamScope to CompleteStream(scope, expectedTailSequenceNumber).

Pass expectedTailSequenceNumber when your decision depends on the events you have read. The kernel compares it with the sequence number of the last event inside the scope and closes in the same step. If the tail has changed, the close fails instead of acting on an outdated decision. Scoped closing shows how to use the number returned by your final append.

Error Meaning
AlreadyCompleted A manual closure already covers the scope. Nothing was written
DefaultStreamCannotBeCompleted The scope would close the default stream on its own, see above
EmptyScope No dimension is set
ExpectedTailMismatch The scope’s tail differs from expectedTailSequenceNumber. Nothing was written

A scope is covered when an existing closure’s dimensions are a subset of the scope’s dimensions and their values match. A narrower scope than an existing manual closure is therefore AlreadyCompleted. A broader one is not covered and creates a new closure.

Coverage by an event-driven closure alone does not return AlreadyCompleted. The call succeeds and writes a manual closure next to it. A later ReopenedBy event cannot remove that manual closure; undoing it requires the admin repair path.

Retrying a close is safe: a second call returns AlreadyCompleted before the expected-tail check runs.

An append inside a closed scope is rejected with a StreamClosed violation. The violation details name the owner (ClosedBy, empty for a manual closure) and the sequence number at which the scope closed (ClosedAtSequenceNumber):

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
using Cratis.Chronicle.EventSequences;
using System.Linq;
[EventType]
public record ClosingStreamsInvoiceLineAdded(string Description, decimal Amount);
public class ClosingStreamsInvoiceLineAppender(IEventLog eventLog)
{
public async Task<bool> TryAppendLine(EventSourceId invoiceId)
{
var appendResult = await eventLog.Append(
invoiceId,
new ClosingStreamsInvoiceLineAdded("Consulting", 500m),
new EventStreamType("invoices"),
new EventStreamId("invoice-42"));
if (!appendResult.IsSuccess)
{
var violation = appendResult.ConstraintViolations
.FirstOrDefault(v => v.ConstraintType == ConstraintType.StreamClosed);
return violation is null;
}
return true;
}
}

View C# snippet source on GitHub

The check is active for every event sequence without configuration.

Closing does not touch what is already stored or how it is read:

  • Reads, observers, projections, reactors and replays work as before. A closed stream replays like any other.
  • Events already in the stream stay in the log.
  • A redacted closing event keeps its closure.

An event that creates a closure is accepted before that closure takes effect. A closing event is still rejected if it falls inside an already-closed scope.

The kernel writes an event-driven closure in the same turn as the durable append. No other append to that event sequence can land between the closing event and its closure. Unique constraints use the same mechanism. The two writes are not crash-atomic, however: if the kernel stops after storing the event but before storing the closure, the scope stays open until the closure is rebuilt.

A constraint reindex that names a closing constraint rebuilds its closures from the log. It never touches manual closures. Registering or changing a declaration does not start a reindex or close historical scopes, and removing a declaration leaves its closures in force.

Redaction matters when the stream id comes from an event property. A rebuild can recover a redacted closing or reopening event’s scope only if the existing closure snapshot has a record at that event’s sequence number. Without one, it leaves all closures owned by that constraint untouched, logs a warning identifying the constraint and event position, and continues with other constraints. Scopes derived entirely from event context do not have this payload-recovery limit.

A property-sourced scope is read from the generation in which the event was appended. If a new generation renames the property, update the declaration or closing and reopening fail for events of that generation.

Use a kernel that supports scoped closing and closing constraints. The .NET client throws ClosedStreamScopesNotSupported when a scoped-closing call is unimplemented; it does not fall back to the broader two-argument close. Closing-constraint registration also checks the kernel’s advertised capabilities.