From 5f53eea57cee7a6e619f3e192b66b734a3d9342e Mon Sep 17 00:00:00 2001 From: Rhys Bevilaqua Date: Mon, 23 Nov 2026 15:40:10 +0800 Subject: [PATCH] Add index readiness check for online migration steps --- .../ravendb-to-sql-migration-instructions.md | 4 + .../ravendb-to-sql-migration-overview.md | 2 + .../ravendb-to-sql-migration-system-design.md | 4 +- .../Writers/FailedMessagesWriter.cs | 20 ++-- .../Readers/FailedMessageStatusReader.cs | 48 +++++++++- .../Readers/FailedMessagesReader.cs | 3 +- .../Readers/UnresolvedFailedMessagesReader.cs | 10 +- .../UnresolvedFailedMessageSourceTests.cs | 95 ++++++++++++++++++- .../MigrationGroupInsertSeekTests.cs | 3 +- .../MigrationPlanReuseTests.cs | 3 +- .../FailedMessagesMigrationTargetTests.cs | 48 +++++++++- 11 files changed, 217 insertions(+), 23 deletions(-) diff --git a/docs/migration/ravendb-to-sql-migration-instructions.md b/docs/migration/ravendb-to-sql-migration-instructions.md index f2414e8e77..ec71a0b428 100644 --- a/docs/migration/ravendb-to-sql-migration-instructions.md +++ b/docs/migration/ravendb-to-sql-migration-instructions.md @@ -185,6 +185,10 @@ ServiceControl is open and works as usual while the optional categories copy. Yo If the copy slows down your production work, raise `ServiceControl/Migration/ThrottlePauseMilliseconds` and restart. This is the pause between two background batches. The default is 100 milliseconds. +The unresolved-message copy waits up to ten minutes for the RavenDB failed-message index to become trustworthy. If it stays behind, the copy logs a warning and scans the whole failed-message collection instead. Archived and resolved messages are filtered out, but reading them makes this fallback slower on a large archive. Resume paused indexing in RavenDB Studio to avoid the scan. Restarting the copy preserves its document-id cursor even if the read path changes. + +The ten-minute fallback applies only to the background copy. During the offline copy, a stale index still waits under the required category's 30-minute stall watchdog; missing, errored, disabled, or incomplete indexes trigger the full scan. + > [!IMPORTANT] > To give up an optional category, use [the abandon command](#to-abandon-a-category). diff --git a/docs/migration/ravendb-to-sql-migration-overview.md b/docs/migration/ravendb-to-sql-migration-overview.md index f11ed47478..62ae4577c7 100644 --- a/docs/migration/ravendb-to-sql-migration-overview.md +++ b/docs/migration/ravendb-to-sql-migration-overview.md @@ -287,6 +287,8 @@ flowchart LR - **Both source databases are opened through one `IDocumentStore`**, which is why they must be on the same server or cluster. - **Upgrade on RavenDB first**, so the build doing the copy is the one that last ran against the source. Nothing checks this. - **Distance to the source sets the pace.** Each message body is one round trip, and they are not batched. Egress out of RavenDB Cloud is billed to the customer. +- **The unresolved background copy waits up to ten minutes for a trustworthy failed-message index.** The budget covers index readiness and repeated stale count checks. At the limit, it logs a warning and reads the whole failed-message collection, including archived and resolved messages, filtering for unresolved messages. This preserves completeness but can make a large archive slow the background copy. Both paths use document-id cursors, so a restart can switch paths without gaps or duplicates. Caller cancellation stops the read instead of selecting the fallback. +- **The required copy has no ten-minute index fallback.** It waits for the index under the required copy's existing 30-minute stall watchdog. This avoids automatically expanding the outage into a full archive scan merely because indexing is slow. Missing, errored, disabled, or incomplete indexes still select the full-collection fallback. ### Writing to SQL diff --git a/docs/migration/ravendb-to-sql-migration-system-design.md b/docs/migration/ravendb-to-sql-migration-system-design.md index 9d371bc434..2eb718cc5a 100644 --- a/docs/migration/ravendb-to-sql-migration-system-design.md +++ b/docs/migration/ravendb-to-sql-migration-system-design.md @@ -177,6 +177,8 @@ Windowing for the other two: `MigrationEngineOptions.WindowFor` supplies the win | Early stop | `HaltThreshold.Exceeded` on per-run counters | Fault skips (reasons not `IsBenign`, plus body skips) must exceed both `Migration/HaltThresholdPercent` and `Migration/HaltThresholdMinimum`. Counters are not persisted, so the threshold is per run | | Settle | `MigrationEngine.Settle`, after `IMigrationTarget.Count` at the end of the source | Saves the category's SQL row count on the row it settles, as `TargetCountAtSettle`. A halt saves without it, because the target may be what failed, and `--migration-abandon` reads it later. Logs before saving, because the checkpoint store shares the target database and a failed save would hide the cause | +`FailedMessageStatusReader` gives the optional `UnresolvedFailedMessagesReader` a ten-minute budget for the entire index-readiness process, including repeated stale counts and subsequent waits. At the deadline it warns and selects the full-collection path, never a stale index. Caller cancellation propagates rather than selecting the fallback. The full scan can be slower on a large archive, but the document-id cursor and missing-cursor validation apply to both paths. The required `FailedMessagesReader` has no such budget: its stale-index wait remains under `ClosedWindowProgress`'s 30-minute stall watchdog, avoiding an automatic full archive scan during the outage. Missing, errored, disabled, or incomplete indexes select the existing fallback in either category. + `FailedMessagesWriterBase` inserts only messages the target lacks, so an existing SQL row always wins. Live ingestion can therefore replace RavenDB's earlier failure history with the attempt it stores. The overview describes the [accepted edge cases](ravendb-to-sql-migration-overview.md#writing-to-sql). Failed message body placement lives in `FailedMessagesWriterBase`, shared by `FailedMessagesWriter` and `UnresolvedFailedMessagesWriter`, and by the archived and resolved writer when it exists. `MessageBodyClassifier.Classify` decides placement and `FailedMessageDocumentTranslator.SetBody` fills the columns: text up to `MaxBodySizeToStore` (100 KB default) inline; longer text inline prefix plus external copy; binary, invalid UTF-8 or NUL-containing text external only; empty bodies not stored. External writes go through `IBodyStoragePersistence.WriteBody`, which owns compression and the filesystem, Azure Blob or S3 backend, and complete before the transaction opens. `FailedErrorImportsWriter` places a failed error import's body by the SQL import store's own rule, inline up to `MaxBodySizeToStore` and otherwise external only, under `FailedErrorImportEntity.ExternalBodyId`, also before the transaction opens. @@ -282,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 | `UnresolvedAndRetryIssuedFailedMessages` | 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. Phase one is the retry-issued messages, where `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 non-retry-issued messages they name by `id()`, with `RetryClaimHeld` true and no index built. 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 retry-issued rows and rows with a claim | +| 12 | `UnresolvedAndRetryIssuedFailedMessages` | 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. Phase one is the retry-issued messages, where `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 non-retry-issued messages they name by `id()`, with `RetryClaimHeld` true and no index built. 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. Every row in the required category must carry an explicit Boolean `RetryClaimHeld`, whatever its status; a missing or wrong-type value fails the batch. Only `UnresolvedFailedMessagesWriter` accepts an absent flag as no claim; a wrong-type value still fails the batch. The writer counts retry-issued rows and rows with a claim | | 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 070312530e..cd9a1b2ee6 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 in a category that sets . 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,12 @@ abstract class FailedMessagesWriterBase(IMigrationSqlDialect migrationDialect, I /// protected abstract IQueryable Copied(ServiceControlDbContext dbContext); + /// + /// Whether a row may arrive without RetryClaimHeld, which then means no claim. A source resolves the flag for every row of a + /// required category, so a missing one there is a defect. Only the optional unresolved category, whose rows carry none, sets this. + /// + protected virtual bool RetryClaimHeldMayBeAbsent => false; + public override int BatchSize(ServiceControlDbContext dbContext) => migrationDialect.RowsPerStatementFor(dbContext); public override Task Count(ServiceControlDbContext dbContext, CancellationToken cancellationToken = default) => @@ -71,7 +77,7 @@ protected override async Task PrepareDocuments(ServiceControlDbCo externalBodies.Add((row.SourceId, translation.Row, body)); } - if (SourceHeldRetryClaim(row, translation.Row.Status)) + if (SourceHeldRetryClaim(row)) { heldClaims.Add(translation.Row.UniqueMessageId); } @@ -126,12 +132,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) => 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 RetryClaimHeldMayBeAbsent => false, + null => throw new InvalidOperationException($"Row '{row.SourceId}' arrived without a {MigrationMetadataKeys.RetryClaimHeld} value, which the source resolves for every row of category {CategoryId}"), 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 +212,8 @@ sealed class UnresolvedFailedMessagesWriter(IMigrationSqlDialect migrationDialec { public override string CategoryId => MigrationCategoryIds.UnresolvedFailedMessages; + protected override bool RetryClaimHeldMayBeAbsent => true; + protected override IQueryable Copied(ServiceControlDbContext dbContext) => dbContext.FailedMessages.Where(message => message.Status == FailedMessageStatus.Unresolved); } diff --git a/src/ServiceControl.Persistence.RavenDB/DataMigration/Readers/FailedMessageStatusReader.cs b/src/ServiceControl.Persistence.RavenDB/DataMigration/Readers/FailedMessageStatusReader.cs index a96980273c..a856af092c 100644 --- a/src/ServiceControl.Persistence.RavenDB/DataMigration/Readers/FailedMessageStatusReader.cs +++ b/src/ServiceControl.Persistence.RavenDB/DataMigration/Readers/FailedMessageStatusReader.cs @@ -25,12 +25,21 @@ namespace ServiceControl.Persistence.RavenDB.DataMigration.Readers; /// Reads the failed messages with one of a category's statuses. The archived and resolved messages in the same collection can /// outnumber the others many times, so it queries for just these statuses instead of reading them all. /// -abstract class FailedMessageStatusReader(RavenReadOnlySourceLifecycle lifecycle, IReadOnlyCollection statuses) : MigrationCategoryReader(lifecycle) +abstract class FailedMessageStatusReader(RavenReadOnlySourceLifecycle lifecycle, IReadOnlyCollection statuses, TimeSpan? indexBudget) : MigrationCategoryReader(lifecycle) { /// - /// Waits for to catch up, then streams the messages with the category's statuses in id + /// How long a reader that runs after ServiceControl has opened waits for the index before it reads the whole collection. Ten + /// minutes is a chosen tolerance, not a measured catch-up time: a large index rebuild can take longer, and then the slower read, which the + /// copy's throttle paces and no outage depends on, is accepted rather than leaving the unresolved messages uncopied. + /// + protected static readonly TimeSpan OnlineIndexBudget = TimeSpan.FromMinutes(10); + + /// + /// Waits for to catch up, up to the reader's index budget, then streams the messages with the category's statuses in id /// order, starting after . When the index is missing, errored or disabled, or does not hold - /// every failed message with a status some category copies, it logs a warning and reads the whole collection instead. + /// every failed message with a status some category copies, or when the budget runs out first, it logs a warning and reads the + /// whole collection instead. A reader with no budget leaves cancellation to its caller, so slow indexing alone does not + /// turn the required copy's outage into a read of the whole archive. /// Both ways use the document id as the cursor, so a copy can switch from one to the other between runs. /// Throws when the source holds no document with the id in , /// or when a failed message has a status no category copies. @@ -78,7 +87,31 @@ async IAsyncEnumerable ThroughIndex( // A full read passes a document RavenDB could not index to the target to skip, and refuses a status no category copies, // but a query on the index sees neither, so either kind of document sends the copy back to a full read. + // The budget covers the whole check, the waits, the repeats on a stale count and the requests in between alike. It cancels a + // token linked to the caller's, and only a cancellation the caller did not ask for becomes the fallback. async Task IndexHoldsEveryCopiedFailedMessage(string databaseName, CancellationToken cancellationToken) + { + using var budget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + + if (indexBudget is { } limit) + { + budget.CancelAfter(limit); + } + + try + { + return await IndexHoldsEveryCopiedFailedMessageWithin(databaseName, budget.Token); + } +#pragma warning disable PS0020 // The try runs on the budget's linked token, so the caller's own token is the one that must not be set for this to be the budget's cancellation + catch (OperationCanceledException) when (budget.IsCancellationRequested && !cancellationToken.IsCancellationRequested) +#pragma warning restore PS0020 + { + logger.LogWarning("The RavenDB index {IndexName} in {DatabaseName} was still behind after {Budget}, so copying {CategoryId} reads every failed message instead, archived and resolved ones included, which makes the copy slower. If indexing is paused, resume it in RavenDB Studio", IndexName, databaseName, indexBudget, CategoryId); + return false; + } + } + + async Task IndexHoldsEveryCopiedFailedMessageWithin(string databaseName, CancellationToken cancellationToken) { using var session = Lifecycle.OpenSession(databaseName); @@ -117,6 +150,7 @@ async Task IndexHoldsEveryCopiedFailedMessage(string databaseName, Cancell if (statistics.IsStale) { + await Task.Delay(PollEvery, cancellationToken); continue; } @@ -146,7 +180,7 @@ async Task StoredFailedMessages(string databaseName, CancellationToken can var statistics = await Lifecycle.DocumentStore.Maintenance.ForDatabase(databaseName).SendAsync(new GetStatisticsOperation(), cancellationToken); var index = statistics.Indexes.SingleOrDefault(candidate => candidate.Name == IndexName); - // A missing, errored or disabled index never catches up, so waiting for it would keep ServiceControl closed for good. + // A missing, errored or disabled index never catches up, so waiting for it would never end. if (index is null || !index.IsStale || index.State is IndexState.Error or IndexState.Disabled) { return index; @@ -171,6 +205,12 @@ async Task LogWait(string databaseName, TimeSpan waited, CancellationToken cance if (paused) { + if (indexBudget is { } limit) + { + logger.LogWarning("Copying {CategoryId} is waiting for the RavenDB index {IndexName} in {DatabaseName}, but indexing is paused, so the copy waits up to {Budget} for it to be resumed in RavenDB Studio and then reads every failed message instead. Waited {Waited} so far", CategoryId, IndexName, databaseName, limit, waited); + return; + } + logger.LogWarning("Copying {CategoryId} is waiting for the RavenDB index {IndexName} in {DatabaseName}, but indexing is paused, so the copy waits until it is resumed in RavenDB Studio. Waited {Waited} so far", CategoryId, IndexName, databaseName, waited); return; } diff --git a/src/ServiceControl.Persistence.RavenDB/DataMigration/Readers/FailedMessagesReader.cs b/src/ServiceControl.Persistence.RavenDB/DataMigration/Readers/FailedMessagesReader.cs index 0a668e6b5d..154de409e9 100644 --- a/src/ServiceControl.Persistence.RavenDB/DataMigration/Readers/FailedMessagesReader.cs +++ b/src/ServiceControl.Persistence.RavenDB/DataMigration/Readers/FailedMessagesReader.cs @@ -12,8 +12,9 @@ namespace ServiceControl.Persistence.RavenDB.DataMigration.Readers; /// Reads the retry-issued messages and the messages that hold a retry claim, which are copied while ServiceControl is closed: every /// retry-issued message, whether or not its retry claim remains, and then every other message that still holds a retry claim, /// whatever its status. The unresolved messages without a claim are 's. +/// The required copy's stall watchdog bounds its stale-index wait; it does not switch to a full scan on an index-readiness timeout. /// -sealed class FailedMessagesReader(RavenReadOnlySourceLifecycle lifecycle) : FailedMessageStatusReader(lifecycle, MigrationCategoryRegistry.RetryIssuedStatuses) +sealed class FailedMessagesReader(RavenReadOnlySourceLifecycle lifecycle) : FailedMessageStatusReader(lifecycle, MigrationCategoryRegistry.RetryIssuedStatuses, indexBudget: null) { public override string CategoryId => MigrationCategoryIds.UnresolvedAndRetryIssuedFailedMessages; diff --git a/src/ServiceControl.Persistence.RavenDB/DataMigration/Readers/UnresolvedFailedMessagesReader.cs b/src/ServiceControl.Persistence.RavenDB/DataMigration/Readers/UnresolvedFailedMessagesReader.cs index 3e43214cdb..8e5ff49b1d 100644 --- a/src/ServiceControl.Persistence.RavenDB/DataMigration/Readers/UnresolvedFailedMessagesReader.cs +++ b/src/ServiceControl.Persistence.RavenDB/DataMigration/Readers/UnresolvedFailedMessagesReader.cs @@ -2,16 +2,22 @@ namespace ServiceControl.Persistence.RavenDB.DataMigration.Readers; +using System; using System.Collections.Generic; using System.Threading; using ServiceControl.Persistence.DataMigration; /// /// Reads every unresolved failed message, whatever its age, for the copy that runs while ServiceControl is open. A message that -/// holds a retry claim was copied with the required category and is already present, which the copy counts as such. +/// holds a retry claim was copied with the required category and is already present, which the copy counts as such. It waits at most +/// for the index before it reads the whole collection. /// -sealed class UnresolvedFailedMessagesReader(RavenReadOnlySourceLifecycle lifecycle) : FailedMessageStatusReader(lifecycle, MigrationCategoryRegistry.UnresolvedStatuses) +sealed class UnresolvedFailedMessagesReader(RavenReadOnlySourceLifecycle lifecycle, TimeSpan indexBudget) : FailedMessageStatusReader(lifecycle, MigrationCategoryRegistry.UnresolvedStatuses, indexBudget) { + public UnresolvedFailedMessagesReader(RavenReadOnlySourceLifecycle lifecycle) : this(lifecycle, OnlineIndexBudget) + { + } + public override string CategoryId => MigrationCategoryIds.UnresolvedFailedMessages; public override IAsyncEnumerable Read(string? resumeAfter, int batchSize, CancellationToken cancellationToken = default) => diff --git a/src/ServiceControl.Persistence.Tests.RavenDB/DataMigration/UnresolvedFailedMessageSourceTests.cs b/src/ServiceControl.Persistence.Tests.RavenDB/DataMigration/UnresolvedFailedMessageSourceTests.cs index dd55778870..bf1e7253c3 100644 --- a/src/ServiceControl.Persistence.Tests.RavenDB/DataMigration/UnresolvedFailedMessageSourceTests.cs +++ b/src/ServiceControl.Persistence.Tests.RavenDB/DataMigration/UnresolvedFailedMessageSourceTests.cs @@ -3,6 +3,7 @@ namespace ServiceControl.Persistence.Tests.RavenDB.DataMigration; using System; using System.Collections.Generic; using System.Linq; +using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using Raven.Client.Documents.Indexes; @@ -15,6 +16,7 @@ namespace ServiceControl.Persistence.Tests.RavenDB.DataMigration; using ServiceControl.Persistence.DataMigration; using ServiceControl.Persistence.RavenDB; using ServiceControl.Persistence.RavenDB.DataMigration; +using ServiceControl.Persistence.RavenDB.DataMigration.Readers; [TestFixture] class UnresolvedFailedMessageSourceTests : RavenMigrationSourceTestBase @@ -168,7 +170,7 @@ public async Task The_category_reads_no_archived_or_resolved_document() await using var source = await OpenMigrationSource(); var batches = await CollectBatches(source, Category, batchSize: 2); - Assert.That(batches, Is.Empty, "the copy runs while ServiceControl is closed, so reading the archive only to drop it makes the outage grow with the archive"); + Assert.That(batches, Is.Empty, "reading the archive only to drop it would make the copy slower with the archive for nothing"); } [Test] @@ -229,6 +231,77 @@ public async Task Waits_for_the_index_to_catch_up_so_no_unresolved_message_is_mi } } + [Test] + public async Task Reads_the_whole_collection_once_a_paused_index_has_stayed_behind_for_the_whole_budget() + { + var stored = await SeedFailedMessage(new IngestedFailure().ToFailedMessage(FailedMessageStatus.Archived)); + await CompleteDatabaseOperation(); + await DocumentStore.Maintenance.SendAsync(new StopIndexOperation(IndexName), TestContext.CurrentContext.CancellationToken); + + using (var session = DocumentStore.OpenAsyncSession()) + { + (await session.LoadAsync(stored.Id, TestContext.CurrentContext.CancellationToken)).Status = FailedMessageStatus.Unresolved; + await session.SaveChangesAsync(TestContext.CurrentContext.CancellationToken); + } + + var rows = await ReadWithBudget(TimeSpan.FromSeconds(2), null, TestContext.CurrentContext.CancellationToken).WaitAsync(TimeSpan.FromSeconds(60), TestContext.CurrentContext.CancellationToken); + + Assert.That(rows.Select(row => row.SourceId), Is.EqualTo(new[] { stored.Id }), "the index never saw the message become unresolved, so only a full read finds it"); + } + + [Test] + public async Task A_full_read_after_the_budget_resumes_from_a_cursor_the_index_issued_with_no_row_repeated_or_skipped() + { + var ids = await SeedInIdOrder( + FailedMessageStatus.Unresolved, FailedMessageStatus.Archived, FailedMessageStatus.Unresolved, + FailedMessageStatus.RetryIssued, FailedMessageStatus.Unresolved, FailedMessageStatus.Unresolved); + + await using var source = await OpenMigrationSource(); + var first = (await CollectBatches(source, Category, batchSize: 2))[0]; + + await DocumentStore.Maintenance.SendAsync(new StopIndexOperation(IndexName), TestContext.CurrentContext.CancellationToken); + var late = await SeedFailedMessage(new IngestedFailure().ToFailedMessage(FailedMessageStatus.Unresolved)); + var resumed = await ReadWithBudget(TimeSpan.FromSeconds(2), first.Cursor, TestContext.CurrentContext.CancellationToken).WaitAsync(TimeSpan.FromSeconds(60), TestContext.CurrentContext.CancellationToken); + + var expected = new[] { ids[4], ids[5], late.Id }.OrderBy(id => id, StringComparer.Ordinal).ToList(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(first.Rows.Select(row => row.SourceId), Is.EqualTo(new[] { ids[0], ids[2] })); + Assert.That(resumed.Select(row => row.SourceId), Is.EqualTo(expected), "the full read starts after the same document id the index path saved, and also finds what the stale index had not seen"); + } + } + + [Test] + public async Task A_full_read_after_the_budget_still_refuses_a_cursor_this_source_never_issued() + { + await SeedInIdOrder(FailedMessageStatus.Unresolved); + await DocumentStore.Maintenance.SendAsync(new StopIndexOperation(IndexName), TestContext.CurrentContext.CancellationToken); + await SeedFailedMessage(new IngestedFailure().ToFailedMessage(FailedMessageStatus.Unresolved)); + const string cursor = "FailedMessages/zzz-from-another-database"; + + var refusal = Assert.ThrowsAsync(() => ReadWithBudget(TimeSpan.FromSeconds(1), cursor, TestContext.CurrentContext.CancellationToken).WaitAsync(TimeSpan.FromSeconds(60), TestContext.CurrentContext.CancellationToken)); + + Assert.That(refusal.Message, Does.Contain(Category.Id).And.Contain(cursor)); + } + + [Test] + public async Task Cancelling_while_the_index_is_behind_stops_the_read_instead_of_falling_back_to_a_full_read() + { + await SeedInIdOrder(FailedMessageStatus.Unresolved); + await DocumentStore.Maintenance.SendAsync(new StopIndexOperation(IndexName), TestContext.CurrentContext.CancellationToken); + await SeedFailedMessage(new IngestedFailure().ToFailedMessage(FailedMessageStatus.Unresolved)); + + using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CurrentContext.CancellationToken); + var reading = ReadWithBudget(TimeSpan.FromMinutes(5), null, cancellation.Token); + + await Task.Delay(TimeSpan.FromSeconds(2), TestContext.CurrentContext.CancellationToken); + Assert.That(reading.IsCompleted, Is.False, "the read must be waiting on the index for the test to prove anything"); + await cancellation.CancelAsync(); + + Assert.That(async () => await reading.WaitAsync(TimeSpan.FromSeconds(15), TestContext.CurrentContext.CancellationToken), Throws.InstanceOf(), "the caller asked to stop, which a timeout fallback would answer with rows"); + } + [Test] public async Task Resumes_after_a_cursor_that_names_an_archived_message() { @@ -303,7 +376,7 @@ public async Task Reads_the_whole_collection_instead_of_waiting_for_a_disabled_i var rows = await ReadAll().WaitAsync(TimeSpan.FromSeconds(30), TestContext.CurrentContext.CancellationToken); - Assert.That(rows.Select(row => row.SourceId), Is.EqualTo(new[] { stored.Id }), "a disabled index never catches up, so waiting for it would keep ServiceControl closed for good"); + Assert.That(rows.Select(row => row.SourceId), Is.EqualTo(new[] { stored.Id }), "a disabled index never catches up, so waiting for it would never end"); } [Test] @@ -318,7 +391,7 @@ public async Task Reads_the_whole_collection_instead_of_waiting_for_an_errored_i var rows = await ReadAll().WaitAsync(TimeSpan.FromSeconds(30), TestContext.CurrentContext.CancellationToken); - Assert.That(rows.Select(row => row.SourceId), Is.EquivalentTo(new[] { unindexable.Id, stored.Id }), "an errored index never catches up, so waiting for it would keep ServiceControl closed for good"); + Assert.That(rows.Select(row => row.SourceId), Is.EquivalentTo(new[] { unindexable.Id, stored.Id }), "an errored index never catches up, so waiting for it would never end"); } [Test] @@ -882,6 +955,22 @@ async Task> ReadAll() return (await CollectBatches(source, Category)).SelectMany(batch => batch.Rows).ToList(); } + // Reads through a reader with a short index budget, because the production one is ten minutes. + async Task> ReadWithBudget(TimeSpan budget, string resumeAfter, CancellationToken cancellationToken) + { + await using var lifecycle = new RavenReadOnlySourceLifecycle((RavenPersisterSettings)PersistenceSettings, new SettingsRootNamespace("ServiceControl")); + await lifecycle.Open(TestContext.CurrentContext.CancellationToken); + + var rows = new List(); + + await foreach (var batch in new UnresolvedFailedMessagesReader(lifecycle, budget).Read(resumeAfter, 100, cancellationToken)) + { + rows.AddRange(batch.Rows); + } + + return rows; + } + // RavenDB streams in id order, so statuses are handed out by sorted id rather than by seeding order. async Task> SeedInIdOrder(params FailedMessageStatus[] statuses) { diff --git a/src/ServiceControl.Persistence.Tests.SqlServer/MigrationGroupInsertSeekTests.cs b/src/ServiceControl.Persistence.Tests.SqlServer/MigrationGroupInsertSeekTests.cs index f1914f23b1..7c9c6563cc 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 f6135cc924..ce1f48acbb 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 62ce59904d..6a3a27b1cc 100644 --- a/src/ServiceControl.Persistence.Tests/EFCore/Migration/FailedMessagesMigrationTargetTests.cs +++ b/src/ServiceControl.Persistence.Tests/EFCore/Migration/FailedMessagesMigrationTargetTests.cs @@ -417,6 +417,49 @@ public void A_retry_issued_message_without_its_claim_flag_fails_the_write_naming "the source resolves the flag for every retry-issued message, so a missing one is a defect that must not pass as a held claim"); } + [Test] + public void A_non_retry_issued_message_without_its_claim_flag_fails_the_required_write_naming_the_row() + { + var document = new IngestedFailure().ToFailedMessage(FailedMessageStatus.Unresolved); + + 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 source sets the flag on every row of the required category, claim holders of any status included, so status alone must not excuse a missing one"); + } + + [Test] + public async Task An_unresolved_message_without_its_claim_flag_is_copied_without_a_claim_by_the_optional_write() + { + var failure = new IngestedFailure(); + + var result = await Target.Write(UnresolvedCategory, BatchOf(WithClaimHeld(RowOf(failure.ToFailedMessage(), SmallTextBody), null)), Checkpoint(MigrationCategoryIds.UnresolvedFailedMessages)); + var claims = await Query(db => db.FailedMessageRetries.AsNoTracking().CountAsync()); + + using (Assert.EnterMultipleScope()) + { + Assert.That(result.Copied, Is.EqualTo(1)); + Assert.That(claims, Is.Zero, "the optional source sends no flag, and the claim holders were copied with the required category"); + } + } + + [Test] + public async Task An_unresolved_message_whose_claim_flag_is_not_a_bool_fails_the_optional_write_and_stores_nothing() + { + var document = new IngestedFailure().ToFailedMessage(); + var row = RowOf(document, SmallTextBody); + row = row with { Metadata = new Dictionary(row.Metadata) { [MigrationMetadataKeys.RetryClaimHeld] = "true" } }; + + var exception = Assert.ThrowsAsync(() => Target.Write(UnresolvedCategory, BatchOf(row), Checkpoint(MigrationCategoryIds.UnresolvedFailedMessages))); + var messages = await Query(db => db.FailedMessages.AsNoTracking().CountAsync()); + + using (Assert.EnterMultipleScope()) + { + Assert.That(exception.Message, Does.Contain($"'FailedMessages/{document.UniqueMessageId}'").And.Contain(MigrationMetadataKeys.RetryClaimHeld).And.Contain(typeof(string).FullName)); + Assert.That(messages, Is.Zero, "only an absent flag is accepted, so a wrong type is a defect in either category"); + } + } + [Test] public async Task A_retry_issued_message_whose_claim_flag_is_not_a_bool_fails_the_write_and_stores_nothing() { @@ -866,10 +909,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); }