Skip to content

Commit 4bc951e

Browse files
Enhance migration engine to handle benign skips and update related tests
- Introduced `BenignSkipped` property in `MigrationWriteResult` to track rows that the target would have deleted anyway. - Updated `MigrationEngine` logic to ensure benign skips do not count towards the halt threshold. - Added tests to verify that benign skips are handled correctly and do not cause category halts. - Updated skip reasons to include `PastRetention` for better clarity on skipped rows. - Created approval files for category selection tests to ensure correct order and configuration.
1 parent fa6c14e commit 4bc951e

10 files changed

Lines changed: 226 additions & 24 deletions

‎docs/migration/ravendb-to-sql-migration-overview.md‎

Lines changed: 91 additions & 12 deletions
Large diffs are not rendered by default.

‎src/ServiceControl.Persistence/DataMigration/IMigrationTarget.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,5 @@ Task<MigrationWriteResult> Write(
2323
}
2424

2525
/// <summary>What the target did with one batch, and the checkpoint it committed alongside the rows. Every skipped row must have a reason in SkipReasons.</summary>
26-
public sealed record MigrationWriteResult(MigrationCheckpoint Saved, int Copied, int Skipped, IReadOnlyList<string> SkippedIds, int AlreadyPresent = 0, IReadOnlyDictionary<MigrationSkipReason, long>? SkipReasons = null);
26+
/// <param name="BenignSkipped">How many of Skipped the target would have deleted anyway, such as a row already past retention. Counted and reported like any skip, but never counted toward the halt threshold.</param>
27+
public sealed record MigrationWriteResult(MigrationCheckpoint Saved, int Copied, int Skipped, IReadOnlyList<string> SkippedIds, int AlreadyPresent = 0, IReadOnlyDictionary<MigrationSkipReason, long>? SkipReasons = null, int BenignSkipped = 0);

‎src/ServiceControl.Persistence/DataMigration/MigrationEngine.cs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,8 +128,15 @@ public async Task<MigrationCheckpoint> RunCategoryAsync(MigrationCategory catego
128128
logger.LogWarning("Skipped {SourceId} in category {CategoryId}", id, category.Id);
129129
}
130130

131+
// A negative fault count would silently disarm the halt threshold for the rest of the run.
132+
if (result.BenignSkipped > result.Skipped)
133+
{
134+
throw new InvalidOperationException($"The target reported {result.BenignSkipped} benign skips in category {category.Id} out of {result.Skipped} skipped rows. Benign skips are a subset of the skipped rows.");
135+
}
136+
131137
processedThisRun += bodySkips + result.Copied + result.Skipped + result.AlreadyPresent;
132-
skippedThisRun += bodySkips + result.Skipped;
138+
// Rows the target would have deleted anyway are not faults, so they never halt a category.
139+
skippedThisRun += bodySkips + result.Skipped - result.BenignSkipped;
133140

134141
if (HaltThreshold.Exceeded(skippedThisRun, processedThisRun, options.HaltThresholdPercent, options.HaltThresholdMinimum))
135142
{

‎src/ServiceControl.Persistence/DataMigration/MigrationSkipReason.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ namespace ServiceControl.Persistence.DataMigration;
33
public enum MigrationSkipReason
44
{
55
BodyUnreadable,
6+
PastRetention,
67
// Never written by a copier. A database a newer build wrote still reads rather than throwing where the host decides whether to start.
78
Unknown
89
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
Required 1: KnownEndpoints
2+
Required 2: EndpointSettings, after KnownEndpoints
3+
Required 3: MessageRedirects
4+
Required 4: Subscriptions
5+
Required 5: NotificationSettings
6+
Required 6: TrialEndDate
7+
Required 7: RetryOperations
8+
Required 8: LicensingEndpoints
9+
Required 9: LicensingThroughput, after LicensingEndpoints
10+
Required 10: LicensingReportMasks
11+
Required 11: LicensedEndpointDetails
12+
Required 12: UnresolvedAndRetryIssuedFailedMessages, with bodies
13+
Optional 1: EventLog
14+
Optional 2: CustomChecks
15+
Optional 3: FailedErrorImports, with bodies
16+
Optional 4: FailedMessageEdits
17+
Optional 5: ArchivedAndResolvedFailedMessages, with bodies
18+
Optional 6: GroupComments, after ArchivedAndResolvedFailedMessages
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Configured: GroupComments, EventLog, ArchivedAndResolvedFailedMessages
2+
Runs as:
3+
Optional 1: EventLog
4+
Optional 5: ArchivedAndResolvedFailedMessages, with bodies
5+
Optional 6: GroupComments, after ArchivedAndResolvedFailedMessages
6+
Never copied: CustomChecks, FailedErrorImports, FailedMessageEdits

‎src/ServiceControl.UnitTests/Migration/Fakes/InMemoryMigrationTarget.cs‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public sealed class InMemoryMigrationTarget(IMigrationCheckpointStore checkpoint
1111
readonly Dictionary<string, HashSet<string>> writtenKeysByCategory = [];
1212
readonly Dictionary<string, List<MigrationRow>> writtenRowsByCategory = [];
1313
readonly HashSet<string> preExistingKeys = [];
14-
readonly Dictionary<string, MigrationSkipReason> rejectedKeys = [];
14+
readonly Dictionary<string, (MigrationSkipReason Reason, bool Benign)> rejectedKeys = [];
1515

1616
public int DefaultBatchSize { get; set; } = 3;
1717
public string NoBatchSizeFor { get; set; }
@@ -21,7 +21,7 @@ public sealed class InMemoryMigrationTarget(IMigrationCheckpointStore checkpoint
2121

2222
public void SeedExistingKey(string sourceId) => preExistingKeys.Add(sourceId);
2323

24-
public void RejectKey(string sourceId, MigrationSkipReason reason) => rejectedKeys[sourceId] = reason;
24+
public void RejectKey(string sourceId, MigrationSkipReason reason, bool benign = false) => rejectedKeys[sourceId] = (reason, benign);
2525

2626
public IReadOnlyList<MigrationRow> WrittenRows(string categoryId) =>
2727
writtenRowsByCategory.TryGetValue(categoryId, out var rows) ? rows : [];
@@ -53,15 +53,20 @@ public async Task<MigrationWriteResult> Write(
5353

5454
var copied = 0;
5555
var alreadyPresent = 0;
56+
var benignSkipped = 0;
5657
var skippedIds = new List<string>();
5758
var skipReasons = new Dictionary<MigrationSkipReason, long>();
5859

5960
foreach (var row in batch.Rows)
6061
{
61-
if (rejectedKeys.TryGetValue(row.SourceId, out var reason))
62+
if (rejectedKeys.TryGetValue(row.SourceId, out var rejection))
6263
{
6364
skippedIds.Add(row.SourceId);
64-
skipReasons[reason] = skipReasons.GetValueOrDefault(reason) + 1;
65+
skipReasons[rejection.Reason] = skipReasons.GetValueOrDefault(rejection.Reason) + 1;
66+
if (rejection.Benign)
67+
{
68+
benignSkipped++;
69+
}
6570
continue;
6671
}
6772

@@ -81,7 +86,7 @@ public async Task<MigrationWriteResult> Write(
8186
checkpointToExtend.Extend(copied, skippedIds.Count, alreadyPresent, skipReasons),
8287
cancellationToken);
8388

84-
return new MigrationWriteResult(saved, copied, skippedIds.Count, skippedIds, alreadyPresent, skipReasons);
89+
return new MigrationWriteResult(saved, copied, skippedIds.Count, skippedIds, alreadyPresent, skipReasons, benignSkipped);
8590
}
8691

8792
public Task<long> Count(MigrationCategory category, CancellationToken cancellationToken = default) =>

‎src/ServiceControl.UnitTests/Migration/MigrationEngineCategorySelectionTests.cs‎

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ namespace ServiceControl.UnitTests.Migration;
66
using Microsoft.Extensions.Logging.Abstractions;
77
using Microsoft.Extensions.Time.Testing;
88
using NUnit.Framework;
9+
using Particular.Approvals;
910
using ServiceControl.Persistence.DataMigration;
1011
using ServiceControl.UnitTests.Migration.Fakes;
1112

@@ -20,22 +21,45 @@ static MigrationEngine BuildEngine(IReadOnlyCollection<string> selectedOptionalI
2021
return new MigrationEngine(new InMemoryMigrationSource(), target, checkpointStore, new FakeTimeProvider(), options, NullLogger<MigrationEngine>.Instance);
2122
}
2223

24+
static string Describe(MigrationCategory category) =>
25+
$"{category.Kind} {category.Order}: {category.Id}"
26+
+ (category.CarriesBodies ? ", with bodies" : string.Empty)
27+
+ (category.MustFollow is null ? string.Empty : $", after {category.MustFollow}");
28+
2329
[Test]
24-
public void All_twelve_required_categories_are_always_selected()
30+
public void Every_category_runs_in_a_fixed_order()
2531
{
26-
var engine = BuildEngine([], out _);
32+
var everyOptionalId = MigrationCategoryRegistry.All
33+
.Where(category => category.Kind == MigrationCategoryKind.Optional)
34+
.Select(category => category.Id)
35+
.ToArray();
36+
var engine = BuildEngine(everyOptionalId, out _);
37+
38+
var runOrder = engine.SelectCategories(MigrationCategoryKind.Required)
39+
.Concat(engine.SelectCategories(MigrationCategoryKind.Optional))
40+
.Select(Describe);
2741

28-
Assert.That(engine.SelectCategories(MigrationCategoryKind.Required), Has.Count.EqualTo(12));
42+
Approver.Verify(string.Join(Environment.NewLine, runOrder));
2943
}
3044

3145
[Test]
3246
public void Only_configured_optional_categories_are_selected()
3347
{
34-
var engine = BuildEngine(["EventLog"], out _);
48+
string[] configured = [MigrationCategoryIds.GroupComments, MigrationCategoryIds.EventLog, MigrationCategoryIds.ArchivedAndResolvedFailedMessages];
49+
var engine = BuildEngine(configured, out _);
3550

3651
var selected = engine.SelectCategories(MigrationCategoryKind.Optional);
52+
var left = MigrationCategoryRegistry.All
53+
.Where(category => category.Kind == MigrationCategoryKind.Optional && !selected.Contains(category))
54+
.Select(category => category.Id);
3755

38-
Assert.That(selected.Select(c => c.Id), Is.EqualTo(new[] { "EventLog" }));
56+
Approver.Verify(string.Join(Environment.NewLine,
57+
[
58+
$"Configured: {string.Join(", ", configured)}",
59+
"Runs as:",
60+
.. selected.Select(Describe),
61+
$"Never copied: {string.Join(", ", left)}"
62+
]));
3963
}
4064

4165
[Test]

‎src/ServiceControl.UnitTests/Migration/MigrationEngineHaltTests.cs‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,33 @@ public async Task A_systemic_failure_halts_the_category_partway_through()
4646
}
4747
}
4848

49+
[Test]
50+
public async Task Rows_the_target_would_have_deleted_anyway_never_count_toward_the_halt_threshold()
51+
{
52+
var category = MigrationCategoryRegistry.Find("ArchivedAndResolvedFailedMessages")!;
53+
var source = new InMemoryMigrationSource();
54+
// The same 20% that halts the category above, except these rows are past the target's retention
55+
// cutoff, so leaving them behind is the copy working rather than failing.
56+
source.Seed(category.Id, [.. Enumerable.Range(1, 1_000).Select(i => Row($"row-{i}"))]);
57+
var checkpointStore = new InMemoryMigrationCheckpointStore();
58+
var target = new InMemoryMigrationTarget(checkpointStore) { DefaultBatchSize = 100 };
59+
foreach (var i in Enumerable.Range(1, 1_000).Where(i => i % 5 == 0))
60+
{
61+
target.RejectKey($"row-{i}", MigrationSkipReason.PastRetention, benign: true);
62+
}
63+
var options = new MigrationEngineOptions(TimeSpan.Zero, HaltThresholdPercent: 5, HaltThresholdMinimum: 100, []);
64+
var engine = new MigrationEngine(source, target, checkpointStore, new FakeTimeProvider(), options, NullLogger<MigrationEngine>.Instance);
65+
66+
var checkpoint = await engine.RunCategoryAsync(category);
67+
68+
using (Assert.EnterMultipleScope())
69+
{
70+
Assert.That(checkpoint.State, Is.EqualTo(MigrationCategoryState.CompleteWithErrors));
71+
Assert.That((checkpoint.CopiedCount, checkpoint.SkippedCount), Is.EqualTo((800L, 200L)));
72+
Assert.That(target.WrittenRows(category.Id), Has.Count.EqualTo(800), "the last row was reached, so nothing halted partway");
73+
}
74+
}
75+
4976
[Test]
5077
public async Task Rows_already_present_in_the_target_never_count_toward_the_halt_threshold()
5178
{

‎src/ServiceControl.UnitTests/Migration/MigrationEngineSkipReasonTests.cs‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,40 @@ public async Task A_target_whose_skip_reasons_do_not_add_up_to_its_skips_halts_t
7979
}
8080
}
8181

82+
[Test]
83+
public async Task A_target_counting_more_benign_skips_than_skipped_rows_halts_the_category()
84+
{
85+
var category = MigrationCategoryRegistry.Find(MigrationCategoryIds.KnownEndpoints)!;
86+
var source = new InMemoryMigrationSource();
87+
source.Seed(category.Id, Row("a"));
88+
var checkpointStore = new InMemoryMigrationCheckpointStore();
89+
var target = new OverCountedBenignTarget(checkpointStore);
90+
var options = new MigrationEngineOptions(TimeSpan.Zero, 5, 100, []);
91+
var engine = new MigrationEngine(source, target, checkpointStore, new FakeTimeProvider(), options, NullLogger<MigrationEngine>.Instance);
92+
93+
var checkpoint = await engine.RunCategoryAsync(category);
94+
95+
using (Assert.EnterMultipleScope())
96+
{
97+
Assert.That(checkpoint.State, Is.EqualTo(MigrationCategoryState.Halted));
98+
Assert.That(checkpoint.LastError, Does.Contain("2 benign skips").And.Contain("out of 1 skipped"));
99+
}
100+
}
101+
102+
sealed class OverCountedBenignTarget(IMigrationCheckpointStore checkpointStore) : IMigrationTarget
103+
{
104+
public int BatchSizeFor(MigrationCategory category) => 10;
105+
106+
public async Task<MigrationWriteResult> Write(MigrationCategory category, MigrationBatch batch, MigrationCheckpoint checkpointToExtend, CancellationToken cancellationToken = default)
107+
{
108+
var reasons = new Dictionary<MigrationSkipReason, long> { [MigrationSkipReason.PastRetention] = batch.Rows.Count };
109+
var saved = await checkpointStore.Upsert(checkpointToExtend.Extend(0, batch.Rows.Count, 0, reasons), cancellationToken);
110+
return new MigrationWriteResult(saved, 0, batch.Rows.Count, [], 0, reasons, BenignSkipped: batch.Rows.Count + 1);
111+
}
112+
113+
public Task<long> Count(MigrationCategory category, CancellationToken cancellationToken = default) => Task.FromResult(0L);
114+
}
115+
82116
sealed class UnexplainedSkipTarget(IMigrationCheckpointStore checkpointStore) : IMigrationTarget
83117
{
84118
public int BatchSizeFor(MigrationCategory category) => 10;

0 commit comments

Comments
 (0)