Close a scoped stream in Cratis Chronicle
Use ClosedStreamScope in Cratis Chronicle to close one event source’s stream without closing other sources that share its stream type and id. Pass the scope to CompleteStream, with an expected tail when the close depends on the history you have read.
The two-argument CompleteStream(streamType, streamId) closes that pair across every event source. The examples below use the .NET scope API to narrow the close to one report or extend it to every stream of one entity. If you need another combination, start with the scope dimensions and matching rules.
Close one event source’s stream
Section titled “Close one event source’s stream”Set the event source id together with the stream type and stream id. This closes the April stream for one report; it leaves other reports using monthly-report / 2026-04 open:
using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.Events;
public class ScopedClosingReportCloser(IEventLog eventLog){ public async Task CloseApprovedReport(EventSourceId reportId) { // Close one report's "2026-04" stream. Other reports that use the same // stream type and stream id stay open. var scope = new ClosedStreamScope( EventSourceId: reportId, EventStreamType: new EventStreamType("monthly-report"), EventStreamId: new EventStreamId("2026-04"));
var result = await eventLog.CompleteStream(scope);
result.Switch( sequenceNumber => Console.WriteLine($"Closed at sequence number {sequenceNumber}"), error => Console.WriteLine($"Not closed: {error}")); }}defmodule MyApp.ScopedClosingReportCloser do alias Chronicle.EventSequences.Streams
def close_approved_report(report_id) do # Close one report's "2026-04" stream. Other reports that use the same # stream type and stream id stay open. result = Streams.complete_scope( event_source_id: report_id, event_stream_type: "monthly-report", event_stream_id: "2026-04" )
case result do {:ok, sequence_number} -> IO.puts("Closed at sequence number #{sequence_number}") {:error, reason} -> IO.puts("Not closed: #{inspect(reason)}") end endendThe scope has three dimensions set, so an append is refused only when it carries all three values.
Close every stream of an event source
Section titled “Close every stream of an event source”To stop all future appends for an entity, use ClosedStreamScope.ForEventSource. It sets only the event source id, so the closure covers every stream of that source, including its default stream. This also works when the entity’s events use no explicit stream id:
using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.Events;
public class ScopedClosingCustomerArchiver(IEventLog eventLog){ public async Task ArchiveCustomer(EventSourceId customerId) { // Every stream of this event source is closed, including its default stream. var result = await eventLog.CompleteStream(ClosedStreamScope.ForEventSource(customerId));
result.Switch( sequenceNumber => Console.WriteLine($"Customer archived at sequence number {sequenceNumber}"), error => Console.WriteLine($"Not archived: {error}")); }}defmodule MyApp.ScopedClosingCustomerArchiver do alias Chronicle.EventSequences.Streams
def archive_customer(customer_id) do # Every stream of this event source is closed, including its default stream. case Streams.complete_scope(event_source_id: customer_id) do {:ok, sequence_number} -> IO.puts("Customer archived at sequence number #{sequence_number}")
{:error, reason} -> IO.puts("Not archived: #{inspect(reason)}") end endendClosedStreamScope.ForStream is the matching helper for the stream type and stream id pair, and it is what the two-argument overload uses.
Close only if nothing landed
Section titled “Close only if nothing landed”An approval followed by a manual close takes two calls. If another event arrives between them, the approval may no longer describe the history you intended to close. Pass the approval’s sequence number as expectedTailSequenceNumber so the kernel checks for that change before closing.
The kernel compares the expected number with the scope’s tail, meaning the sequence number of its last event. It performs that check and the close in the same step. A changed tail returns ExpectedTailMismatch and writes no closure:
using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.Events;
[EventType]public record ScopedClosingReportApproved(string Approver);
public class ScopedClosingApprover(IEventLog eventLog){ public async Task<bool> ApproveAndClose(EventSourceId reportId) { var scope = new ClosedStreamScope( EventSourceId: reportId, EventStreamType: new EventStreamType("monthly-report"), EventStreamId: new EventStreamId("2026-04"));
var approved = await eventLog.Append( reportId, new ScopedClosingReportApproved("alice"), new EventStreamType("monthly-report"), new EventStreamId("2026-04")); if (!approved.IsSuccess) return false;
// Close only if nothing has landed in this scope after the approval. var result = await eventLog.CompleteStream(scope, expectedTailSequenceNumber: approved.SequenceNumber);
var closed = false; result.Switch( _ => closed = true, error => closed = error == CompleteStreamError.AlreadyCompleted); return closed; }}defmodule MyApp.Events.ScopedClosingReportApproved do use Chronicle.Events.EventType, id: "scoped-closing-report-approved"
defstruct [:approver]end
defmodule MyApp.ScopedClosingApprover do alias Chronicle.EventSequences.{EventLog, Streams} alias MyApp.Events.ScopedClosingReportApproved
def approve_and_close(report_id) do with {:ok, approved} <- EventLog.append_with_result( report_id, %ScopedClosingReportApproved{approver: "alice"}, event_stream_type: "monthly-report", event_stream_id: "2026-04" ) do # Close only if nothing has landed in this scope after the approval. result = Streams.complete_scope( event_source_id: report_id, event_stream_type: "monthly-report", event_stream_id: "2026-04", expected_tail_sequence_number: approved.sequence_number )
match?({:ok, _}, result) or result == {:error, :already_completed} else {:error, _result} -> false end endendA scope with no matching events has the tail EventSequenceNumber.Unavailable. Events appended elsewhere in the sequence do not change this scope’s tail and do not cause a mismatch.
In the example, an accepted approval supplies the expected tail. A failed append returns before attempting the close. The result treats AlreadyCompleted as success because a manual closure already covers the scope. That check runs before the expected-tail check, so retrying a successful close does not fail with a tail mismatch.
Handle the errors
Section titled “Handle the errors”Check the result before treating the scope as closed. An expected-tail mismatch needs a new decision based on the current history, not a retry with the same number:
using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.Events;
public class ScopedClosingErrorHandling(IEventLog eventLog){ public async Task<string> Close(ClosedStreamScope scope) { var message = string.Empty; var result = await eventLog.CompleteStream(scope);
result.Switch( sequenceNumber => message = $"Closed at {sequenceNumber}", error => message = error switch { CompleteStreamError.AlreadyCompleted => "Already closed by an earlier manual close", CompleteStreamError.DefaultStreamCannotBeCompleted => "The default stream cannot be closed on its own", CompleteStreamError.EmptyScope => "The scope names no dimension", CompleteStreamError.ExpectedTailMismatch => "Something landed in the scope since you last looked", _ => $"Unexpected error {error}" });
return message; }}defmodule MyApp.ScopedClosingErrorHandling do alias Chronicle.EventSequences.Streams
def close(scope) when is_list(scope) do case Streams.complete_scope(scope) do {:ok, sequence_number} -> "Closed at #{sequence_number}" {:error, :already_completed} -> "Already closed by an earlier manual close" {:error, :default_stream_cannot_be_completed} -> "The default stream cannot be closed on its own" {:error, :empty_scope} -> "The scope names no dimension" {:error, :expected_tail_mismatch} -> "Something landed in the scope since you last looked" {:error, other} -> "Unexpected error #{inspect(other)}" end endend| Error | What to do |
|---|---|
AlreadyCompleted |
A manual closure covers the scope. Usually a success from your point of view |
DefaultStreamCannotBeCompleted |
Add an event source id or another specific dimension |
EmptyScope |
The scope has no dimension set. This is a bug in the caller |
ExpectedTailMismatch |
Read the stream again and decide whether to close |
Event-driven closures alone do not produce AlreadyCompleted. The call succeeds and writes a manual closure as well, which a ReopenedBy event can no longer undo.
After a successful close, use Inspecting and repairing to check the persisted scope or investigate an unexpected rejection. Manual closures have no normal client reopen call; undoing a mistaken close requires the operator repair path.
To take the scope from an event source definition rather than construct it from strings, follow Close a stream of a definition. For the relationship between a closed scope and decisions based on its history, see Dynamic Consistency Boundary in Chronicle.