Archiving Streams
Polecat supports archiving event streams to logically remove them from active queries without permanently deleting the data.
Archiving a Stream
session.Events.ArchiveStream(streamId);
await session.SaveChangesAsync();This sets is_archived = 1 on both the pc_streams and pc_events tables for the stream.
Effects of Archiving
When a stream is archived:
- Archived events are left out of event reads unless you opt in. The rows stay in
pc_events, butFetchStreamAsync,QueryAllRawEvents(),QueryRawEvents(),QueryEventsAsync,QueryEventData<T>,QueryRawEventDataOnly<T>,LoadAsync, live aggregation and tag queries all read past them. See Reading archived events. - The async daemon's event loader skips archived events
FetchStreamStateAsyncandQueryStreamStates()still answer for the stream, withIsArchivedset- Attempting to append to an archived stream throws
ArchivedStreamException ApplyEventDataMaskingstill reaches it, because archiving a stream doesn't erase it
The append refusal is raised at SaveChangesAsync(), when Polecat reads the stream's state, and it names the way back:
Event stream 'a1b2…' is archived and cannot be appended to. Call UnArchiveStream to reopen it, or start a new stream.
Polecat.Exceptions.ArchivedStreamException derives from JasperFx.Events.ArchivedStreamException, so store-agnostic code can catch the shared type. (It replaces InvalidStreamException, which is now obsolete and never thrown.)
WARNING
Masking reaches archived streams from every source: both kinds of IncludeStream, and IncludeEvents unless your filter rules them out itself with IsArchived.
Before this was fixed, masking left archived rows out, so protected data stayed in place while the pass reported success. If you relied on masking for data that was archived when you ran it, run the same ApplyEventDataMasking call again after upgrading. That also runs your rules again over everything the first pass reached, so if a rule isn't safe to run twice, such as one that draws a new pseudonym, add x.IsArchived to the filter of an IncludeEvents that still names the same subject, like IncludeEvents(x => x.StreamId == streamId && x.IsArchived). Never use x.IsArchived as the whole filter for this, which masks every archived event in the store.
Unarchiving a Stream
Restore an archived stream — this is what the refusal above points you at:
session.Events.UnArchiveStream(streamId);
await session.SaveChangesAsync();This sets is_archived = 0 on both tables, making the stream active again.
Reading archived events
Archived events are filtered out unless you ask for them, as on Marten and Fisher. There are two ways to ask, both in a predicate over IEvent, on QueryAllRawEvents() or QueryRawEvents():
// Live and archived events together. MaybeArchived() is in Polecat.Events.Archiving.
var everything = await session.Events.QueryAllRawEvents()
.Where(x => x.MaybeArchived() && x.StreamId == streamId)
.ToListAsync();
// Naming IsArchived replaces the implicit filter, so this finds only archived events...
var archived = await session.Events.QueryAllRawEvents()
.Where(x => x.IsArchived && x.StreamId == streamId)
.ToListAsync();
// ...and this finds only live ones.
var live = await session.Events.QueryAllRawEvents()
.Where(x => !x.IsArchived && x.StreamId == streamId)
.ToListAsync();Naming IsArchived replaces the implicit is_archived = 0 rather than sitting beside it, so a predicate answers for itself. What counts:
- Any predicate that filters rows.
Where, and the predicate of a terminal such asCountAsync,AnyAsyncorFirstOrDefaultAsync, wherever it sits in the chain. - Either side of an
||.x.IsArchived || x.Version == 1finds every archived event and every first event.!x.IsArchived || x.Version == 1also finds the first event of an archived stream, because namingIsArchivedtook the implicit filter away. - Not
OrderByorSelect. They name the member without filtering anything, so archived events stay out.
AggregateToAsync folds what its query matched, so it reaches archived events through the same predicates.
FetchStreamAsync, LoadAsync and QueryEventsAsync(EventQuery) have no opt-in, so read an archived stream through one of the predicates above. Neither do QueryEventData<T> and QueryRawEventDataOnly<T>, because those predicates are over the event body, which cannot speak for the row. An IsArchived member on the body itself has no effect on archiving. The IEventStore explorer's ReadStreamAsync is a diagnostic read and shows archived events, as it does on Marten and Fisher.
Tombstoning (Deleting a Stream)
ArchiveStream hides a stream but keeps every row. When the data has to actually go, for a GDPR erasure request, test or demo data, or a purge job, TombstoneStream is the hard delete: it removes the stream and every event in it from the database.
await using var session2 = theStore.LightweightSession();
// Queues a hard DELETE of the stream, its events and their tag rows.
// Nothing touches the database until SaveChangesAsync()
session2.Events.TombstoneStream(streamId);
await session2.SaveChangesAsync(TestContext.Current.CancellationToken);There is an overload for each stream identity, TombstoneStream(Guid) and TombstoneStream(string); use the one that matches StreamIdentity.
WARNING
Tombstoning permanently DELETEs the stream record and all associated events from the database. This cannot be undone, and unlike ArchiveStream there is no UnArchiveStream to bring it back.
What to expect:
- It is queued. Like
ArchiveStreamandAppend,TombstoneStreamonly adds an operation to the session's unit of work. TheDELETEruns when you callSaveChangesAsync(), in the same transaction as anything else in that session, and discarding the session without saving deletes nothing. - The whole stream goes. The row in
pc_streamsand every row for that stream inpc_eventsare deleted. The stream's DCB tag rows go with them, through a cascade or, underUseArchivedStreamPartitioning, a delete of their own. So do its natural key rows, through a cascade or, under conjoined tenancy, a delete of their own, which frees the key for a new stream. - Tag values go when nothing carries them any more.
pc_dcb_tag_versionkeeps a row per tag value, with the value as text. A tombstone deletes the row of each tag on the stream that no other stream in the tenant carries, in the same transaction, and it never creates one. See what a tombstone erases. - It conflicts with a boundary that read the stream's tags. A boundary that read them throws
DcbConcurrencyExceptionon save instead of saving a decision made from events that are gone, whether the tag's row was moved, deleted or never existed. The retry reads the stream as deleted. - It is tenant-scoped. Only the stream in the session's tenant is deleted. Under conjoined tenancy, a stream with the same id in another tenant is untouched.
- A missing stream is a no-op. Tombstoning a stream that does not exist, or was already deleted, is not an error.
- The id can be reused. After the delete, you can start a new stream with the same identity.
- Sequence numbers are not reused. The deleted events leave a gap in the event sequence, and new events keep counting up from the high-water mark. A tombstoned stream can never hide later events from an async projection.
- Projected documents are left alone. Tombstoning deletes events, not the documents that projections already built from them. If an aggregate snapshot or read model should go too, delete it in the same session (for example with
session.Delete<T>(id)) so both land in one transaction.
TombstoneStream is part of the shared JasperFx.Events.IEventStoreOperations contract as of JasperFx 2.90.0, the same surface Marten implements, so store-agnostic code can call it through IEventStoreOperations without referencing Polecat. Polecat's behaviour is pinned by the shared StreamTombstoningCompliance suite.
Archiving vs Tombstoning
| Operation | Reversible | Data Preserved | Use Case |
|---|---|---|---|
| Archive | Yes | Yes | Soft removal, compliance holds |
Tombstone (TombstoneStream) | No | No | GDPR right to erasure, cleanup |
Compacting a Stream
Compaction is the third option in that table: it replaces a stream's history with a single Compacted<T> snapshot event and deletes the events it folded. The stream keeps its version, so appending carries on as before, but a fold no longer has to replay everything below the compaction point — Compacted<T> fast-forwards it.
await using var session = store.LightweightSession();
await session.Events.CompactStreamAsync<Freighter>(streamId);
await session.SaveChangesAsync();Like every other session operation, the typed overload only queues the work — the replace, the deletes and the compaction watermark all land on SaveChangesAsync().
WARNING
Compaction DELETEs the events it folds. What survives is the snapshot inside the marker, so an aggregate that cannot be rebuilt from that snapshot alone cannot be rebuilt at all. Use StreamCompactingRequest<T>.Archiver to copy the events somewhere first if you need them.
An archiver can be closed over either IDocumentOperations or IDocumentSession. If you set one that Polecat cannot call, CompactStreamAsync throws an InvalidOperationException and nothing is compacted, because the alternative is deleting the events without archiving them.
WARNING
A stream that folds to no aggregate is left alone. That is a stream deleted by its own aggregate through ShouldDelete, at the cutoff you asked for if you set one. CompactStreamAsync queues nothing for it, doesn't call the archiver, and doesn't record a compaction watermark.
Before this was fixed, compacting such a stream replaced its whole history with a Compacted<T> event holding a null snapshot, and nothing threw. The deleted events can only come back from a backup, or from wherever your archiver copied them to.
Compacting without a compile-time type
IEventStore.CompactStreamAsync is the untyped overload. It reads the stream's recorded aggregate type from pc_streams and closes the typed operation over it, which is the only form available to a caller holding a runtime Type — a compaction policy that selects streams by aggregate type, for instance, or a tool with a "compact this stream" button:
var streams = ((IEventStore)store).OpenReadOnlyEventStore().QueryStreamStates();
var overgrown = await streams
.Where(x => x.AggregateType == typeof(Freighter) && x.Version - x.CompactedVersion > 500)
.ToListAsync();
foreach (var state in overgrown)
{
// Resolves Freighter from the stream state, and commits on its own
await ((IEventStore)store).CompactStreamAsync(state.Id, cancellationToken);
}Two differences from the typed overload are worth knowing:
- It opens and commits its own session, so there is no
SaveChangesAsync()to call. - It needs an aggregate type on the stream. A stream started with
StartStream<T>()records one; a stream started without a type has nothing to resolve, and the call is refused rather than silently doing nothing. Name the type explicitly withCompactStreamAsync<T>in that case.
StreamState.CompactedVersion is the watermark the last compaction reached, so Version - CompactedVersion is the stream's un-compacted growth — which is what makes a policy like the one above idempotent instead of re-compacting the same streams on every pass.
Compacting a stream in one tenant's scope
Both untyped overloads take an optional tenant id. The stream-state read and the compaction itself then run on a session opened for that tenant, which is the action-side twin of OpenReadOnlyEventStore(tenantId):
var streams = ((IEventStore)store).OpenReadOnlyEventStore("blue").QueryStreamStates();
var overgrown = await streams
.Where(x => x.Version - x.CompactedVersion > 500)
.ToListAsync();
foreach (var state in overgrown)
{
await ((IEventStore)store).CompactStreamAsync(state.Id, "blue", cancellationToken);
}Pass this overload whenever the selector was tenanted, and the tenant-less one only for a single-tenanted store. A policy that selects a tenant's streams through the tenanted reader and then calls the tenant-less action is reading and writing in two different scopes: on a conjoined store the action looks for those stream ids in the default tenant's partition, where they are not visible and are reported as missing, and on a store whose default tenant is disabled the call is refused outright. A null or empty tenant id means the default tenant, matching the reader.

JasperFx provides formal support for Polecat and other Critter Stack libraries. Please check our