Skip to content
Open
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
2 changes: 2 additions & 0 deletions docs/migration/ravendb-to-sql-migration-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,8 @@ If the copy slows down your production work, raise `ServiceControl/Migration/Thr
> [!IMPORTANT]
> To give up an optional category, use [the abandon command](#to-abandon-a-category).

SQL retention deletes nothing until every category is Done or Abandoned, including while a category is Failed, so the SQL database grows past the retention period during that time. Retention resumes at the next hourly check after the last category finishes. The purge API answers `400` with status `error` and names the unfinished categories. If a category stays unfinished for a long time, retry or abandon it.

Keep RavenDB running until every category is Done or Abandoned. If RavenDB goes down after ServiceControl opens, ServiceControl keeps running. The optional categories wait for RavenDB to come back, or you can abandon them.

## Step 8: Finish the migration
Expand Down
9 changes: 5 additions & 4 deletions docs/migration/ravendb-to-sql-migration-overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ flowchart LR

- **The [free abort](#going-back-to-ravendb) window runs from the first `--start-data-migration` invocation until ServiceControl opens.** A successful command does not end this window; starting ServiceControl does.
- **While required data is still copying, none of ServiceControl's own clean-up runs**: the retention sweep, the purge API, the heartbeat settings sync and throughput collection. The offline command never starts the host, and normal startup refuses while a required category is unfinished.
- **While any category is unfinished, SQL retention deletes nothing.** The hourly sweep, the manual purge API and every other sweep check the persisted category checkpoints before they delete a row. An unfinished category is any checkpoint that is not Complete or Abandoned: not started, in progress, blocked, halted, or complete with errors. A category the running version does not know counts as unfinished until it is Complete or Abandoned. A database with no checkpoints is not paused.

## Design

Expand Down Expand Up @@ -159,7 +160,7 @@ There are nineteen *categories*: fifteen required and four optional.
| Custom checks, with their last status | Required | Not every check reports again. An endpoint that is down never does, and a check with no repeat interval reports only when its endpoint starts. Leaving one out could hide a known failure until that endpoint restarts. Results of the six checks the RavenDB persister runs about its own database, matched on id and category, are left out, as harmless skips |
| Failed error imports, with bodies | Required | Messages taken off the error queue but not ingested. They exist nowhere else and never expire. After the move the "Error Message Ingestion" custom check keeps flagging them and `--import-failed-errors` imports them into SQL. Importing them on RavenDB first is better still |
| Unresolved failed messages, with bodies | Optional | Copied once ServiceControl has opened, whatever the age of the message, because an operator is waiting on each one. It has no window and no setting turns it off. A message the required category already copied, because it holds a retry claim or is one of the recent errors, counts as already present, and the copy leaves its row, groups, body and claim as they are. An existing SQL row always wins, see [Writing to SQL](#writing-to-sql). Group retry, archive and unarchive act only on the messages copied so far, an accepted edge case |
| Group comments | Optional | Copied in the background right after the unresolved failed messages, before the event log and the archived and resolved messages. It has no window and no setting turns it off. A comment is missing from SQL until this copy reaches it. Blank comments are not copied. The next retention sweep removes a copied comment on a group with no failed message in SQL, see [Rows removed after the copy](#rows-removed-after-the-copy) |
| Group comments | Optional | Copied in the background right after the unresolved failed messages, before the event log and the archived and resolved messages. It has no window and no setting turns it off. A comment is missing from SQL until this copy reaches it. Blank comments are not copied. Retention is paused until every category is finished. After that, a sweep removes a copied comment on a group with no failed message in SQL, see [Rows removed after the copy](#rows-removed-after-the-copy) |
| Event log | Optional | The history behind the ServicePulse activity feed. On a busy instance it holds a row for every failure, retry and submission |
| Archived and resolved failed messages, with bodies | Optional | The biggest category by far, and most of the copying time |

Expand Down Expand Up @@ -252,7 +253,7 @@ A value SQL can hold only after changing it is not a skip. Those rows are copied
- **Rows RavenDB expires during the copy are not skips either.** Only archived or resolved failed messages and event log items expire, plus some unresolved messages from 6.18 or earlier (see [Open decisions](#rows-removed-after-the-copy)).
- A message that expires between the copy reading it and reading its body is a `BodyMissing` fault skip. A retry gets past it.
- If the message a stopped copy was at expires before the next start, the category stops with an error naming the missing id. `--migration-retry` gets past it.
- A window shorter than the retention period keeps the background copy clear of the expiry sweep.
- A window shorter than the retention period keeps the background copy clear of RavenDB's expiry. SQL retention does not delete during the copy.

### Startup checks

Expand Down Expand Up @@ -302,7 +303,7 @@ flowchart LR

- **A failed message is written as one row**, with its status unchanged. Its older attempts are dropped, see [Open decisions](#values-that-change-or-merge-in-sql).
- **An existing SQL row always wins.** The copy never updates a row and counts an existing row as already present, not as a skip. When ingestion created the row first, its attempt count and first failure time can omit earlier RavenDB failures, and it can hold an older payload than RavenDB's newest attempt. These outcomes are accepted.
- **The copy accepts unlikely races with live operations.** A delayed retry confirmation can be consumed before an unresolved message whose claim a re-failure removed arrives, leaving it unresolved, unless the message is among the recent errors. A message archived or resolved in SQL and then deleted by retention before the copy reaches it can arrive again as unresolved. A queued edit-and-retry is discarded if its original message has not arrived.
- **The copy accepts unlikely races with live operations.** A delayed retry confirmation can be consumed before an unresolved message whose claim a re-failure removed arrives, leaving it unresolved, unless the message is among the recent errors. A queued edit-and-retry is discarded if its original message has not arrived.
- **Bodies are immutable and written only if absent.** The body store keeps one body per `UniqueMessageId`, and each backend refuses to replace one that exists: the file system through an exclusive move, Azure Blob and S3 through a conditional upload. The first writer wins, so a body the copy stores just before ingestion does is the body that stays. That is safe only because every attempt of one message carries the same body bytes, which ingestion already assumes. An S3-compatible store that ignores `If-None-Match` falls back to a check followed by an unconditional upload, which can replace a live body.
- **A failed message keeps its failure groups and its last-modified time**, so filtered lists show the same messages as before. A failure group with no id is the exception, see [Open decisions](#values-that-change-or-merge-in-sql).
- **`UniqueMessageId` keeps its value** but becomes a `uniqueidentifier`. It is the primary key, the ServicePulse URL, the retry key and the body key.
Expand Down Expand Up @@ -511,7 +512,7 @@ The dry run counts the subscription and endpoint settings merges before anything

### Rows removed after the copy

- **The next retention sweep removes a copied group comment whose group has no failed message in SQL**, because the sweep deletes a comment whose group has no row. The group has none when its messages are archived or resolved, when they are gone from RavenDB, or when the copy skipped them. Comments wait until the unresolved failed messages category is Done or Abandoned, so waiting for that copy alone does not cause comment loss. Abandoning it can leave groups without messages in SQL. Nothing keeps a comment on a group with only archived or resolved messages, even when those messages copy later. The copy names each such comment, in a warning starting `Changed GroupComment/<group id> in category GroupComments on the way into SQL: The group '<group id>' has no copied failed message`, which also quotes the whole comment.
- **After every category is finished, a retention sweep removes a copied group comment whose group has no failed message in SQL**, because the sweep deletes a comment whose group has no row. The group has none when its messages are archived or resolved and were not copied, when they are gone from RavenDB, when the copy skipped them, or when the copy of the unresolved or archived and resolved messages was abandoned. Retention is paused while any category is unfinished, so a comment survives while the messages of its group are still copying. The copy names each comment on a group with no copied failed message, in a warning starting `Changed GroupComment/<group id> in category GroupComments on the way into SQL: The group '<group id>' has no copied failed message`, which also quotes the whole comment.
- **A `MessageFailed` event still waiting to be sent for a message outside the recent errors, retry-issued messages and claim holders is lost when the message is archived, resolved or not yet copied.** ServiceControl looks the message up when it sends the event. Archived and resolved messages last modified before the cutoff arrive only with the background copy, so the lookup finds nothing, and the event is deleted with no log line. RavenDB would have sent it. The same lookup can fail for an older unresolved message the background copy has not reached yet. The required copy covers the events for messages last modified at or after one hour before the anchor, with no upper bound, or messages that are retry-issued or hold a claim, and nothing else covers the rest, an accepted gap.
- **Unresolved messages from version 6.18 or earlier can expire during the copy.** On those versions, a message that failed again after being archived or resolved kept its expiry. One deleted before the copy reads it is not copied and not counted. No log line names these messages yet.

Expand Down
10 changes: 9 additions & 1 deletion docs/migration/ravendb-to-sql-migration-system-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,14 @@ Windowing for the other two: `MigrationEngineOptions.WindowFor` supplies the win

`Migration/ThrottlePauseMilliseconds` inserts a delay between optional-category batches, skipping the first batch of each category. Required categories are never throttled.

## Retention during migration

`RetentionSweeper` reads every checkpoint through `IMigrationCheckpointStore` before it records a start or deletes a row, on the hourly tick, in `SweepNow` and in `TryStartManualSweep`. A checkpoint whose state is not `IsFinished` pauses it, an unknown category included. No copier flag is involved, so a restart pauses and resumes from the persisted checkpoints alone.

The check happens before the sweeper takes its single-flight lock. An unfinished category causes the check to log and return without recording a run, so `GetStatus` reports not running. `TryStartManualSweep` returns `Error` with a reason, and the controller maps it to 400.

A failed read deletes nothing. The hourly path logs the error and tries again on the next tick, and the manual path throws.

## Copying a batch

`MigrationEngine.RunCategoryAsync` is the per-category loop. Every store-specific step is delegated.
Expand Down Expand Up @@ -289,7 +297,7 @@ Every reader derives from `MigrationCategoryReader<TDocument>` and every writer
| 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` |
| 1 | `UnresolvedFailedMessages` | Optional | `UnresolvedFailedMessagesReader`, `UnresolvedFailedMessagesWriter` | Carries bodies, no window, and attaches no claim state. `MigrationEngineOptions.FromSettings` always selects it, and the engine runs it as optional: it throttles between batches, and an exception leaves it copying with `LastError` until the next start. `FailedMessagesWriterBase` inserts only messages the target lacks. The writer counts unresolved rows. `RavenMigrationSource.ReadBody` reads the body attachment for both failed-message categories |
| 2 | `GroupComments` | Optional | `GroupCommentsReader`, `GroupCommentsWriter` | Unwindowed and always selected, with `MustFollow` set to `UnresolvedFailedMessages`, not a data link, so the retention sweep does not find a comment before the unresolved messages of its group. The engine blocks it until that category is `IsFinished`. A comment is absent from SQL until this copy reaches it. Skips blanks as `BlankGroupComment`. Reports group ids that differ only in trailing spaces as merges on SQL Server. Reports each copied comment on a group with no copied failed message as a change. Abandoning the unresolved failed messages copy can leave such groups. Nothing protects a comment on a group with only archived or resolved messages |
| 2 | `GroupComments` | Optional | `GroupCommentsReader`, `GroupCommentsWriter` | Unwindowed and always selected, with `MustFollow` set to `UnresolvedFailedMessages`, not a data link, so the copy does not add a comment before the unresolved messages of its group. The engine blocks it until that category is `IsFinished`. A comment is absent from SQL until this copy reaches it. Skips blanks as `BlankGroupComment`. Reports group ids that differ only in trailing spaces as merges on SQL Server. Reports each copied comment on a group with no copied failed message as a change. Abandoning the unresolved failed messages copy can leave such groups. Retention is paused until every category is finished, so a comment on a group with only archived or resolved messages survives while those copy, and a sweep after the pause removes it if the group still has no message |
| 3 | `EventLog` | Optional | `EventLogReader`, `EventLogWriter` | Windowed, store-keyed, abandon-only. Skips as `PastRetention` |
| 4 | `ArchivedAndResolvedFailedMessages` | Optional | `ArchivedAndResolvedFailedMessagesReader`, `ArchivedAndResolvedFailedMessagesWriter` | Windowed, carries bodies, shares `FailedMessagesWriter` preparation. Skips as `PastRetention` |

Expand Down
6 changes: 3 additions & 3 deletions src/ServiceControl.Api/Contracts/RetentionPurgeResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ namespace ServiceControl.Api.Contracts;

/// <summary>
/// Response body for <c>POST /api/maintenance/retention/purge</c>. The <c>Status</c> field signals the
/// outcome: <c>started</c> (202), <c>already-running</c> (409), or
/// <c>not-supported</c> (501).
/// outcome: <c>started</c> (202), <c>alreadyRunning</c> (409),
/// <c>error</c> (400, with a <c>Reason</c>), or <c>notSupported</c> (501).
/// </summary>
public class RetentionPurgeResponse
{
Expand All @@ -17,6 +17,6 @@ public class RetentionPurgeResponse

public DateTime? EventsCutoff { get; set; }

/// <summary>A human-readable reason included when the operation is not supported.</summary>
/// <summary>A human-readable reason included when the operation is not supported or cannot start.</summary>
public string Reason { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ namespace ServiceControl.Migration.AcceptanceTests;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using ServiceControl.Hosting.Commands;
using ServiceControl.MessageFailures;
using ServiceControl.Persistence;
using ServiceControl.Persistence.DataMigration;
using ServiceControl.Persistence.Infrastructure;
using ServiceControl.Persistence.Tests;
Expand Down Expand Up @@ -59,13 +61,17 @@ public async Task A_comment_on_an_unresolved_group_survives_a_retention_sweep_be

await MigrateCommand.Run(Settings, AllowingAnUnreleasedMigration());

// The sweep that runs once ServiceControl opens, before the background copy has reached the unresolved message.
await RunRetentionSweep();
// A sweep that runs once ServiceControl opens, before the background copy has reached the unresolved message.
Assert.That((await TryRetentionSweep()).Outcome, Is.EqualTo(RetentionSweepStatus.Error), "no category is finished, so nothing is deleted");
await RunHostUntilTheApiAnswers();
await WaitUntil(
async () => (await ReadCheckpoint(MigrationCategoryIds.GroupComments))?.State.IsFinished() == true,
"the group comments copy finished",
TimeSpan.FromMinutes(1));
await WaitUntil(
async () => (await QueryTarget(dbContext => dbContext.MigrationCheckpoints.AsNoTracking().Select(checkpoint => checkpoint.State).ToListAsync())).All(state => state.IsFinished()),
"every migration category finished",
TimeSpan.FromMinutes(1));
await RunRetentionSweep();

var comments = (await GroupsStore.GetUnresolvedGroupsByClassifier(unresolved.Groups.Single().Type, null, new PagingInfo())).ToDictionary(view => view.Id, view => view.Comment);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -593,13 +593,17 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
// Resolved from the target services, whose hosted sweeper never starts, so a test decides when a sweep runs.
protected async Task RunRetentionSweep()
{
var sweeper = targetServices.GetRequiredService<IRetentionSweeper>();
var attempt = sweeper.TryStartManualSweep(null, null);
var attempt = await TryRetentionSweep();
Assert.That(attempt.Outcome, Is.EqualTo(RetentionSweepStatus.Started));
var sweeper = targetServices.GetRequiredService<IRetentionSweeper>();
await WaitUntil(() => Task.FromResult(!sweeper.GetStatus().IsRunning), "the retention sweep finished", TimeSpan.FromMinutes(1));
Assert.That(sweeper.GetStatus().LastOutcome, Is.EqualTo(RetentionSweepOutcome.Succeeded));
}

// Retention does not delete while a migration category is unfinished, so a test that sweeps then asks for this.
protected Task<ManualSweepAttempt> TryRetentionSweep() =>
targetServices.GetRequiredService<IRetentionSweeper>().TryStartManualSweep(null, null);

sealed class UnstartedApplicationLifetime : IHostApplicationLifetime
{
public CancellationToken ApplicationStarted => CancellationToken.None;
Expand Down
Loading
Loading