From eee919a2d46d7a99d74d28700dbf74b1583978db Mon Sep 17 00:00:00 2001 From: nook0110 Date: Mon, 9 Nov 2026 02:02:43 +0300 Subject: [PATCH 1/5] [uci] Support go nodes "go nodes N" stops the search once main plus quiescence nodes reach N. The limit lives in DepthCondition as a NodeBudget shared by all search threads, counted through a CountsNodes hook that compiles to nothing for the other exit conditions. With one thread a fresh engine process gives the same best move and node count for the same command; the info lines report the nodes of the last completed iteration. The clock-controlled search used in games adds no instruction, call or store: the TimeCondition search nodes differ from the base only in stack slot assignment, and the Pondering ones gain only the budget compare in their DepthCondition branch. Fixed-depth search stays node-for-node identical on 30 positions at depth 11 and costs 0.07% more instructions per node for the counter check. Bench: 2709383 Co-Authored-By: Claude Opus 5.5 --- Chess/Concepts.h | 3 +++ Chess/ExitCondition.h | 34 +++++++++++++++++++++++++++++----- Chess/Quiescence.cpp | 1 + Chess/SearchImplementation.h | 1 + Chess/UciCommunicator.h | 22 +++++++++++++++++++++- 5 files changed, 55 insertions(+), 6 deletions(-) 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..e9c7e2d 100644 --- a/Chess/ExitCondition.h +++ b/Chess/ExitCondition.h @@ -1,6 +1,7 @@ #pragma once #include #include +#include #include #include #include @@ -47,7 +48,7 @@ struct TimeCondition { return !stop_now_ && Elapsed() <= deepen_limit && Elapsed() < hard_limit_; } - bool IsTimeToExit() const { + [[gnu::always_inline]] bool IsTimeToExit() const { return IsStopped() || (managed_ && stop_now_) || Elapsed() >= hard_limit_; } @@ -85,15 +86,37 @@ 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)) {} + explicit DepthCondition(Depth max_depth, StopSignal stop_signal = {}, + std::shared_ptr node_budget = {}) + : max_depth_(max_depth), + stop_signal_(std::move(stop_signal)), + node_budget_(std::move(node_budget)) {} bool ShouldContinueIteration() const { return !IsTimeToExit() && cur_depth < max_depth_; } - bool IsTimeToExit() const { - return stop_signal_ && stop_signal_->load(std::memory_order_relaxed); + [[gnu::always_inline]] bool IsTimeToExit() const { + return (stop_signal_ && stop_signal_->load(std::memory_order_relaxed)) || + (node_budget_ && node_budget_->IsSpent()); + } + + [[gnu::always_inline]] void CountNode() const { + if (node_budget_) node_budget_->Spend(); } void Update(const IterationInfo& info) { cur_depth = info.depth; } @@ -101,6 +124,7 @@ struct DepthCondition { Depth cur_depth = 0; Depth max_depth_; StopSignal stop_signal_; + std::shared_ptr node_budget_; }; static_assert(SearchCondition); diff --git a/Chess/Quiescence.cpp b/Chess/Quiescence.cpp index 11d3baf..ee24398 100644 --- a/Chess/Quiescence.cpp +++ b/Chess/Quiescence.cpp @@ -39,6 +39,7 @@ SearchResult Quiescence::Search(Position& current_position, searched_nodes_ = 0; } searched_nodes_++; + if constexpr (CountsNodes) exit_condition_.CountNode(); if (IsTimeToExit()) { return std::nullopt; diff --git a/Chess/SearchImplementation.h b/Chess/SearchImplementation.h index f3d77a0..553637b 100644 --- a/Chess/SearchImplementation.h +++ b/Chess/SearchImplementation.h @@ -217,6 +217,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/UciCommunicator.h b/Chess/UciCommunicator.h index bbf81bf..3cbc711 100644 --- a/Chess/UciCommunicator.h +++ b/Chess/UciCommunicator.h @@ -44,7 +44,11 @@ struct MaxDepth { Depth depth; }; -using TimeControl = std::variant; +struct MaxNodes { + std::shared_ptr budget; +}; + +using TimeControl = std::variant; struct Info { Position position; @@ -166,6 +170,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 DepthCondition{static_cast(kMaxSearchPly - 1), stop_signal_, + max_nodes->budget}; + } assert(false); std::unreachable(); } @@ -712,6 +720,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); @@ -1021,6 +1030,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); @@ -1082,6 +1093,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) { From 4af883bfaeccc553bfa2133b3503e4e4a1f4ce94 Mon Sep 17 00:00:00 2001 From: nook0110 Date: Mon, 9 Nov 2026 02:02:43 +0300 Subject: [PATCH 2/5] [uci] Report quiescence nodes in info nodes "info nodes" now counts main plus quiescence nodes, the same total that "nps" is computed from. The separate "info quiescence_nodes" line is gone; no tool or test reads it. Search is unchanged: the same 30 positions at depth 11 give the same best moves, and each new node count equals the old main plus quiescence count. Bench: 2709383 Co-Authored-By: Claude Opus 5.5 --- Chess/SimpleChessEngine.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Chess/SimpleChessEngine.h b/Chess/SimpleChessEngine.h index 3032096..f3fe92e 100644 --- a/Chess/SimpleChessEngine.h +++ b/Chess/SimpleChessEngine.h @@ -159,11 +159,12 @@ class ChessEngine { PrincipalVariationInfo pv{current_depth, searcher_.GetPrincipalVariation( current_depth, position_)}; PrintInfo(pv); - PrintInfo(NodesInfo{info.searched_nodes}); + PrintInfo(NodesInfo{info.searched_nodes + info.quiescence_nodes}); PrintInfo(NodePerSecondInfo{static_cast( (info.searched_nodes + info.quiescence_nodes) / 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"; } } From 84dfe3bd0940ef09e3596396c65b8fe033660b25 Mon Sep 17 00:00:00 2001 From: nook0110 Date: Mon, 9 Nov 2026 02:02:43 +0300 Subject: [PATCH 3/5] [tests] Give the Lazy SMP test time to start The test waited 15 seconds for "uciok". An idle start takes about a second, but on a loaded machine a cold start once took 34 seconds. The wait is now 60 seconds. The other two tests that were excluded locally do not need changes: SharedClusterTable.ConcurrentEntriesStayConsistent passed every run in a few milliseconds, and BestMove.WinAtChess is a strength test with a wall-clock budget per position, so it stays excluded as in CI. Bench: 2709383 Co-Authored-By: Claude Opus 5.5 --- Tests/uci_lazy_smp_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/uci_lazy_smp_test.py b/Tests/uci_lazy_smp_test.py index 02c0d02..070d98a 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 = { From 7280d89891acd1daf5a0d609f5059ba744ecc9cd Mon Sep 17 00:00:00 2001 From: nook0110 Date: Mon, 9 Nov 2026 02:02:43 +0300 Subject: [PATCH 4/5] [uci] Reject malformed FEN positions "position fen" used to read any string into a Position: a garbage board, a pawn on the back rank, two kings, a castling right without its rook or an en passant square without a pushed pawn all produced a corrupt position for the search. PositionFactory::TryParse now parses the FEN once and returns std::nullopt for anything the engine cannot represent, and the UCI handler also refuses positions where the side to move could capture the king. A rejected FEN is reported with "info string invalid fen" and keeps the previous position. Before the first "position" command the engine now holds the initial position instead of an empty board. Shredder-FEN castling files (A-H, a-h) are accepted and ignored, as before. Valid FENs give the same Position as before: perft and the fixed-depth search checks are unchanged. Bench: 2709383 Co-Authored-By: Claude Opus 5.5 --- Chess/PositionFactory.h | 358 +++++++++++++++++++++++++++------------- Chess/UciCommunicator.h | 18 +- Tests/uci_input_test.py | 16 ++ 3 files changed, 274 insertions(+), 118 deletions(-) diff --git a/Chess/PositionFactory.h b/Chess/PositionFactory.h index 8d9466a..3a04035 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 = { {{rook_between[kings[0]][kKingCastlingDestination[0][0]], rook_between[kings[0]][kKingCastlingDestination[0][1]]}, {rook_between[kings[1]][kKingCastlingDestination[1][0]], rook_between[kings[1]][kKingCastlingDestination[1][1]]}}}; std::array, kColors> cs_rook = { - {{rook_between[rooks[0][0]][kRookCastlingDestination[0][0]], - rook_between[rooks[0][1]][kRookCastlingDestination[0][1]]}, - {rook_between[rooks[1][0]][kRookCastlingDestination[1][0]], - rook_between[rooks[1][1]][kRookCastlingDestination[1][1]]}}}; + {{rook_between[rook_squares[0][0]][kRookCastlingDestination[0][0]], + rook_between[rook_squares[0][1]][kRookCastlingDestination[0][1]]}, + {rook_between[rook_squares[1][0]][kRookCastlingDestination[1][0]], + rook_between[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/UciCommunicator.h b/Chess/UciCommunicator.h index 3cbc711..22aefe8 100644 --- a/Chess/UciCommunicator.h +++ b/Chess/UciCommunicator.h @@ -705,7 +705,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); @@ -734,7 +734,7 @@ class UciChessEngine { SearchThread search_thread_; - Info info_; + Info info_{.position = PositionFactory{}(), .time_control = {}}; EngineOptions options_; bool quit_ = false; @@ -866,8 +866,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() { @@ -917,7 +925,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; diff --git a/Tests/uci_input_test.py b/Tests/uci_input_test.py index d6ffd90..2ec6313 100644 --- a/Tests/uci_input_test.py +++ b/Tests/uci_input_test.py @@ -17,6 +17,22 @@ ("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"), ] From 552c6e34bcc91515c3d5db45c44f260a1f000f7b Mon Sep 17 00:00:00 2001 From: nook0110 Date: Mon, 9 Nov 2026 02:02:43 +0300 Subject: [PATCH 5/5] [tests] Feed randomized malformed input to the UCI parsers A fixed-seed batch of mutated FENs, illegal or truncated moves and garbage go and setoption arguments runs through one engine process and checks that the engine neither crashes nor changes its position. It takes about ten seconds in Release and also passes under AddressSanitizer and UndefinedBehaviorSanitizer. Bench: 2709383 Co-Authored-By: Claude Opus 5.5 --- Tests/uci_input_test.py | 66 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/Tests/uci_input_test.py b/Tests/uci_input_test.py index 2ec6313..94d1d44 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 @@ -38,7 +39,68 @@ 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: @@ -56,6 +118,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: