Migration Guide
Deprecation: MapPolecatMcp
Polecat.AspNetCore's built-in MapPolecatMcp() is now [Obsolete] and will be removed in the next major version (polecat#821). It duplicates the Polecat.Mcp package, which is built on the official ModelContextProtocol SDK. Replace the call with MapPolecatMcpServer() from Polecat.Mcp; both default to /polecat/mcp, and RequireAuthorization(...) chains the same way. Do not map both on one host: they share a route.
Upgrading past 5.47.0: DCB tag versions come from a sequence
If you have registered a tag type, the schema gains pc_dcb_tag_version_sequence, and every tag version comes from it (polecat#890). It is an additive change, so any AutoCreate setting but None applies it on first use, and existing rows keep working. Under AutoCreate.None, apply the migration first, because tagged appends, archives and tombstones fail without the sequence. A login granted individual tables rather than db_datawriter also needs UPDATE on the sequence.
TombstoneStream now deletes a tag's pc_dcb_tag_version row once no other stream carries it, and no longer creates one. See what a tombstone erases. A session's two boundaries over one tag now conflict whenever they captured different versions. Anything reading pc_dcb_tag_version.version directly can't treat it as a count of commits any more.
Finish a rolling upgrade before you rely on any of this: a node still on 5.47.0 counts up from the current value and doesn't delete rows.
Upgrading past 5.47.0: documents a patch may have damaged
Through 5.47.0, on the native json type, two patches could leave a document with a member overwritten, a write lost, or a member corrupted (polecat#907). Patches no longer do this, but it can't undo what's stored, so if you store documents as json and have used the patching API, run Advanced.FindDocumentsWithMismatchedIdsAsync() once. It only finds damage to a document's id. nvarchar(max) storage was never affected.
Upgrading past 5.47.0: the full-text term column
polecat#877 widened the full-text token table's term column from varchar(255) to nvarchar(255). As varchar it lost every character outside the database's code page, so under the default collation nothing written in Chinese, Japanese, Korean, Cyrillic, Greek, Arabic or Hebrew could be found, and every search scanned the token table, because the term is bound as nvarchar. A new token table has the new column. An existing one needs a step from you, and until then it keeps working exactly as it did.
- Run
ApplyAllConfiguredChangesToDatabaseAsync(), or the script fromdb-patch. This drops the token index, alters the column and builds the index again, now withmemberin its key. It also adds thedoc_idindex described below. - Run
RebuildFullTextIndexAsync<T>()for each type with a full-text index, to recover what the old column lost. A rebuild refuses until step 1 has been done.
Step 1 is a size-of-data operation
Nothing does it at first use, because it would run inside whichever request touched the type first. 8 million tokens, which is what 8,000 documents of 5,000 characters amount to, took 72 seconds to alter and 36 to index on the development container, far past the 30 second command timeout a migration runs under. A store of that size should apply the db-patch script through a tool with no timeout, in a maintenance window, rather than through ApplyAllConfiguredChangesToDatabaseAsync() or ApplyAllDatabaseChangesOnStartup, which would stop the application from starting. The table is locked while the column changes, so searches and writes to that document type wait for it, and it takes about 13% to 25% more space afterwards.
The doc_id index
polecat#916 added a second index to the token table, on doc_id and tenant_id, which the trigger finds a document's old tokens through. Without it, every write to a type with a full-text index scans the token table: 3,819 logical reads for a document of 25 tokens among half a million, and more as the table grows, against 253 with the index. Those scanning writes also hold up each other.
A new token table has the index. An existing one gets it from step 1 above and works as it did until then, so if you have already widened the column, apply the schema once more. It is the same kind of step: the index took 0.6 seconds over half a million tokens on the development container, and db-patch is the way to add it to a large table. The index is not there for what AssertDatabaseMatchesConfigurationAsync() compares until it has been applied, so that check reports the difference in the meantime.
Upgrading past 5.47.0: LINQ answers that change
polecat#916 fixed a set of queries that threw or that answered wrongly. Nothing needs changing unless something had come to depend on one of these.
| Query | Before | Now |
|---|---|---|
Select(...).First() and Single, Last | threw | the projected value |
Select(x => new { x.A, x.B }).Distinct() | threw, or duplicates on nvarchar(max) storage | distinct rows |
...Distinct().OrderBy(y => y.A) | Msg 145 | ordered |
Select(...).Distinct().Count() | the rows of the table | the distinct rows |
Query<T>().Distinct() | threw on json storage | the documents |
x.Id == "abc ", x.Id.IsOneOf("abc ") | matched abc | no match |
GroupBy(x => x.Name) over abc and abc | one group | two groups |
x.Name == "??" over a varchar index | matched 東京 | no match |
x.Name == "a" over a varchar index | matched ā | no match |
Select(x => x.Name), a GroupBy key, Distinct, DistinctBy, Min or Max of an indexed member | ?? for 東京, and two such keys merged | the stored value |
anything over a key like [JsonPropertyName("a-b")] or on a kebab-case store | SQL error | works |
a [JsonPropertyName] on an event body in QueryRawEventDataOnly<T>() | the CLR name, which matched nothing | the key it was written under |
These are refused with BadLinqExpressionException now, and were either a raw SQL error or a quiet wrong answer before:
OrderBy,ThenBy,GroupByorDistinctByon a member stored as a JSON object or array. They readNULLfor every row. A class with a converter that stores it as a scalar still works.Distinct()over a projection SQL cannot compare: an object, a computed value or a constructor call.- An ordering by something a
Selectdid not project, on aDistinct(). Sum,Min,MaxorAverageafterDistinct(), which aggregated the rows of the table.ToJsonPageByCursorAsyncover aDistinct(), which dropped it.- A
Selectof anything but one scalar withFirst,SingleorLaston an event query.
One of these costs an index
Reading a value back through a default varchar index is what answered ??, so that now reads the document. An unfiltered GroupBy on an indexed string member over 100,000 documents takes 5,160 reads and 155ms rather than 588 and 16. A Select or a Distinct of the member loses a covering index the same way. A filter on the member still seeks. If you need the index for these, declare the column nvarchar.
Upgrading past 5.47.0: event predicates naming IsArchived
Archived events are still filtered out by default, and now you can opt in. MaybeArchived() in Polecat.Events.Archiving is new, and a predicate naming IEvent.IsArchived now replaces the implicit is_archived = 0 instead of sitting beside it. A query that never names IsArchived is unchanged, and so is !x.IsArchived alone. These do change, and all of them start reading rows they never read before:
Predicate over IEvent | Before | Now |
|---|---|---|
x.IsArchived, x.IsArchived == true | matched nothing | archived events |
x.IsArchived || y | live events matching y | archived events, and any event matching y |
!x.IsArchived || y | live events | live events, and archived events matching y |
ApplyEventDataMasking's IncludeEvents(x => x.IsArchived) | masked nothing | masks archived events |
Predicates over an event body are unaffected, including QueryEventData<T> and QueryRawEventDataOnly<T> over a body with an IsArchived of its own. So is QueryStreamStates(), which has no implicit filter.
Upgrading past 5.47.0: string predicates and full-text tokens
polecat#835 and polecat#839 fixed how string members over 4000 characters and whitespace are read. Nothing needs changing in your code, but if you use full-text search there is one step to take.
Rebuild your full-text indexes
The tokenizer now splits on every whitespace character rather than only a space, and clips a token to 255 characters rather than failing the save. It lives in the maintenance trigger, so this is a schema change:
- The trigger is replaced by your next migration, or on first use under
AutoCreate.CreateOrUpdateor above. The token table does not change. UnderAutoCreate.None, apply it withdb-patch. - A document with some tokens keeps them until it is next written, however stale.
"quick\nbrown fox"still holds the single termquick\nbrown, and a search forbrowndoes not find it. - A document with no tokens for a member, which is what a member over 4000 characters used to produce, stays that way too, so it is not found until it is next written.
So once the schema change is applied, run this once for each type with a full-text index:
await store.Advanced.RebuildFullTextIndexAsync<Article>();It is explicit because it can be a lot of work, and that work should not land on the first request after a deployment. See Rebuilding the index. The same rebuild is what makes a phrase search find quick brown in an older document holding quick, brown.
Queries that now answer differently
These were wrong and are now what .NET says, so anything that had come to depend on them will see a change:
| Predicate | Value | Before | Now |
|---|---|---|---|
string.IsNullOrEmpty(x.Text) | spaces only | matched | no match |
string.IsNullOrEmpty(x.Text) | over 4000 characters | matched | no match |
string.IsNullOrWhiteSpace(x.Text) | tabs or line breaks only | no match | matches |
x.Text == null | over 4000 characters | matched | no match |
x.Text != "a", !(x.Text == "a") | over 4000 characters | no match | matches |
x.Text.Contains("a") and friends | over 4000 characters | no match | matches |
x.Code.Trim() == "ABC" | "\tABC\n" | no match | matches |
Later in the same line, for polecat#875 and polecat#877:
| Query | Before | Now |
|---|---|---|
x.Text == "abc", x.Text.Equals("abc"), x.Text.ToLower() == "abc", IsOneOf("abc"), list.Contains(x.Text), x.Tags.Contains("abc") against "abc " | matched | no match |
x.Text == "" against spaces only | matched | no match |
x.Text != "abc" against "abc " | no match | matches |
An indexed x.Code == prefix on nvarchar(max) storage, against a stored value longer than the index and starting with prefix | matched | no match |
x.Address == null, for any object or array member, including a nullable struct stored as an object | matched every row | matches a null |
x.Address != null, likewise | matched nothing | matches a value |
Select(x => x.Address), for any object or array member | a null for every row | the value |
Select(x => x.Address).Where(a => a.City == "x") and any other operator reading a member of a Select | matched nothing, or did nothing | what it says |
Select(x => new { A = x.Age }).Select(y => y.A) | a default for every row | the value |
Select(x => new Dto { A = x.A }).Where(y => y.B == 0), or a member of new Dto(x.A) | matched nothing | refused |
QueryAllRawEvents().OrderBy(e => ((Body)e.Data).Id), Max(e => ((Body)e.Data).Version) | read the event's own column | refused |
x.Text.Trim().ToLower() == "abc" and any other chain of string methods | InvalidCastException | translated |
x.Name.Substring(1).ToLower() == "a" | InvalidCastException | refused |
x.Text == x.Other, comparing two members | InvalidOperationException | refused |
x.Address == someAddress | ArgumentException from SqlClient | refused |
x.Name == input.ToLower() | refused | translated |
Select(x => new { x.Created.DayOfWeek }) as JSON under EnumStorage.AsString | a number | a name, as a stored enum is |
Upgrading past 5.47.0: string ids outside the code page
polecat#919. A string document id or stream key is stored in a varchar(250) column, which holds what the database's code page holds. Anything else was changed with no error: under the default collation 東京 and 大阪 are both ??, so they were one row, the second write overwrote the first, and LoadAsync("東京") returned Osaka's document. ā was stored as a, which can be another document's id.
This is a behaviour change. A write that used to succeed and lose data now throws StringIdOutsideCodePageException:
| What you call | Before | Now |
|---|---|---|
Store, Insert, Update, StoreObjects | saved under ??, over whatever was there | refused by SaveChangesAsync |
BulkInsertAsync, BulkInsertWithVersionAsync | the same | refused before the first chunk is written |
StartStream, Append, FetchForWriting and appending | a false ExistingStreamIdCollisionException, or the events joined the ?? stream | refused by SaveChangesAsync |
| A projection that takes a document's id from an event | the same as Store | refused, inline at the save, and a daemon shard fails on it |
LoadAsync, LoadManyAsync, CheckExistsAsync, FetchStreamAsync, FetchLatest, AggregateStreamAsync | found the row it collapsed onto | finds nothing, with no error |
FetchForWriting | handed back the stream it collapsed onto | a new stream |
AppendOptimistic, AppendExclusive | appended to it | NonExistentStreamException |
Delete, HardDelete, ArchiveStream, TombstoneStream | acted on that row or stream | does nothing, as for any id that isn't there |
The exception comes from SaveChangesAsync and not from Store, because finding out the code page takes a round trip and Store is synchronous. Nothing is written, including anything else in that save.
What's refused is what the column can't hold, not whatever isn't ASCII. café, ñ and €100 are in code page 1252 and work as they always did. Under Japanese_CI_AS, 東京 is fine and café is refused. Under a _UTF8 collation nothing is refused, because varchar holds everything there. Each tenant database answers for itself. An ASCII id costs nothing, and the first id outside ASCII that a table sees costs one round trip to read its code page, after which the store remembers it.
Rows that are already stored
Nothing changes them, and nothing can repair them. A document that was overwritten this way can't be recovered: only the last writer's survives, and nothing records what it replaced. A stream under such a key can hold events appended under several different keys.
The row stays where it is, under the key its column actually holds, so it can only be reached by that:
var document = await session.LoadAsync<City>("??"); // what the key holds
document.Id; // "大阪", from the JSON body
await session.LoadAsync<City>("大阪"); // null: the column can't hold that id
session.Store(document); // refused, for the same reason
session.Delete(document); // does nothing, for the same reason
session.Delete<City>("??"); // removes the rowTo find them, compare the key with the id in the document's body. The member's name in the JSON follows your serializer's casing, and this assumes id:
SELECT id, JSON_VALUE(data, '$.id') AS id_in_the_document
FROM dbo.pc_doc_city
WHERE CONVERT(varbinary(1000), CONVERT(nvarchar(250), id))
<> CONVERT(varbinary(1000), JSON_VALUE(data, '$.id'));What to do instead
- Use a
Guidid, or for a stream,StreamIdentity.AsGuid. - Keep string ids within the database's code page. An id made from a name can be kept apart from the name, with the name as an ordinary member you can index.
- Create the database with a
_UTF8collation, such asLatin1_General_100_CI_AS_SC_UTF8. It has to be a new database, or at least new tables:ALTER DATABASE ... COLLATEchanges the default and leaves every existing column as it was, so those go on being refused. The limit of 250 is in bytes, so東京takes 6 of them.
Widening the keys to nvarchar is the lasting fix. It's a size-of-data change to the primary key of every string-keyed table, and it's planned for a major version.
Key Changes in 5.30.0
Polecat 5.30 adopts the shared vector and hybrid search surface from JasperFx.Events.Vectors (JasperFx 2.70.0, polecat#633). Most of it is a type moving house and is source-compatible. Two things are not.
HybridTextStyle.Phrase removed
HybridSearchOptions, HybridMatch<T> and HybridTextStyle are now the shared types in JasperFx.Events.Vectors rather than Polecat's own. The shared HybridTextStyle has exactly two members — PlainText and WebStyle — and Polecat's third, Phrase, is removed rather than renamed.
// before (Polecat 5.29)
options: new HybridSearchOptions(TextStyle: HybridTextStyle.Phrase)
// after (Polecat 5.30) — phrase search moves to Query<T>()
var matches = await session.Query<Passage>()
.Where(x => x.Body.PhraseSearch("fox in the snow"))
.ToListAsync();This is a removal on purpose, not an oversight. Both shared members are safe to hand a search box's raw contents, and that is the property the short list exists to keep: a malformed query in one leg of a fused search fails the whole call, where the same query through Query<T>() fails only the thing the caller asked for. PhraseSearch itself is untouched.
There is also nothing lost in ranking. The phrase leg never carried a relevance order of its own — a document contains the phrase or it does not — so fusing it leaned the fused order onto the vector leg, and when more documents contained the phrase than CandidateDepth, which of them were read was not decided by relevance either.
PlainText and WebStyle keep their names, their meanings and their behaviour. Distance still defaults to null, meaning "the metric the index declared" — Polecat's default was already the one the shared type took.
filter is a new parameter BEFORE token
VectorSearchAsync, VectorSearchWithScoresAsync, HybridSearchAsync, HybridSearchWithScoresAsync, FullTextSearchAsync and FullTextSearchWithScoresAsync all gained an optional filter immediately before the cancellation token, matching the shared IDocumentSearchOperations signatures. A call that passed the token positionally no longer compiles:
// before
await session.VectorSearchWithScoresAsync<Passage>(x => x.Embedding, q, 4, DistanceFunction.L2, token);
// after — name it
await session.VectorSearchWithScoresAsync<Passage>(x => x.Embedding, q, 4, DistanceFunction.L2, token: token);The break is a compile error at every affected call site, never a silent behaviour change. Calls that already named token: are unaffected.
See Vector Search for what the filter does and why it is applied before the limit.
BM25 k1 and b are configurable — additively, with nothing to change
FullTextSearchAsync and FullTextSearchWithScoresAsync can now take a FullTextSearchOptions carrying the BM25 k1 and b (polecat#630). Nothing existing changes: the options arrive through a new overload and the signatures 5.29 shipped are untouched, so every existing call still compiles and still binds — no rebuild required.
// unchanged, still binds to the original signature
await session.FullTextSearchAsync<Article>(x => x.Body, "fox", 10, x => x.Team == "red", token);
// new — b = 0 turns length normalization off, so a long document no longer pays for its length
await session.FullTextSearchAsync<Article>(x => x.Body, "fox", new FullTextSearchOptions(B: 0.0));TIP
An overload rather than an optional parameter, deliberately. Adding an optional parameter to an existing public method is a binary break as well as a source one: optional arguments are resolved at the call site, so a caller's IL hard-codes the full signature and any assembly compiled against 5.29 that is not recompiled throws MissingMethodException — while its source still compiles, which is what makes it quiet. It bites hardest through a prebuilt integration sitting between an application and Polecat.
options is required on the new overload for a second reason: were it optional, the two would be ambiguous for every call that omits it.
The defaults are the constants 5.29 hard-coded (k1 1.2, b 0.75), so omitting options changes no ranking.
PrefixSearch is new
A LINQ operator, so nothing existing changes. See Full Text Search for what it matches and what it does not.
Vector projections take the shared map
VectorProjection<TDoc, TId>.Configure now receives the shared VectorProjectionMap<TId> instead of Polecat's VectorProjectionMap<TDoc, TId>:
// before
protected override void Configure(VectorProjectionMap<PageVector, string> map)
// after
protected override void Configure(VectorProjectionMap<string> map)The mapping calls inside are unchanged, and so is the content hash — still lowercase hex SHA-256 of the UTF-8 text, verified byte-for-byte against the previous spelling before the swap, so no stored document is re-embedded by this upgrade. The new MapFromAggregate is documented in Vector Projections.
Vector projections are new in 5.30.0 (#628), so the before shape above never shipped in a release — it existed only between that work landing and this rename, both inside 5.30.0. Nobody upgrading from 5.29 or earlier has a VectorProjection to migrate, so the signature above is simply the one to write against rather than a change to make.
Hand-written projections start being validated
ProjectionGraph.AssertValidity now unwraps the ProjectionWrapper that a bare IProjection is registered through before looking for IValidatedProjection<T>. A hand-written IProjection in your application that implements IValidatedProjection<StoreOptions> was never being asked; it is now. If it reports a problem, the store refuses to build.
That is the fix working rather than a regression — but it can surface a configuration error that was quietly passing before this upgrade, which is worth knowing before a deploy.
New: store-neutral search
JasperFx.Events.Documents.IDocumentReadOperations gained a Search accessor carrying vector and hybrid search, so a library written against the store-agnostic contract can reach them without naming Polecat. The member has a throwing default, so this is purely additive. See Store-Neutral Search.
Key Changes in 5.0.0
The 5.0.0 release itself changes no public API
Measured, not recalled: the public surface of Polecat.dll is identical in 4.8.0 and 5.0.0. Every break in the 4.x → 5.0 upgrade shipped in 4.8.0, a minor release, which is why this section covers 4.6.0 through 5.0.0 rather than 5.0.0 alone.
Those releases were published to NuGet without git tags, so the version boundaries are easy to lose. This section was produced by building Polecat.dll at each published release and diffing its public and protected surface by reflection:
| Release | Commit | Public API vs. previous | What it means for an upgrade |
|---|---|---|---|
| 4.6.0 | bd610ce (tag v4.6.0) | — | starting point |
| 4.7.0 | b939bd7 | 88 added, 0 removed | additive; behaviour changes below |
| 4.7.1 | b2ca2a3 | unchanged | one behaviour change below |
| 4.8.0 | 4e3b011 | 26 removed or changed, 35 added | every source and binary break below |
| 5.0.0 | d7e0fa5 | unchanged | internal: the event append path, pin bumps |
Where to start reading:
- From 4.6.x or 4.7.x: all of it. The breaks are in 4.8.0.
- From 4.8.0: only What 5.0.0 itself changed and the pin bumps. Your code already compiles against the 5.0 API.
Foundation pin bumps, 4.6 to 5.0
| Package | 4.6.0 | 4.7.x | 4.8.0 | 5.0.0 |
|---|---|---|---|---|
JasperFx | 2.16.0 | 2.18.0 | 2.24.0 | 2.24.1 |
JasperFx.Events | 2.16.0 | 2.18.0 | 2.24.0 | 2.24.1 |
Weasel.SqlServer | 9.3.0 | 9.3.0 | 9.16.0 | 9.16.2 |
Weasel.Storage | (not referenced) | (not referenced) | 9.16.0 | 9.16.2 |
Weasel.Storage is a new dependency in 4.8.0: it is the shared document and event storage runtime Polecat moved onto (#273). It arrives transitively; pin it alongside Weasel.SqlServer if you pin the Weasel family centrally. Target frameworks are unchanged (net9.0;net10.0).
Removed: the Polecat.CodeGeneration package and [Document] (4.8.0)
#274. The last published Polecat.CodeGeneration is 4.7.1; no 4.8.0 exists. Polecat.Attributes.DocumentAttribute — its discovery marker, with an optional IdType — went with it.
The generator was never wired into Polecat's runtime, and nothing in Polecat read [Document] or its IdType, so removing both changes no behaviour. Delete the package reference and the attributes:
// before (4.7.x)
[Document(IdType = typeof(Guid))]
public class Invoice { public Guid Id { get; set; } }
// after (4.8.0+) — identity is found exactly as it always was: by convention, or [Identity]
public class Invoice { public Guid Id { get; set; } }Changed: session listeners receive the change set (4.8.0)
#269 / #272. IDocumentSessionListener.AfterCommitAsync gains an IChangeSet parameter carrying what the commit wrote — inserted, updated and deleted documents, streams and events:
// before (4.7.x)
public Task AfterCommitAsync(IDocumentSession session, CancellationToken token)
// after (4.8.0+)
public Task AfterCommitAsync(IDocumentSession session, IChangeSet commit, CancellationToken token)IChangeSet and IDeletion live in Polecat.Services.
Changed: subscription change listeners move and widen (4.8.0)
Same issue, the daemon side. Polecat.Subscriptions.IChangeListener — one AfterCommitAsync(token) — is replaced by Polecat.IChangeListener, which mirrors Marten's and has two hooks:
| Hook | Runs | Delivery |
|---|---|---|
BeforeCommitAsync(session, commit, token) | before the projection batch commits | at least once |
AfterCommitAsync(session, commit, token) | after the batch commits | at most once — the right place for cache invalidation |
What that means for your code:
- An implementation of the old interface implements the new one, and takes both hooks.
NullChangeListenermoved fromPolecat.SubscriptionstoPolecat. A subscription that returnsNullChangeListener.Instanceneeds only theusing.ISubscription.ProcessEventsAsyncandSubscriptionBase.ProcessEventsAsyncnow returnTask<Polecat.IChangeListener>.- New: a listener can be registered for every async projection batch with
opts.Projections.AsyncListeners.Add(...), not only returned from a subscription.
// before (4.7.x)
using Polecat.Subscriptions;
public override async Task<IChangeListener> ProcessEventsAsync(EventRange page,
ISubscriptionController controller, IDocumentOperations operations, CancellationToken token)
{
// ...
return NullChangeListener.Instance;
}
// after (4.8.0+) — same body; IChangeListener and NullChangeListener now resolve from Polecat
using Polecat;Changed: IWorkTracker.Operations holds the shared operation type (4.8.0)
#281 / #298. session.PendingChanges.Operations is now IReadOnlyList<Weasel.Storage.IStorageOperation> rather than IReadOnlyList<Polecat.Internal.IStorageOperation>, because every document and event write now runs on the shared storage runtime. IWorkTracker also now extends IChangeSet.
Polecat.Internal.IStorageOperation still exists and now extends Weasel.Storage.IStorageOperation, so code that only reads the list through the base interface keeps working. Code that typed a variable or pattern-matched as Polecat.Internal.IStorageOperation changes to Weasel.Storage.IStorageOperation.
Changed: ISerializer's members are declared on Weasel's base interface (4.8.0)
#277. Polecat.Serialization.ISerializer now extends Weasel.Core.ISerializer, and ToJson, the FromJson / FromJsonAsync overloads, Casing and EnumStorage are declared there instead. The set of members is unchanged, so:
- Calling a serializer is source-compatible.
- Implementing one (
opts.Serializer = new MySerializer()) is source-compatible with ordinary, implicit implementations. Explicit implementations must change their qualifier:Polecat.Serialization.ISerializer.ToJson(...)becomesWeasel.Core.ISerializer.ToJson(...). - It is a binary break either way: recompile anything built against 4.7.x.
A custom serializer does not need to implement Weasel.Storage.IStorageSerializer. The built-in Serializer does, and Polecat adapts any other ISerializer to it.
Behaviour changes
Code that still compiles and acts differently, by the release it changed in.
4.7.0
- Auto-assigned
Guidids are sequential (#245). Polecat usedGuid.NewGuid(), whose random values fragment SQL Server's clustereduniqueidentifierindex; it now generates ids that sort in insertion order. They remain unique, but they are predictable — do not hand an auto-assigned id out as an unguessable token. CorrelationId/CausationIdare seeded fromActivity.Currentwhen a session opens (#250), as Marten does. Withopts.Events.EnableCorrelationId/EnableCausationIdon, events now carry trace ids where they were previously null. A value you set explicitly still wins.Patch().Set()honoursEnumStorage(#264). UnderEnumStorage.AsStringa patched enum is now written as its name; it was written as an integer while the rest of the document held names. Documents patched before upgrading keep the integer.Patch().Set()acceptsDateTime,DateTimeOffset,DateOnlyandTimeOnly(#265).
4.7.1
AutoCreate.Noneis honoured at runtime (#268). The async daemon's storage ensure, Hi-Lo'spc_hiloand the master-table tenancy'spc_tenantswere each still being provisioned on first use underNone. They no longer are — so a store that was silently relying on that now has to provision those objects itself, asNonealways said.
4.8.0
- Single-tenant document tables have no
tenant_idcolumn (#234 / #303), matching Marten. Existing tables keep theirs — defaulted and no longer modeled — so there is no migration. But the implicit tenant filter is now conjoined-only, so on a single-tenant storeForTenant(...),AnyTenant()andTenantIsOneOf(...)no longer filter documents. If you were usingForTenanton a store without conjoined tenancy to keep documents apart, configure conjoined tenancy. [JsonPropertyName]and[JsonStringEnumMemberName]are honoured by LINQ and patching (#270 / #271). A renamed member was stored under its JSON name but queried and patched under its CLR name, so predicates matched nothing and patches wrote a second, stray key. Both now use the stored name. ⚠️ Stray keys an earlier patch wrote are still in those documents.
What 5.0.0 itself changed
Nothing in the public API (see the top of this section). Internally, the event append path moved onto the shared storage runtime (#306–#312), and Polecat's own inline SqlCommand append was deleted once the whole suite passed on the new one. It went in only once it was at parity — the whole suite passed with it as the only path — so appends behave as they did. An Events.UseClosedShapeEventStorage opt-in existed briefly during that work; it was added and removed between 4.8.0 and 5.0.0, so no published release ever had it.
The rest of 5.0.0 moved the remaining document paths onto the same runtime — batched loads, bulk insert with and without version checks, set-based delete and undelete (#313–#317) — and bumped JasperFx to 2.24.1 and Weasel to 9.16.2.
Schema changes in 4.7 and 4.8
- Strong-typed id columns use the inner type (4.8.0, #296 / #302). A document with a
Guid-,int- orlong-backed id wrapper got avarchar(250)id column, and Lightweight and IdentityMap reads of it threwInvalidCastException. The column is nowuniqueidentifier,intorbigint. An existing table is converted in place, data preserved — drop the primary key, alter the column, re-add it — by the lazy schema ensure on first access to that document type. Because it is part of that ensure, a store runningAutoCreate.Nonehas to apply the column change itself. String-backed wrappers keepvarchar(250). - Index and foreign-key computed columns changed expression (4.7.0, #236 / #246) to
JSON_VALUE(data, '$.path' RETURNING type)on nativejsonstorage, so the persisted column and the LINQ predicate stay textually identical and the index stays seekable. That is still the form today. Before 5.32.0 these columns were created outside Weasel's schema model, so an existing column was not reconciled to a changed expression; from 5.32.0 they are modeled and a migration does reconcile them.
Key Changes in 4.0.0
Polecat 4.0 ships in lockstep with Marten 9.0 and JasperFx 2.0 as part of the Critter Stack 2026 release wave. The 4.0 line builds on the same JasperFx 2.0 / JasperFx.Events 2.0 / Weasel 9.0 release-candidate matrix that Marten 9 consumes — this is the consolidation cycle, not a rewrite. Most upgrades are pin bumps; the breaking surface is small and localized, and the bulk of the rc-line dedup work is source-compatible for typical applications (see rc dedup-wave relocations).
Foundation pin bumps
Polecat 4 consumes the 2026-wave release-candidate line for the shared substrate. Update your Directory.Packages.props (or the equivalent in your csproj):
| Package | 3.x | 4.0 (current rc) |
|---|---|---|
JasperFx | 1.31.0 | 2.0.0-rc.3 |
JasperFx.Events | 1.36.0 | 2.0.0-rc.3 |
JasperFx.Events.SourceGenerator | 1.4.0 | 2.0.0-rc.3 |
JasperFx.SourceGeneration (transitive, but pin centrally) | (no equivalent) | 2.0.0-rc.3 |
Weasel.SqlServer | 8.15.2 | 9.0.0-alpha.8 |
Weasel.EntityFrameworkCore | 8.15.2 | 9.0.0-alpha.8 |
Polecat 4 itself is at 4.0.0-rc.2 (the consolidation wave converged through an alpha series into the rc line). The four JasperFx.* packages move as a matrix and must be pinned to the same rc together; the two Weasel.* packages share their own version and currently trail one wave behind on alpha.8 (the rc.3 line resolves cleanly against them). Keep all six in one renovate/dependabot group. Expect a final tick to the matched 9.0/2.0 GA set as the 2026 wave closes out.
Polecat does not need JasperFx.RuntimeCompiler, directly or transitively: projection dispatch is source-generated. Don't add it to your pins on Polecat's account.
Target frameworks (net9.0;net10.0) are unchanged from late Polecat 3.x; .NET 8 was already dropped before Polecat 3.2.
Dedup audit relocations
The Marten ↔ Polecat dedup audit (JasperFx/jasperfx#218) consolidated several enums that had parallel definitions in Polecat and Marten into the canonical Weasel / JasperFx homes. The relocations are mechanical — same values, different namespace.
Polecat.BulkInsertMode → Weasel.Core.BulkInsertMode
#50, audit row weasel#264.
Third-party consumers that referenced Polecat.BulkInsertMode by full name need to update their using directive:
// before (Polecat 3.x)
using Polecat;
await store.Advanced.BulkInsertAsync(docs, BulkInsertMode.OverwriteExisting);
// after (Polecat 4.0)
using Weasel.Core;
await store.Advanced.BulkInsertAsync(docs, BulkInsertMode.OverwriteExisting);The enum gained a fourth value — OverwriteIfVersionMatches — that did not exist on the Polecat 3.x enum. See the new-behavior section below.
Polecat.Storage.CascadeAction → Weasel.Core.CascadeAction
#47 / #61, audit row 2 in JasperFx/jasperfx#218.
DocumentForeignKey.OnDelete is now typed as Weasel.Core.CascadeAction. The same four values (NoAction, Cascade, SetNull, SetDefault) remain available; Weasel.Core's version additionally exposes Restrict. Existing call sites only need a using Weasel.Core; addition:
// before (Polecat 3.x)
mapping.ForeignKey<User>(x => x.AssigneeId, fk => fk.OnDelete = CascadeAction.Cascade);
// ^ resolved Polecat.Storage.CascadeAction
// after (Polecat 4.0) — add `using Weasel.Core;` to the file
mapping.ForeignKey<User>(x => x.AssigneeId, fk => fk.OnDelete = CascadeAction.Cascade);
// ^ resolves Weasel.Core.CascadeActionPolecat.Metadata.ITenanted now extends JasperFx.MultiTenancy.IHasTenantId
Multi-tenancy dedup audit slice (jasperfx#224, row 1). Polecat.Metadata.ITenanted no longer declares its own TenantId property — it inherits it from IHasTenantId. Polecat-side framework code that accepts IHasTenantId now accepts any ITenanted document type.
Source-compatible for the typical case (your document class implementing ITenanted keeps a single string TenantId { get; set; } property and compiles unchanged). Only affects code that referenced the explicit ITenanted.TenantId property symbol via reflection or interface forwarding.
Polecat.Exceptions.UnknownTenantException → JasperFx.MultiTenancy.UnknownTenantIdException
Multi-tenancy dedup audit slice (jasperfx#224, row 2). The local Polecat.Exceptions.UnknownTenantException was removed; throw sites and consumers use the canonical JasperFx.MultiTenancy.UnknownTenantIdException. In Polecat 2.0.0-alpha.7 the JasperFx exception gained a TenantId property so consumers can catch (UnknownTenantIdException ex) { ex.TenantId } without parsing the message string.
// before (Polecat 3.x)
catch (Polecat.Exceptions.UnknownTenantException ex)
{
var id = ex.TenantId;
}
// after (Polecat 4.0)
catch (JasperFx.MultiTenancy.UnknownTenantIdException ex)
{
var id = ex.TenantId;
}rc dedup-wave relocations
The rc.1 → rc.3 cycle finished the Critter Stack 2026 dedup pillar: a batch of types that Polecat and Marten each declared in parallel were consolidated into the canonical JasperFx / Weasel homes (Polecat #125–#141). The values, members, and ordinals are unchanged — only the namespace moved.
Inside Polecat the old unqualified names keep resolving (the assembly carries global using aliases / empty inheriting interfaces), so the framework's own API surface is unaffected. The break, if any, is in your code: if you referenced one of these types by its old Polecat.* name — most often by implementing a marker interface on a document class, or by a fully-qualified catch / config reference — update the using directive (or the fully-qualified name) to the new home.
| Old name (Polecat 3.x / early 4.0) | New canonical home | PR |
|---|---|---|
TenancyStyle (inline in StoreOptions) | JasperFx.MultiTenancy.TenancyStyle | #127 |
Polecat.Metadata.DeleteStyle | JasperFx.DeleteStyle | #127 |
Polecat.Events.Dcb.DcbConcurrencyException | JasperFx.Events.DcbConcurrencyException | #128 |
Polecat.Exceptions.ProgressionProgressOutOfOrderException | JasperFx.Events.Daemon.ProgressionProgressOutOfOrderException | #128 |
Polecat.Metadata.ISoftDeleted | JasperFx.Metadata.ISoftDeleted | #130 |
Polecat.Metadata.IVersioned | JasperFx.Metadata.IVersioned | #130 |
Polecat.Metadata.ITracked ⚠️ | JasperFx.Metadata.ITracked (non-nullable members — see below) | #130 |
Polecat.Patching.RemoveAction | JasperFx.Events.RemoveAction | #131 |
Polecat.Patching.IPatchExpression<T> ⚠️ | JasperFx.Events.IPatchExpression<T> (predicate overloads — see below) | #131 |
Polecat.Internal.OpenTelemetry.TrackLevel | JasperFx.OpenTelemetry.TrackLevel | #132 |
Polecat.Attributes.IdentityAttribute (document [Identity] — marks a non-Id identity member on a plain document) | JasperFx.IdentityAttribute | #135 |
Polecat.Schema.Identity.Sequences.{ISequence, HiloSettings, IReadOnlyHiloSettings} | Weasel.Core.Sequences.* | #137 |
Polecat.Serialization.{Casing, CollectionStorage, NonPublicMembersStorage, EnumStorage} | Weasel.Core.* | #137 |
Polecat.Exceptions.DocumentAlreadyExistsException ⚠️ | JasperFx.DocumentAlreadyExistsException (message text — see below) | #140 |
The two you are most likely to touch directly are the document marker interfaces (ISoftDeleted / IVersioned / ITracked — you implement these on your own document classes) and the serialization-config enums (Casing / CollectionStorage / NonPublicMembersStorage / EnumStorage, set via StoreOptions). Both just need their using swapped:
// before (Polecat 3.x)
using Polecat.Metadata;
public class Invoice : ISoftDeleted { /* ... */ }
// after (Polecat 4.0)
using JasperFx.Metadata;
public class Invoice : ISoftDeleted { /* ... */ }Three of the relocations carry a behavior change beyond the namespace move:
ITracked members are now non-nullable
#130. The lifted JasperFx.Metadata.ITracked declares CorrelationId / CausationId / LastModifiedBy as non-nullable string (Marten's canonical shape); Polecat's old interface declared them string?. If your document class declared those members nullable to match the old interface, the compiler now warns (CS8766) that the nullability doesn't line up with the interface. Drop the ? (and add a default) on the implementing class — the session always copies non-null values onto them:
// before
public string? CorrelationId { get; set; }
// after
public string CorrelationId { get; set; } = string.Empty;IPatchExpression<T> predicate overloads throw on SQL Server
#131. Polecat adopted Marten's superset IPatchExpression<T>, which adds predicate-based overloads — AppendIfNotExists(expr, element, predicate), InsertIfNotExists(expr, element, predicate, index), Remove(expr, predicate, action) — and the object-shaped Rename(string, Expression<Func<T, object>>) (replacing Polecat's generic Rename<TElement>). The predicate variants require translating the predicate into a JSON-array search, which Polecat's JSON_MODIFY patch translation does not implement yet, so they throw NotSupportedException with a message pointing at the supported non-predicate overload. The element/key/index overloads you were already using are unchanged; only the new predicate forms are unimplemented.
DocumentAlreadyExistsException message text changed
#140. The lifted JasperFx.DocumentAlreadyExistsException keeps Polecat's DocumentType (Type) and Id properties and the (Type, object) ctor, so the duplicate-key catch path is a near-no-op rebind. But the thrown Message now uses Marten's FullName-based format — "Document already exists {FullName}: {id}" (was "A document of type '{Name}' with id '{id}' already exists."). If you assert on or parse .Message, update the expectation; assertions on .DocumentType / .Id are unaffected.
Numeric revisions are now strictly-greater, and honoured on insert
#559, settled by the maintainer ruling on jasperfx#785. Polecat previously read an explicit numeric revision as an equality expectation — the supplied value had to match the stored revision, and the row then auto-incremented past it — and discarded an explicit revision entirely on insert. Both are now Marten's and Fisher's rule: an explicit revision is the target version, accepted only when it is strictly greater than what is stored, and stored verbatim. A revision of 0 still means "auto". This affects every document implementing IRevisioned or ILongVersioned, and it breaks in two different ways.
The update path breaks loudly. The natural read-modify-write spelling now throws:
// before (Polecat 3.x / early 4.x): the loaded revision was an equality expectation
session.UpdateRevision(doc, doc.Version); // now throws ConcurrencyException
// after: name the revision the document is moving TO
session.UpdateRevision(doc, doc.Version + 1);Store(doc) passes the document's own Version as the target revision, so Store on a document still carrying the revision it was loaded at throws for the same reason. Set doc.Version = 0 before storing to take the auto path instead. In exchange, an explicit revision may now jump (3 → 10) and lands at exactly the value named rather than one past it — which is what lets a caller adopt a revision decided upstream.
The insert path breaks silently, and this is the one to search your code for. A document built with a non-zero Version and inserted was previously normalised to revision 1. It is now stored at that revision:
session.Insert(new Order { Id = id, Version = 7 });
// before: the row landed at revision 1
// after: the row lands at revision 7Nothing throws at the call site. The failure surfaces later, when an UpdateRevision computed against an assumed revision of 1 is refused. The escape hatch is to set Version = 0 on any document you are inserting and expecting the store to number for you — which is what a freshly constructed document does by default, so only code that populates Version before a first write is affected.
WARNING
Negative revisions changed as a side effect. Polecat's hard-coded insert value used to swallow a negative Version into 1; the new CASE stores it verbatim, after which the strictly-greater guard refuses every write below it. No store range-checks a negative revision and the shared compliance suite deliberately leaves the case unpinned — treat a negative Version as unsupported rather than as a behavior to rely on.
Event-sourcing API changes
Projections and self-aggregating documents must be partial
JasperFx/jasperfx#276 (FEC elimination, Phase 1) removed the FastExpressionCompiler fallback in JasperFx.Events's projection apply-method dispatch. Source-generated dispatchers emitted by JasperFx.Events.SourceGenerator are now the only path — runtime registration fails fast when no [GeneratedEvolver] is found for a projection that uses conventional Apply / Create / ShouldDelete methods:
JasperFx.Events.Projections.InvalidProjectionException:
No source-generated dispatcher found for MyApp.MyProjection.
When using conventional Apply/Create/ShouldDelete methods, the projection class must be
declared `partial` in an assembly that references the JasperFx.Events.SourceGenerator analyzer,
or alternatively override Evolve / EvolveAsync / DetermineAction / DetermineActionAsync directly.To clear this exception, every projection class that uses conventional apply-method discovery must be partial, including:
- Subclasses of
SingleStreamProjection<TDoc, TId>,MultiStreamProjection<TDoc, TId>,EventProjection, andPolecatCompositeProjection. - Self-aggregating document types registered via
opts.Projections.Snapshot<T>(...), queried viasession.Events.AggregateStreamAsync<T>(...), or live-projected viasession.Events.FetchLatest<T>(...)/FetchForWriting<T>(...). The source generator emits a standaloneTEvolverclass for the closedSingleStreamProjection<T, T.IdType>runtime instance, and it can only do that whenTispartial.
// before (Polecat 3.x — works because of FEC fallback)
public class QuestParty
{
public Guid Id { get; set; }
public List<string> Members { get; } = [];
public static QuestParty Create(QuestStarted e) => new();
public void Apply(MembersJoined e) => Members.AddRange(e.Members);
}
// after (Polecat 4.0 — `partial` required)
public partial class QuestParty
{
public Guid Id { get; set; }
public List<string> Members { get; } = [];
public static QuestParty Create(QuestStarted e) => new();
public void Apply(MembersJoined e) => Members.AddRange(e.Members);
}Every assembly that defines such a projection or aggregate also needs to reference the JasperFx.Events.SourceGenerator NuGet as an analyzer-only package — Polecat itself already pulls it in through JasperFx.Events for projection types declared in your store-host project, but any sibling assembly that declares its own projection / aggregate types needs its own reference:
<ItemGroup>
<PackageReference Include="JasperFx.Events.SourceGenerator"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup>If you have a projection that cannot be made partial (e.g. a sealed class from a third-party library, or one you want to keep as a non-source-generator path), the escape hatch is to override the dispatch methods directly:
public class MyProjection : SingleStreamProjection<MyAggregate, Guid>
{
public override ValueTask<MyAggregate?> EvolveAsync(
MyAggregate? snapshot, Guid id, IEvent e, CancellationToken ct)
{
// hand-written dispatch — no SG, no FEC
}
}This matches Marten 9's adoption story for the same JasperFx.Events Phase-1 change. The shared consumer-side contract is documented at greater length in Marten's migration guide — "Projection apply dispatch is now source-generator-only"; the Polecat-side adoption tracking lives in Polecat#46, with the audit harness from #110 standing as the pre-release gate against future SG regressions.
Convention-method visibility, identity, and required members
The source generator inspects only public instance / static methods. Apply / Create / ShouldDelete methods that were private / internal / protected under Polecat 3.x (the reflective FEC path picked those up) are silently skipped by the SG and trip the fail-fast above. Make them public:
// before (Polecat 3.x — FEC reflected over non-public members too)
public partial class Quest
{
public Guid Id { get; set; }
private void Apply(MembersJoined e) { /* ... */ } // <-- skipped by SG
}
// after (Polecat 4.0)
public partial class Quest
{
public Guid Id { get; set; }
public void Apply(MembersJoined e) { /* ... */ } // <-- discovered
}The event argument of those conventional methods is identified by type, not by parameter name: a parameter typed IEvent<T> is the event, otherwise the single concrete parameter that isn't an interface (IQuerySession / IDocumentOperations), IEvent, CancellationToken, or the aggregate type. You do not need to name it @event — Apply(MembersJoined e) and Apply(MembersJoined joined) are equivalent. A conventional name (@event, event, e, or ev) is only consulted to disambiguate a signature with more than one candidate parameter. See Identifying the Event Parameter.
Aggregate identity discovery follows the same convention rule as Marten — by default, the SG looks for a property literally named Id (or <TypeName>Id). If your aggregate's identity uses a different member name, annotate that member with [Identity] from JasperFx (the same JasperFx.IdentityAttribute Polecat uses for document identity — see the rc dedup-wave relocations table; it moved out of Polecat.Attributes in #135):
using JasperFx; // JasperFx.IdentityAttribute — NOT JasperFx.Events
public partial class Quest
{
[Identity]
public Guid QuestKey { get; set; } // <-- explicit identity slot
public static Quest Create(QuestStarted e) => new() { QuestKey = e.QuestId };
public void Apply(MembersJoined e) { /* ... */ }
}The source generator matches the identity attribute by simple name, so any attribute named IdentityAttribute works — but JasperFx.IdentityAttribute is the canonical one. As an alternative to a member-level [Identity], you can declare the identity type explicitly at the class level with [AggregateIdentity(typeof(TId))] from JasperFx.Events.Aggregation — useful when the identity is a strong-typed id or isn't a simple property.
For aggregates with required members, the SG's null-snapshot "create-from-default + apply" branch can't new T() directly — required members would leave the compiler complaining. Either provide a static Create(TEvent e) factory (preferred — gives full control) or use the default! init-pattern Marten's guide documents:
public partial class Account
{
public Guid Id { get; set; }
public required string Owner { get; init; }
// Preferred: explicit factory — SG calls this, no default! required.
public static Account Create(AccountOpened e) => new()
{
Id = e.AccountId,
Owner = e.Owner,
};
public void Apply(Deposited e) { /* ... */ }
}If no Create factory is supplied and the SG falls back to the create-from-default path, the emitted code is var s = new Account { Owner = default! }; Apply(e, s); — semantically valid, but the default! hands the aggregate over to your Apply methods in a partially-initialized state. The factory route is cleaner.
Surfaces unaffected by the partial requirement
FlatTableProjection— has its own dictionary-keyed dispatch viaProject<TEvent>(...)/Delete<TEvent>(...), doesn't go through JasperFx.Events apply-method discovery. Nopartialrequired.EfCoreSingleStreamProjection<TDoc, TDbContext>/EfCoreEventProjection<TDbContext>(fromPolecat.EntityFrameworkCore) — overrideDetermineActionAsyncdirectly, also bypass the SG-required path.
Inline-lambda projection registration APIs removed
JasperFx/jasperfx#276 / #286 removed the inline-lambda registration overloads on EventProjection, IAggregationSteps<T, TQuerySession>, and JasperFxAggregationProjectionBase — the source generator cannot dispatch a runtime closure, so these were the last thing keeping FEC reachable. Migrate to conventional method declarations on the projection class:
// before (Polecat 3.x)
public class MyEventProjection : EventProjection
{
public MyEventProjection()
{
Project<OrderPlaced>((e, ops) =>
{
ops.Store(new OrderSummary { Id = e.OrderId, ... });
});
}
}
// after (Polecat 4.0)
public partial class MyEventProjection : EventProjection
{
public void Project(OrderPlaced e, IDocumentSession ops)
{
ops.Store(new OrderSummary { Id = e.OrderId, ... });
}
}The same shape — public void Project(TEvent, IDocumentSession) for inline mutation, plus the conventional Create / Apply / ShouldDelete methods for aggregations — covers everything the lambda APIs used to do. DeleteEvent<TEvent>() (no-args, populates the internal delete-types list) and TransformsEvent<TEvent>() remain available; only the lambda-taking overloads were dropped.
The migration recipe is identical between Polecat and Marten — see Marten's migration guide — "Inline-lambda projection registration APIs removed" for the same content + a longer worked example.
IInlineProjection.ApplyAsync parameter widening
JasperFx.Events 2.0 widened IInlineProjection<TOperations>.ApplyAsync(...) so the streams parameter is IEnumerable<StreamAction> instead of IReadOnlyList<StreamAction> (jasperfx-events#4306). Polecat's built-in projection types (NaturalKeyProjection, FlatTableProjection) were updated to match; third-party IInlineProjection<TOperations> implementors must update their parameter type:
// before
public Task ApplyAsync(TOperations operations,
IReadOnlyList<StreamAction> streams,
CancellationToken cancellation) { ... }
// after
public Task ApplyAsync(TOperations operations,
IEnumerable<StreamAction> streams,
CancellationToken cancellation) { ... }If your implementation relied on streams.Count or indexed access, materialize the parameter once with .ToList() at the top of the method — the widening is intentional to give callers room to stream without forcing materialization.
IJasperFxAggregateGrouper.Group parameter tightening
JasperFx.Events 2.0 promoted the events parameter on IJasperFxAggregateGrouper<TId, TQuerySession>.Group(...) from IEnumerable<IEvent> to IReadOnlyList<IEvent> (jasperfx#201). Polecat does not ship any IAggregateGrouper implementations of its own, so most Polecat users see no impact. If your application has custom groupers, update the parameter type — no logic change is required, and you can drop any defensive events.ToList() you'd been doing at the top of Group:
// before
public Task Group(IQuerySession session,
IEnumerable<IEvent> events,
IEventGrouping<TId> grouping) { ... }
// after
public Task Group(IQuerySession session,
IReadOnlyList<IEvent> events,
IEventGrouping<TId> grouping) { ... }New behavior worth flagging
BulkInsertWithVersionAsync — optimistic concurrency on bulk inserts
#48 / #62. The new BulkInsertMode.OverwriteIfVersionMatches value (added by the Weasel.Core relocation) is exposed through a dedicated sibling method on AdvancedOperations rather than the existing BulkInsertAsync surface — the version-check needs per-row expected versions that the versionless overload has no way to thread:
var batch = new[]
{
(new User { Id = userId, FirstName = "Updated" }, expectedVersion: 1L),
(new User { Id = newUserId, FirstName = "Fresh" }, expectedVersion: 0L),
};
await store.Advanced.BulkInsertWithVersionAsync(batch);Semantics:
- Row exists + stored version == expected version → UPDATE, version bumped to
target.version + 1. - Row does not exist → INSERT at version 1; the expected version is irrelevant on inserts.
- Row exists + stored version != expected version → MERGE is a no-op; after the batch's reader drains,
JasperFx.ConcurrencyException(typeof(T), id)is thrown for the first mismatched id. Matches the per-row pattern used byUpdateOperation/UpsertOperation.
Calling the versionless BulkInsertAsync(docs, BulkInsertMode.OverwriteIfVersionMatches) overload now throws InvalidOperationException pointing callers at BulkInsertWithVersionAsync rather than the Polecat-3.x-era NotSupportedException stub.
WARNING
The concurrency throw is best-effort, not transactional. Matched-and-updated rows in the batch commit before the throw fires; the exception is the signal rather than a rollback. If you need transactional semantics, wrap the call in an outer transaction (TransactionScope or your own BEGIN TRAN / ROLLBACK flow).
FlatTableProjection column casing on SQL Server
#49 (Weasel side: 99e40f0 fix(SqlServer): preserve user casing on TableColumn names, shipped as Weasel 9.0.0-alpha.2). TableColumn names declared on a FlatTableProjection now preserve the casing you wrote in code; pre-fix the projection was silently lower-casing column names, breaking case-sensitive collations. No user action required — the projection schema is regenerated on next migration.
ILongVersioned — 64-bit document revisions
#136 / #138 (consumes jasperfx#348). Polecat already supported JasperFx.IRevisioned (an int Version optimistic-concurrency counter). 4.0 adds the new JasperFx.ILongVersioned (long Version) for documents whose version is a global event sequence number that can exceed Int32.MaxValue — typically MultiStreamProjection-derived views. Implement ILongVersioned instead of IRevisioned on those document types; the store, concurrency check, and read-back all flow the 64-bit value end to end. IRevisioned (int) keeps working unchanged for ordinary per-document revision counters.
This required a one-time schema change — see below.
StoreOptions.SchemaResolver — table-name diagnostics surface
#133 (implements the lifted JasperFx.Events.IDocumentSchemaResolver). A new StoreOptions.SchemaResolver resolves the database table backing any document, projection, or event-store table — qualified ([schema].[table]) or bare. Useful for schema inspection, diagnostics, and projection-coordinator activity tags:
var resolver = store.Options.SchemaResolver;
resolver.For<Customer>(); // "[dbo].[pc_doc_customer]"
resolver.ForEvents(qualified: false); // "pc_events"(Named SchemaResolver rather than Schema because StoreOptions.Schema is already Polecat's SchemaConfiguration.)
Projection-emitted side-effect messages
#84 / #98 / #100. Aggregation projections can now publish side-effect messages through an IMessageOutbox / IMessageBatch, flushed in the same transaction as the projection's storage writes. This is the foundation for Wolverine integration where a projection raises follow-on messages. Inline projections gained the same side-effect support in #99 / #101.
Hot-cold async-daemon coordination
#96, refined through the rc wave (#117–#120, #126, #141). The async daemon now coordinates across nodes: a ProjectionCoordinator (built on the lifted JasperFx.Events.Daemon.ProjectionCoordinatorBase) negotiates per-shard / per-database leadership via SQL Server sp_getapplock (through Weasel.SqlServer.AdvisoryLock), so multiple instances of your app run each projection on exactly one node with automatic failover. No configuration change is required for single-node deployments; multi-node deployments get safe hot-cold handover for free. When the daemon is disabled (DaemonMode.Disabled, the default), no coordinator distributor is built at all.
Schema changes
Unlike the 3.x → early-4.0 transition (which touched no table shapes), the ILongVersioned work introduced one DDL change:
- Revision column widened
int→bigint. #136. Theversioncolumn on document tables (pc_doc_*) is nowbigintto hold 64-bitILongVersionedvalues.IRevisioned(int) reads downcast transparently. The change ships as a non-destructive widening migration — existingintcolumns areALTERed in place (no drop/recreate, no data loss) on the next schema migration. Run your normalApplyAllConfiguredChangesToDatabaseAsync()/ migration step after upgrading; no manual SQL is required.
AOT / codegen posture
Polecat 4 inherits the same AOT-friendly posture introduced in JasperFx 2.0 (jasperfx#213 AOT pillar, jasperfx#190 ITypeLoader abstraction). Polecat itself has been source-generator-first since 3.x — there is no Roslyn runtime-compile path to disable — so:
PublishAot=trueis the supported posture for Polecat 4 applications, modulo the usual System.Text.JsonJsonSerializerContextsetup for your document and event types.IsAotCompatible=trueis now set on the Polecat assembly (PR #67), and the reflective surfaces of Polecat have been progressively annotated for the trimmer / AOT analyzer — Serialization (#74), ProjectionReplay (#75), LINQ extension/provider surface (#76), Storage / Registry / EventStoreExplorer (#77), and the class-level → call-site refactor of the remaining reflective surface (#107).- FastExpressionCompiler is no longer pulled in transitively through
JasperFx.Events(jasperfx#276). Projection apply-method dispatch routes exclusively through[GeneratedEvolver]outputs fromJasperFx.Events.SourceGenerator— see the "Projections and self-aggregating documents must bepartial" section above for the consumer-side migration. - An AOT smoke-test consumer (Polecat.AotSmoke, PR #106) ships with the repo and runs in CI with
WarningsAsErrorscoveringIL2026 / IL2046 / IL2055 / IL2065 / IL2067 / IL2070 / IL2072 / IL2075 / IL2090 / IL2091 / IL2111 / IL3050 / IL3051. Regressions in Polecat's AOT-clean surface fail the build.
Publishing AOT
Polecat 4 applications target the same Critter Stack 2026 AOT pre-gen flow Marten 9 uses — Polecat is a thin consumer of JasperFx.Events, so the consumer-side recipe (csproj flags, WarningsAsErrors=IL* set, source-generator-backed ISerializer swap, projection-class partial requirement, smoke-test pattern) lives in JasperFx's docs rather than being forked here:
- Publishing AOT with JasperFx — the end-to-end Critter Stack guide. Read this first.
- Marten's AOT publishing walkthrough — longer worked example with full csproj + program snippets. Polecat-applicable apart from the Marten-specific service registrations.
Polecat-specific call-outs:
Polecat.AotSmoke(source, originally PR #106) ships in-tree as the canonical AOT consumer example. The csproj setsIsAotCompatible=true+TrimMode=fulland promotes IL2026 / IL2046 / IL2055 / IL2065 / IL2067 / IL2070 / IL2072 / IL2075 / IL2090 / IL2091 / IL2111 / IL3050 / IL3051 to errors — any regression in Polecat's AOT-clean surface fails the build.IsAotCompatible=trueis set onPolecat.csprojitself, plus both shipping extension packages —Polecat.AspNetCoreandPolecat.EntityFrameworkCore(mirrors Marten PR #4468's per-extension audit). Both flagged carry method-level annotations that name the AOT-hostile upstream APIs they wrap:Polecat.AspNetCore—StreamMany<T>/StreamOne<T>/StreamAggregate<T>ExecuteAsyncoverrides carry[RequiresDynamicCode]+[RequiresUnreferencedCode]for theJsonSerializer.SerializeToUtf8Bytes<T>reflective overloads;McpEndpointExtensionsclass-level RUC/RDC for the JSON-RPC payload serialization inMapPolecatMcp. AOT consumers building Minimal-API endpoints can returnnew StreamMany<MyDoc>(query)from a[RequiresDynamicCode]-annotated endpoint, or supply aJsonSerializerContextand write a customIResult.Polecat.EntityFrameworkCore—TDoctype parameters carry the full EF Core entity DAM set (PublicConstructors | NonPublicConstructors | PublicFields | NonPublicFields | PublicProperties | NonPublicProperties | Interfaces) matchingDbContext.Find<TEntity>requirements;TDbContextparameters carryPublicConstructorsmatchingActivator.CreateInstance(typeof(TDbContext), ...). Concrete closed generics (EfCoreSingleStreamProjection<MyEntity, MyDbContext>) satisfy these implicitly.
Polecat.AotSmokealso references both extensions and exercises a constructor /typeof()from each, so a future annotation regression in either extension trips the smoke build before downstream consumers see it.- The post-#276 fail-fast semantics apply identically to AOT consumers — a projection registered without a
[GeneratedEvolver]dispatcher throwsInvalidProjectionExceptionat host build (not at runtime via FEC fallback like Polecat 3.x). The remediation is the same as the non-AOT story — see the SG-only projection apply dispatch section above.
Out of scope (no Polecat 4 change)
- Obsolete API removals. A grep of the 3.x codebase for
[Obsolete]declarations returned no matches; the 4.0 release does not remove any APIs that were obsoleted in 3.x. - Schema migrations. The only
pc_*table-shape change in the whole 3.x → 4.0 line is the documentversioncolumn widening tobigint— covered in Schema changes above, applied non-destructively by the normal migration step. Everything else (event store, streams, tags, hilo, snapshots) is unchanged; a 3.x database upgrades in place.
Dependency lockstep
Polecat 4 ships in lockstep with the rest of the Critter Stack 2026 wave. The supported pairings are:
| Polecat | Marten | JasperFx | JasperFx.Events | Weasel |
|---|---|---|---|---|
| 4.0 | 9.0 | 2.0 | 2.0 | 9.0 |
Mixing major versions across products is unsupported in this wave (the dedup work moves abstractions between assemblies and ABI-binds them to specific majors). If you upgrade Polecat to 4.0, plan to upgrade Marten and Weasel-side dependencies to their 9.0 lines at the same time.

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