diff --git a/Chess/Concepts.h b/Chess/Concepts.h index a2b92d5..6e8ff3c 100644 --- a/Chess/Concepts.h +++ b/Chess/Concepts.h @@ -5,3 +5,6 @@ template concept StopSearchCondition = requires(const T& condition) { { condition.IsTimeToExit() } -> std::convertible_to; }; + +template +concept CountsNodes = requires(const T& condition) { condition.CountNode(); }; diff --git a/Chess/ExitCondition.h b/Chess/ExitCondition.h index 4d03908..0495e89 100644 --- a/Chess/ExitCondition.h +++ b/Chess/ExitCondition.h @@ -1,6 +1,8 @@ #pragma once #include +#include #include +#include #include #include #include @@ -85,6 +87,20 @@ struct TimeCondition { }; static_assert(SearchCondition); +class NodeBudget { + public: + explicit NodeBudget(std::uint64_t limit) : limit_(limit) {} + + void Spend() { searched_.fetch_add(1, std::memory_order_relaxed); } + [[nodiscard]] bool IsSpent() const { + return searched_.load(std::memory_order_relaxed) >= limit_; + } + + private: + std::atomic searched_{0}; + const std::uint64_t limit_; +}; + struct DepthCondition { explicit DepthCondition(Depth max_depth, StopSignal stop_signal = {}) : max_depth_(max_depth), stop_signal_(std::move(stop_signal)) {} @@ -104,7 +120,38 @@ struct DepthCondition { }; static_assert(SearchCondition); -using Condition = std::variant; +class NodeCondition { + public: + NodeCondition(Depth max_depth, StopSignal stop_signal, + std::shared_ptr node_budget) + : depth_condition_(max_depth, std::move(stop_signal)), + node_budget_(std::move(node_budget)) { + assert(node_budget_); + } + + bool ShouldContinueIteration() const { + return !node_budget_->IsSpent() && + depth_condition_.ShouldContinueIteration(); + } + + [[gnu::always_inline]] bool IsTimeToExit() const { + return depth_condition_.IsTimeToExit() || node_budget_->IsSpent(); + } + + [[gnu::always_inline]] void CountNode() const { node_budget_->Spend(); } + + void Update(const IterationInfo& info) { depth_condition_.Update(info); } + + private: + DepthCondition depth_condition_; + std::shared_ptr node_budget_; +}; +static_assert(SearchCondition); +static_assert(CountsNodes); +static_assert(!CountsNodes); +static_assert(!CountsNodes); + +using Condition = std::variant; struct Pondering { explicit Pondering(StopSignal signal = {}) diff --git a/Chess/PositionFactory.h b/Chess/PositionFactory.h index 822103f..a909b4e 100644 --- a/Chess/PositionFactory.h +++ b/Chess/PositionFactory.h @@ -1,168 +1,300 @@ #pragma once +#include +#include +#include +#include +#include +#include #include +#include +#include #include +#include #include "BitBoard.h" #include "Position.h" #include "StreamUtility.h" namespace SimpleChessEngine { +inline constexpr std::string_view kStartFen = + "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; + struct PositionFactory { - Position operator()( - const std::string &fen = - "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") const; + [[nodiscard]] std::optional TryParse(std::string_view fen) const; + [[nodiscard]] Position operator()(std::string_view fen = kStartFen) const; + + private: + static constexpr File kFiles = 8; + static constexpr Rank kRanks = 8; + static constexpr int kMaxPiecesPerSide = 16; + static constexpr int kMaxPawnsPerSide = 8; + + using CastlingRightsBySide = std::array, kColors>; + using RookSquares = std::array, 2>, kColors>; + + struct Fields { + std::string board; + std::string side_to_move; + std::string castling; + std::string en_passant = "-"; + std::string halfmove_clock = "0"; + std::string fullmove_number = "1"; + }; + + struct Placement { + std::array kings{}; + std::array, kColors> back_rank_rooks{}; + }; + + [[nodiscard]] static constexpr Rank BackRank(Player color) { + return color == Player::kWhite ? 0 : kRanks - 1; + } + + [[nodiscard]] static std::optional Split(std::string_view fen); + [[nodiscard]] static std::optional PlacePieces( + std::string_view board, Position &position); + [[nodiscard]] static std::optional ParseSideToMove( + std::string_view text); + [[nodiscard]] static RookSquares FindCastlingRooks( + const Placement &placement); + [[nodiscard]] static std::optional ParseCastlingRights( + std::string_view text, const Placement &placement, + const RookSquares &rooks); + [[nodiscard]] static std::optional ParseSquare( + std::string_view text); + [[nodiscard]] static bool IsEnPassantTarget(const Position &position, + BitIndex square); + [[nodiscard]] static std::optional ParseNumber( + std::string_view text); }; struct FenFactory { std::string operator()(const Position &position); }; -inline Position PositionFactory::operator()(const std::string &fen) const { - std::stringstream fen_stream; - - fen_stream << fen; - - Position position; - - static constexpr size_t kBoardSize = 8; - - std::string board; - - fen_stream >> board; +inline std::optional PositionFactory::Split( + std::string_view fen) { + std::istringstream stream{std::string{fen}}; + const std::vector tokens{ + std::istream_iterator{stream}, + std::istream_iterator{}}; + if (tokens.size() < 3 || tokens.size() > 6) return std::nullopt; + + Fields fields{tokens[0], tokens[1], tokens[2]}; + if (tokens.size() > 3) fields.en_passant = tokens[3]; + if (tokens.size() > 4) fields.halfmove_clock = tokens[4]; + if (tokens.size() > 5) fields.fullmove_number = tokens[5]; + return fields; +} - auto current = board.begin(); +inline std::optional PositionFactory::PlacePieces( + std::string_view board, Position &position) { + Placement placement; + std::array kings{}; + std::array pawns{}; + std::array pieces{}; + + Rank rank = kRanks - 1; + File file = 0; + for (const char symbol : board) { + if (symbol == '/') { + if (file != kFiles || rank == 0) return std::nullopt; + --rank; + file = 0; + continue; + } + if (symbol >= '1' && symbol <= '8') { + file += symbol - '0'; + if (file > kFiles) return std::nullopt; + continue; + } - std::array kings{}; - std::array, kColors> rooks{}; - std::array, kColors> back_rank_rooks{}; + const auto entry = kCharToPiece.find(symbol); + if (entry == kCharToPiece.end() || file == kFiles) return std::nullopt; + const auto [piece, color] = entry->second; + const auto us = static_cast(color); + const auto square = GetSquareIndex(file, rank); - for (int row = kBoardSize - 1; row >= 0; --row) { - size_t column = 0; - while (column < kBoardSize) { - if (std::isdigit(*current)) { - // convert char to number - column += *current - '0'; + if (++pieces[us] > kMaxPiecesPerSide) return std::nullopt; + if (piece == Piece::kKing) { + if (++kings[us] > 1) return std::nullopt; + placement.kings[us] = square; + } + if (piece == Piece::kPawn && + (rank == 0 || rank == kRanks - 1 || ++pawns[us] > kMaxPawnsPerSide)) { + return std::nullopt; + } + if (piece == Piece::kRook && rank == BackRank(color)) { + placement.back_rank_rooks[us][file] = true; + } - ++current; - continue; - } + position.PlacePiece(square, piece, color); + ++file; + } - const auto &[piece, color] = kCharToPiece[*current]; - auto square = static_cast(row * kBoardSize + column); - position.PlacePiece(square, piece, color); + if (rank != 0 || file != kFiles || kings != std::array{1, 1}) { + return std::nullopt; + } + return placement; +} - const auto us = static_cast(color); +inline std::optional PositionFactory::ParseSideToMove( + std::string_view text) { + if (text == "w") return Player::kWhite; + if (text == "b") return Player::kBlack; + return std::nullopt; +} - if (piece == Piece::kKing) { - kings[us] = square; +inline PositionFactory::RookSquares PositionFactory::FindCastlingRooks( + const Placement &placement) { + RookSquares rooks{}; + for (const auto color : {Player::kWhite, Player::kBlack}) { + const auto us = static_cast(color); + const auto &back_rank_rooks = placement.back_rank_rooks[us]; + const auto king_file = static_cast(placement.kings[us] % kFiles); + for (File file = 0; file < king_file; ++file) { + if (back_rank_rooks[file]) { + rooks[us][static_cast(CastlingSide::k000)] = + GetSquareIndex(file, BackRank(color)); + break; } - - const auto back_rank = color == Player::kWhite ? 0 : kBoardSize - 1; - if (piece == Piece::kRook && static_cast(row) == back_rank) { - back_rank_rooks[us][column] = true; + } + for (File file = kFiles - 1; file > king_file; --file) { + if (back_rank_rooks[file]) { + rooks[us][static_cast(CastlingSide::k00)] = + GetSquareIndex(file, BackRank(color)); + break; } - - assert(piece != Piece::kNone); - - ++column; - ++current; } - - // skip '/' - if (current != board.end()) ++current; } + return rooks; +} - std::string side_to_move; - fen_stream >> side_to_move; +inline std::optional +PositionFactory::ParseCastlingRights(std::string_view text, + const Placement &placement, + const RookSquares &rooks) { + CastlingRightsBySide rights; + if (text == "-") return rights; + + constexpr std::string_view kSymbols = "KQkq"; + const auto is_shredder_file = [](const char symbol) { + return (symbol >= 'A' && symbol <= 'H') || (symbol >= 'a' && symbol <= 'h'); + }; + for (const char symbol : text) { + const auto index = kSymbols.find(symbol); + if (index == std::string_view::npos) { + if (is_shredder_file(symbol)) continue; + return std::nullopt; + } - if (side_to_move != "b") - position.SetSideToMove(Player::kWhite); - else - position.SetSideToMove(Player::kBlack); + const auto color = index < 2 ? Player::kWhite : Player::kBlack; + const auto side = index % 2 == 0 ? CastlingSide::k00 : CastlingSide::k000; + const auto us = static_cast(color); + const auto bit = static_cast(side); + const bool king_on_back_rank = + placement.kings[us] / kFiles == BackRank(color); + if (rights[us].test(bit) || !king_on_back_rank || !rooks[us][bit]) { + return std::nullopt; + } + rights[us].set(bit); + } + return rights; +} - // TODO: Attributes - std::string castling_rights_string; - fen_stream >> castling_rights_string; +inline std::optional PositionFactory::ParseSquare( + std::string_view text) { + if (text.size() != 2 || text[0] < 'a' || text[0] > 'h' || text[1] < '1' || + text[1] > '8') { + return std::nullopt; + } + return GetSquareIndex(static_cast(text[0] - 'a'), + static_cast(text[1] - '1')); +} - std::array, 2> castling_rights; +inline bool PositionFactory::IsEnPassantTarget(const Position &position, + const BitIndex square) { + const auto us = position.GetSideToMove(); + const auto them = Flip(us); + const Rank target_rank = us == Player::kWhite ? kRanks - 3 : 2; + if (square / kFiles != target_rank) return false; + + const auto forward = static_cast(us == Player::kWhite ? kFiles : -kFiles); + const auto pushed_pawn = static_cast(square - forward); + const auto pawn_origin = static_cast(square + forward); + return position.GetPieceAt(pushed_pawn) == Piece::kPawn && + (position.GetPieces(them) & SingleSquare(pushed_pawn)).Any() && + position.GetPieceAt(square) == Piece::kNone && + position.GetPieceAt(pawn_origin) == Piece::kNone; +} - for (auto castling_right : castling_rights_string) { - switch (castling_right) { - case 'K': - castling_rights[static_cast(Player::kWhite)] |= - static_cast(CastlingRights::k00); - break; - case 'k': - castling_rights[static_cast(Player::kBlack)] |= - static_cast(CastlingRights::k00); - break; - case 'Q': - castling_rights[static_cast(Player::kWhite)] |= - static_cast(CastlingRights::k000); - break; - case 'q': - castling_rights[static_cast(Player::kBlack)] |= - static_cast(CastlingRights::k000); - break; - default: - break; - } - } +inline std::optional PositionFactory::ParseNumber( + std::string_view text) { + std::size_t number = 0; + const auto end = text.data() + text.size(); + const auto [parsed_end, error] = std::from_chars(text.data(), end, number); + if (error != std::errc{} || parsed_end != end) return std::nullopt; + return number; +} - position.SetCastlingRights(castling_rights); +inline std::optional PositionFactory::TryParse( + std::string_view fen) const { + const auto fields = Split(fen); + if (!fields) return std::nullopt; - std::string en_croissant_square; - fen_stream >> en_croissant_square; - if (!en_croissant_square.empty() && en_croissant_square != "-") { - assert(en_croissant_square.size() == 2); - const auto file = static_cast(en_croissant_square[0] - 'a'); - const auto rank = static_cast(en_croissant_square[1] - '1'); - position.SetEnCroissantSquare(GetSquareIndex(file, rank)); + Position position; + const auto placement = PlacePieces(fields->board, position); + if (!placement) return std::nullopt; + + const auto side_to_move = ParseSideToMove(fields->side_to_move); + if (!side_to_move) return std::nullopt; + position.SetSideToMove(*side_to_move); + + const auto rooks = FindCastlingRooks(*placement); + const auto castling_rights = + ParseCastlingRights(fields->castling, *placement, rooks); + if (!castling_rights) return std::nullopt; + position.SetCastlingRights(*castling_rights); + + if (fields->en_passant != "-") { + const auto square = ParseSquare(fields->en_passant); + if (!square || !IsEnPassantTarget(position, *square)) return std::nullopt; + position.SetEnCroissantSquare(*square); } - size_t halfmove_clock = 0; - size_t fullmove_number = 1; - fen_stream >> halfmove_clock >> fullmove_number; - if (fullmove_number == 0) fullmove_number = 1; + const auto halfmove_clock = ParseNumber(fields->halfmove_clock); + const auto fullmove_number = ParseNumber(fields->fullmove_number); + if (!halfmove_clock || !fullmove_number) return std::nullopt; + const auto &kings = placement->kings; + std::array, kColors> rook_squares{}; for (size_t us = 0; us < kColors; ++us) { - const auto back_rank = - us == static_cast(Player::kWhite) ? 0 : kBoardSize - 1; - const auto king_file = static_cast(kings[us]) % kBoardSize; - for (size_t file = 0; file < king_file; ++file) { - if (back_rank_rooks[us][file]) { - rooks[us][static_cast(CastlingSide::k000)] = - static_cast(back_rank * kBoardSize + file); - break; - } - } - for (size_t file = kBoardSize - 1; file > king_file; --file) { - if (back_rank_rooks[us][file]) { - rooks[us][static_cast(CastlingSide::k00)] = - static_cast(back_rank * kBoardSize + file); - break; - } + for (size_t side = 0; side < 2; ++side) { + rook_squares[us][side] = rooks[us][side].value_or(BitIndex{0}); } } - position.SetKingPositions(kings); - position.SetRookPositions(rooks); + position.SetRookPositions(rook_squares); std::array, kColors> cs_king = { {{RookBetween(kings[0], kKingCastlingDestination[0][0]), RookBetween(kings[0], kKingCastlingDestination[0][1])}, {RookBetween(kings[1], kKingCastlingDestination[1][0]), RookBetween(kings[1], kKingCastlingDestination[1][1])}}}; std::array, kColors> cs_rook = { - {{RookBetween(rooks[0][0], kRookCastlingDestination[0][0]), - RookBetween(rooks[0][1], kRookCastlingDestination[0][1])}, - {RookBetween(rooks[1][0], kRookCastlingDestination[1][0]), - RookBetween(rooks[1][1], kRookCastlingDestination[1][1])}}}; + {{RookBetween(rook_squares[0][0], kRookCastlingDestination[0][0]), + RookBetween(rook_squares[0][1], kRookCastlingDestination[0][1])}, + {RookBetween(rook_squares[1][0], kRookCastlingDestination[1][0]), + RookBetween(rook_squares[1][1], kRookCastlingDestination[1][1])}}}; position.SetCastlingSquares(cs_king, cs_rook); - position.Init(halfmove_clock, fullmove_number); + position.Init(*halfmove_clock, std::max(*fullmove_number, 1)); return position; } +inline Position PositionFactory::operator()(std::string_view fen) const { + return TryParse(fen).value(); +} + inline std::string SimpleChessEngine::FenFactory::operator()( const Position &position) { std::ostringstream ss; diff --git a/Chess/Quiescence.cpp b/Chess/Quiescence.cpp index 886ccb1..b6bb85b 100644 --- a/Chess/Quiescence.cpp +++ b/Chess/Quiescence.cpp @@ -27,6 +27,7 @@ SearchResult Quiescence::Search(Position& current_position, searched_nodes_ = 0; } searched_nodes_++; + if constexpr (CountsNodes) exit_condition_.CountNode(); if (IsTimeToExit()) { return std::nullopt; @@ -206,6 +207,7 @@ bool Quiescence::IsTimeToExit() { template class Quiescence; template class Quiescence; template class Quiescence; +template class Quiescence; template SearchResult Quiescence::Search( Position& current_position, Eval alpha, const Eval beta, @@ -219,6 +221,12 @@ template SearchResult Quiescence::Search( template SearchResult Quiescence::Search( Position& current_position, Eval alpha, const Eval beta, const Depth current_depth, bool pv_node); +template SearchResult Quiescence::Search( + Position& current_position, Eval alpha, const Eval beta, + const Depth current_depth, bool pv_node); +template SearchResult Quiescence::Search( + Position& current_position, Eval alpha, const Eval beta, + const Depth current_depth, bool pv_node); template SearchResult Quiescence::Search( Position& current_position, Eval alpha, const Eval beta, const Depth current_depth, bool pv_node); diff --git a/Chess/SearchImplementation.h b/Chess/SearchImplementation.h index 9b56206..7095f48 100644 --- a/Chess/SearchImplementation.h +++ b/Chess/SearchImplementation.h @@ -223,6 +223,7 @@ SearchResult SearchNode::operator()() { } searcher_.debug_info_.searched_nodes++; + if constexpr (CountsNodes) exit_condition_.CountNode(); if (ProbeTranspositionTable()) { searcher_.debug_info_.tt_hits++; diff --git a/Chess/SimpleChessEngine.h b/Chess/SimpleChessEngine.h index 41db835..f29b846 100644 --- a/Chess/SimpleChessEngine.h +++ b/Chess/SimpleChessEngine.h @@ -221,11 +221,12 @@ class ChessEngine { PrintInfo(ScoreInfo{eval}); PrincipalVariationInfo pv{current_depth, principal_variation}; PrintInfo(pv); - PrintInfo(NodesInfo{info.searched_nodes}); + PrintInfo(NodesInfo{info.TotalNodes()}); PrintInfo(NodePerSecondInfo{ static_cast(info.TotalNodes() / search_time.count())}); for (const auto& [name, counter] : kDebugCounters) { - if (counter != &DebugInfo::searched_nodes) { + if (counter != &DebugInfo::searched_nodes && + counter != &DebugInfo::quiescence_nodes) { Output() << "info " << name << " " << info.*counter << "\n"; } } diff --git a/Chess/UciCommunicator.h b/Chess/UciCommunicator.h index 4edf230..ceb5626 100644 --- a/Chess/UciCommunicator.h +++ b/Chess/UciCommunicator.h @@ -47,7 +47,11 @@ struct MaxDepth { Depth depth; }; -using TimeControl = std::variant; +struct MaxNodes { + std::shared_ptr budget; +}; + +using TimeControl = std::variant; struct Info { Position position; @@ -173,6 +177,10 @@ class SearchThread { if (const auto max_depth = std::get_if(&info.time_control)) { return DepthCondition{max_depth->depth, stop_signal_}; } + if (const auto max_nodes = std::get_if(&info.time_control)) { + return NodeCondition{static_cast(kMaxSearchPly - 1), stop_signal_, + max_nodes->budget}; + } assert(false); std::unreachable(); } @@ -692,7 +700,7 @@ class UciChessEngine { void ParseSetOption(std::stringstream command); void ParseIsReady(std::stringstream command) const; void ParseUciNewGame(std::stringstream command); - void ParseFen(const std::string& fen); + [[nodiscard]] bool ParseFen(const std::string& fen); void ParseStartPos(); [[nodiscard]] std::optional ParseLegalMove(const std::string& text); void ParseMoves(std::stringstream command); @@ -707,6 +715,7 @@ class UciChessEngine { void ParseMoveTime(std::stringstream command); void ParsePlayersTime(std::stringstream command); void ParseDepth(std::stringstream command); + void ParseNodes(std::stringstream command); void ParseStop(std::stringstream command); void ParseQuit(std::stringstream command); void ParseDebug(std::stringstream command); @@ -720,7 +729,7 @@ class UciChessEngine { SearchThread search_thread_; - Info info_; + Info info_{.position = PositionFactory{}(), .time_control = {}}; EngineOptions options_; bool quit_ = false; @@ -865,8 +874,16 @@ inline void UciChessEngine::ParseUciNewGame(std::stringstream) { search_thread_.NewGame(); } -inline void UciChessEngine::ParseFen(const std::string& fen) { - info_.position = PositionFactory{}(fen); +inline bool UciChessEngine::ParseFen(const std::string& fen) { + auto position = PositionFactory{}.TryParse(fen); + const bool king_capturable = + position && position->IsUnderCheck(Flip(position->GetSideToMove())); + if (!position || king_capturable) { + Send("info string invalid fen " + fen); + return false; + } + info_.position = std::move(*position); + return true; } inline void UciChessEngine::ParseStartPos() { @@ -915,7 +932,7 @@ inline void UciChessEngine::ParsePosition(std::stringstream command) { if (!fen.empty()) fen += ' '; fen += token; } - ParseFen(fen); + if (!ParseFen(fen)) return; } else if (token == "startpos") { ParseStartPos(); command >> token; @@ -1028,6 +1045,8 @@ inline void UciChessEngine::ParseGo(std::stringstream command) { ParseMoveTime(std::move(command)); } else if (token == "depth") { ParseDepth(std::move(command)); + } else if (token == "nodes") { + ParseNodes(std::move(command)); } StartSearch(ponder); @@ -1089,6 +1108,15 @@ inline void SimpleChessEngine::UciChessEngine::ParseDepth( } } +inline void SimpleChessEngine::UciChessEngine::ParseNodes( + std::stringstream command) { + std::string token; + command >> token; + if (const auto nodes = ParseNumber(token)) { + info_.time_control = MaxNodes{std::make_shared(*nodes)}; + } +} + inline void UciChessEngine::ParseStop(std::stringstream) { StopSearch(); } inline void UciChessEngine::ParseQuit(std::stringstream) { diff --git a/Tests/NullMovePruningTests.cpp b/Tests/NullMovePruningTests.cpp index 2332a76..d6b90ef 100644 --- a/Tests/NullMovePruningTests.cpp +++ b/Tests/NullMovePruningTests.cpp @@ -265,8 +265,9 @@ TEST_F(NullMovePruning, UncappedReductionCanVerifyInQuiescence) { Searcher searcher(position); const auto beta = position.Evaluate() - 707; ASSERT_GE(beta, -788); - DepthCondition stop{16}; - const auto result = SearchNode{ + auto budget = std::make_shared(4); + NodeCondition stop{16, {}, budget}; + const auto result = SearchNode{ searcher, {16, 16, beta - 1, beta, 1}, stop}(); ASSERT_TRUE(result); EXPECT_EQ(*result, beta); @@ -276,6 +277,9 @@ TEST_F(NullMovePruning, UncappedReductionCanVerifyInQuiescence) { EXPECT_EQ(searcher.GetInfo().nmp_cuts, 1u); EXPECT_EQ(searcher.GetNullMoveInfo().verifications, 1u); EXPECT_EQ(searcher.GetPosition().GetHash(), position.GetHash()); + EXPECT_FALSE(budget->IsSpent()); + budget->Spend(); + EXPECT_TRUE(budget->IsSpent()); } TEST_F(NullMovePruning, VerificationMustConfirmTheNullCutoff) { diff --git a/Tests/PositionTests.cpp b/Tests/PositionTests.cpp index e8044fa..f82802a 100644 --- a/Tests/PositionTests.cpp +++ b/Tests/PositionTests.cpp @@ -20,7 +20,7 @@ TEST(KingLegality, RejectsMissingOrDuplicateKings) { {"8/8/8/8/8/8/8/8 w - - 0 1", "8/8/8/8/8/8/8/K7 w - - 0 1", "7k/8/8/8/8/8/8/8 w - - 0 1", "7k/8/8/8/8/8/8/KK6 w - - 0 1", "6kk/8/8/8/8/8/8/K7 w - - 0 1"}) { - EXPECT_FALSE(PositionFactory{}(fen).HasLegalKings()) << fen; + EXPECT_FALSE(PositionFactory{}.TryParse(fen)) << fen; } } diff --git a/Tests/SearchCorrectnessTests.cpp b/Tests/SearchCorrectnessTests.cpp index df3b8fa..894e68a 100644 --- a/Tests/SearchCorrectnessTests.cpp +++ b/Tests/SearchCorrectnessTests.cpp @@ -301,6 +301,38 @@ TEST(ProbCut, QuiescencePassesButPositiveDepthVerificationRejects) { ExpectProbCutPositionRestored(searcher.GetPosition(), position); } +TEST(ProbCut, NodeBudgetIncludesQuiescenceAndVerification) { + const auto position = PositionFactory{}(kProbCutFen); + Searcher reference(position); + DepthCondition unlimited{8}; + const auto expected = ProbCutTestAccess::Run(reference, unlimited); + ASSERT_EQ(expected, NodeExit::Cutoff(-95)); + const auto& info = reference.GetInfo(); + const auto nodes = info.searched_nodes + info.quiescence_nodes; + ASSERT_GT(info.probcut_qsearch_nodes, 0u); + ASSERT_GT(info.probcut_verification_nodes, 0u); + + auto budget = std::make_shared(nodes + 1); + NodeCondition condition{8, {}, budget}; + Searcher searcher(position); + EXPECT_EQ(ProbCutTestAccess::Run(searcher, condition), expected); + EXPECT_FALSE(budget->IsSpent()); + budget->Spend(); + EXPECT_TRUE(budget->IsSpent()); + ExpectProbCutPositionRestored(searcher.GetPosition(), position); +} + +TEST(ProbCut, NodeBudgetAbortRestoresScopedMove) { + const auto position = PositionFactory{}(kProbCutFen); + auto budget = std::make_shared(1); + NodeCondition condition{8, {}, budget}; + Searcher searcher(position); + EXPECT_EQ(ProbCutTestAccess::Run(searcher, condition), NodeExit::Abort()); + EXPECT_TRUE(budget->IsSpent()); + EXPECT_EQ(searcher.GetInfo().probcut_candidates, 1u); + ExpectProbCutPositionRestored(searcher.GetPosition(), position); +} + TEST(ProbCut, QuiescenceRejectionDoesNotVerify) { const auto position = PositionFactory{}(kProbCutFen); Searcher searcher(position); diff --git a/Tests/TablebaseTests.cpp b/Tests/TablebaseTests.cpp index 9f77e60..da6b650 100644 --- a/Tests/TablebaseTests.cpp +++ b/Tests/TablebaseTests.cpp @@ -23,14 +23,18 @@ TEST(Syzygy, RejectsIllegalKings) { struct TablebaseGuard { ~TablebaseGuard() { Tablebase::Syzygy::Disable(); } } guard; + const auto expect_rejected = [&](const Position& position) { + EXPECT_FALSE(tablebase->RootMove(position)); + EXPECT_FALSE(tablebase->Probe(position)); + EXPECT_FALSE(tablebase->ProbeWdl(position)); + }; for (const auto* fen : {"8/8/8/4k3/8/8/2K5/4R3 w - - 0 1", "8/8/8/4k3/8/8/2K5/4Q3 w - - 0 1", - "8/8/8/4k3/8/8/2K5/4R2R w - - 0 1", "8/8/8/8/8/8/2K5/4R3 b - - 0 1"}) { - const auto position = PositionFactory{}(fen); - EXPECT_FALSE(tablebase->RootMove(position)) << fen; - EXPECT_FALSE(tablebase->Probe(position)) << fen; - EXPECT_FALSE(tablebase->ProbeWdl(position)) << fen; + "8/8/8/4k3/8/8/2K5/4R2R w - - 0 1"}) { + SCOPED_TRACE(fen); + expect_rejected(PositionFactory{}(fen)); } + expect_rejected(Position{}); const auto position = PositionFactory{}("8/8/8/4k3/8/8/2K5/R7 w - - 0 1"); EXPECT_TRUE(tablebase->RootMove(position)); EXPECT_EQ(tablebase->ProbeWdl(position), Tablebase::Wdl::kWin); diff --git a/Tests/tablebase_search_test.py b/Tests/tablebase_search_test.py index fc61bea..ee76e4f 100644 --- a/Tests/tablebase_search_test.py +++ b/Tests/tablebase_search_test.py @@ -70,17 +70,22 @@ def ready(self) -> None: self.send("isready") self.wait_for("readyok", timeout=60) - def search(self, fen: str, control: str, invalid: bool = False, - root_hit: bool = False) -> None: + def reject_fen(self, fen: str) -> None: + start = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" + self.send("position startpos") + self.send(f"position fen {fen}") + self.wait_for(re.escape(f"info string invalid fen {fen}")) + self.send("debug") + self.wait_for(re.escape(start)) + + def search(self, fen: str, control: str, root_hit: bool = False) -> None: self.send(f"position fen {fen}") start = len(self.lines) self.send(f"go {control}") - expected = "0000" if invalid else r"[a-h][1-8][a-h][1-8][qrbn]?" + expected = r"[a-h][1-8][a-h][1-8][qrbn]?" self.wait_for(rf"bestmove {expected}( ponder [a-h][1-8][a-h][1-8][qrbn]?)?", timeout=1.0 if control == CLOCK else 2.0) lines = self.lines[start:] - if invalid and "info string invalid position: illegal kings" not in lines: - raise RuntimeError(f"invalid root was not rejected: {fen}") if root_hit and any(line.startswith("info depth ") for line in lines): raise RuntimeError(f"root tablebase probe failed: {fen}") @@ -107,13 +112,15 @@ def run(executable: str) -> None: engine.send(f"setoption name SyzygyPath value {TABLEBASE}") engine.ready() for fen in INVALID_FENS: - for control in ("depth 2", "movetime 1000", CLOCK): - engine.search(fen, control, invalid=True) + engine.reject_fen(fen) for fen in VALID_FENS: for control in ("movetime 1000", CLOCK): engine.search(fen, control, root_hit=True) for fen in (*INVALID_FENS, *VALID_FENS[:3]): - engine.send(f"position fen {fen}") + if fen in INVALID_FENS: + engine.reject_fen(fen) + else: + engine.send(f"position fen {fen}") engine.send(f"go ponder {CLOCK}") engine.ready() engine.send("stop") @@ -136,7 +143,7 @@ def run(executable: str) -> None: engine.send(f"setoption name SyzygyPath value {TABLEBASE}") engine.ready() - engine.send(f"position fen {INVALID_FENS[0]}") + engine.reject_fen(INVALID_FENS[0]) engine.send(f"go ponder {CLOCK}") engine.ready() engine.send("quit") diff --git a/Tests/uci_input_test.py b/Tests/uci_input_test.py index 9c73239..9da7a0f 100644 --- a/Tests/uci_input_test.py +++ b/Tests/uci_input_test.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 import argparse +import random import subprocess import sys @@ -21,12 +22,89 @@ ("fen without clocks", ["position fen 4k3/8/8/8/8/8/4P3/4K3 w -", "debug"], "4k3/8/8/8/8/8/4P3/4K3 w - - 0 1"), ("trailing space after moves", ["position startpos moves e2e4 ", "debug"], "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq"), + ("invalid initial fen", ["position fen ?", "debug"], + "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"), + ("castling right without its rook", ["position fen 4k3/8/8/8/8/8/8/4K3 w K - 0 1"], + "info string invalid fen"), + ("en passant square without a pushed pawn", ["position fen 4k3/8/8/8/8/8/8/4K3 w - e6 0 1"], + "info string invalid fen"), + ("side to move can capture the king", ["position fen 7k/8/8/8/3Q4/8/8/K7 w - - 0 1"], + "info string invalid fen"), + ("pawn on the back rank", ["position fen P3k3/8/8/8/8/8/8/4K3 w - - 0 1"], "info string invalid fen"), + ("two white kings", ["position fen 4k3/8/8/8/8/8/8/3KK3 w - - 0 1"], "info string invalid fen"), + ("illegal move", ["position startpos moves e2e5", "debug"], "info string illegal move e2e5"), + ("shredder castling file is ignored", ["position fen 4k3/8/8/8/8/8/8/6KR w H - 0 1", "debug"], + "4k3/8/8/8/8/8/8/6KR w - - 0 1"), + ("en passant after a double push", + ["position fen rnbqkbnr/ppp1pppp/8/8/3pP3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 3", "debug"], + "rnbqkbnr/ppp1pppp/8/8/3pP3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 3"), ] def run_case(engine: str, commands: list[str]) -> subprocess.CompletedProcess: script = "\n".join(["uci", *commands, "isready", "quit"]) + "\n" - return subprocess.run([engine], input=script, capture_output=True, text=True, timeout=30) + return subprocess.run([engine], input=script, capture_output=True, text=True, timeout=90) + + +def randomized_inputs(engine: str) -> list[str]: + rng = random.Random(0x5CE2026) + fens = [ + "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", + "4k3/8/8/8/8/8/4P3/4K3 w - - 0 1", + "r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 0 1", + ] + start = fens[0] + commands = [] + for _ in range(120): + fen = rng.choice(fens) + board, side, rights, ep, halfmove, fullmove = fen.split() + mutation = rng.randrange(5) + if mutation == 0: + index = rng.choice([i for i, char in enumerate(board) if char.isalpha()]) + board = board[:index] + "?" + board[index + 1:] + elif mutation == 1: + board = board[:-1] + elif mutation == 2: + side = "x" + elif mutation == 3: + ep = "z9" + else: + fullmove = "-1" + invalid_fen = " ".join((board, side, rights, ep, halfmove, fullmove)) + commands.extend(("position startpos", "position fen " + invalid_fen, + "debug", "isready")) + move = rng.choice(("z9z9", "e2e5", "a3a4", "e2", "e2e4x")) + commands.extend(("position startpos moves " + move, "debug", "isready")) + commands.extend(("position startpos moves e2e4 " + move, + "debug", "isready")) + + for _ in range(12): + garbage = "".join(rng.choice("xyz!?09") for _ in range(rng.randrange(1, 7))) + commands.extend(("setoption name Threads value " + garbage, + "go " + rng.choice(("depth", "nodes", "movetime")) + + " " + garbage, "stop", "isready")) + + result = run_case(engine, commands) + if result.returncode != 0: + return [f"randomized input: engine exited with {result.returncode}: {result.stderr[-300:]}"] + segments = [] + current = [] + for line in result.stdout.splitlines(): + if line == "readyok": + segments.append(current) + current = [] + else: + current.append(line) + failures = [] + if len(segments) != 373: + return [f"randomized input: expected 373 responses, got {len(segments)}"] + for i, segment in enumerate(segments[:360]): + expected = start if i % 3 != 2 else \ + "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1" + observed = segment[-1] if segment else "" + if observed != expected: + failures.append(f"randomized input case {i}: {observed!r}") + return failures def main() -> int: @@ -44,6 +122,8 @@ def main() -> int: elif expected is not None and expected not in result.stdout: failures.append(f"{name}: expected {expected!r} in output") + failures.extend(randomized_inputs(args.engine)) + for failure in failures: print(failure, file=sys.stderr) if failures: diff --git a/Tests/uci_lazy_smp_test.py b/Tests/uci_lazy_smp_test.py index 57ad917..d023ca5 100644 --- a/Tests/uci_lazy_smp_test.py +++ b/Tests/uci_lazy_smp_test.py @@ -50,7 +50,7 @@ def wait_for(predicate, description: str, timeout: float = 15.0) -> str: return line send("uci") - wait_for(lambda line: line == "uciok", "uciok") + wait_for(lambda line: line == "uciok", "uciok", timeout=60.0) if "option name Threads type spin default 1 min 1 max 256" not in lines: raise RuntimeError("Threads UCI option was not advertised") expected_tuning_options = {