Skip to content

Commit 5c5c381

Browse files
Scanner: backfill the deferred secondary history after fast catch-up (#2167)
* feat(scanner): backfill deferred secondary history after catch-up * fix(scanner): address backfill review findings * fix(scanner): seed the history watermark on the upgrade path
1 parent 1ef6272 commit 5c5c381

10 files changed

Lines changed: 1025 additions & 24 deletions

File tree

‎api-server/CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@ All notable changes to the API server will be documented in this file.
44

55
The format is loosely based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
66

7+
## [Unreleased]
8+
9+
### Fixed
10+
- The scanner's fast catch-up mode no longer leaves the address and token transaction history permanently incomplete: a backfill pass now rebuilds the deferred history rows from the locally stored blocks after catching up, without touching balances or UTXOs. Databases written by builds predating the history watermark are seeded at startup so their history is rebuilt too.
11+
712
## [1.4.5] - 2026-11-10
813

914
### Fixed

‎api-server/api-server-common/src/storage/impls/in_memory/mod.rs‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ struct ApiServerInMemoryStorage {
101101
genesis_block: Arc<WithId<Genesis>>,
102102
number_of_coin_decimals: u8,
103103
storage_version: u32,
104+
secondary_indexed_height: Option<BlockHeight>,
104105
// kept so that order/pool identifiers can be encoded exactly like the postgres
105106
// backend does (bech32 address strings), keeping tie-break orders identical
106107
chain_config: ChainConfig,
@@ -131,6 +132,7 @@ impl ApiServerInMemoryStorage {
131132
genesis_block: chain_config.genesis_block().clone(),
132133
number_of_coin_decimals: chain_config.coin_decimals(),
133134
storage_version: CURRENT_STORAGE_VERSION,
135+
secondary_indexed_height: None,
134136
chain_config: chain_config.clone(),
135137
}
136138
}
@@ -406,6 +408,37 @@ impl ApiServerInMemoryStorage {
406408
Ok(version_table_handle)
407409
}
408410

411+
fn secondary_indexed_height(&self) -> Result<Option<BlockHeight>, ApiServerStorageError> {
412+
Ok(self.secondary_indexed_height)
413+
}
414+
415+
fn get_block_transaction_indices(
416+
&self,
417+
block_height: BlockHeight,
418+
) -> Result<Vec<(Id<Transaction>, u64)>, ApiServerStorageError> {
419+
let Some(block_id) = self.main_chain_blocks_table.get(&block_height) else {
420+
return Ok(Vec::new());
421+
};
422+
Ok(self
423+
.ordered_transaction_table
424+
.iter()
425+
.filter(|(_, tx_id)| {
426+
self.transaction_table
427+
.get(*tx_id)
428+
.is_some_and(|(owning_block_id, _)| owning_block_id == block_id)
429+
})
430+
.map(|(index, tx_id)| (*tx_id, *index))
431+
.collect())
432+
}
433+
434+
fn set_secondary_indexed_height(
435+
&mut self,
436+
block_height: BlockHeight,
437+
) -> Result<(), ApiServerStorageError> {
438+
self.secondary_indexed_height = Some(block_height);
439+
Ok(())
440+
}
441+
409442
fn get_best_block(&self) -> Result<BlockAuxData, ApiServerStorageError> {
410443
let result = self.main_chain_blocks_table.last_key_value().map_or_else(
411444
|| {

‎api-server/api-server-common/src/storage/impls/in_memory/transactional/read.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,17 @@ impl ApiServerStorageRead for ApiServerInMemoryStorageTransactionalRo<'_> {
215215
self.transaction.get_best_block()
216216
}
217217

218+
async fn secondary_indexed_height(&self) -> Result<Option<BlockHeight>, ApiServerStorageError> {
219+
self.transaction.secondary_indexed_height()
220+
}
221+
222+
async fn get_block_transaction_indices(
223+
&self,
224+
block_height: BlockHeight,
225+
) -> Result<Vec<(Id<Transaction>, u64)>, ApiServerStorageError> {
226+
self.transaction.get_block_transaction_indices(block_height)
227+
}
228+
218229
async fn get_block_aux_data(
219230
&self,
220231
block_id: Id<Block>,

‎api-server/api-server-common/src/storage/impls/in_memory/transactional/write.rs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,13 @@ use super::ApiServerInMemoryStorageTransactionalRw;
3636

3737
#[async_trait::async_trait]
3838
impl ApiServerStorageWrite for ApiServerInMemoryStorageTransactionalRw<'_> {
39+
async fn set_secondary_indexed_height(
40+
&mut self,
41+
block_height: BlockHeight,
42+
) -> Result<(), ApiServerStorageError> {
43+
self.transaction.set_secondary_indexed_height(block_height)
44+
}
45+
3946
async fn reinitialize_storage(
4047
&mut self,
4148
chain_config: &ChainConfig,
@@ -381,6 +388,17 @@ impl ApiServerStorageRead for ApiServerInMemoryStorageTransactionalRw<'_> {
381388
self.transaction.get_best_block()
382389
}
383390

391+
async fn secondary_indexed_height(&self) -> Result<Option<BlockHeight>, ApiServerStorageError> {
392+
self.transaction.secondary_indexed_height()
393+
}
394+
395+
async fn get_block_transaction_indices(
396+
&self,
397+
block_height: BlockHeight,
398+
) -> Result<Vec<(Id<Transaction>, u64)>, ApiServerStorageError> {
399+
self.transaction.get_block_transaction_indices(block_height)
400+
}
401+
384402
async fn get_block(
385403
&self,
386404
block_id: Id<Block>,

‎api-server/api-server-common/src/storage/impls/postgres/queries.rs‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1651,6 +1651,92 @@ impl<'a, 'b> QueryFromConnection<'a, 'b> {
16511651
Ok(())
16521652
}
16531653

1654+
/// The height through which the secondary history tables are complete;
1655+
/// `None` when no fast catch-up has deferred them. See the scanner-lib
1656+
/// backfill pass.
1657+
pub async fn secondary_indexed_height(
1658+
&mut self,
1659+
) -> Result<Option<BlockHeight>, ApiServerStorageError> {
1660+
let row = self
1661+
.tx
1662+
.query_opt(
1663+
"SELECT value FROM ml.misc_data WHERE name = 'secondary_indexed_height';",
1664+
&[],
1665+
)
1666+
.await
1667+
.map_err(|e| ApiServerStorageError::LowLevelStorageError(e.to_string()))?;
1668+
1669+
let Some(bytes) = row.map(|row| row.get::<_, Vec<u8>>(0)) else {
1670+
return Ok(None);
1671+
};
1672+
let bytes: [u8; 8] = bytes.try_into().map_err(|_| {
1673+
ApiServerStorageError::DeserializationError(
1674+
"Invalid secondary indexed height stored in the database".to_owned(),
1675+
)
1676+
})?;
1677+
Ok(Some(BlockHeight::new(u64::from_be_bytes(bytes))))
1678+
}
1679+
1680+
/// Records the height through which the secondary history tables are
1681+
/// complete.
1682+
pub async fn set_secondary_indexed_height(
1683+
&mut self,
1684+
block_height: BlockHeight,
1685+
) -> Result<(), ApiServerStorageError> {
1686+
let bytes = u64::to_be_bytes(block_height.into_int()).to_vec();
1687+
self.tx
1688+
.execute(
1689+
"INSERT INTO ml.misc_data (name, value) VALUES ('secondary_indexed_height', $1)
1690+
ON CONFLICT (name) DO UPDATE SET value = EXCLUDED.value;",
1691+
&[&bytes],
1692+
)
1693+
.await
1694+
.map_err(|e| ApiServerStorageError::LowLevelStorageError(e.to_string()))?;
1695+
Ok(())
1696+
}
1697+
1698+
/// The `(transaction id, global index)` pairs of all transactions owned by
1699+
/// the main-chain block at `block_height`, ascending by index.
1700+
pub async fn get_block_transaction_indices(
1701+
&mut self,
1702+
block_height: BlockHeight,
1703+
) -> Result<Vec<(Id<Transaction>, u64)>, ApiServerStorageError> {
1704+
let height = Self::block_height_to_postgres_friendly(block_height);
1705+
let rows = self
1706+
.tx
1707+
.query(
1708+
"SELECT t.transaction_id, t.tx_global_index
1709+
FROM ml.transactions t
1710+
JOIN ml.blocks b ON t.owning_block_id = b.block_id
1711+
WHERE b.block_height = $1
1712+
ORDER BY t.tx_global_index ASC;",
1713+
&[&height],
1714+
)
1715+
.await
1716+
.map_err(|e| ApiServerStorageError::LowLevelStorageError(e.to_string()))?;
1717+
1718+
let mut result = Vec::with_capacity(rows.len());
1719+
for row in rows {
1720+
let tx_id_bytes: Vec<u8> = row.get(0);
1721+
let index: i64 = row.get(1);
1722+
let tx_id =
1723+
Id::<Transaction>::decode_all(&mut tx_id_bytes.as_slice()).map_err(|_| {
1724+
ApiServerStorageError::DeserializationError(
1725+
"Invalid transaction id in transactions table".to_owned(),
1726+
)
1727+
})?;
1728+
result.push((
1729+
tx_id,
1730+
u64::try_from(index).map_err(|_| {
1731+
ApiServerStorageError::DeserializationError(
1732+
"Invalid transaction global index".to_owned(),
1733+
)
1734+
})?,
1735+
));
1736+
}
1737+
Ok(result)
1738+
}
1739+
16541740
pub async fn initialize_database(
16551741
&mut self,
16561742
chain_config: &ChainConfig,

‎api-server/api-server-common/src/storage/impls/postgres/transactional/read.rs‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515

1616
use common::{
1717
chain::{
18-
DelegationId, Destination, OrderId, PoolId, block::timestamp::BlockTimestamp,
18+
DelegationId, Destination, OrderId, PoolId, Transaction, block::timestamp::BlockTimestamp,
1919
tokens::TokenId,
2020
},
2121
primitives::{Amount, BlockHeight, CoinOrTokenId, Id},
@@ -143,6 +143,25 @@ impl ApiServerStorageRead for ApiServerPostgresTransactionalRo<'_> {
143143
Ok(res)
144144
}
145145

146+
async fn secondary_indexed_height(&self) -> Result<Option<BlockHeight>, ApiServerStorageError> {
147+
let mut conn =
148+
QueryFromConnection::new(self.connection.as_ref().expect(CONN_ERR), &self.statements);
149+
let res = conn.secondary_indexed_height().await?;
150+
151+
Ok(res)
152+
}
153+
154+
async fn get_block_transaction_indices(
155+
&self,
156+
block_height: BlockHeight,
157+
) -> Result<Vec<(Id<Transaction>, u64)>, ApiServerStorageError> {
158+
let mut conn =
159+
QueryFromConnection::new(self.connection.as_ref().expect(CONN_ERR), &self.statements);
160+
let res = conn.get_block_transaction_indices(block_height).await?;
161+
162+
Ok(res)
163+
}
164+
146165
async fn get_block(
147166
&self,
148167
block_id: Id<common::chain::Block>,

‎api-server/api-server-common/src/storage/impls/postgres/transactional/write.rs‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,15 @@ use super::{ApiServerPostgresTransactionalRw, CONN_ERR};
4141

4242
#[async_trait::async_trait]
4343
impl ApiServerStorageWrite for ApiServerPostgresTransactionalRw<'_> {
44+
async fn set_secondary_indexed_height(
45+
&mut self,
46+
block_height: BlockHeight,
47+
) -> Result<(), ApiServerStorageError> {
48+
let mut conn =
49+
QueryFromConnection::new(self.connection.as_ref().expect(CONN_ERR), &self.statements);
50+
conn.set_secondary_indexed_height(block_height).await
51+
}
52+
4453
async fn reinitialize_storage(
4554
&mut self,
4655
chain_config: &ChainConfig,
@@ -578,6 +587,25 @@ impl ApiServerStorageRead for ApiServerPostgresTransactionalRw<'_> {
578587
Ok(res)
579588
}
580589

590+
async fn secondary_indexed_height(&self) -> Result<Option<BlockHeight>, ApiServerStorageError> {
591+
let mut conn =
592+
QueryFromConnection::new(self.connection.as_ref().expect(CONN_ERR), &self.statements);
593+
let res = conn.secondary_indexed_height().await?;
594+
595+
Ok(res)
596+
}
597+
598+
async fn get_block_transaction_indices(
599+
&self,
600+
block_height: BlockHeight,
601+
) -> Result<Vec<(Id<Transaction>, u64)>, ApiServerStorageError> {
602+
let mut conn =
603+
QueryFromConnection::new(self.connection.as_ref().expect(CONN_ERR), &self.statements);
604+
let res = conn.get_block_transaction_indices(block_height).await?;
605+
606+
Ok(res)
607+
}
608+
581609
async fn get_block(
582610
&self,
583611
block_id: Id<Block>,

‎api-server/api-server-common/src/storage/storage_api/mod.rs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -666,6 +666,21 @@ pub trait ApiServerStorageRead: Sync {
666666

667667
async fn get_best_block(&self) -> Result<BlockAuxData, ApiServerStorageError>;
668668

669+
/// The height through which the secondary history tables (address and
670+
/// token transaction listings) are known to be complete. `None` means no
671+
/// scan has deferred them, i.e. they are complete wherever they exist.
672+
/// See `set_secondary_indexed_height`.
673+
async fn secondary_indexed_height(&self) -> Result<Option<BlockHeight>, ApiServerStorageError>;
674+
675+
/// The transaction global indices of all transactions whose owning block
676+
/// is the main-chain block at `block_height`, in ascending index order.
677+
/// Used by the secondary-index backfill to stamp token transaction rows
678+
/// with the same indices the live scan assigned.
679+
async fn get_block_transaction_indices(
680+
&self,
681+
block_height: BlockHeight,
682+
) -> Result<Vec<(Id<Transaction>, u64)>, ApiServerStorageError>;
683+
669684
async fn get_latest_blocktimestamps(
670685
&self,
671686
) -> Result<Vec<BlockTimestamp>, ApiServerStorageError>;
@@ -949,6 +964,15 @@ pub trait ApiServerStorageWrite: ApiServerStorageRead {
949964
block_height: BlockHeight,
950965
) -> Result<(), ApiServerStorageError>;
951966

967+
/// Records that the secondary history tables are complete through
968+
/// `block_height` inclusive. Maintained by the scan (lagging while fast
969+
/// catch-up defers history rows) and by the backfill pass; rolled back on
970+
/// reorg disconnects together with the rows it describes.
971+
async fn set_secondary_indexed_height(
972+
&mut self,
973+
block_height: BlockHeight,
974+
) -> Result<(), ApiServerStorageError>;
975+
952976
/// Stores the balance under the string encoding carried by the given address:
953977
/// scanning constructs addresses via `Address::new`, so the stored encoding is
954978
/// the canonical one, which the byte-ordered tie-break comparison of the

0 commit comments

Comments
 (0)