Skip to content

Commit 8e6d3e7

Browse files
authored
Implementing UCI time controls (#124)
1 parent 53c42e8 commit 8e6d3e7

12 files changed

Lines changed: 526 additions & 64 deletions

File tree

‎docs/commands.md‎

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,16 @@ Implemented behavior (current state):
125125

126126
- `depth <n>`: fixed-depth search.
127127
- `infinite`: iterative deepening until `stop`.
128-
- If `depth` is not provided, search defaults to infinite mode.
129-
- If `depth` and `infinite` are both present, `infinite` takes precedence.
128+
- `movetime <ms>`: iterative deepening search limited by a per-move budget in milliseconds.
129+
- Non-positive `movetime` values are clamped to `1` ms.
130+
- `movetime` takes precedence over `wtime`/`btime`/`winc`/`binc`.
131+
- `infinite` takes precedence over every other limit, including `movetime` and `depth`.
132+
- If both `depth` and a time-based limit are provided, the current implementation runs the timed search path.
133+
- When `movetime` is not provided, time is estimated from the side-to-move clock:
134+
roughly remaining time divided across future moves, with increment added and a safety reserve kept aside.
135+
136+
- If no argument is provided behind `go`, search defaults to infinite mode.
137+
- If `depth` is not provided and no time control is provided either, search defaults to infinite mode.
130138

131139
Response when search ends:
132140

@@ -205,6 +213,7 @@ Implemented behavior (current state):
205213

206214
- Uses the same limit parser as `go`.
207215
- `depth <n>` runs a fixed-depth benchmark.
216+
- `movetime <ms>` runs a time-limited benchmark using the same semantics as `go`.
208217
- If `infinite` is provided, benchmark mode internally converts to `depth 10`.
209218
- A bare `bench` command (no limits) is parsed as `infinite`, then converted internally to `depth 10`.
210219
- `stop` can still interrupt a running benchmark early.
@@ -223,18 +232,3 @@ Not implemented yet.
223232

224233
- The engine currently does not expose configurable UCI options.
225234
- No `option name ...` lines are emitted in `uci` response.
226-
227-
### `go` time-control fields
228-
229-
The following tokens are parsed but not yet enforced by search scheduling:
230-
231-
- `movetime <ms>`
232-
- `wtime <ms>`
233-
- `btime <ms>`
234-
- `winc <ms>`
235-
- `binc <ms>`
236-
237-
Today, practical stopping control is:
238-
239-
- `go depth <n>` for bounded search
240-
- `go` or `go infinite`, then `stop` for unbounded search

‎include/bitbishop/interface/search_worker.hpp‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#pragma once
22

3-
#include <bitbishop/engine/search.hpp>
43
#include <atomic>
4+
#include <bitbishop/engine/search.hpp>
55
#include <bitbishop/moves/position.hpp>
66
#include <mutex>
77
#include <optional>
@@ -30,6 +30,22 @@ struct SearchLimits {
3030
* @return The built SearchLimits object.
3131
*/
3232
static SearchLimits from_uci_cmd(const std::vector<std::string>& line);
33+
34+
/**
35+
* @brief Returns whether any time-based search limit was provided.
36+
*/
37+
[[nodiscard]] bool has_time_limit() const;
38+
39+
/**
40+
* @brief Estimates how much time the current side should spend on this move.
41+
*
42+
* `movetime` takes precedence when present. Otherwise the estimate is derived
43+
* from the side-to-move remaining clock and increment.
44+
*
45+
* @param side_to_move Side that is currently searching.
46+
* @return Think time budget in milliseconds, or std::nullopt if no clock is available.
47+
*/
48+
[[nodiscard]] std::optional<int> think_time_ms(Color side_to_move) const;
3349
};
3450

3551
/**
@@ -86,7 +102,7 @@ class SearchWorker {
86102
* @brief Starts the search process with given parameters.
87103
*
88104
* Initializes the search controller with a new worker thread and parameters.
89-
* If no depth is specified, switches to infinite search mode.
105+
* If no search limit is specified, switches to infinite search mode.
90106
*/
91107
void start();
92108

‎include/bitbishop/movegen/legal_moves.hpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
#include <vector>
2020

2121
namespace MoveGen {
22-
enum class Scope {
22+
enum class Scope : std::uint8_t {
2323
AllMoves,
2424
CapturesOnly,
2525
};
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#pragma once
2+
3+
#include <atomic>
4+
#include <chrono>
5+
#include <condition_variable>
6+
#include <mutex>
7+
#include <thread>
8+
9+
namespace Tools {
10+
11+
/**
12+
* @class TimeGuard
13+
* @brief An RAII-based asynchronous countdown timer used to signal a timeout via an atomic flag.
14+
*
15+
* This class spawns a background thread that waits for a specified duration. If the duration
16+
* elapses without the object being destroyed or cancelled, it sets the provided @p stop_flag to true.
17+
*
18+
* @note This is designed for search algorithms where a search must
19+
* be terminated after a certain amount of time.
20+
*/
21+
class TimeGuard {
22+
public:
23+
/**
24+
* @brief Constructs the timer and immediately starts the countdown in a background thread.
25+
*
26+
* @param stop_flag Reference to an atomic boolean. This flag is monitored for external
27+
* cancellation and is set to @c true by this class upon timeout.
28+
* @param timeout The maximum duration to wait before setting the flag.
29+
*/
30+
TimeGuard(std::atomic<bool>& stop_flag, std::chrono::steady_clock::duration timeout);
31+
32+
/**
33+
* @brief Destructor. Safely cancels the timer and joins the background thread.
34+
*
35+
* This ensures that no "zombie" threads are left running. If the timer has not yet
36+
* expired, it is signaled to wake up and exit immediately.
37+
*/
38+
~TimeGuard();
39+
40+
// Deleted copy and move operations to prevent accidental thread ownership issues.
41+
TimeGuard(const TimeGuard&) = delete;
42+
TimeGuard& operator=(const TimeGuard&) = delete;
43+
TimeGuard(TimeGuard&&) = delete;
44+
TimeGuard& operator=(TimeGuard&&) = delete;
45+
46+
private:
47+
/**
48+
* @brief The main loop for the worker thread.
49+
*
50+
* Uses a @c std::condition_variable::wait_for to sleep efficiently. It wakes up if:
51+
* 1. The @p timeout expires (sets @p stop_flag to @c true).
52+
* 2. The @p cancelled flag is set via the destructor/cancel().
53+
* 3. The @p stop_flag is set to @c true by external logic.
54+
*/
55+
void start();
56+
57+
/**
58+
* @brief Internal helper to signal the worker thread to stop and clean up resources.
59+
*
60+
* Thread-safe. It notifies the condition variable and joins the worker thread.
61+
*/
62+
void cancel();
63+
64+
std::atomic<bool>& stop_flag;
65+
std::chrono::steady_clock::duration timeout;
66+
std::mutex mutex;
67+
std::condition_variable cv;
68+
bool cancelled = false;
69+
std::thread worker;
70+
};
71+
72+
} // namespace Tools

‎src/bitbishop/interface/search_worker.cpp‎

Lines changed: 83 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,32 @@
1+
#include <algorithm>
12
#include <bitbishop/interface/search_worker.hpp>
3+
#include <bitbishop/tools/time_guard.hpp>
4+
#include <limits>
5+
6+
namespace {
7+
8+
constexpr int DEFAULT_MOVES_TO_GO = 20;
9+
constexpr int MIN_THINK_TIME_MS = 1;
10+
constexpr int SAFETY_BUFFER_MS = 50;
11+
constexpr int MAX_DEPTH = 50;
12+
13+
[[nodiscard]] int estimate_clock_think_time_ms(int remaining_ms, int increment_ms) {
14+
remaining_ms = std::max(remaining_ms, 0);
15+
increment_ms = std::max(increment_ms, 0);
16+
17+
if (remaining_ms <= MIN_THINK_TIME_MS) {
18+
return MIN_THINK_TIME_MS;
19+
}
20+
21+
const int reserve_ms = std::min(remaining_ms - MIN_THINK_TIME_MS, std::max(SAFETY_BUFFER_MS, remaining_ms / 20));
22+
const int spendable_ms = std::max(MIN_THINK_TIME_MS, remaining_ms - reserve_ms);
23+
const int base_ms = spendable_ms / DEFAULT_MOVES_TO_GO;
24+
const int increment_bonus_ms = (increment_ms * 3) / 4;
25+
26+
return std::clamp(base_ms + increment_bonus_ms, MIN_THINK_TIME_MS, spendable_ms);
27+
}
28+
29+
} // namespace
230

331
Uci::SearchLimits Uci::SearchLimits::from_uci_cmd(const std::vector<std::string>& line) {
432
SearchLimits limits;
@@ -29,14 +57,31 @@ Uci::SearchLimits Uci::SearchLimits::from_uci_cmd(const std::vector<std::string>
2957
}
3058
}
3159

32-
const bool has_time_control = limits.movetime || limits.wtime || limits.btime || limits.winc || limits.binc;
33-
if (!limits.depth && !has_time_control && !limits.infinite) {
60+
if (!limits.depth && !limits.has_time_limit() && !limits.infinite) {
3461
limits.infinite = true;
3562
}
3663

3764
return limits;
3865
}
3966

67+
bool Uci::SearchLimits::has_time_limit() const {
68+
return movetime.has_value() || wtime.has_value() || btime.has_value() || winc.has_value() || binc.has_value();
69+
}
70+
71+
std::optional<int> Uci::SearchLimits::think_time_ms(Color side_to_move) const {
72+
if (movetime.has_value()) {
73+
return std::max(*movetime, MIN_THINK_TIME_MS);
74+
}
75+
76+
const std::optional<int>& remaining_opt = (side_to_move == Color::WHITE) ? wtime : btime;
77+
if (!remaining_opt.has_value()) {
78+
return std::nullopt;
79+
}
80+
81+
const std::optional<int>& increment_opt = (side_to_move == Color::WHITE) ? winc : binc;
82+
return estimate_clock_think_time_ms(*remaining_opt, increment_opt.value_or(0));
83+
}
84+
4085
Uci::SearchWorker::SearchWorker(Board board, SearchLimits limits)
4186
: board(board), position(Position(this->board)), limits(limits) {}
4287

@@ -49,47 +94,52 @@ void Uci::SearchWorker::push_report(SearchReport report) {
4994

5095
void Uci::SearchWorker::run() {
5196
using namespace Search;
97+
98+
// scope_exit function is not yet shipped in all stdlibs (linux is fine, not windows nor macos - 2026-04-29)
99+
// const auto guard = std::experimental::scope_exit([this] { finished.store(true); });
100+
// Replacing it by a struct with custom destructor.
52101
struct FinishGuard {
53102
std::atomic<bool>& finished_ref;
54103
~FinishGuard() { finished_ref.store(true); }
55104
} guard{finished};
56105

57106
SearchStats stats{};
58-
BestMove best;
59-
BestMove last_best;
60-
61-
if (limits.infinite) {
62-
for (int current_depth = 1; !stop_flag.load(); ++current_depth) {
63-
best = negamax(position, current_depth, ALPHA_INIT, BETA_INIT, 0, stats, &stop_flag);
64-
if (!stop_flag.load()) {
65-
last_best = best;
66-
push_report(SearchReport{
67-
.kind = SearchReportKind::Iteration,
68-
.best = last_best,
69-
.depth = current_depth,
70-
.stats = stats,
71-
});
72-
}
73-
}
74-
} else if (limits.depth) {
75-
best = negamax(position, *limits.depth, ALPHA_INIT, BETA_INIT, 0, stats, &stop_flag);
107+
SearchReport current_best_report{.kind = SearchReportKind::Iteration};
108+
109+
const auto side = board.get_side_to_move();
110+
const auto think_time = limits.infinite ? std::nullopt : limits.think_time_ms(side);
111+
std::optional<Tools::TimeGuard> timeguard;
112+
if (think_time) {
113+
timeguard.emplace(stop_flag, std::chrono::milliseconds(*think_time));
114+
}
115+
116+
auto perform_search_at_depth = [&](int depth) {
117+
auto result = negamax(position, depth, ALPHA_INIT, BETA_INIT, 0, stats, &stop_flag);
118+
76119
if (!stop_flag.load()) {
77-
push_report(SearchReport{
78-
.kind = SearchReportKind::Iteration,
79-
.best = best,
80-
.depth = *limits.depth,
81-
.stats = stats,
82-
});
120+
current_best_report.best = result;
121+
current_best_report.depth = depth;
122+
current_best_report.stats = stats;
123+
push_report(current_best_report);
124+
return true;
125+
}
126+
return false;
127+
};
128+
129+
if (limits.depth && !limits.infinite && !think_time) {
130+
// Case: Fixed depth search (e.g., "go depth 10")
131+
perform_search_at_depth(*limits.depth);
132+
} else {
133+
// Case: Iterative deepening (Infinite or Time-limited)
134+
for (int depth = 1; depth <= MAX_DEPTH && !stop_flag.load(); ++depth) {
135+
if (!perform_search_at_depth(depth)) {
136+
break;
137+
}
83138
}
84139
}
85140

86-
const BestMove& final = (last_best.move) ? last_best : best;
87-
push_report(SearchReport{
88-
.kind = SearchReportKind::Finish,
89-
.best = final,
90-
.depth = limits.depth.value_or(0),
91-
.stats = stats,
92-
});
141+
current_best_report.kind = SearchReportKind::Finish;
142+
push_report(current_best_report);
93143
}
94144

95145
void Uci::SearchWorker::start() {

‎src/bitbishop/tools/time_guard.cpp‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include <bitbishop/tools/time_guard.hpp>
2+
3+
namespace Tools {
4+
5+
TimeGuard::TimeGuard(std::atomic<bool>& stop_flag, std::chrono::steady_clock::duration timeout)
6+
: stop_flag(stop_flag), timeout(timeout) {
7+
worker = std::thread(&TimeGuard::start, this);
8+
}
9+
10+
TimeGuard::~TimeGuard() { cancel(); }
11+
12+
void TimeGuard::start() {
13+
std::unique_lock<std::mutex> lock(mutex);
14+
15+
const bool was_interrupted = cv.wait_for(lock, timeout, [this] { return cancelled || this->stop_flag.load(); });
16+
17+
if (!was_interrupted) {
18+
this->stop_flag.store(true);
19+
}
20+
}
21+
22+
void TimeGuard::cancel() {
23+
{
24+
std::lock_guard<std::mutex> lock(mutex);
25+
cancelled = true;
26+
}
27+
cv.notify_one();
28+
29+
if (worker.joinable()) {
30+
worker.join();
31+
}
32+
}
33+
34+
} // namespace Tools

‎tests/bitbishop/helpers/async.hpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ void assert_output_contains(const std::stringstream& output, const std::string&
4040

4141
void assert_output_not_contains(const std::stringstream& output, const std::string& token,
4242
std::chrono::milliseconds timeout = std::chrono::milliseconds(500)) {
43-
ASSERT_FALSE(wait_for([&] { return output.str().find(token) == std::string::npos; }))
43+
ASSERT_TRUE(wait_for([&] { return output.str().find(token) == std::string::npos; }))
4444
<< "Expected output not to contain: " << token << "\nActual output:\n"
4545
<< output.str();
4646
}

0 commit comments

Comments
 (0)