[CHAPTER 07 // crates/search & crates/protocol · engine, SPEC 006, engine, SPEC 002] Implemented in engine code

Cooperative Time Management & Non-Blocking UCI Output

Monotonic soft/hard clock bounds anchored at command receipt and lock-free OnceLock SPSC UCI output offloading so stdout I/O never stalls search.

Why does BalouChess do this?

In tournament chess and interactive play, losing on time forfeits even a winning position, while slow GUI stdout pipes can silently stall an engine thread that prints info lines directly from inside the search.

BalouChess solves both in tandem: a dedicated reader thread timestamps UCI go commands monotonically upon arrival to govern soft and hard time bounds, while a dedicated output thread drains search telemetry through a lock-free single-producer/single-consumer slot chain so the search thread never blocks on I/O.

Data Layout, Invariants & Common Pitfalls

Memory & State Layout

In crates/protocol, balou-input reads bounded UCI lines (MAX_LINE = 131_072 B, engine, SPEC 002/R13), records Instant::now() on command arrival, and triggers atomic stop flags; balou-output consumes info and bestmove strings from a contention-free linked OnceLock<Option<(Message, Arc<Slot>)>> SPSC queue. In crates/search, TimeManager computes budget v = max(0, remaining - MoveOverhead), base slice b = v / horizon + tm_inc_share * increment, hard bound h = max(0, min(tm_hard_factor * b, v - tm_margin)), and soft bound s = min(phase_factor * b, h) (engine, SPEC 006 §5, plus single-reply cap R7 and panic mode R10). For the planned Web-Lab, the host-stop feature is specified (engine, SPEC 003/R23, engine, SPEC 017) to poll a WASI stop file (/balou/stop) fed by the JS Worker's SharedArrayBuffer.

Formal Invariants

  • Clock anchored at command arrival & depth-1 floor (engine, SPEC 002/R1, engine, SPEC 006/R1, R3): elapsed time is measured monotonically from the moment balou-input receives go, and depth 1 always completes before any stop or hard bound takes effect so bestmove is always a searched legal move.
  • Contention-free SPSC telemetry & specified Wasm determinism (engine, SPEC 002, engine, SPEC 003/R23): each output Slot is written once by the sole producer and read via OnceLock::get() without mutex contention; the specified Web-Lab build, not built yet, must keep unstopped fixed-depth/fixed-node searches bit-identical to native builds.

Typical Pitfalls & Edge Cases

  • Writing UCI info lines synchronously to stdout on the search thread: a sluggish GUI pipe stalls alpha-beta search mid-iteration and causes time forfeits; offloading all emission to balou-output decouples search speed from pipe backpressure.
  • Thread parking on single-threaded WebAssembly (specified but not built yet, engine, SPEC 006/R12 & engine, SPEC 017): OS condition variables deadlock a single-threaded Wasm Worker, so the upcoming host-stop path polls cooperatively without parking threads.