Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/migration/ravendb-to-sql-migration-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
2 changes: 2 additions & 0 deletions docs/migration/ravendb-to-sql-migration-overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion docs/migration/ravendb-to-sql-migration-system-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -282,7 +284,7 @@ Every reader derives from `MigrationCategoryReader<TDocument>` 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` |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ namespace ServiceControl.Persistence.EFCore.DataMigration.Writers;
/// <summary>
/// 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 <see cref="RetryClaimHeldMayBeAbsent" />. Each category that copies failed messages derives from this and names its category id and
/// which target rows it counts.
/// </summary>
abstract class FailedMessagesWriterBase(IMigrationSqlDialect migrationDialect, IBodyStoragePersistence storagePersistence, EFPersisterSettings persisterSettings) : MigrationCategoryWriter<FailedMessage>
Expand All @@ -25,6 +25,12 @@ abstract class FailedMessagesWriterBase(IMigrationSqlDialect migrationDialect, I
/// </summary>
protected abstract IQueryable<FailedMessageEntity> Copied(ServiceControlDbContext dbContext);

/// <summary>
/// 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.
/// </summary>
protected virtual bool RetryClaimHeldMayBeAbsent => false;

public override int BatchSize(ServiceControlDbContext dbContext) => migrationDialect.RowsPerStatementFor<FailedMessageEntity>(dbContext);

public override Task<long> Count(ServiceControlDbContext dbContext, CancellationToken cancellationToken = default) =>
Expand Down Expand Up @@ -71,7 +77,7 @@ protected override async Task<PreparedBatch> PrepareDocuments(ServiceControlDbCo
externalBodies.Add((row.SourceId, translation.Row, body));
}

if (SourceHeldRetryClaim(row, translation.Row.Status))
if (SourceHeldRetryClaim(row))
{
heldClaims.Add(translation.Row.UniqueMessageId);
}
Expand Down Expand Up @@ -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}")
};

Expand Down Expand Up @@ -206,6 +212,8 @@ sealed class UnresolvedFailedMessagesWriter(IMigrationSqlDialect migrationDialec
{
public override string CategoryId => MigrationCategoryIds.UnresolvedFailedMessages;

protected override bool RetryClaimHeldMayBeAbsent => true;

protected override IQueryable<FailedMessageEntity> Copied(ServiceControlDbContext dbContext) =>
dbContext.FailedMessages.Where(message => message.Status == FailedMessageStatus.Unresolved);
}
Loading
Loading