feat: reuse the search tree between moves

When the new position continues the previous game, find its node in the
old tree (matching the keys of the positions played since) and make it
the root. Its subtree is packed to the front of the arena in place: child
blocks are always allocated after their parent's, so moving the kept
blocks in their original order only moves them towards the front.

A root that was a draw inside the old tree (repetition, 50 moves) or was
never expanded starts afresh. ucinewgame and Hash changes drop the tree.

Built with -DRIGBY_VERIFY_TREE, the engine checks every tree before and
after reuse (legal moves, visit counts); 2900+ such checks over self-play
games, with 16 MB and 1 MB hash, found no inconsistency.

Bench: 546127

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rektdieandclaude committed 2026-11-15 01:23:42 +01:00
1 parent d3044c0b88
commit 5c017ee43f
4 files changed
+175 -3

No files matched your search

+21 -1
View File
@@ -35,6 +35,9 @@ public:
void clear();
// Returns the index of `count` fresh nodes, or 0 when the arena is full.
u32 alloc(u32 count);
// Makes `new_root` the root and packs its subtree to the front of the arena;
// everything else is dropped. Returns the number of nodes kept.
size_t reroot(u32 new_root);
Node& operator[](u32 idx) { return nodes_[idx]; }
const Node& operator[](u32 idx) const { return nodes_[idx]; }
@@ -79,7 +82,13 @@ public:
Searcher();
void set_hash(size_t mb) { tree_.resize_mb(mb); }
void set_hash(size_t mb) {
tree_.resize_mb(mb);
tree_valid_ = false;
}
// Forget the previous tree, e.g. on ucinewgame.
void new_game() { tree_valid_ = false; }
// Synchronous search. `history` holds the keys of every position that led to
// `root`, including the key of `root` itself (for repetition detection).
@@ -95,6 +104,11 @@ private:
size_t root_history_size_ = 0;
std::vector<u32> path_;
// The previous search, kept so its tree can be reused.
bool tree_valid_ = false;
Position prev_root_;
std::vector<u64> prev_history_;
Clock::time_point start_time_;
i64 time_limit_ms_ = 0;
u64 iterations_ = 0;
@@ -106,6 +120,12 @@ private:
float expand(u32 idx, const Position& pos, int depth);
u32 select_child(u32 idx) const;
bool is_repetition(const Position& pos) const;
// Finds the node for `root` in the previous tree and makes it the root.
// Returns the number of nodes kept, 0 when nothing could be reused.
size_t reuse_tree(const Position& root);
#ifdef RIGBY_VERIFY_TREE
void verify_tree() const;
#endif
void compute_time_limit(const SearchLimits& limits);
i64 elapsed_ms() const;