nodedb-cluster 0.1.0

Distributed coordination layer for NodeDB — vShards, QUIC transport, and replication
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// SPDX-License-Identifier: BUSL-1.1

//! In-flight migration recovery.
//!
//! Called from `MigrationExecutor::recover_in_flight_migrations` which
//! is invoked at coordinator startup (after the metadata Raft group is
//! up but before the rebalancer spawns).
//!
//! For each migration row in `MigrationStateTable`:
//!
//! - If the last checkpoint phase is `Complete`, delete the row (cleanup).
//! - If the migration is older than `abort_timeout` wall-clock seconds,
//!   propose a `MigrationAbort` with appropriate compensations.
//! - If the target node is unreachable, propose a `MigrationAbort`.
//! - Otherwise, re-queue the migration so `MigrationExecutor::execute`
//!   can resume from the next phase.

use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use tracing::{info, warn};

use crate::decommission::MetadataProposer;
use crate::error::Result;
use crate::metadata_group::compensation::Compensation;
use crate::metadata_group::entry::MetadataEntry;
use crate::metadata_group::migration_state::{
    MigrationCheckpointPayload, MigrationId, MigrationPhaseTag, SharedMigrationStateTable,
};
use crate::topology::ClusterTopology;

/// Default timeout after which a stale in-flight migration is aborted
/// rather than resumed.
pub const DEFAULT_ABORT_TIMEOUT: Duration = Duration::from_secs(3600); // 1 hour

/// Decision reached by the recovery scan for a single migration.
#[derive(Debug)]
pub enum RecoveryDecision {
    /// Migration completed normally; the row was cleaned up.
    CleanedUp { migration_id: MigrationId },
    /// Migration was resumed by requeueing for the next phase.
    Resumed { migration_id: MigrationId },
    /// Migration was aborted (timeout, unreachable target, etc.).
    Aborted {
        migration_id: MigrationId,
        reason: String,
    },
}

/// Run in-flight migration recovery.
///
/// `topology` is used to check whether target nodes are still reachable.
/// `proposer` is used to propose `MigrationAbort` entries.
/// `table` is the shared migration state table.
/// `abort_timeout` controls when a stale migration is aborted rather than
/// resumed.
///
/// Returns one `RecoveryDecision` per in-flight migration found.
pub async fn recover_in_flight_migrations(
    table: SharedMigrationStateTable,
    topology: Arc<std::sync::RwLock<ClusterTopology>>,
    proposer: Arc<dyn MetadataProposer>,
    abort_timeout: Duration,
) -> Result<Vec<RecoveryDecision>> {
    // Load all rows once — we operate on a snapshot.
    let rows = {
        let guard = table.lock().unwrap_or_else(|p| p.into_inner());
        guard.all_checkpoints()
    };

    if rows.is_empty() {
        info!("migration recovery: no in-flight migrations found");
        return Ok(vec![]);
    }

    info!(
        count = rows.len(),
        "migration recovery: scanning in-flight migrations"
    );

    let now_ms = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_else(|_| {
            tracing::error!(
                "system clock is before UNIX_EPOCH during migration recovery; \
                 using 0 (epoch) — check NTP/RTC configuration"
            );
            std::time::Duration::ZERO
        })
        .as_millis() as u64;
    let abort_threshold_ms = abort_timeout.as_millis() as u64;

    let mut decisions = Vec::with_capacity(rows.len());

    for row in rows {
        let migration_id = match row.migration_uuid() {
            Some(id) => id,
            None => {
                warn!(
                    key = %row.migration_id,
                    "migration recovery: could not parse UUID, skipping"
                );
                continue;
            }
        };

        // 1. Clean up completed migrations.
        if row.payload.phase_tag() == MigrationPhaseTag::Complete {
            let mut guard = table.lock().unwrap_or_else(|p| p.into_inner());
            guard.remove(&migration_id)?;
            drop(guard);
            info!(
                migration_id = %migration_id,
                "migration recovery: cleaned up completed migration"
            );
            decisions.push(RecoveryDecision::CleanedUp { migration_id });
            continue;
        }

        // 2. Check age — abort stale migrations.
        let age_ms = now_ms.saturating_sub(row.ts_ms);
        if age_ms > abort_threshold_ms {
            let reason = format!(
                "migration stale: age {}s exceeds abort timeout {}s",
                age_ms / 1000,
                abort_timeout.as_secs()
            );
            warn!(migration_id = %migration_id, reason, "aborting stale migration");
            let comps = compensations_for_phase(row.payload.phase_tag(), &row.payload);
            let entry = MetadataEntry::MigrationAbort {
                migration_id: migration_id.hyphenated().to_string(),
                reason: reason.clone(),
                compensations: comps,
            };
            proposer.propose_and_wait(entry).await?;
            decisions.push(RecoveryDecision::Aborted {
                migration_id,
                reason,
            });
            continue;
        }

        // 3. Check target reachability.
        let target_reachable = is_target_reachable(&row.payload, &topology);
        if !target_reachable {
            let reason = "migration aborted: target node no longer reachable".to_owned();
            warn!(migration_id = %migration_id, "aborting migration: target unreachable");
            let comps = compensations_for_phase(row.payload.phase_tag(), &row.payload);
            let entry = MetadataEntry::MigrationAbort {
                migration_id: migration_id.hyphenated().to_string(),
                reason: reason.clone(),
                compensations: comps,
            };
            proposer.propose_and_wait(entry).await?;
            decisions.push(RecoveryDecision::Aborted {
                migration_id,
                reason,
            });
            continue;
        }

        // 4. Migration is resumable — the caller (`MigrationExecutor`) will
        //    re-invoke `execute` starting from the checkpoint's next phase.
        info!(
            migration_id = %migration_id,
            phase = ?row.payload.phase_tag(),
            "migration recovery: migration is resumable"
        );
        decisions.push(RecoveryDecision::Resumed { migration_id });
    }

    Ok(decisions)
}

/// Derive the set of compensations needed to undo the effects up to
/// `phase` for the given `payload`.
///
/// The audit's "Recommended `MigrationAbort` compensations" section
/// drives this mapping.
pub fn compensations_for_phase(
    phase: MigrationPhaseTag,
    payload: &MigrationCheckpointPayload,
) -> Vec<Compensation> {
    match phase {
        MigrationPhaseTag::AddLearner => {
            // AddLearner committed; remove the ghost learner.
            if let MigrationCheckpointPayload::AddLearner {
                source_group,
                target_node,
                ..
            } = payload
            {
                vec![Compensation::RemoveLearner {
                    group_id: *source_group,
                    peer_id: *target_node,
                }]
            } else {
                vec![]
            }
        }
        MigrationPhaseTag::CatchUp => {
            // Catch-up started; AddLearner committed.  Remove the learner.
            if let MigrationCheckpointPayload::CatchUp { vshard_id: _, .. } = payload {
                // We don't have group_id/peer_id at CatchUp payload level —
                // the AddLearner checkpoint must have been the prior row.
                // Emit empty (caller should chain with AddLearner payload).
                vec![]
            } else {
                vec![]
            }
        }
        MigrationPhaseTag::PromoteLearner => {
            // PromoteLearner committed; demote back by removing the voter.
            if let MigrationCheckpointPayload::PromoteLearner {
                source_group,
                target_node,
                ..
            } = payload
            {
                vec![Compensation::RemoveVoter {
                    group_id: *source_group,
                    peer_id: *target_node,
                }]
            } else {
                vec![]
            }
        }
        MigrationPhaseTag::LeadershipTransfer => {
            // LeadershipTransfer about to be proposed but did not commit.
            // PromoteLearner committed — remove the voter.
            if let MigrationCheckpointPayload::LeadershipTransfer {
                source_group,
                new_leader_node_id,
                ..
            } = payload
            {
                vec![Compensation::RemoveVoter {
                    group_id: *source_group,
                    peer_id: *new_leader_node_id,
                }]
            } else {
                vec![]
            }
        }
        MigrationPhaseTag::Cutover => {
            // Cut-over committed — this is NOT an abort scenario.
            // The only path is forward: install the ghost and mark Complete.
            // No compensations are valid at this phase (audit §Phase 3 abort
            // committed section).
            vec![]
        }
        MigrationPhaseTag::Complete => {
            // Complete — no compensations needed; cleanup only.
            vec![]
        }
    }
}

/// Check whether the target node in `payload` is currently reachable
/// in the topology.
fn is_target_reachable(
    payload: &MigrationCheckpointPayload,
    topology: &std::sync::Arc<std::sync::RwLock<ClusterTopology>>,
) -> bool {
    let target_node = match payload {
        MigrationCheckpointPayload::AddLearner { target_node, .. } => *target_node,
        MigrationCheckpointPayload::PromoteLearner { target_node, .. } => *target_node,
        MigrationCheckpointPayload::LeadershipTransfer {
            new_leader_node_id, ..
        } => *new_leader_node_id,
        MigrationCheckpointPayload::Cutover {
            new_leader_node_id, ..
        } => *new_leader_node_id,
        // CatchUp and Complete don't carry the target node directly in
        // the payload — treat as reachable (recovery decision will be Resumed
        // or CleanedUp respectively).
        _ => return true,
    };
    let topo = topology.read().unwrap_or_else(|p| p.into_inner());
    topo.get_node(target_node).is_some()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::metadata_group::migration_state::{
        MigrationCheckpointPayload, MigrationStateTable, PersistedMigrationCheckpoint,
    };
    use nodedb_types::Hlc;
    use std::sync::Mutex;
    use uuid::Uuid;

    fn temp_db() -> Arc<redb::Database> {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.redb");
        let db = redb::Database::create(&path).unwrap();
        let txn = db.begin_write().unwrap();
        {
            let _ = txn.open_table(MigrationStateTable::TABLE).unwrap();
        }
        txn.commit().unwrap();
        std::mem::forget(dir);
        Arc::new(db)
    }

    fn shared_table(db: Arc<redb::Database>) -> SharedMigrationStateTable {
        Arc::new(Mutex::new(MigrationStateTable::new(db)))
    }

    fn make_row(
        id: Uuid,
        payload: MigrationCheckpointPayload,
        attempt: u32,
        ts_ms: u64,
    ) -> PersistedMigrationCheckpoint {
        let crc = payload.crc32c().unwrap();
        PersistedMigrationCheckpoint {
            migration_id: id.hyphenated().to_string(),
            attempt,
            payload,
            crc32c: crc,
            ts_ms,
        }
    }

    struct RecordingProposer {
        entries: Mutex<Vec<MetadataEntry>>,
    }

    impl RecordingProposer {
        fn new() -> Arc<Self> {
            Arc::new(Self {
                entries: Mutex::new(Vec::new()),
            })
        }
    }

    #[async_trait::async_trait]
    impl MetadataProposer for RecordingProposer {
        async fn propose_and_wait(&self, entry: MetadataEntry) -> Result<u64> {
            self.entries.lock().unwrap().push(entry);
            Ok(1)
        }
    }

    fn empty_topology() -> Arc<std::sync::RwLock<ClusterTopology>> {
        Arc::new(std::sync::RwLock::new(ClusterTopology::new()))
    }

    #[tokio::test]
    async fn completed_migration_is_cleaned_up() {
        let db = temp_db();
        let table = shared_table(Arc::clone(&db));
        let id = Uuid::new_v4();
        let now_ms = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64;
        let row = make_row(
            id,
            MigrationCheckpointPayload::Complete {
                vshard_id: 1,
                actual_pause_us: 100,
                ghost_stub_installed: true,
            },
            0,
            now_ms,
        );
        {
            let mut g = table.lock().unwrap();
            g.upsert(row).unwrap();
        }
        let proposer = RecordingProposer::new();
        let decisions = recover_in_flight_migrations(
            Arc::clone(&table),
            empty_topology(),
            proposer.clone(),
            DEFAULT_ABORT_TIMEOUT,
        )
        .await
        .unwrap();

        assert_eq!(decisions.len(), 1);
        assert!(matches!(&decisions[0], RecoveryDecision::CleanedUp { .. }));
        // No abort proposed.
        assert!(proposer.entries.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn stale_migration_is_aborted() {
        let db = temp_db();
        let table = shared_table(Arc::clone(&db));
        let id = Uuid::new_v4();
        // ts_ms = 0 means the migration is extremely old.
        let row = make_row(
            id,
            MigrationCheckpointPayload::AddLearner {
                vshard_id: 2,
                source_node: 1,
                target_node: 99,
                source_group: 0,
                write_pause_budget_us: 500_000,
                started_at_hlc: Hlc::default(),
            },
            0,
            0, // very old
        );
        {
            let mut g = table.lock().unwrap();
            g.upsert(row).unwrap();
        }
        let proposer = RecordingProposer::new();
        let decisions = recover_in_flight_migrations(
            Arc::clone(&table),
            empty_topology(),
            proposer.clone(),
            DEFAULT_ABORT_TIMEOUT,
        )
        .await
        .unwrap();

        assert_eq!(decisions.len(), 1);
        assert!(matches!(&decisions[0], RecoveryDecision::Aborted { .. }));
        // An abort entry was proposed.
        let entries = proposer.entries.lock().unwrap();
        assert_eq!(entries.len(), 1);
        assert!(matches!(entries[0], MetadataEntry::MigrationAbort { .. }));
    }

    #[tokio::test]
    async fn reachable_migration_is_resumed() {
        let db = temp_db();
        let table = shared_table(Arc::clone(&db));
        let id = Uuid::new_v4();
        let now_ms = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64;
        let row = make_row(
            id,
            MigrationCheckpointPayload::CatchUp {
                vshard_id: 3,
                learner_log_index_at_add: 5,
            },
            0,
            now_ms,
        );
        {
            let mut g = table.lock().unwrap();
            g.upsert(row).unwrap();
        }
        let proposer = RecordingProposer::new();
        let decisions = recover_in_flight_migrations(
            Arc::clone(&table),
            empty_topology(),
            proposer.clone(),
            DEFAULT_ABORT_TIMEOUT,
        )
        .await
        .unwrap();

        assert_eq!(decisions.len(), 1);
        assert!(matches!(&decisions[0], RecoveryDecision::Resumed { .. }));
        assert!(proposer.entries.lock().unwrap().is_empty());
    }
}