fix(api): bridge history treats a failed archive read as unresolved
The pre-node history read found all sixteen supply changes and recorded thirteen. Two silent paths dropped mints: a chunk read error read as an empty chunk, and a block_at error discarded a mint already found. The cursor was then saved, so the 0.996, 0.5 and 5,990 QTC deposits stayed unlinked for good. Archive reads are now bounded, with backoff, and log at warn when they give up. Each change is linked, mismatched or unread, and unread changes are retried in later passes. The cursor is saved only once nothing is unread. supply_at no longer retries forever. Migration 0019 clears the cursor so the read runs again. /bridge/deposits and the hash job also skip the fee payer's gas top-ups, which were counted as 337 unlinked deposits. Closes #46 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015tyzzRVjH9AdwGtYwsH5VC
This commit is contained in:
@@ -564,6 +564,18 @@ Every pre-node withdrawal paid exactly 0.002 QTC less (0.998→0.996,
|
||||
#218,636,504) is found by bisecting `ft_total_supply`: 16 changes, 204 archive
|
||||
calls, against a day of block-by-block reads.
|
||||
|
||||
**A failed archive read is unresolved, never empty.** The bridge history read
|
||||
found all sixteen supply changes and recorded thirteen: `if let Ok(..)` around a
|
||||
`chunk` call turned a 429 into "no mint in this chunk", a `let Ok(..) else
|
||||
{ continue }` around `block_at` dropped a mint already found, and the cursor was
|
||||
saved regardless, so the 5,990 QTC mint was lost for good with no log line
|
||||
(#46). The FastNEAR archive 429s most `chunk` and `block` calls, so this is the
|
||||
normal case. Archive reads go through `archive_read`, which is bounded and
|
||||
loud, and a change is linked, mismatched (every read succeeded and nothing
|
||||
sums to it) or unread, and only unread is retried. The opposite mistake is just
|
||||
as bad: a retry with no bound and a `debug` log is a query that can hang
|
||||
forever while looking like progress.
|
||||
|
||||
**A chunk call for a block with no new chunk returns the previous one.**
|
||||
`height_included` is the check; without it a quiet shard's trades are counted
|
||||
once per block until it produces again.
|
||||
|
||||
@@ -26,6 +26,7 @@ use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use blackbeard_core::intents as core;
|
||||
use blackbeard_data::DataError;
|
||||
use blackbeard_data::near::NearClient;
|
||||
use blackbeard_data::store::{BridgeMintRow, BridgeWithdrawalRow, Store};
|
||||
use serde_json::json;
|
||||
@@ -293,40 +294,83 @@ async fn mints(
|
||||
}
|
||||
}
|
||||
|
||||
/// `ft_total_supply` at `height` on the archive, paced and retried. A height
|
||||
/// never produced reads as the block before it.
|
||||
async fn supply_at(near: &NearClient, token: &str, mut height: u64) -> u128 {
|
||||
/// Attempts at one archive read before it is given up for this pass. With the
|
||||
/// backoff in `archive_read` that is about three minutes: FastNEAR's 429s
|
||||
/// clear in seconds, and a read that still fails after that is a read that
|
||||
/// failed, not one to wait on forever (blackbeard/observer#46).
|
||||
const ARCHIVE_ATTEMPTS: u32 = 8;
|
||||
|
||||
/// Between passes over supply changes whose reads failed.
|
||||
const HISTORY_PASS_WAIT: Duration = Duration::from_secs(600);
|
||||
|
||||
/// One archive read, paced, retried with a doubling backoff, and given up
|
||||
/// loudly. A block that was never produced is an answer, not a failure, so
|
||||
/// `unknown` comes straight back for the caller to step past.
|
||||
async fn archive_read<T, F, Fut>(what: &str, height: u64, mut read: F) -> Result<T, DataError>
|
||||
where
|
||||
F: FnMut() -> Fut,
|
||||
Fut: std::future::Future<Output = Result<T, DataError>>,
|
||||
{
|
||||
let mut wait = Duration::from_secs(2);
|
||||
let mut attempt = 1;
|
||||
loop {
|
||||
tokio::time::sleep(ARCHIVE_SPACING).await;
|
||||
match near
|
||||
.view_at(token, "ft_total_supply", json!({}), height)
|
||||
.await
|
||||
{
|
||||
Ok(Some(v)) => {
|
||||
if let Some(n) = v.as_str().and_then(|s| s.parse().ok()) {
|
||||
return n;
|
||||
}
|
||||
tracing::warn!(%token, height, "supply did not parse; retrying");
|
||||
match read().await {
|
||||
Ok(v) => return Ok(v),
|
||||
Err(e) if blackbeard_data::near::unknown(&e) => return Err(e),
|
||||
Err(e) if attempt >= ARCHIVE_ATTEMPTS => {
|
||||
tracing::warn!(read = what, near_height = height, attempts = attempt, error = %e,
|
||||
"archive read failed; left for the next pass");
|
||||
return Err(e);
|
||||
}
|
||||
Ok(None) => height -= 1,
|
||||
Err(e) => {
|
||||
tracing::debug!(%token, height, error = %e, "archive supply read failed; retrying");
|
||||
tokio::time::sleep(RETRY).await;
|
||||
tracing::debug!(read = what, near_height = height, attempt, error = %e,
|
||||
"archive read failed; retrying");
|
||||
tokio::time::sleep(wait).await;
|
||||
wait = (wait * 2).min(Duration::from_secs(60));
|
||||
attempt += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ft_total_supply` at `height` on the archive. A height never produced
|
||||
/// reads as the block before it.
|
||||
async fn supply_at(near: &NearClient, token: &str, mut height: u64) -> Result<u128, DataError> {
|
||||
loop {
|
||||
let read = archive_read("supply", height, || {
|
||||
near.view_at(token, "ft_total_supply", json!({}), height)
|
||||
})
|
||||
.await?;
|
||||
let Some(v) = read else {
|
||||
height -= 1;
|
||||
continue;
|
||||
};
|
||||
return v
|
||||
.as_str()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.ok_or_else(|| DataError::Malformed {
|
||||
method: "ft_total_supply".into(),
|
||||
message: format!("not a decimal string: {v}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Every height in `(a, b]` where the supply changed, with the change.
|
||||
async fn supply_changes(near: &NearClient, token: &str, a: u64, b: u64) -> Vec<(u64, i128)> {
|
||||
async fn supply_changes(
|
||||
near: &NearClient,
|
||||
token: &str,
|
||||
a: u64,
|
||||
b: u64,
|
||||
) -> Result<Vec<(u64, i128)>, DataError> {
|
||||
let mut out = Vec::new();
|
||||
// Explicit stack rather than recursion: async recursion needs boxing, and
|
||||
// the depth is the log of the span anyway.
|
||||
let mut todo = vec![(
|
||||
a,
|
||||
supply_at(near, token, a).await,
|
||||
supply_at(near, token, a).await?,
|
||||
b,
|
||||
supply_at(near, token, b).await,
|
||||
supply_at(near, token, b).await?,
|
||||
)];
|
||||
while let Some((lo, s_lo, hi, s_hi)) = todo.pop() {
|
||||
if s_lo == s_hi {
|
||||
@@ -337,15 +381,23 @@ async fn supply_changes(near: &NearClient, token: &str, a: u64, b: u64) -> Vec<(
|
||||
continue;
|
||||
}
|
||||
let mid = lo + (hi - lo) / 2;
|
||||
let s_mid = supply_at(near, token, mid).await;
|
||||
let s_mid = supply_at(near, token, mid).await?;
|
||||
todo.push((mid, s_mid, hi, s_hi));
|
||||
todo.push((lo, s_lo, mid, s_mid));
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Mints and withdrawals from before our nodes' history, once.
|
||||
///
|
||||
/// Every supply change ends in one of three states, and only the third is
|
||||
/// retried: linked; mismatched, where every read succeeded and what was found
|
||||
/// still does not account for the change (logged, left unlinked); or unread,
|
||||
/// where a read failed. A failed read is never taken as "nothing there" — that
|
||||
/// is how three mints, 5,990 QTC among them, were dropped while the cursor
|
||||
/// said the history was read (blackbeard/observer#46). The cursor is saved
|
||||
/// only once nothing is left unread.
|
||||
async fn history(
|
||||
chain: Arc<ChainRuntime>,
|
||||
store: Store,
|
||||
@@ -374,38 +426,96 @@ async fn history(
|
||||
};
|
||||
let from = intents.start_height;
|
||||
tracing::info!(chain = %id, from, horizon, "reading the bridge's history before our nodes");
|
||||
let changes = supply_changes(&archive, &token, from, horizon).await;
|
||||
tracing::info!(chain = %id, changes = changes.len(), "supply changes found before our nodes");
|
||||
let mut pending = loop {
|
||||
match supply_changes(&archive, &token, from, horizon).await {
|
||||
Ok(changes) => break changes,
|
||||
Err(e) => {
|
||||
tracing::warn!(chain = %id, error = %e,
|
||||
"bridge supply bisection failed; retrying after a pause");
|
||||
tokio::time::sleep(HISTORY_PASS_WAIT).await;
|
||||
}
|
||||
}
|
||||
};
|
||||
tracing::info!(chain = %id, changes = pending.len(), "supply changes found before our nodes");
|
||||
|
||||
for (height, delta) in changes {
|
||||
let reader = HistoryReader {
|
||||
id: &id,
|
||||
store: &store,
|
||||
archive: &archive,
|
||||
bridge: &bridge,
|
||||
intents: &intents,
|
||||
token: &token,
|
||||
};
|
||||
let (mut linked, mut mismatched) = (0usize, 0usize);
|
||||
for pass in 1u32.. {
|
||||
let mut unread = Vec::new();
|
||||
for (height, delta) in pending {
|
||||
match reader.resolve(height, delta).await {
|
||||
Ok(true) => linked += 1,
|
||||
Ok(false) => mismatched += 1,
|
||||
Err(e) => {
|
||||
tracing::warn!(chain = %id, near_height = height, delta, error = %e,
|
||||
"bridge supply change unread; will retry");
|
||||
unread.push((height, delta));
|
||||
}
|
||||
}
|
||||
}
|
||||
tracing::info!(chain = %id, pass, linked, mismatched, unread = unread.len(),
|
||||
"bridge history pass");
|
||||
if unread.is_empty() {
|
||||
break;
|
||||
}
|
||||
pending = unread;
|
||||
tokio::time::sleep(HISTORY_PASS_WAIT).await;
|
||||
}
|
||||
if let Err(e) = store.set_intents_scan(&id, &key, from, horizon).await {
|
||||
tracing::warn!(chain = %id, error = %e, "bridge history cursor not saved");
|
||||
}
|
||||
tracing::info!(chain = %id, linked, mismatched, "bridge history before our nodes read");
|
||||
}
|
||||
|
||||
/// What one supply change needs to be read.
|
||||
struct HistoryReader<'a> {
|
||||
id: &'a blackbeard_entities::ChainId,
|
||||
store: &'a Store,
|
||||
archive: &'a NearClient,
|
||||
bridge: &'a BridgeConfig,
|
||||
intents: &'a IntentsConfig,
|
||||
token: &'a str,
|
||||
}
|
||||
|
||||
impl HistoryReader<'_> {
|
||||
/// Link one supply change to the mints or withdrawals that made it.
|
||||
/// `Ok(true)` recorded, `Ok(false)` every read succeeded and nothing
|
||||
/// accounts for it, `Err` a read failed and the change is unresolved.
|
||||
async fn resolve(&self, height: u64, delta: i128) -> Result<bool, DataError> {
|
||||
let (id, archive) = (self.id, self.archive);
|
||||
// A change can be recorded at a skipped height (the supply read falls
|
||||
// back to the block before), so walk down past any that were never
|
||||
// produced rather than asking about the same one forever.
|
||||
let mut at = height;
|
||||
let layout = loop {
|
||||
tokio::time::sleep(ARCHIVE_SPACING).await;
|
||||
match archive.shard_layout(at).await {
|
||||
match archive_read("layout", at, || archive.shard_layout(at)).await {
|
||||
Ok(l) => break l,
|
||||
Err(e) if blackbeard_data::near::unknown(&e) && at + LOOKBACK > height => at -= 1,
|
||||
Err(e) => {
|
||||
tracing::debug!(chain = %id, near_height = at, error = %e,
|
||||
"archive layout unreadable; retrying");
|
||||
tokio::time::sleep(RETRY).await
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
};
|
||||
let shard_of = |a: &str| core::shard_for(a, &layout.boundary_accounts, &layout.shard_ids);
|
||||
let window = height.saturating_sub(LOOKBACK)..=height;
|
||||
if delta > 0 {
|
||||
let Some(shard) = shard_of(&bridge.near_minter) else {
|
||||
continue;
|
||||
let Some(shard) = shard_of(&self.bridge.near_minter) else {
|
||||
tracing::error!(chain = %id, near_height = height, minter = %self.bridge.near_minter,
|
||||
"minter maps to no shard; supply rise not linked");
|
||||
return Ok(false);
|
||||
};
|
||||
let mut found: Vec<(u64, String, blackbeard_core::bridge::NearMint)> = Vec::new();
|
||||
for h in window {
|
||||
tokio::time::sleep(ARCHIVE_SPACING).await;
|
||||
if let Ok(Some(chunk)) = archive.chunk(h, shard, u64::MAX).await {
|
||||
if let Some(chunk) =
|
||||
archive_read("chunk", h, || archive.chunk(h, shard, u64::MAX)).await?
|
||||
{
|
||||
found.extend(
|
||||
mints_in(&chunk, &bridge)
|
||||
mints_in(&chunk, self.bridge)
|
||||
.into_iter()
|
||||
.map(|(t, m)| (h, t, m)),
|
||||
);
|
||||
@@ -415,14 +525,11 @@ async fn history(
|
||||
if total as i128 != delta {
|
||||
tracing::warn!(chain = %id, near_height = height, delta, found = total,
|
||||
"mints around a supply rise do not sum to it; not linked");
|
||||
continue;
|
||||
return Ok(false);
|
||||
}
|
||||
let mut rows = Vec::new();
|
||||
for (h, tx_hash, m) in found {
|
||||
tokio::time::sleep(ARCHIVE_SPACING).await;
|
||||
let Ok((_, at)) = archive.block_at(json!(h)).await else {
|
||||
continue;
|
||||
};
|
||||
let (_, at) = archive_read("block", h, || archive.block_at(json!(h))).await?;
|
||||
rows.push(BridgeMintRow {
|
||||
near_height: h,
|
||||
tx_hash,
|
||||
@@ -432,37 +539,42 @@ async fn history(
|
||||
quantus_tx: m.quantus_tx,
|
||||
});
|
||||
}
|
||||
if let Err(e) = store.record_bridge_mints(&id, &rows).await {
|
||||
tracing::warn!(chain = %id, error = %e, "historical mints not recorded");
|
||||
self.store.record_bridge_mints(id, &rows).await?;
|
||||
for r in &rows {
|
||||
tracing::info!(chain = %id, near_height = r.near_height, quantus_tx = %r.quantus_tx,
|
||||
account = %r.account, "historical QTC mint linked");
|
||||
}
|
||||
} else {
|
||||
let Some(shard) = shard_of(&intents.contract) else {
|
||||
continue;
|
||||
let contract = &self.intents.contract;
|
||||
let Some(shard) = shard_of(contract) else {
|
||||
tracing::error!(chain = %id, near_height = height, %contract,
|
||||
"intents contract maps to no shard; supply fall not linked");
|
||||
return Ok(false);
|
||||
};
|
||||
let mut rows = Vec::new();
|
||||
for h in window {
|
||||
tokio::time::sleep(ARCHIVE_SPACING).await;
|
||||
let Ok(Some(chunk)) = archive.chunk(h, shard, u64::MAX).await else {
|
||||
let Some(chunk) =
|
||||
archive_read("chunk", h, || archive.chunk(h, shard, u64::MAX)).await?
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
for tx in chunk
|
||||
.transactions
|
||||
.iter()
|
||||
.filter(|t| t.receiver_id == intents.contract && t.calls("execute_intents"))
|
||||
.filter(|t| &t.receiver_id == contract && t.calls("execute_intents"))
|
||||
{
|
||||
tokio::time::sleep(ARCHIVE_SPACING).await;
|
||||
let Ok(outcomes) = archive.tx_outcomes(&tx.hash, &tx.signer_id).await else {
|
||||
continue;
|
||||
};
|
||||
let outcomes = archive_read("outcomes", h, || {
|
||||
archive.tx_outcomes(&tx.hash, &tx.signer_id)
|
||||
})
|
||||
.await?;
|
||||
for o in outcomes
|
||||
.iter()
|
||||
.filter(|o| o.executor_id == intents.contract && o.succeeded)
|
||||
.filter(|o| &o.executor_id == contract && o.succeeded)
|
||||
{
|
||||
for w in blackbeard_core::bridge::near_withdrawals(&o.logs, &token) {
|
||||
tokio::time::sleep(ARCHIVE_SPACING).await;
|
||||
let Ok((_, at)) = archive.block_at(json!(o.block_hash)).await else {
|
||||
continue;
|
||||
};
|
||||
for w in blackbeard_core::bridge::near_withdrawals(&o.logs, self.token) {
|
||||
let (_, at) =
|
||||
archive_read("block", h, || archive.block_at(json!(o.block_hash)))
|
||||
.await?;
|
||||
rows.push(BridgeWithdrawalRow {
|
||||
near_height: h,
|
||||
tx_hash: tx.hash.clone(),
|
||||
@@ -476,15 +588,19 @@ async fn history(
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Err(e) = store.record_bridge_withdrawals(&id, &rows).await {
|
||||
tracing::warn!(chain = %id, error = %e, "historical withdrawals not recorded");
|
||||
let total: u128 = rows
|
||||
.iter()
|
||||
.filter_map(|r| r.amount.parse::<u128>().ok())
|
||||
.sum();
|
||||
if total as i128 != -delta {
|
||||
tracing::warn!(chain = %id, near_height = height, delta, found = total,
|
||||
"withdrawals around a supply fall do not sum to it; not linked");
|
||||
return Ok(false);
|
||||
}
|
||||
self.store.record_bridge_withdrawals(id, &rows).await?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
if let Err(e) = store.set_intents_scan(&id, &key, from, horizon).await {
|
||||
tracing::warn!(chain = %id, error = %e, "bridge history cursor not saved");
|
||||
}
|
||||
tracing::info!(chain = %id, "bridge history before our nodes read");
|
||||
}
|
||||
|
||||
/// Hash the transfers into deposit addresses that were indexed without one.
|
||||
@@ -525,7 +641,12 @@ async fn hashes(chain: Arc<ChainRuntime>, store: Store, bridge: BridgeConfig) {
|
||||
let Ok(into) = store.transfers_into(&id, &addresses).await else {
|
||||
continue;
|
||||
};
|
||||
for t in into.iter().filter(|t| t.hash.is_none()) {
|
||||
// The fee payer's funding of a deposit address is never minted against,
|
||||
// so its hash links nothing and is not worth a body fetch.
|
||||
for t in into
|
||||
.iter()
|
||||
.filter(|t| t.hash.is_none() && t.from != fee_payer)
|
||||
{
|
||||
let Some(index) = t.extrinsic_index else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -2186,7 +2186,8 @@ async fn bridge_deposits(
|
||||
) -> Result<Json<blackbeard_entities::BridgeDeposits>, Failure> {
|
||||
let runtime = state.chain(&chain).ok_or_else(|| unknown_chain(&chain))?;
|
||||
let id = runtime.id();
|
||||
let (_, movements, _) = bridge_movements(&state, &runtime).await?;
|
||||
let (config, movements, _) = bridge_movements(&state, &runtime).await?;
|
||||
let fee_payer = config.fee_payer_hex();
|
||||
let sweeps: Vec<&blackbeard_core::bridge::Movement> = movements
|
||||
.iter()
|
||||
.filter(|m| m.kind == blackbeard_core::bridge::Kind::Deposit)
|
||||
@@ -2215,7 +2216,9 @@ async fn bridge_deposits(
|
||||
.and_then(blackbeard_core::wormhole::account_id);
|
||||
let mut deposits: Vec<blackbeard_entities::BridgeDeposit> = into
|
||||
.iter()
|
||||
.filter(|t| t.from != t.to)
|
||||
// The fee payer funds each deposit address before it sweeps; that is
|
||||
// the bridge paying gas, not anyone depositing.
|
||||
.filter(|t| t.from != t.to && fee_payer.as_ref() != Some(&t.from))
|
||||
.map(|t| {
|
||||
let mint = t.hash.as_ref().and_then(|h| mints.get(h));
|
||||
let swept = sweeps
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
-- Read the bridge's pre-node history again. blackbeard/observer#46.
|
||||
--
|
||||
-- The first read found all sixteen supply changes and recorded thirteen: an
|
||||
-- archive read that failed (FastNEAR answering 429) was taken as "no mint
|
||||
-- here", or dropped a mint already found, and the cursor was saved anyway.
|
||||
-- The three it lost are the 0.996, 0.5 and 5,990 QTC deposits, which is why
|
||||
-- they list unlinked. The read now treats a failed read as unresolved and
|
||||
-- saves the cursor only when nothing is; clearing it here makes it run once
|
||||
-- more. The inserts are `on conflict do nothing`, so what it already
|
||||
-- recorded is untouched.
|
||||
delete from intents_scan where asset like 'bridge-history:%';
|
||||
Reference in New Issue
Block a user