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.
Overview
Section titled “Overview”The patch system:
- Automatically discovers patches that implement
ICanApplyPatchfromCratis.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
Key Concepts
Section titled “Key Concepts”SemanticVersion
Section titled “SemanticVersion”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.
Patch Lifecycle
Section titled “Patch Lifecycle”- Discovery: On startup, all
ICanApplyPatchimplementations are discovered - Filtering: Only patches with versions newer than the current system version are selected
- Ordering: Selected patches are sorted in ascending version order
- Application: Each patch’s
Up()method is called sequentially - Tracking: Successfully applied patches are recorded in storage
- Version Update: System version is updated to the latest applied patch version
Storage
Section titled “Storage”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
patchescollection (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
Writing a Patch
Section titled “Writing a Patch”Basic Structure
Section titled “Basic Structure”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()); }}Kotlin does not support this workflow yet.Java does not support this workflow yet.Elixir does not support this workflow yet.TypeScript does not support this workflow yet.Patch Naming Conventions
Section titled “Patch Naming Conventions”- 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
Nameproperty 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.
Dependencies
Section titled “Dependencies”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"); } }}Kotlin does not support this workflow yet.Java does not support this workflow yet.Elixir does not support this workflow yet.TypeScript does not support this workflow yet.Best Practices
Section titled “Best Practices”1. Semantic Logging
Section titled “1. Semantic Logging”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;}Kotlin does not support this workflow yet.Java does not support this workflow yet.Elixir does not support this workflow yet.TypeScript does not support this workflow yet.2. Handle Idempotency
Section titled “2. Handle Idempotency”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 }}Kotlin does not support this workflow yet.Java does not support this workflow yet.Elixir does not support this workflow yet.TypeScript does not support this workflow yet.3. Test Thoroughly
Section titled “3. Test Thoroughly”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();}Kotlin does not support this workflow yet.Java does not support this workflow yet.Elixir does not support this workflow yet.TypeScript does not support this workflow yet.Runtime Behavior
Section titled “Runtime Behavior”Startup Sequence
Section titled “Startup Sequence”- Server Initialization: Chronicle server starts
- Patch Discovery: the patch manager grain of Cratis Choreography discovers all
ICanApplyPatchimplementations - Version Check: The patching kernel high-water mark is checked, then the current system version is retrieved from storage
- Patch Selection: Patches newer than current version are selected
- Sequential Application: Patches are applied in ascending version order
- 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
- Normal Startup: Chronicle continues with normal initialization
Mixed-version Clusters
Section titled “Mixed-version Clusters”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.
Error Handling
Section titled “Error Handling”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
Version Comparison
Section titled “Version Comparison”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)
Example: RenameReactors Patch
Section titled “Example: RenameReactors Patch”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; }}Kotlin does not support this workflow yet.Java does not support this workflow yet.Elixir does not support this workflow yet.TypeScript does not support this workflow yet.Troubleshooting
Section titled “Troubleshooting”Patch Not Running
Section titled “Patch Not Running”- Check version: Ensure patch version is greater than current system version
- Check registration: Verify patch implements
ICanApplyPatchand is in correct namespace - Check logs: Look for patch discovery and application logs at startup
Patch Failing
Section titled “Patch Failing”- Review exception: Check startup logs for detailed error information
- Test locally: Run patch specs to verify logic
- Check storage: Ensure storage connections are working
- Verify state: Check if system is in expected state before migration
Need to Re-run Patch
Section titled “Need to Re-run Patch”If you need to re-run a patch (e.g., during development):
- Remove patch record from
patchescollection in MongoDB - Optionally reset system version if needed
- Restart server
Warning: Only do this in development environments. Production systems should use new patch versions.
Migration from Older Versions
Section titled “Migration from Older Versions”When upgrading Chronicle from versions without the patch system:
- System version defaults to
0.0.0(orSemanticVersion.NotSet) - All patches will be discovered and applied in order
- After successful application, system version is set to latest patch version
- Future upgrades will only apply newer patches
Summary
Section titled “Summary”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.