fix(restore): keep the legacy restore snapshot when filing it under its node fails

Open
#856 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
78/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
rust, sqlite

Research direction

Start with rust/src/api/orders.rs, especially migrate_unnamed_restore_snapshot and file_unnamed_restore_snapshot, then inspect the existing orders tests using throwaway_store(). Add failure-path coverage for get_setting and set_setting, verify the legacy key survives and is retried, and update specs/004-mostro-p2p-client/contracts/identity.md. Run cargo test and cargo clippy -- -D warnings.

Written by the indexing model from the issue text.

Description

Follow-up to #812 / PR #841, found in its round-2 review. The code below is introduced by #841 (commit 44520537), so this can only be done once #841 is merged.

Context

Before #812, a restore stored a single snapshot (floor + live order ids) under the settings key restore_snapshot, and that snapshot did not say which node answered. #841 keeps one snapshot per node (restore_snapshot:<node>) and migrates the old one with migrate_unnamed_restore_snapshot (rust/src/api/orders.rs):

  • every row of its live orders names the same node → file_unnamed_restore_snapshot stores it under that node's key, unless the node already has its own;
  • otherwise → it is dropped;
  • in both cases the legacy restore_snapshot key is then deleted.

The migration runs at start, in _run_order_subscription before seed_global_dm_coverage() opens the kind-14 feed, so the feed's replay finds the snapshot already filed and rebuilds nothing it hid. The history pass (reconcile_restored_history, 60 s after start, then every 30 min) runs it too if the legacy key is still there.

Problem

file_unnamed_restore_snapshot returns false in two cases the caller cannot tell apart:

Case Today Should the legacy key go?
The node already has its own snapshot (get_setting → Ok(Some(_))) false Yes, the node's own snapshot is newer
The node's key cannot be read (get_setting → Err) false No
serde_json::to_string fails false No
set_setting fails false No

migrate_unnamed_restore_snapshot deletes restore_snapshot whatever filed is:

let filed = match named {
    Some(snapshot) => file_unnamed_restore_snapshot(db, &snapshot).await,
    None => false,
};
match db.delete_setting(key).await {
    Ok(()) if !filed => /* logs "restore snapshot without its node dropped" */,
    ...
}

So after a database error during the one start that migrates, the only copy of the snapshot is lost:

  1. The kind-14 feed opens right after and replays the whole history. With no snapshot for that node, unwritten_row_state reads those orders as never written, and rebuild_trade_from_dm rebuilds their rows.
  2. visible_trades does not hide them and the history pass does not drop them, because no snapshot exists for their node.
  3. Nothing retries: the history pass looks for the legacy key and no longer finds it.

My Trades fills back up with the history #614 hid. That lasts until the user runs Account → Refresh on that node, and nothing tells the user to do it. On top of that, the log is misleading: a failed write logs the warning and then restore snapshot without its node dropped, which reads like a deliberate decision.

This also breaks the rule restore_snapshot_to_settle follows a few lines below: "One that cannot be read is left for the next pass."

Likelihood: low. It needs a storage error at exactly that start, for example SQLite with a full disk or a locked database, or IndexedDB over quota or with an aborted transaction on web. But the loss is permanent and silent, and it brings back the exact outcome the migration exists to prevent.

Proposed fix

Let file_unnamed_restore_snapshot tell "not filed" from "failed", and keep the legacy key on failure:

/// Store the legacy `snapshot`, now naming its node, under that node's key,
/// unless the node already has a snapshot of its own (`Ok(false)`). An
/// error leaves the legacy key for the next pass.
async fn file_unnamed_restore_snapshot(
    db: &impl Storage,
    snapshot: &crate::mostro::restore_history::RestoreSnapshot,
) -> anyhow::Result<bool> {
    let Some(node) = snapshot.node.as_deref() else {
        return Ok(false);
    };
    let key = crate::db::settings_keys::restore_snapshot(node);
    if db.get_setting(&key).await?.is_some() {
        return Ok(false);
    }
    db.set_setting(&key, &serde_json::to_string(snapshot)?).await?;
    crate::api::logging::blog_info(
        "restore",
        format!(
            "restore snapshot without its node filed under node={}",
            crate::api::logging::short_id(node)
        ),
    );
    Ok(true)
}
let filed = match named {
    Some(snapshot) => match file_unnamed_restore_snapshot(db, &snapshot).await {
        Ok(filed) => filed,
        // Deleted now, it would be lost: kept for the next pass.
        Err(e) => {
            log::warn!("[restore] restore snapshot without its node not filed, kept: {e}");
            return;
        }
    },
    None => false,
};

With the key kept, recovery is automatic:

  • The history pass, 60 s later, runs the migration again (it is called from reconcile_restored_history). If filing now works, the same pass settles that node's rows with the filed snapshot, and the rows the replay rebuilt are dropped as history.
  • The next start retries too, before the feed opens.

An unreadable legacy snapshot (serde_json::from_str fails) or one whose live rows do not name a single node can still be dropped: nothing can ever file it, so keeping it would only retry forever.

Tests

Following the quality bar: a test: commit that fails before the fix.

  • a_legacy_snapshot_is_kept_when_it_cannot_be_filed: a Storage that wraps the throwaway SQLite store (throwaway_store() in the orders.rs tests) and fails for RESTORE_SNAPSHOT_PREFIX keys. Cover both a failing set_setting and a failing get_setting, or add a variant to PersistProbe. After migrate_unnamed_restore_snapshot, assert:
    • the legacy restore_snapshot key is still there;
    • no restore_snapshot:<node> key was written.
  • Then, with the failure removed, a second migrate_unnamed_restore_snapshot files it under the node and deletes the legacy key, as a_legacy_snapshot_is_filed_under_the_node_of_its_live_rows expects.
  • a_legacy_snapshot_never_replaces_a_nodes_own and a_legacy_snapshot_of_an_unknown_node_is_dropped keep passing unchanged: a node with its own snapshot, or an unknown node, still drops the legacy key.

Acceptance criteria

  • A storage error while filing the legacy snapshot leaves restore_snapshot in place, and the log says it was kept, not dropped.
  • The next history pass or start files it once storage works, and settles that node's rows the same pass.
  • A node that already has its own snapshot, an unknown node and an unreadable snapshot behave as today (legacy key dropped).
  • Red test first, then the fix; cargo test and cargo clippy -- -D warnings pass.
  • specs/004-mostro-p2p-client/contracts/identity.md (the legacy snapshot paragraph) says that a failed migration keeps the snapshot for the next pass.
Dominant language
Dart
Stars
11
Forks
9
Avg merge
2d 1h
Merged PRs (30d)
16

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from MostroP2P/app

All issues in MostroP2P/app

Similar issues

More Dart issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.