diff --git a/docs/migration/ravendb-to-sql-migration-system-design.md b/docs/migration/ravendb-to-sql-migration-system-design.md index 9dace474bb..921800a4f8 100644 --- a/docs/migration/ravendb-to-sql-migration-system-design.md +++ b/docs/migration/ravendb-to-sql-migration-system-design.md @@ -284,7 +284,7 @@ Every reader derives from `MigrationCategoryReader` and every writer | 9 | `LicensingThroughput` | Required | `LicensingThroughputReader`, `LicensingThroughputWriter` | Throughput database. Data link to `LicensingEndpoints`. The reader gives one batch per endpoint from `ThroughputDocuments.Endpoints` with a batch size of one, and ignores the requested batch size, because one endpoint can hold a year or more of days. Each batch's cursor is its endpoint's id. The writer keeps the last row of a day repeated for one source endpoint, compared ordinally. `AddLicensingEndpointThroughput` splits the batch into statements and adds each day's count to the stored one, summing endpoints whose names the key column treats as the same, in one batch or across batches. A re-read is not idempotent, so a resume relies on each batch committing with its checkpoint, and a retry deletes the copied rows first | | 10 | `LicensingReportMasks` | Required | `LicensingReportMasksReader`, `LicensingReportMasksWriter` | Throughput database. One `Settings` row via `SettingRowMapper` | | 11 | `LicensedEndpointDetails` | Required | `LicensedEndpointDetailsReader`, `LicensedEndpointDetailsWriter` | Throughput database. One `Settings` row via `SettingRowMapper` | -| 12 | `RecentAndRetriedFailedMessages` | Required | `FailedMessagesReader`, `FailedMessagesWriter` | Carries bodies. `FailedMessageStream` projection, `FailedMessageDocumentTranslator`. `FailedMessagesReader` and `UnresolvedFailedMessagesReader` both derive from `FailedMessageStatusReader`, which streams the category's statuses in id order through `FailedMessageViewIndex` after waiting for the index, or through `RavenDocumentStream.ByPrefix` when the index cannot be trusted, with the document id as the cursor either way. `FailedMessagesReader` reads in two phases. First it asks `FailedMessageStatusReader.CanQueryIndex` which way to read, then `LatestUnresolvedLastModified` for the anchor: through the index it is one query for the unresolved message with the highest `LastModified`, and otherwise one pass over the `FailedMessages/` documents that keeps only the newest time. It then reads in the same way and finds nothing recent when there is no unresolved message. Phase one is `ReadStatuses` with the retry-issued status or a last-modified time at or after the cutoff, in any status. The index query is `Status in (RetryIssued) OR LastModified >= cutoff ticks` ordered by `id()`. The full read applies the same predicate in `FailedMessageStream.IsSelected` to the document's `@last-modified`, and a document without one is selected so that it fails by name in the writer. `FailedMessageStream.ResolveRetryClaims` looks up each batch's claims in one request and sets `RetryClaimHeld` on every row. Phase two is `FailedMessageStream.ClaimHolders`, which streams the `FailedMessageRetries/` documents by id prefix and, per batch of claims, queries the messages they name by `id()`, with `RetryClaimHeld` true and no index built. It leaves out every message `IsSelected` takes, because phase one read it, so no message is read or counted twice and the claim a row carries is the one phase one resolved. A claim whose message is gone makes no row, and memory stays bounded by the batch size. The phase-two cursor is `claim-holder:` and the last claim id. A cursor without the prefix, which is the end of phase one, runs phase one after it and then starts phase two. A prefixed cursor skips phase one and its document-existence check. The writer, through `FailedMessagesWriterBase`, inserts a claim for every inserted row whose flag is true, so the claims mirror RavenDB's. A retry-issued row with no flag fails the batch, and any other status with no flag means no claim. The writer counts every row of the failed message table for this category, which equals the rows it copied only while the host is closed and the target started empty. The optional `UnresolvedFailedMessagesWriter` shares `FailedMessagesWriterBase`, so it too inserts only missing rows and leaves a recent row, its groups and its claim as the required copy wrote them | +| 12 | `RecentAndRetriedFailedMessages` | Required | `FailedMessagesReader`, `FailedMessagesWriter` | Carries bodies. `FailedMessageStream` projection, `FailedMessageDocumentTranslator`. `FailedMessagesReader` and `UnresolvedFailedMessagesReader` both derive from `FailedMessageStatusReader`, which streams the category's statuses in id order through `FailedMessageViewIndex` after waiting for the index, or through `RavenDocumentStream.ByPrefix` when the index cannot be trusted, with the document id as the cursor either way. `FailedMessagesReader` reads in two phases. First it asks `FailedMessageStatusReader.CanQueryIndex` which way to read, then `LatestUnresolvedLastModified` for the anchor: through the index it is one query for the unresolved message with the highest `LastModified`, and otherwise one pass over the `FailedMessages/` documents that keeps only the newest time. It then reads in the same way and finds nothing recent when there is no unresolved message. Phase one is `ReadStatuses` with the retry-issued status or a last-modified time at or after the cutoff, in any status. The index query is `Status in (RetryIssued) OR LastModified >= cutoff ticks` ordered by `id()`. The full read applies the same predicate in `FailedMessageStream.IsSelected` to the document's `@last-modified`, and a document without one is selected so that it fails by name in the writer. `FailedMessageStream.ResolveRetryClaims` looks up each batch's claims in one request and sets `RetryClaimHeld` on every row. Phase two is `FailedMessageStream.ClaimHolders`, which streams the `FailedMessageRetries/` documents by id prefix and, per batch of claims, queries the messages they name by `id()`, with `RetryClaimHeld` true and no index built. It leaves out every message `IsSelected` takes, because phase one read it, so no message is read or counted twice and the claim a row carries is the one phase one resolved. A claim whose message is gone makes no row, and memory stays bounded by the batch size. The phase-two cursor is `claim-holder:` and the last claim id. A cursor without the prefix, which is the end of phase one, runs phase one after it and then starts phase two. A prefixed cursor skips phase one and its document-existence check. The writer, through `FailedMessagesWriterBase`, inserts a claim for every inserted row whose flag is true, so the claims mirror RavenDB's. A row with no flag fails the batch. The writer counts every row of the failed message table for this category, which equals the rows it copied only while the host is closed and the target started empty. The optional `UnresolvedFailedMessagesWriter` shares `FailedMessagesWriterBase` and its reader omits the flag, so it takes a row that is not retry-issued without one as holding no claim and fails a retry-issued row without one. It too inserts only missing rows and leaves a recent row, its groups and its claim as the required copy wrote them | | 13 | `PendingIntegrationEvents` | Required | `PendingIntegrationEventsReader`, `PendingIntegrationEventsWriter` | Store-keyed via `StoreKeyedInsert`. Deletes its rows on retry | | 14 | `CustomChecks` | Required | `CustomChecksReader`, `CustomChecksWriter` | The RavenDB reader flags a check whose id and category match one of the RavenDB persister's own six checks with the `SourceStorageCheck` metadata key, and the writer skips a flagged row as `SourceStorageCheck` without knowing any id. A RavenDB audit instance's dirty memory result reports under another category, so it is copied | | 15 | `FailedErrorImports` | Required | `FailedErrorImportsReader`, `FailedErrorImportsWriter` | Carries bodies inline in `Read`, never calls `ReadBody` | diff --git a/src/ServiceControl.Persistence.EFCore/DataMigration/Writers/FailedMessagesWriter.cs b/src/ServiceControl.Persistence.EFCore/DataMigration/Writers/FailedMessagesWriter.cs index b79d5446d1..850869e9de 100644 --- a/src/ServiceControl.Persistence.EFCore/DataMigration/Writers/FailedMessagesWriter.cs +++ b/src/ServiceControl.Persistence.EFCore/DataMigration/Writers/FailedMessagesWriter.cs @@ -11,8 +11,8 @@ namespace ServiceControl.Persistence.EFCore.DataMigration.Writers; /// /// Writes failed messages, their failure group rows and a retry claim for each message the source still held one for, /// inserting only messages the target does not already hold and never updating one it does. The claims -/// mirror the source, so a retry by id behaves as it did before the move. A retry-issued row with no bool RetryClaimHeld -/// value fails the batch. Each category that copies failed messages derives from this and names its category id and +/// mirror the source, so a retry by id behaves as it did before the move. A row with no bool RetryClaimHeld +/// value fails the batch, except a row that is not retry-issued in a category whose source omits the value. Each category that copies failed messages derives from this and names its category id and /// which target rows it counts. /// abstract class FailedMessagesWriterBase(IMigrationSqlDialect migrationDialect, IBodyStoragePersistence storagePersistence, EFPersisterSettings persisterSettings) : MigrationCategoryWriter @@ -25,6 +25,8 @@ abstract class FailedMessagesWriterBase(IMigrationSqlDialect migrationDialect, I /// protected abstract IQueryable Copied(ServiceControlDbContext dbContext); + protected virtual bool SourceMayOmitRetryClaim => false; + public override int BatchSize(ServiceControlDbContext dbContext) => migrationDialect.RowsPerStatementFor(dbContext); public override Task Count(ServiceControlDbContext dbContext, CancellationToken cancellationToken = default) => @@ -126,12 +128,12 @@ .. translation.Groups ]; // Throws rather than guess, because a wrong guess either blocks a retry by id or lets one send the message twice. - static bool SourceHeldRetryClaim(MigrationRow row, FailedMessageStatus status) => + bool SourceHeldRetryClaim(MigrationRow row, FailedMessageStatus status) => row.Metadata.GetValueOrDefault(MigrationMetadataKeys.RetryClaimHeld) switch { bool held => held, - null when status != FailedMessageStatus.RetryIssued => false, - null => throw new InvalidOperationException($"Row '{row.SourceId}' is retry-issued but arrived without a {MigrationMetadataKeys.RetryClaimHeld} value, which the source resolves for every retry-issued failed message"), + null when SourceMayOmitRetryClaim && status != FailedMessageStatus.RetryIssued => false, + null => throw new InvalidOperationException($"Row '{row.SourceId}' in category '{CategoryId}' requires a {MigrationMetadataKeys.RetryClaimHeld} value but arrived without one"), var other => throw new InvalidOperationException($"Row '{row.SourceId}' carries a {other.GetType().FullName} as its {MigrationMetadataKeys.RetryClaimHeld} value, where the source sets a {typeof(bool).FullName}") }; @@ -206,6 +208,8 @@ sealed class UnresolvedFailedMessagesWriter(IMigrationSqlDialect migrationDialec { public override string CategoryId => MigrationCategoryIds.UnresolvedFailedMessages; + protected override bool SourceMayOmitRetryClaim => true; + protected override IQueryable Copied(ServiceControlDbContext dbContext) => dbContext.FailedMessages.Where(message => message.Status == FailedMessageStatus.Unresolved); } diff --git a/src/ServiceControl.Persistence.Tests.SqlServer/MigrationGroupInsertSeekTests.cs b/src/ServiceControl.Persistence.Tests.SqlServer/MigrationGroupInsertSeekTests.cs index 19de168ce3..8b6350b7e5 100644 --- a/src/ServiceControl.Persistence.Tests.SqlServer/MigrationGroupInsertSeekTests.cs +++ b/src/ServiceControl.Persistence.Tests.SqlServer/MigrationGroupInsertSeekTests.cs @@ -36,7 +36,8 @@ public async Task The_group_insert_seeks_existing_rows_by_key_while_the_group_ta .Select(document => new MigrationRow($"FailedMessages/{document.UniqueMessageId}", document, new Dictionary { [MigrationMetadataKeys.StatusChangedAt] = new DateTime(2026, 9, 1, 8, 0, 0, DateTimeKind.Utc), - [MigrationMetadataKeys.LastModified] = new DateTime(2026, 9, 2, 8, 0, 0, DateTimeKind.Utc) + [MigrationMetadataKeys.LastModified] = new DateTime(2026, 9, 2, 8, 0, 0, DateTimeKind.Utc), + [MigrationMetadataKeys.RetryClaimHeld] = false }, new MigrationBody("1"u8.ToArray(), "text/xml"))) .ToList(); diff --git a/src/ServiceControl.Persistence.Tests.SqlServer/MigrationPlanReuseTests.cs b/src/ServiceControl.Persistence.Tests.SqlServer/MigrationPlanReuseTests.cs index 9a792f8cb0..a471b249a6 100644 --- a/src/ServiceControl.Persistence.Tests.SqlServer/MigrationPlanReuseTests.cs +++ b/src/ServiceControl.Persistence.Tests.SqlServer/MigrationPlanReuseTests.cs @@ -67,7 +67,8 @@ static MigrationBatch BatchOf(FailedMessage document) var row = new MigrationRow($"FailedMessages/{document.UniqueMessageId}", document, new Dictionary { [MigrationMetadataKeys.StatusChangedAt] = new DateTime(2026, 9, 1, 8, 0, 0, DateTimeKind.Utc), - [MigrationMetadataKeys.LastModified] = new DateTime(2026, 9, 2, 8, 0, 0, DateTimeKind.Utc) + [MigrationMetadataKeys.LastModified] = new DateTime(2026, 9, 2, 8, 0, 0, DateTimeKind.Utc), + [MigrationMetadataKeys.RetryClaimHeld] = false }, new MigrationBody("1"u8.ToArray(), "text/xml")); return new MigrationBatch([row], row.SourceId); diff --git a/src/ServiceControl.Persistence.Tests/EFCore/Migration/FailedMessagesMigrationTargetTests.cs b/src/ServiceControl.Persistence.Tests/EFCore/Migration/FailedMessagesMigrationTargetTests.cs index 29c0bd05bd..5c2fe5b7f8 100644 --- a/src/ServiceControl.Persistence.Tests/EFCore/Migration/FailedMessagesMigrationTargetTests.cs +++ b/src/ServiceControl.Persistence.Tests/EFCore/Migration/FailedMessagesMigrationTargetTests.cs @@ -522,6 +522,41 @@ await Query(db => Assert.That(await Target.Count(UnresolvedCategory), Is.EqualTo(2)); } + [Test] + public void A_message_of_any_status_without_its_claim_flag_fails_the_required_write() + { + var document = new IngestedFailure().ToFailedMessage(FailedMessageStatus.Archived); + + var exception = Assert.ThrowsAsync(() => Target.Write(FailedMessagesCategory, BatchOf(WithClaimHeld(RowOf(document, SmallTextBody), null)), Checkpoint())); + + Assert.That(exception.Message, Does.Contain($"'FailedMessages/{document.UniqueMessageId}'").And.Contain(MigrationMetadataKeys.RetryClaimHeld), + "the required source resolves the flag for every row, so a missing one is a defect whatever the status"); + } + + [Test] + public async Task An_unresolved_copy_accepts_a_message_without_the_claim_flag_as_holding_no_claim() + { + var failure = new IngestedFailure(); + + var result = await Target.Write(UnresolvedCategory, BatchOf(WithClaimHeld(RowOf(failure.ToFailedMessage(), SmallTextBody), null)), Checkpoint(MigrationCategoryIds.UnresolvedFailedMessages)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(result.Copied, Is.EqualTo(1)); + Assert.That(await Query(db => db.FailedMessageRetries.AsNoTracking().CountAsync()), Is.Zero); + } + } + + [Test] + public void An_unresolved_copy_still_fails_a_retry_issued_message_without_the_claim_flag() + { + var document = new IngestedFailure().ToFailedMessage(FailedMessageStatus.RetryIssued); + + var exception = Assert.ThrowsAsync(() => Target.Write(UnresolvedCategory, BatchOf(WithClaimHeld(RowOf(document, SmallTextBody), null)), Checkpoint(MigrationCategoryIds.UnresolvedFailedMessages))); + + Assert.That(exception.Message, Does.Contain(MigrationMetadataKeys.RetryClaimHeld)); + } + [Test] public async Task A_claim_holder_of_any_status_gets_a_retry_claim_and_a_message_without_one_does_not() { @@ -857,7 +892,7 @@ async Task Query(Func> query) static MigrationBatch BatchOf(params MigrationRow[] rows) => new(rows, rows[^1].SourceId); - // Every row carries the values the source resolves, as a real source's rows do, and a retry-issued one finds its claim still held. + // Every row carries the values the required source resolves, as a real source's rows do, and a retry-issued one finds its claim still held. static MigrationRow RowOf(FailedMessage document, MigrationBody body) { var metadata = new Dictionary @@ -866,10 +901,7 @@ static MigrationRow RowOf(FailedMessage document, MigrationBody body) [MigrationMetadataKeys.LastModified] = new DateTime(2026, 9, 2, 8, 0, 0, DateTimeKind.Utc) }; - if (document.Status == FailedMessageStatus.RetryIssued) - { - metadata[MigrationMetadataKeys.RetryClaimHeld] = true; - } + metadata[MigrationMetadataKeys.RetryClaimHeld] = document.Status == FailedMessageStatus.RetryIssued; return new($"FailedMessages/{document.UniqueMessageId}", document, metadata, body); }