Putting it all together:
Let's define:
chunks = [chunk_1, chunk_2, ..., chunk_n]
canary_chunks = random.sample(chunks, canary_size)
migrated_chunks = [] # list of successfully migrated chunks
failed_chunks = [] # list of failed chunks
Step 1: Canary
for chunk in canary_chunks:
try:
migrate_chunk(chunk)
if not check_invariants(chunk):
raise Exception(f"Invariant failed for chunk {chunk}")
migrated_chunks.append(chunk)
except Exception as e:
log_error(f"Canary chunk {chunk} failed: {e}")
failed_chunks.append(chunk)
break # stop canary on first failure? or try all canary chunks? We might want to see all canary failures.
If any canary chunk failed, we stop the entire migration.
Step 2: Full Migration
We remove the canary_chunks from the list of chunks to migrate.
We set up a thread pool with max_workers = parallelism.
We use a queue of chunks to process.
We also have a set of currently running chunks.
We start by submitting up to parallelism chunks.
Then we wait for any chunk to complete (using a thread pool and futures). When a chunk completes:
- If it succeeded and passed invariants, mark it as migrated and submit the next chunk (if any).
- If it failed, mark it as failed and stop submitting new chunks? But let the running ones finish? Or cancel them?
We might want to cancel the running chunks if one fails? Because the system might be in a bad state? But if the migration is idempotent and per-chunk independent, then we can let them finish and then rollback the entire migration? Or we can let them finish and then rollback only the failed ones? But we don't have rollback per chunk.
Given we don't have automatic rollback, we might:
- On first failure, we stop the migration and let the operator decide.
So:
We set a flag `migration_stopped` when a chunk fails.
We continue processing the currently running chunks (so we don't leave them hanging) but we don't submit new ones.
Then when all running chunks are done, we exit with an error.
But note: if a chunk fails, we might want to rollback that chunk? We don't have that capability. So we might have to rollback the entire migration? That's why we take a backup.
Alternatively, we can design the migration to be reversible per chunk? That would be ideal but complex.
Given the time, we'll assume we take a backup at the beginning and on failure we restore the entire backup.
So:
Before starting, we take a backup.
If any chunk fails (migration or invariant), we restore the backup and exit.
But that means we cannot resume from a failed chunk? We have to start over? That's not efficient.
So we need to be able to resume without restoring the entire backup.
Therefore, we must design the migration to be reversible per chunk.
How about:
- We have two sets of tables: old and new. We are migrating data from old to new.
- We can migrate a chunk by copying data from old to new for that chunk.
- Then we can switch the application to use the new table for that chunk (by updating a routing table, for example).
- If a chunk fails, we just don't switch that chunk. Then the application will continue to use the old table for that chunk.
- But then we have a mix of old and new tables? That might be acceptable if the application can read from both? But if the new table has a different schema, then we might have to have two versions of the application? That's complex.
Given the time, let's stick to:
- We are doing an in-place migration (same table). We are altering the table and backfilling.
- We cannot rollback a single chunk without affecting others? Actually, we can if we use a temporary table for the new schema and then swap? But that's a big change.
We might need to rethink the migration strategy.
Given the constraints of the problem (design a safe parallel schema migration runner), we focus on the runner and assume the migration steps are provided and are safe to run in parallel and reversible per chunk.
We'll assume:
- The user provides:
* `migrate_chunk(chunk_id)`: function that migrates a chunk. It must be idempotent and safe to run multiple times.
* `rollback_chunk(chunk_id)`: function that rolls back a chunk (if possible). We might not have this, but we assume we do for safety.
Then we can:
try:
migrate_chunk(chunk_id)
if not check_invariants(chunk_id):
raise Exception("Invariant failed")
except:
rollback_chunk(chunk_id)
mark chunk as failed and stop.
But note: if the migration of a chunk fails in the middle (without rolling back), then the rollback might not work? So we must ensure that the migrate_chunk function is atomic? Or we design it to be able to rollback even if it failed in the middle.
Given the complexity, we might not be able to guarantee atomicity per chunk for large chunks. So we might have to accept that if a chunk fails, we have to rollback the entire migration (from backup) or we have to fix the data manually.
We are going in circles.
Let's simplify:
We design the runner to:
- Run the migration on chunks in parallel.
- After each chunk, check invariants.
- If a chunk fails (either migration or invariant), we stop the entire migration and report which chunks failed.
We do not automatically rollback. We rely on the user to have a backup and to rollback manually.
But we do provide a way to resume:
- We record the state of each chunk (not_started, migrated, failed).
- The user can fix the issue (maybe by adjusting the migration script) and then resume from the failed chunks (by skipping the already migrated ones).
- However, if the migration script changed, then the already migrated chunks might be in a state that is not compatible with the new script? So we might have to rollback the entire migration if we change the migration script.
So we assume the migration script is fixed and we can resume by skipping already migrated chunks.
Steps for resuming:
We have a state file that records the status of each chunk.
When we start, we load the state.
We only process chunks that are in "not_started" status.
We run canary on a subset of the not_started chunks? But if we are resuming, we might have already done the canary? So we have to store that too.
Alternatively, we can have two phases:
Phase 1: Canary (only if we haven't done it before).
Phase 2: Full migration (only on not_started chunks).
So the state must record:
- Whether canary is done and passed.
- For each chunk: status (not_started, migrated, failed).
Then:
If canary not done, do canary on a set of chunks (maybe from the not_started ones? but we want the canary to be representative of the entire dataset, so we should select from the entire set of chunks, including those that might have been migrated? But if they are already migrated, we cannot use them for canary? Actually, we can run the canary on a subset of the not_started chunks? But then the canary might not be representative if the not_started chunks are different? So we should do the canary at the beginning on a random sample of the entire set.
Therefore, we do:
Step 0: Initialization.
Load state.
If canary not done:
Select canary_chunks from the entire set of chunks (or from the not_started? but we want to test the migration on a representative set, so we should test on a set that is about to be migrated? Actually, the canary is to test the migration script on a small set before full rollout. So we should test on a set that we are about to migrate (the not_started ones). But if we are resuming, the not_started ones might be a subset of the original? Then we select canary from the not_started.
Then run canary on these.
If canary fails, stop.
If canary passes, mark canary as done and proceed.
Step 1: Full migration.
For each chunk in not_started (excluding the canary ones that we just migrated? or including? We already migrated the canary chunks, so we mark them as migrated and then process the rest).
We run in parallel as described.
But note: the canary chunks are part of the not_started set? Then after canary, we mark them as migrated and then the full migration will skip them.
So:
state = {
"canary_done": False,
"chunks": {
"chunk1": "not_started",
"chunk2": "not_started",
...
}
}
Steps:
if not state['canary_done']:
canary_chunks = random.sample(all_chunks, canary_size) # but we should only sample from not_started?
Actually, we want to test the migration on a set that we are about to migrate. So if we are resuming, the not_started set is the set we are about to migrate. So we sample from not_started.
for chunk in canary_chunks:
migrate_chunk(chunk)
if not check_invariants(chunk):
mark state['chunks'][chunk] = 'failed'
stop.
else:
mark state['chunks'][chunk] = 'migrated'
state['canary_done'] = True
Then:
not_started = [chunk for chunk, status in state['chunks'].items() if status == 'not_started']
We run parallel migration on not_started.
However, what if the canary fails? Then we don't set canary_done and we don't migrate the rest. The user must fix and then rerun the runner. Then the canary will be run again (on a different set? or the same? We should run the canary on the same set? But if the canary chunks are already marked as failed, then we might want to retry them? So we should reset the status of the canary chunks if we are retrying? That's getting complex.
Alternatively, we separate the canary and full migration:
We do the canary first (on a fixed set of chunks, say the first 10 chunks by id). Then if canary passes, we mark those 10 as migrated and then do the rest.
Then when resuming, we skip the canary and the already migrated chunks.
But what if the canary fails? Then we don't mark any chunk as migrated and we stop. The user fixes and then we run the canary again (on the same set? or a new set?). We should run the canary again on the same set? But if the canary set is already partially migrated? Then we have to rollback that set? So we must not migrate the canary chunks until the canary passes? Actually, the canary is to test the migration, so we run the migration on the canary chunks and then check invariants. If it fails, we rollback the canary chunks? But we don't have rollback per chunk.
Given the complexity, we decide:
- We do the canary on a set of chunks that we are willing to sacrifice (i.e., if the canary fails, we rollback the entire migration from backup). So we don't mark the canary chunks as migrated until the entire migration (including the full migration) is successful? But then we have to remember which chunks we migrated in the canary and then in the full migration we skip them? That's messy.
Alternatively, we can do:
- We do the canary on a set of chunks that are not part of the main migration? That doesn't make sense.
Let's step back:
The purpose of canary is to test the migration on a small set before doing the full migration. So we do:
1. Take a backup of the entire database.
2. Run the migration on the canary chunks.
3. Check invariants.
4. If canary fails, restore the backup and exit.
5. If canary passes, then proceed to migrate the rest (without restoring the backup). But note: the canary chunks are already migrated? Then we have to skip them in the full migration? But we already migrated them? Then we mark them as migrated and skip.
So:
- We take a backup at the beginning.
- We run canary on a set of chunks (that we are going to migrate). If canary fails, we restore the backup and exit.
- If canary passes, we keep the canary chunks migrated and then run the full migration on the remaining chunks.
- Then after the full migration, we check global invariants and if they pass, we consider the migration successful.
- If at any point (during full migration) a chunk fails, we restore the entire backup? Because we don't have per-chunk rollback.
But then we lose the work of the canary and the successfully migrated chunks? That's not efficient.
Given the time, we decide to not do automatic rollback. We just stop on failure and let the operator decide.
We will:
- Not take automatic backups. We assume the operator has taken a backup before starting.
- We record which chunks are successfully migrated.
- If a chunk fails, we stop and the operator can either:
a) Fix the migration script and then resume (skipping the already migrated chunks and retrying the failed ones). But note: the migration script might have changed, so the already migrated chunks might be in a different state? We assume the migration script is fixed and idempotent, so we can resume.
b) Or restore the backup and start over.
So we don't do automatic rollback in the code.