diff --git a/triedb/pathdb/database.go b/triedb/pathdb/database.go index 7c8c327484..23a7d383b5 100644 --- a/triedb/pathdb/database.go +++ b/triedb/pathdb/database.go @@ -520,6 +520,16 @@ func (db *Database) Enable(root common.Hash) error { // Re-construct a new disk layer backed by persistent state // and schedule the state snapshot generation if it's permitted. db.tree.init(generateSnapshot(db, root, db.isVerkle || db.config.SnapshotNoBuild)) + + // After snap sync, the state of the database may have changed completely. + // To ensure the history indexer always matches the current state, we must: + // 1. Close any existing indexer + // 2. Re-initialize the indexer so it starts indexing from the new state root. + if db.indexer != nil && db.freezer != nil && db.config.EnableStateIndexing { + db.indexer.close() + db.indexer = newHistoryIndexer(db.diskdb, db.freezer, db.tree.bottom().stateID()) + log.Info("Re-enabled state history indexing") + } log.Info("Rebuilt trie database", "root", root) return nil } diff --git a/triedb/pathdb/history_indexer.go b/triedb/pathdb/history_indexer.go index 6df74de61c..90816e6ef6 100644 --- a/triedb/pathdb/history_indexer.go +++ b/triedb/pathdb/history_indexer.go @@ -494,7 +494,18 @@ func (i *indexIniter) index(done chan struct{}, interrupt *atomic.Int32, lastID // when the state is reverted manually (chain.SetHead) or the deep reorg is // encountered. In such cases, no indexing should be scheduled. if beginID > lastID { - log.Debug("State history is fully indexed", "last", lastID) + if lastID == 0 && beginID == 1 { + // Initialize the indexing flag if the state history is empty by + // using zero as the disk layer ID. This is a common case that + // can occur after snap sync. + // + // This step is essential to avoid spinning up indexing thread + // endlessly until a history object is produced. + storeIndexMetadata(i.disk, 0) + log.Info("Initialized history indexing flag") + } else { + log.Debug("State history is fully indexed", "last", lastID) + } return } log.Info("Start history indexing", "beginID", beginID, "lastID", lastID)