zebra_state/service/finalized_state/disk_format/
upgrade.rs

1//! In-place format upgrades and format validity checks for the Zebra state database.
2
3use std::{
4    cmp::Ordering,
5    sync::Arc,
6    thread::{self, JoinHandle},
7};
8
9use crossbeam_channel::{bounded, Receiver, RecvTimeoutError, Sender};
10use semver::Version;
11use tracing::Span;
12
13use zebra_chain::{
14    block::Height,
15    diagnostic::{
16        task::{CheckForPanics, WaitForPanics},
17        CodeTimer,
18    },
19};
20
21use DbFormatChange::*;
22
23use crate::service::finalized_state::ZebraDb;
24
25pub(crate) mod add_subtrees;
26pub(crate) mod block_info_and_address_received;
27pub(crate) mod cache_genesis_roots;
28pub(crate) mod fix_tree_key_type;
29pub(crate) mod no_migration;
30pub(crate) mod prune_trees;
31pub(crate) mod tree_keys_and_caches_upgrade;
32
33#[cfg(not(feature = "indexer"))]
34pub(crate) mod drop_tx_locs_by_spends;
35
36#[cfg(feature = "indexer")]
37pub(crate) mod track_tx_locs_by_spends;
38
39/// Defines method signature for running disk format upgrades.
40pub trait DiskFormatUpgrade {
41    /// Returns the version at which this upgrade is applied.
42    fn version(&self) -> Version;
43
44    /// Returns the description of this upgrade.
45    fn description(&self) -> &'static str;
46
47    /// Runs disk format upgrade.
48    fn run(
49        &self,
50        initial_tip_height: Height,
51        db: &ZebraDb,
52        cancel_receiver: &Receiver<CancelFormatChange>,
53    ) -> Result<(), CancelFormatChange>;
54
55    /// Check that state has been upgraded to this format correctly.
56    ///
57    /// The outer `Result` indicates whether the validation was cancelled (due to e.g. node shutdown).
58    /// The inner `Result` indicates whether the validation itself failed or not.
59    fn validate(
60        &self,
61        _db: &ZebraDb,
62        _cancel_receiver: &Receiver<CancelFormatChange>,
63    ) -> Result<Result<(), String>, CancelFormatChange> {
64        Ok(Ok(()))
65    }
66
67    /// Prepare for disk format upgrade.
68    fn prepare(
69        &self,
70        _initial_tip_height: Height,
71        _upgrade_db: &ZebraDb,
72        _cancel_receiver: &Receiver<CancelFormatChange>,
73        _older_disk_version: &Version,
74    ) -> Result<(), CancelFormatChange> {
75        Ok(())
76    }
77
78    /// Returns true if the [`DiskFormatUpgrade`] needs to run a migration on existing data in the db.
79    fn needs_migration(&self) -> bool {
80        true
81    }
82
83    /// Returns true if the upgrade is a major upgrade that can reuse the cache in the previous major db format version.
84    fn is_reusable_major_upgrade(&self) -> bool {
85        let version = self.version();
86        version.minor == 0 && version.patch == 0
87    }
88}
89
90fn format_upgrades(
91    min_version: Option<Version>,
92) -> impl DoubleEndedIterator<Item = Box<dyn DiskFormatUpgrade>> {
93    let min_version = move || min_version.clone().unwrap_or(Version::new(0, 0, 0));
94
95    // Note: Disk format upgrades must be run in order of database version.
96    ([
97        Box::new(prune_trees::PruneTrees),
98        Box::new(add_subtrees::AddSubtrees),
99        Box::new(tree_keys_and_caches_upgrade::FixTreeKeyTypeAndCacheGenesisRoots),
100        Box::new(no_migration::NoMigration::new(
101            "add value balance upgrade",
102            Version::new(26, 0, 0),
103        )),
104        Box::new(block_info_and_address_received::Upgrade),
105    ] as [Box<dyn DiskFormatUpgrade>; 5])
106        .into_iter()
107        .filter(move |upgrade| upgrade.version() > min_version())
108}
109
110/// Returns a list of all the major db format versions that can restored from the
111/// previous major database format.
112pub fn restorable_db_versions() -> Vec<u64> {
113    format_upgrades(None)
114        .filter_map(|upgrade| {
115            upgrade
116                .is_reusable_major_upgrade()
117                .then_some(upgrade.version().major)
118        })
119        .collect()
120}
121
122/// The kind of database format change or validity check we're performing.
123#[derive(Clone, Debug, Eq, PartialEq)]
124pub enum DbFormatChange {
125    // Data Format Changes
126    //
127    /// Upgrade the format from `older_disk_version` to `newer_running_version`.
128    ///
129    /// Until this upgrade is complete, the format is a mixture of both versions.
130    Upgrade {
131        older_disk_version: Version,
132        newer_running_version: Version,
133    },
134
135    // Format Version File Changes
136    //
137    /// Mark the format as newly created by `running_version`.
138    ///
139    /// Newly created databases are opened with no disk version.
140    /// It is set to the running version by the format change code.
141    NewlyCreated { running_version: Version },
142
143    /// Mark the format as downgraded from `newer_disk_version` to `older_running_version`.
144    ///
145    /// Until the state is upgraded to `newer_disk_version` by a Zebra version with that state
146    /// version (or greater), the format will be a mixture of both versions.
147    Downgrade {
148        newer_disk_version: Version,
149        older_running_version: Version,
150    },
151
152    // Data Format Checks
153    //
154    /// Check that the database from a previous instance has the current `running_version` format.
155    ///
156    /// Current version databases have a disk version that matches the running version.
157    /// No upgrades are needed, so we just run a format check on the database.
158    /// The data in that database was created or updated by a previous Zebra instance.
159    CheckOpenCurrent { running_version: Version },
160
161    /// Check that the database from this instance has the current `running_version` format.
162    ///
163    /// The data in that database was created or updated by the currently running Zebra instance.
164    /// So we periodically check for data bugs, which can happen if the upgrade and new block
165    /// code produce different data. (They can also be caused by disk corruption.)
166    CheckNewBlocksCurrent { running_version: Version },
167}
168
169/// A handle to a spawned format change thread.
170///
171/// Cloning this struct creates an additional handle to the same thread.
172///
173/// # Concurrency
174///
175/// Cancelling the thread on drop has a race condition, because two handles can be dropped at
176/// the same time.
177///
178/// If cancelling the thread is required for correct operation or usability, the owner of the
179/// handle must call force_cancel().
180#[derive(Clone, Debug)]
181pub struct DbFormatChangeThreadHandle {
182    /// A handle to the format change/check thread.
183    /// If configured, this thread continues running so it can perform periodic format checks.
184    ///
185    /// Panics from this thread are propagated into Zebra's state service.
186    /// The task returns an error if the upgrade was cancelled by a shutdown.
187    update_task: Option<Arc<JoinHandle<Result<(), CancelFormatChange>>>>,
188
189    /// A channel that tells the running format thread to finish early.
190    cancel_handle: Sender<CancelFormatChange>,
191}
192
193/// Marker type that is sent to cancel a format upgrade, and returned as an error on cancellation.
194#[derive(Copy, Clone, Debug, Eq, PartialEq)]
195pub struct CancelFormatChange;
196
197impl DbFormatChange {
198    /// Returns the format change for `running_version` code loading a `disk_version` database.
199    ///
200    /// Also logs that change at info level.
201    ///
202    /// If `disk_version` is `None`, Zebra is creating a new database.
203    pub fn open_database(running_version: &Version, disk_version: Option<Version>) -> Self {
204        let running_version = running_version.clone();
205
206        let Some(disk_version) = disk_version else {
207            info!(
208                %running_version,
209                "creating new database with the current format"
210            );
211
212            return NewlyCreated { running_version };
213        };
214
215        match disk_version.cmp_precedence(&running_version) {
216            Ordering::Less => {
217                info!(
218                    %running_version,
219                    %disk_version,
220                    "trying to open older database format: launching upgrade task"
221                );
222
223                Upgrade {
224                    older_disk_version: disk_version,
225                    newer_running_version: running_version,
226                }
227            }
228            Ordering::Greater => {
229                info!(
230                    %running_version,
231                    %disk_version,
232                    "trying to open newer database format: data should be compatible"
233                );
234
235                Downgrade {
236                    newer_disk_version: disk_version,
237                    older_running_version: running_version,
238                }
239            }
240            Ordering::Equal => {
241                info!(%running_version, "trying to open current database format");
242
243                CheckOpenCurrent { running_version }
244            }
245        }
246    }
247
248    /// Returns a format check for newly added blocks in the currently running Zebra version.
249    /// This check makes sure the upgrade and new block code produce the same data.
250    ///
251    /// Also logs the check at info level.
252    pub fn check_new_blocks(db: &ZebraDb) -> Self {
253        let running_version = db.format_version_in_code();
254
255        info!(%running_version, "checking new blocks were written in current database format");
256        CheckNewBlocksCurrent { running_version }
257    }
258
259    /// Returns true if this format change/check is an upgrade.
260    #[allow(dead_code)]
261    pub fn is_upgrade(&self) -> bool {
262        matches!(self, Upgrade { .. })
263    }
264
265    /// Returns true if this format change/check happens at startup.
266    #[allow(dead_code)]
267    pub fn is_run_at_startup(&self) -> bool {
268        !matches!(self, CheckNewBlocksCurrent { .. })
269    }
270
271    /// Returns the running version in this format change.
272    pub fn running_version(&self) -> Version {
273        match self {
274            Upgrade {
275                newer_running_version,
276                ..
277            } => newer_running_version,
278            Downgrade {
279                older_running_version,
280                ..
281            } => older_running_version,
282            NewlyCreated { running_version }
283            | CheckOpenCurrent { running_version }
284            | CheckNewBlocksCurrent { running_version } => running_version,
285        }
286        .clone()
287    }
288
289    /// Returns the initial database version before this format change.
290    ///
291    /// Returns `None` if the database was newly created.
292    pub fn initial_disk_version(&self) -> Option<Version> {
293        match self {
294            Upgrade {
295                older_disk_version, ..
296            } => Some(older_disk_version),
297            Downgrade {
298                newer_disk_version, ..
299            } => Some(newer_disk_version),
300            CheckOpenCurrent { running_version } | CheckNewBlocksCurrent { running_version } => {
301                Some(running_version)
302            }
303            NewlyCreated { .. } => None,
304        }
305        .cloned()
306    }
307
308    /// Launch a `std::thread` that applies this format change to the database,
309    /// then continues running to perform periodic format checks.
310    ///
311    /// `initial_tip_height` is the database height when it was opened, and `db` is the
312    /// database instance to upgrade or check.
313    pub fn spawn_format_change(
314        self,
315        db: ZebraDb,
316        initial_tip_height: Option<Height>,
317    ) -> DbFormatChangeThreadHandle {
318        // # Correctness
319        //
320        // Cancel handles must use try_send() to avoid blocking waiting for the format change
321        // thread to shut down.
322        let (cancel_handle, cancel_receiver) = bounded(1);
323
324        let span = Span::current();
325        let update_task = thread::spawn(move || {
326            span.in_scope(move || {
327                self.format_change_run_loop(db, initial_tip_height, cancel_receiver)
328            })
329        });
330
331        let mut handle = DbFormatChangeThreadHandle {
332            update_task: Some(Arc::new(update_task)),
333            cancel_handle,
334        };
335
336        handle.check_for_panics();
337
338        handle
339    }
340
341    /// Run the initial format change or check to the database. Under the default runtime config,
342    /// this method returns after the format change or check.
343    ///
344    /// But if runtime validity checks are enabled, this method periodically checks the format of
345    /// newly added blocks matches the current format. It will run until it is cancelled or panics.
346    fn format_change_run_loop(
347        self,
348        db: ZebraDb,
349        initial_tip_height: Option<Height>,
350        cancel_receiver: Receiver<CancelFormatChange>,
351    ) -> Result<(), CancelFormatChange> {
352        self.run_format_change_or_check(&db, initial_tip_height, &cancel_receiver)?;
353
354        let Some(debug_validity_check_interval) = db.config().debug_validity_check_interval else {
355            return Ok(());
356        };
357
358        loop {
359            // We've just run a format check, so sleep first, then run another one.
360            // But return early if there is a cancel signal.
361            if !matches!(
362                cancel_receiver.recv_timeout(debug_validity_check_interval),
363                Err(RecvTimeoutError::Timeout)
364            ) {
365                return Err(CancelFormatChange);
366            }
367
368            Self::check_new_blocks(&db).run_format_change_or_check(
369                &db,
370                initial_tip_height,
371                &cancel_receiver,
372            )?;
373        }
374    }
375
376    /// Run a format change in the database, or check the format of the database once.
377    #[allow(clippy::unwrap_in_result)]
378    pub(crate) fn run_format_change_or_check(
379        &self,
380        db: &ZebraDb,
381        initial_tip_height: Option<Height>,
382        cancel_receiver: &Receiver<CancelFormatChange>,
383    ) -> Result<(), CancelFormatChange> {
384        match self {
385            // Perform any required upgrades, then mark the state as upgraded.
386            Upgrade { .. } => self.apply_format_upgrade(db, initial_tip_height, cancel_receiver)?,
387
388            NewlyCreated { .. } => {
389                Self::mark_as_newly_created(db);
390            }
391
392            Downgrade { .. } => {
393                // # Correctness
394                //
395                // At the start of a format downgrade, the database must be marked as partially or
396                // fully downgraded. This lets newer Zebra versions know that some blocks with older
397                // formats have been added to the database.
398                Self::mark_as_downgraded(db);
399
400                // Older supported versions just assume they can read newer formats,
401                // because they can't predict all changes a newer Zebra version could make.
402                //
403                // The responsibility of staying backwards-compatible is on the newer version.
404                // We do this on a best-effort basis for versions that are still supported.
405            }
406
407            CheckOpenCurrent { running_version } => {
408                // If we're re-opening a previously upgraded or newly created database,
409                // the database format should be valid. This check is done below.
410                info!(
411                    %running_version,
412                    "checking database format produced by a previous zebra instance \
413                     is current and valid"
414                );
415            }
416
417            CheckNewBlocksCurrent { running_version } => {
418                // If we've added new blocks using the non-upgrade code,
419                // the database format should be valid. This check is done below.
420                //
421                // TODO: should this check panic or just log an error?
422                //       Currently, we panic to avoid consensus bugs, but this could cause a denial
423                //       of service. We can make errors fail in CI using ZEBRA_FAILURE_MESSAGES.
424                info!(
425                    %running_version,
426                    "checking database format produced by new blocks in this instance is valid"
427                );
428            }
429        }
430
431        #[cfg(feature = "indexer")]
432        if let (
433            Upgrade { .. } | CheckOpenCurrent { .. } | Downgrade { .. },
434            Some(initial_tip_height),
435        ) = (self, initial_tip_height)
436        {
437            // Indexing transaction locations by their spent outpoints and revealed nullifiers.
438            let timer = CodeTimer::start();
439
440            // Add build metadata to on-disk version file just before starting to add indexes
441            let mut version = db
442                .format_version_on_disk()
443                .expect("unable to read database format version file")
444                .expect("should write database format version file above");
445            version.build = db.format_version_in_code().build;
446
447            db.update_format_version_on_disk(&version)
448                .expect("unable to write database format version file to disk");
449
450            info!("started checking/adding indexes for spending tx ids");
451            track_tx_locs_by_spends::run(initial_tip_height, db, cancel_receiver)?;
452            info!("finished checking/adding indexes for spending tx ids");
453
454            timer.finish(module_path!(), line!(), "indexing spending transaction ids");
455        };
456
457        #[cfg(not(feature = "indexer"))]
458        if let (
459            Upgrade { .. } | CheckOpenCurrent { .. } | Downgrade { .. },
460            Some(initial_tip_height),
461        ) = (self, initial_tip_height)
462        {
463            let mut version = db
464                .format_version_on_disk()
465                .expect("unable to read database format version file")
466                .expect("should write database format version file above");
467
468            if version.build.contains("indexer") {
469                // Indexing transaction locations by their spent outpoints and revealed nullifiers.
470                let timer = CodeTimer::start();
471
472                info!("started removing indexes for spending tx ids");
473                drop_tx_locs_by_spends::run(initial_tip_height, db, cancel_receiver)?;
474                info!("finished removing indexes for spending tx ids");
475
476                // Remove build metadata to on-disk version file after indexes have been dropped.
477                version.build = db.format_version_in_code().build;
478                db.update_format_version_on_disk(&version)
479                    .expect("unable to write database format version file to disk");
480
481                timer.finish(module_path!(), line!(), "removing spending transaction ids");
482            }
483        };
484
485        // These checks should pass for all format changes:
486        // - upgrades should produce a valid format (and they already do that check)
487        // - an empty state should pass all the format checks
488        // - since the running Zebra code knows how to upgrade the database to this format,
489        //   downgrades using this running code still know how to create a valid database
490        //   (unless a future upgrade breaks these format checks)
491        // - re-opening the current version should be valid, regardless of whether the upgrade
492        //   or new block code created the format (or any combination).
493        Self::format_validity_checks_detailed(db, cancel_receiver)?.unwrap_or_else(|_| {
494            panic!(
495                "unexpected invalid database format: delete and re-sync the database at '{:?}'",
496                db.path()
497            )
498        });
499
500        let inital_disk_version = self
501            .initial_disk_version()
502            .map_or_else(|| "None".to_string(), |version| version.to_string());
503        info!(
504            running_version = %self.running_version(),
505            %inital_disk_version,
506            "database format is valid"
507        );
508
509        Ok(())
510    }
511
512    // TODO: Move state-specific upgrade code to a finalized_state/* module.
513
514    /// Apply any required format updates to the database.
515    /// Format changes should be launched in an independent `std::thread`.
516    ///
517    /// If `cancel_receiver` gets a message, or its sender is dropped,
518    /// the format change stops running early, and returns an error.
519    ///
520    /// See the format upgrade design docs for more details:
521    /// <https://github.com/ZcashFoundation/zebra/blob/main/book/src/dev/state-db-upgrades.md#design>
522    //
523    // New format upgrades must be added to the *end* of this method.
524    #[allow(clippy::unwrap_in_result)]
525    fn apply_format_upgrade(
526        &self,
527        db: &ZebraDb,
528        initial_tip_height: Option<Height>,
529        cancel_receiver: &Receiver<CancelFormatChange>,
530    ) -> Result<(), CancelFormatChange> {
531        let Upgrade {
532            newer_running_version,
533            older_disk_version,
534        } = self
535        else {
536            unreachable!("already checked for Upgrade")
537        };
538
539        // # New Upgrades Sometimes Go Here
540        //
541        // If the format change is outside RocksDb, put new code above this comment!
542        let Some(initial_tip_height) = initial_tip_height else {
543            // If the database is empty, then the RocksDb format doesn't need any changes.
544            info!(
545                %newer_running_version,
546                %older_disk_version,
547                "marking empty database as upgraded"
548            );
549
550            Self::mark_as_upgraded_to(db, newer_running_version);
551
552            info!(
553                %newer_running_version,
554                %older_disk_version,
555                "empty database is fully upgraded"
556            );
557
558            return Ok(());
559        };
560
561        // Apply or validate format upgrades
562        for upgrade in format_upgrades(Some(older_disk_version.clone())) {
563            if upgrade.needs_migration() {
564                let timer = CodeTimer::start();
565
566                upgrade.prepare(initial_tip_height, db, cancel_receiver, older_disk_version)?;
567                upgrade.run(initial_tip_height, db, cancel_receiver)?;
568
569                // Before marking the state as upgraded, check that the upgrade completed successfully.
570                upgrade
571                    .validate(db, cancel_receiver)?
572                    .expect("db should be valid after upgrade");
573
574                timer.finish(module_path!(), line!(), upgrade.description());
575            }
576
577            // Mark the database as upgraded. Zebra won't repeat the upgrade anymore once the
578            // database is marked, so the upgrade MUST be complete at this point.
579            info!(
580                newer_running_version = ?upgrade.version(),
581                "Zebra automatically upgraded the database format"
582            );
583            Self::mark_as_upgraded_to(db, &upgrade.version());
584        }
585
586        Ok(())
587    }
588
589    /// Run quick checks that the current database format is valid.
590    #[allow(clippy::vec_init_then_push)]
591    pub fn format_validity_checks_quick(db: &ZebraDb) -> Result<(), String> {
592        let timer = CodeTimer::start();
593        let mut results = Vec::new();
594
595        // Check the entire format before returning any errors.
596        results.push(db.check_max_on_disk_tip_height());
597
598        // This check can be run before the upgrade, but the upgrade code is finished, so we don't
599        // run it early any more. (If future code changes accidentally make it depend on the
600        // upgrade, they would accidentally break compatibility with older Zebra cached states.)
601        results.push(add_subtrees::subtree_format_calculation_pre_checks(db));
602
603        results.push(cache_genesis_roots::quick_check(db));
604        results.push(fix_tree_key_type::quick_check(db));
605
606        // The work is done in the functions we just called.
607        timer.finish(module_path!(), line!(), "format_validity_checks_quick()");
608
609        if results.iter().any(Result::is_err) {
610            let err = Err(format!("invalid quick check: {results:?}"));
611            error!(?err);
612            return err;
613        }
614
615        Ok(())
616    }
617
618    /// Run detailed checks that the current database format is valid.
619    #[allow(clippy::vec_init_then_push)]
620    pub fn format_validity_checks_detailed(
621        db: &ZebraDb,
622        cancel_receiver: &Receiver<CancelFormatChange>,
623    ) -> Result<Result<(), String>, CancelFormatChange> {
624        let timer = CodeTimer::start();
625        let mut results = Vec::new();
626
627        // Check the entire format before returning any errors.
628        //
629        // Do the quick checks first, so we don't have to do this in every detailed check.
630        results.push(Self::format_validity_checks_quick(db));
631
632        for upgrade in format_upgrades(None) {
633            results.push(upgrade.validate(db, cancel_receiver)?);
634        }
635
636        // The work is done in the functions we just called.
637        timer.finish(module_path!(), line!(), "format_validity_checks_detailed()");
638
639        if results.iter().any(Result::is_err) {
640            let err = Err(format!("invalid detailed check: {results:?}"));
641            error!(?err);
642            return Ok(err);
643        }
644
645        Ok(Ok(()))
646    }
647
648    /// Mark a newly created database with the current format version.
649    ///
650    /// This should be called when a newly created database is opened.
651    ///
652    /// # Concurrency
653    ///
654    /// The version must only be updated while RocksDB is holding the database
655    /// directory lock. This prevents multiple Zebra instances corrupting the version
656    /// file.
657    ///
658    /// # Panics
659    ///
660    /// If the format should not have been upgraded, because the database is not newly created.
661    fn mark_as_newly_created(db: &ZebraDb) {
662        let running_version = db.format_version_in_code();
663        let disk_version = db
664            .format_version_on_disk()
665            .expect("unable to read database format version file path");
666
667        let default_new_version = Some(Version::new(running_version.major, 0, 0));
668
669        // The database version isn't empty any more, because we've created the RocksDB database
670        // and acquired its lock. (If it is empty, we have a database locking bug.)
671        assert_eq!(
672            disk_version, default_new_version,
673            "can't overwrite the format version in an existing database:\n\
674             disk: {disk_version:?}\n\
675             running: {running_version}"
676        );
677
678        db.update_format_version_on_disk(&running_version)
679            .expect("unable to write database format version file to disk");
680
681        info!(
682            %running_version,
683            disk_version = %disk_version.map_or("None".to_string(), |version| version.to_string()),
684            "marked database format as newly created"
685        );
686    }
687
688    /// Mark the database as upgraded to `format_upgrade_version`.
689    ///
690    /// This should be called when an older database is opened by an older Zebra version,
691    /// after each version upgrade is complete.
692    ///
693    /// # Concurrency
694    ///
695    /// The version must only be updated while RocksDB is holding the database
696    /// directory lock. This prevents multiple Zebra instances corrupting the version
697    /// file.
698    ///
699    /// # Panics
700    ///
701    /// If the format should not have been upgraded, because the running version is:
702    /// - older than the disk version (that's a downgrade)
703    /// - the same as to the disk version (no upgrade needed)
704    ///
705    /// If the format should not have been upgraded, because the format upgrade version is:
706    /// - older or the same as the disk version
707    ///   (multiple upgrades to the same version are not allowed)
708    /// - greater than the running version (that's a logic bug)
709    fn mark_as_upgraded_to(db: &ZebraDb, format_upgrade_version: &Version) {
710        let running_version = db.format_version_in_code();
711        let disk_version = db
712            .format_version_on_disk()
713            .expect("unable to read database format version file")
714            .expect("tried to upgrade a newly created database");
715
716        assert!(
717            running_version > disk_version,
718            "can't upgrade a database that is being opened by an older or the same Zebra version:\n\
719             disk: {disk_version}\n\
720             upgrade: {format_upgrade_version}\n\
721             running: {running_version}"
722        );
723
724        assert!(
725            format_upgrade_version > &disk_version,
726            "can't upgrade a database that has already been upgraded, or is newer:\n\
727             disk: {disk_version}\n\
728             upgrade: {format_upgrade_version}\n\
729             running: {running_version}"
730        );
731
732        assert!(
733            format_upgrade_version <= &running_version,
734            "can't upgrade to a newer version than the running Zebra version:\n\
735             disk: {disk_version}\n\
736             upgrade: {format_upgrade_version}\n\
737             running: {running_version}"
738        );
739
740        db.update_format_version_on_disk(format_upgrade_version)
741            .expect("unable to write database format version file to disk");
742
743        info!(
744            %running_version,
745            %disk_version,
746            // wait_for_state_version_upgrade() needs this to be the last field,
747            // so the regex matches correctly
748            %format_upgrade_version,
749            "marked database format as upgraded"
750        );
751    }
752
753    /// Mark the database as downgraded to the running database version.
754    /// This should be called after a newer database is opened by an older Zebra version.
755    ///
756    /// # Concurrency
757    ///
758    /// The version must only be updated while RocksDB is holding the database
759    /// directory lock. This prevents multiple Zebra instances corrupting the version
760    /// file.
761    ///
762    /// # Panics
763    ///
764    /// If the format should have been upgraded, because the running version is newer.
765    /// If the state is newly created, because the running version should be the same.
766    ///
767    /// Multiple downgrades are allowed, because they all downgrade to the same running version.
768    fn mark_as_downgraded(db: &ZebraDb) {
769        let running_version = db.format_version_in_code();
770        let disk_version = db
771            .format_version_on_disk()
772            .expect("unable to read database format version file")
773            .expect("can't downgrade a newly created database");
774
775        assert!(
776            disk_version >= running_version,
777            "can't downgrade a database that is being opened by a newer Zebra version:\n\
778             disk: {disk_version}\n\
779             running: {running_version}"
780        );
781
782        db.update_format_version_on_disk(&running_version)
783            .expect("unable to write database format version file to disk");
784
785        info!(
786            %running_version,
787            %disk_version,
788            "marked database format as downgraded"
789        );
790    }
791}
792
793impl DbFormatChangeThreadHandle {
794    /// Cancel the running format change thread, if this is the last handle.
795    /// Returns true if it was actually cancelled.
796    pub fn cancel_if_needed(&self) -> bool {
797        // # Correctness
798        //
799        // Checking the strong count has a race condition, because two handles can be dropped at
800        // the same time.
801        //
802        // If cancelling the thread is important, the owner of the handle must call force_cancel().
803        if let Some(update_task) = self.update_task.as_ref() {
804            if Arc::strong_count(update_task) <= 1 {
805                self.force_cancel();
806                return true;
807            }
808        }
809
810        false
811    }
812
813    /// Force the running format change thread to cancel, even if there are other handles.
814    pub fn force_cancel(&self) {
815        // There's nothing we can do about errors here.
816        // If the channel is disconnected, the task has exited.
817        // If it's full, it's already been cancelled.
818        let _ = self.cancel_handle.try_send(CancelFormatChange);
819    }
820
821    /// Check for panics in the code running in the spawned thread.
822    /// If the thread exited with a panic, resume that panic.
823    ///
824    /// This method should be called regularly, so that panics are detected as soon as possible.
825    pub fn check_for_panics(&mut self) {
826        self.update_task.panic_if_task_has_panicked();
827    }
828
829    /// Wait for the spawned thread to finish. If it exited with a panic, resume that panic.
830    ///
831    /// Exits early if the thread has other outstanding handles.
832    ///
833    /// This method should be called during shutdown.
834    pub fn wait_for_panics(&mut self) {
835        self.update_task.wait_for_panics();
836    }
837}
838
839impl Drop for DbFormatChangeThreadHandle {
840    fn drop(&mut self) {
841        // Only cancel the format change if the state service is shutting down.
842        if self.cancel_if_needed() {
843            self.wait_for_panics();
844        } else {
845            self.check_for_panics();
846        }
847    }
848}
849
850#[test]
851fn format_upgrades_are_in_version_order() {
852    let mut last_version = Version::new(0, 0, 0);
853    for upgrade in format_upgrades(None) {
854        assert!(upgrade.version() > last_version);
855        last_version = upgrade.version();
856    }
857}