Skip to content

Version Patch System

Chronicle uses the startup patching of Cratis Choreography to handle breaking changes during upgrades. Patches are automatically discovered and applied during server startup, ensuring the system state is migrated correctly between versions. A new Chronicle release can join a running cluster while the previous release keeps serving, so an upgrade never needs the replica set scaled down and back up.

The patch system:

  • Automatically discovers patches that implement ICanApplyPatch from Cratis.Choreography.Patching
  • Applies patches in order based on semantic version
  • Tracks applied patches to prevent re-execution
  • Runs at startup before other Chronicle services initialize

Patches are tied to semantic versions (e.g., 1.5.0, 2.0.0-beta.1). The system compares the current system version with patch versions to determine which patches to apply.

  1. Discovery: On startup, all ICanApplyPatch implementations are discovered
  2. Filtering: Only patches with versions newer than the current system version are selected
  3. Ordering: Selected patches are sorted in ascending version order
  4. Application: Each patch’s Up() method is called sequentially
  5. Tracking: Successfully applied patches are recorded in storage
  6. Version Update: System version is updated to the latest applied patch version

Chronicle keeps the record in its system storage, as every release has, so a store patched by an earlier release is not patched again:

  • Applied patches: the patches collection (in the system database) or the equivalent SQL table
  • Patched version: stored on the system grain as the current system version
  • Patching kernel version: the newest kernel that completed patching, stored beside it

Create a patch by implementing ICanApplyPatch from Cratis.Choreography.Patching. A patch has a Version and an Up() method; Chronicle never runs patches backwards:

public class PatchesBasicPatch(IStorage storage, ILogger<PatchesBasicPatch> logger) : ICanApplyPatch
{
public SemanticVersion Version => new(1, 5, 0);
public async Task Up()
{
logger.LogInformation("Applying PatchesBasicPatch");
var eventStore = storage.GetEventStore(EventStoreName.System);
var reactors = await eventStore.Reactors.GetAll();
logger.LogInformation("Found {Count} reactors", reactors.Count());
}
}

View C# snippet source on GitHub

  • Folder structure: Organize patches by version in Source/Kernel/Core/Patches/{version}/
  • File naming: Use descriptive names (e.g., RenameReactors.cs, MigrateEventSchema.cs)
  • Class naming: Match the file name (the Name property is auto-derived from the type name)

Never delete a shipped patch. If its work is superseded, keep its name and version and make Up() a no-op. Mixed-version clusters may still discover the older implementation during an upgrade.

Patches can inject any services registered in the DI container:

public class PatchesComplexPatch(
IStorage storage,
IEventTypes eventTypes,
ILogger<PatchesComplexPatch> logger) : ICanApplyPatch
{
public SemanticVersion Version => new(2, 0, 0);
public async Task Up()
{
if (await storage.HasEventStore(EventStoreName.System))
{
await eventTypes.DiscoverAndRegister(EventStoreName.System);
logger.LogInformation("Discovered and registered event types");
}
}
}

View C# snippet source on GitHub

Use proper semantic logging with LoggerMessage attributes:

internal static partial class PatchesLoggingPatchLogMessages
{
[LoggerMessage(LogLevel.Information, "Starting PatchesLoggingPatch migration")]
internal static partial void StartingMigration(this ILogger<PatchesLoggingPatch> logger);
[LoggerMessage(LogLevel.Information, "Migrated {Count} items")]
internal static partial void MigratedItems(this ILogger<PatchesLoggingPatch> logger, int count);
}
public class PatchesLoggingPatch(IStorage storage, ILogger<PatchesLoggingPatch> logger) : ICanApplyPatch
{
public SemanticVersion Version => new(1, 6, 0);
public async Task Up()
{
logger.StartingMigration();
var count = (await storage.GetEventStores()).Count();
logger.MigratedItems(count);
}
public Task Down() => Task.CompletedTask;
}

View C# snippet source on GitHub

A patch is recorded only after Up() completes, so a patch that was interrupted runs again from the beginning, for example when the silo that was running it is replaced during a rolling deployment. Write Up() so that running it twice is safe:

public class PatchesIdempotentPatch(IStorage storage, ILogger<PatchesIdempotentPatch> logger) : ICanApplyPatch
{
public SemanticVersion Version => new(1, 8, 0);
public async Task Up()
{
var eventStore = storage.GetEventStore(EventStoreName.System);
var reactors = await eventStore.Reactors.GetAll();
// Filter to only process items that need migration
var reactorsToMigrate = reactors
.Where(r => r.Identifier.Value.Contains("OldPattern"))
.ToList();
if (reactorsToMigrate.Count == 0)
{
logger.LogInformation("Nothing to migrate");
return;
}
// Proceed with migration
}
}

View C# snippet source on GitHub

Write comprehensive specs for your patches:

using Cratis.Specifications;
using NSubstitute;
using Xunit;
public class when_applying_the_patch : Specification
{
readonly IStorage _storage = Substitute.For<IStorage>();
readonly ILogger<PatchesBasicPatch> _logger = Substitute.For<ILogger<PatchesBasicPatch>>();
PatchesBasicPatch _patch = default!;
void Establish() => _patch = new PatchesBasicPatch(_storage, _logger);
Task Because() => _patch.Up();
[Fact] void should_complete_without_throwing() => true.ShouldBeTrue();
}

View C# snippet source on GitHub

  1. Server Initialization: Chronicle server starts
  2. Patch Discovery: the patch manager grain of Cratis Choreography discovers all ICanApplyPatch implementations
  3. Version Check: The patching kernel high-water mark is checked, then the current system version is retrieved from storage
  4. Patch Selection: Patches newer than current version are selected
  5. Sequential Application: Patches are applied in ascending version order
  6. Version Update: System version is updated to the latest applied patch; after a successful run, the patching kernel high-water mark is recorded even if no patches were pending
  7. Normal Startup: Chronicle continues with normal initialization

Patch selection uses the last applied patch version, while a separate patching kernel version records the newest kernel that successfully completed patching. They are not the event-store generation floor: an older kernel skips patching with a warning when the recorded kernel version is newer, but continues starting. Generation-floor admission still runs first and can refuse an incompatible kernel independently.

The patch manager is one grain for the whole cluster. If it is active on a silo that runs an older kernel than the one asking, it answers that it must relocate and moves to the asking silo; the new silo asks again with back-off. Exhausting the relocation attempts fails startup rather than silently omitting patches. A call that fails for a reason other than a failing patch, such as a lost silo or a patch that outlasts the grain call timeout, is asked again until patching completes, for up to PatchingOptions.MaxWait (15 minutes by default). The IPatchManager grain of earlier Chronicle releases remains and forwards to the new manager, so a silo of an earlier release that starts during an upgrade is served.

The high-water mark uses system-information record Id = 1 in MongoDB and SQL, separate from the last patch version at Id = 0. In-memory storage keeps the same separation. Successful patching never lowers the mark. Failed patching does not advance it. Each patch application logs the running kernel version without changing the stored patch schema.

Development placeholder versions 1.0.0 and 0.0.0 (or an unreadable version) bypass this gate with a warning and record no kernel version. Release builds must stamp the server executable’s informational version; build metadata is excluded from version comparisons.

Rolling back does not undo patches or clear the high-water mark. An older kernel continues without patching. Resetting the mark is an explicit manual recovery action, never an automatic downgrade: stop all kernels, restore a known-compatible backup, and only then remove the patching-kernel record if the recovery requires patch execution again. Never lower it while a newer kernel can still patch the store.

If a patch fails:

  • The exception is logged and re-thrown
  • Startup is halted to prevent running with inconsistent state
  • Manual intervention is required to fix the issue
  • The patch can be fixed and server restarted

Patches are applied based on version comparison:

  • Current: 1.0.0, Patch: 1.5.0 → Patch IS applied
  • Current: 2.0.0, Patch: 1.5.0 → Patch is NOT applied
  • Current: 1.5.0, Patch: 1.5.0 → Patch is NOT applied (equal versions)
  • Current: null, Patch: 1.0.0 → Patch IS applied (treats null as 0.0.0)

The RenameReactors patch (version 15.3.0) demonstrates a real-world migration:

internal static partial class RenameReactorsLogMessages
{
[LoggerMessage(LogLevel.Information, "Starting patch to rename reactors")]
internal static partial void StartingPatch(this ILogger<RenameReactors> logger);
[LoggerMessage(LogLevel.Information, "Found {Count} reactors to rename")]
internal static partial void FoundReactorsToRename(this ILogger<RenameReactors> logger, int count);
[LoggerMessage(LogLevel.Information, "Renaming reactor from {CurrentId} to {NewId}")]
internal static partial void RenamingReactor(this ILogger<RenameReactors> logger, string currentId, string newId);
[LoggerMessage(LogLevel.Information, "Patch completed")]
internal static partial void PatchCompleted(this ILogger<RenameReactors> logger);
[LoggerMessage(LogLevel.Information, "Starting rollback")]
internal static partial void StartingRollback(this ILogger<RenameReactors> logger);
[LoggerMessage(LogLevel.Information, "Rollback completed")]
internal static partial void RollbackCompleted(this ILogger<RenameReactors> logger);
}
public class RenameReactors(IStorage storage, ILogger<RenameReactors> logger) : ICanApplyPatch
{
public SemanticVersion Version => new(15, 3, 0);
public async Task Up()
{
logger.StartingPatch();
var systemEventStore = storage.GetEventStore(EventStoreName.System);
var reactors = await systemEventStore.Reactors.GetAll();
var reactorsToRename = reactors
.Where(r => r.Identifier.Value.Contains("Grains", StringComparison.OrdinalIgnoreCase))
.ToList();
logger.FoundReactorsToRename(reactorsToRename.Count);
foreach (var reactor in reactorsToRename)
{
var currentId = reactor.Identifier;
var newIdValue = currentId.Value.Replace("Grains", string.Empty, StringComparison.OrdinalIgnoreCase);
logger.RenamingReactor(currentId.Value, newIdValue);
await systemEventStore.Reactors.Rename(currentId, newIdValue);
}
logger.PatchCompleted();
}
public Task Down()
{
logger.StartingRollback();
logger.RollbackCompleted();
return Task.CompletedTask;
}
}

View C# snippet source on GitHub

  1. Check version: Ensure patch version is greater than current system version
  2. Check registration: Verify patch implements ICanApplyPatch and is in correct namespace
  3. Check logs: Look for patch discovery and application logs at startup
  1. Review exception: Check startup logs for detailed error information
  2. Test locally: Run patch specs to verify logic
  3. Check storage: Ensure storage connections are working
  4. Verify state: Check if system is in expected state before migration

If you need to re-run a patch (e.g., during development):

  1. Remove patch record from patches collection in MongoDB
  2. Optionally reset system version if needed
  3. Restart server

Warning: Only do this in development environments. Production systems should use new patch versions.

When upgrading Chronicle from versions without the patch system:

  1. System version defaults to 0.0.0 (or SemanticVersion.NotSet)
  2. All patches will be discovered and applied in order
  3. After successful application, system version is set to latest patch version
  4. Future upgrades will only apply newer patches

The patch system provides a robust, automated way to handle breaking changes during Chronicle upgrades. By following the conventions and best practices outlined here, you can write safe, testable patches that keep Chronicle systems properly migrated across versions.