Nondeterministic behavior in Stockfish is likely caused by uninitialized memory, race conditions, or other issues that make the search process behave inconsistently across runs. From the context provided, it seems you added a "cheat move pruning" feature, but it occasionally produces different results. Let's identify potential causes of nondeterminism in your modification.
Key Areas to Investigate
Move Ordering and Pruning Logic
Stockfish's search heavily relies on deterministic move ordering and pruning techniques. If "cheat move pruning" modifies the move ordering or pruning criteria unpredictably (e.g., based on uninitialized memory or thread-unsafe data), the search results can vary.
Thread Safety
Stockfish is multithreaded. Any shared state modified without proper synchronization (e.g., using std::atomic or thread-safe access patterns) can lead to race conditions. This is especially relevant in the Search::Worker class or move generation (movegen.cpp).
Uninitialized Memory
If variables related to "cheat move pruning" are not properly initialized, their values could differ between runs, causing nondeterministic behavior.
Non-Reproducible Search
Stockfish aims for reproducible searches. If your change introduces randomness (e.g., based on system time, non-deterministic functions like std::rand, or multithreading issues), it will break this reproducibility.
Steps to Debug
1. Reproduce the Issue
Use the reprosearch.sh script (file provided in tests/reprosearch.sh) to verify reproducibility. It runs Stockfish in a deterministic setup and checks for consistent results.
If the test fails, your "cheat move pruning" is likely introducing nondeterminism.
2. Review Changes in Move Pruning
Look at how "cheat move pruning" interacts with the move generation and scoring in movepick.cpp, movegen.cpp, or search.cpp. Examples:
MovePicker (movepick.cpp):
cpp
// Sort moves in descending order up to and including a given limit
void partial_insertion_sort(ExtMove* begin, ExtMove* end, int limit);
If your pruning logic affects move order without proper determinism, this could cause the issue.
Move Generation (movegen.cpp):
If "cheat move pruning" modifies the target move list in a nondeterministic way, it will affect reproducibility.
Ensure all data structures used by "cheat move pruning" are local to threads or properly synchronized.
3. Thread Safety
In search.cpp, Stockfish's Search::Worker objects run on separate threads. If "cheat move pruning" uses shared data (e.g., global or static variables), ensure access is thread-safe.
Verify that you are not modifying shared state like rootMoves, tt, or any history table (ButterflyHistory, CapturePieceToHistory, etc.) without synchronization.
4. Uninitialized Memory
Check all newly added variables. If any variable used by "cheat move pruning" is uninitialized, its value could vary between runs. For example:
cpp
int cheat_prune_flag; // Uninitialized variable
if (cheat_prune_flag) { /* prune move */ }
Make sure to explicitly initialize such variables:
cpp
int cheat_prune_flag = 0;
5. Randomness or Time Dependency
Avoid using random number generators (std::rand, std::random_device) or system time (std::chrono, time()) in search code. Stockfish's reproducibility depends on deterministic behavior.
Common Sources of Nondeterminism in Stockfish
Move Picker & Ordering
The MovePicker class in movepick.cpp is responsible for ordering moves. If "cheat move pruning" affects the order inconsistently, it will lead to nondeterministic behavior.
History Tables
Stockfish uses history tables like ButterflyHistory, CapturePieceToHistory, and ContinuationHistory for move sorting. If these are modified inconsistently (e.g., by multiple threads), search results can vary.
Shared Transposition Table (TT)
The transposition table (tt) is shared across threads. If "cheat move pruning" modifies TT entries inconsistently or without proper locking, it can cause nondeterminism.
Example Debugging Steps
Scenario: "Cheat Move Pruning" Affects Move Order
Suppose you added a pruning condition in MovePicker::score():
cpp
if (use_cheat_pruning && some_condition) {
m.value = -VALUE_INFINITE; // [Redacted Person] move as bad
}
Problem: If some_condition depends on uninitialized or non-thread-safe data, move scores (m.value) will vary between threads, causing nondeterminism.
Solution:
Ensure some_condition is purely deterministic (e.g., depends only on the board state or precomputed values).
Use thread-local storage for data accessed by multiple threads.
Scenario: "Cheat Move Pruning" Modifies Shared State
Suppose you added a global flag to enable pruning:
cpp
bool cheat_prune_active = false;
Problem: If multiple threads modify cheat_prune_active without synchronization, behavior will vary.
Solution:
Use thread-local storage:
cpp
thread_local bool cheat_prune_active = false;
Or synchronize access with a mutex:
cpp
std::atomic<bool> cheat_prune_active = false;
Recommendations
Run reprosearch.sh to verify reproducibility. Debug any failures.
Review Thread Safety: Ensure all shared data is thread-safe.
Ensure Determinism: Avoid randomness or uninitialized variables.
Simplify the Feature: Temporarily disable "cheat move pruning" and re-enable it step-by-step to isolate the issue.
Let me know if you need help debugging further!
Unfortunately, you haven't provided the implementation or context for the cheat_move_pruning function, so I cannot directly examine its code. However, I can guide you on how to check for out-of-bounds access based on the typical patterns in Stockfish's move generation and pruning logic.
If you can provide the code for cheat_move_pruning, I can give a more tailored analysis. For now, here's how you can check for out-of-bounds issues in the context of Stockfish.
Common Out-of-Bounds Risks in Stockfish
Array Indexing
Stockfish uses arrays or std::array extensively (e.g., PieceToHistory, ContinuationHistory, MultiArray).
If cheat_move_pruning accesses an array without bounds checking, ensure all indices are valid:
cpp
some_array[index] // Ensure 0 <= index < array.size()
Move Lists
Stockfish generates moves into ExtMove arrays (e.g., in generate or MovePicker):
cpp
ExtMove moveList[MAX_MOVES];
If cheat_move_pruning modifies or iterates over these lists, ensure no indices exceed the bounds of moveList.
Bitboards
Stockfish often uses bitboards to represent legal moves. Ensure you're not accessing invalid squares:
cpp
Square sq = ... // Ensure sq is a valid square (0 <= sq < 64)
History Tables
Stockfish's history tables (e.g., PieceToHistory, CapturePieceToHistory) are multi-dimensional arrays. Ensure indices for the piece type, square, or move are always valid.
Example: Common Out-of-Bounds Patterns
Move List Indexing
If cheat_move_pruning modifies a move list, ensure the iterator or index is within bounds:
cpp
for (int i = 0; i < numMoves; i++) {
// Ensure numMoves does not exceed the allocated size of moveList
moveList[i] = ...;
}
Multi-Dimensional Array Access
If cheat_move_pruning accesses history tables, ensure all indices are valid:
cpp
continuationHistory[pieceType][toSquare] += value;
// Check pieceType is valid: PAWN <= pieceType <= KING
// Check toSquare is valid: 0 <= toSquare < 64
Bitboard Access
If cheat_move_pruning uses bitboards to filter moves:
sideToMove = ~sideToMove;
put_piece(st->capturedPiece, cheatsquare); // Restore the captured piece
st = st->previous;
--gamePly;
}
After carefully reviewing the cheat function and the associated undo_cheat_move function, I can see a few areas that could potentially cause out-of-bounds access or undefined behavior. Below, I'll explain each section of concern and suggest fixes.
Key Observations and Potential Issues
1. Access to piece_on(to)
cpp
Piece captured = piece_on(to);
Issue: The piece_on(to) function assumes that to is a valid square and contains a piece. However:
If checkers() is invalid or pop_lsb(Temp) produces an invalid square, this could result in undefined behavior.
The checkers() Bitboard is assumed to contain at least one square, as pop_lsb is called without checking if Temp is empty.
Fix: Add a check to ensure Temp is not empty before calling pop_lsb:
cpp
assert(Temp); // Ensure there's a valid square in the checkers Bitboard
Square to = pop_lsb(Temp);
Issue: The captured piece is assumed to be valid. If piece_on(to) returns NO_PIECE or another invalid value, accessing Zobrist::psq[captured][to] could go out of bounds.
captured must be a valid Piece type, and to must be a valid square (0–63).
Fix: Add a check to ensure captured is valid:
cpp
assert(captured >= W_PAWN && captured <= B_KING); // Ensure captured is a valid piece
assert(to >= 0 && to < 64); // Ensure 'to' is a valid square
Issue: The pieceCount[captured] array is indexed by captured, which must be a valid Piece type. If captured is invalid, this could result in out-of-bounds access.
Fix: Ensure captured is valid (see Fix #2).
4. Logic in undo_cheat_move
cpp
put_piece(st->capturedPiece, cheatsquare);
Issue: The st->capturedPiece is assumed to be valid. If it is NO_PIECE or uninitialized, this could cause issues in put_piece.
Fix: Add a check to ensure st->capturedPiece is valid:
Issue: square<KING>(them) assumes that the king for the opposing side exists on the board. If the board state is corrupted (e.g., the king is missing), this could cause undefined behavior.
Fix: Add an assertion to ensure the king exists:
cpp
assert(square<KING>(them) != SQ_NONE); // Ensure the king is on the board
6. Prefetching Transposition Table
cpp
prefetch(tt.first_entry(key()));
Issue: The key() function is assumed to be valid after all the operations. If the key computation is corrupted (e.g., due to invalid captured or to values), it could lead to invalid memory access during prefetching.
Fix: Ensure that key() is valid and deterministic:
cpp
assert(key() != 0); // Ensure the computed key is valid
7. General Missing Initialization
Problem: In the std::memcpy step, fields in the StateInfo structure are copied to newSt. However, fields that are recalculated (e.g., checkersBB) are subsequently overwritten. If any required fields are missed or improperly initialized, it could lead to undefined behavior.
Fix: Ensure all fields in StateInfo are properly initialized after the std::memcpy.
Revised cheat Function
Here’s the revised cheat function with proper bounds checking and assertions: