Files
chess-endgame-trainer/lib/chesstrainer/endgames/tablebase.ex
T
owenrees 3fadd4397c Key the tablebase cache by position instead of full FEN (#28)
Add FEN.position_key/1 (board, side, castling and en-passant; clocks dropped) and have Tablebase.new/1 key cache reads and writes on it, so transpositions and clock-only differences share an entry. The Lichess category is a position property, so dropping the clocks is safe.

Update the cache docs and tests, and give the play fixture's after_first/after_losing distinct positions since they previously differed only by the halfmove clock.
2026-11-03 13:09:45 +01:00

77 lines
2.2 KiB
Elixir

defmodule Chesstrainer.Endgames.Tablebase do
@moduledoc """
All endgame tablebase related functions.
Lookups are routed by piece count through `Tablebase.Router`, which picks the
backend that can answer the position.
The cached value carries only what the trainer reads: `category`,
`checkmate`, and `moves`. Cursed-win/blessed-loss are normalised to `:draw` at
parse time, and distance fields (`dtm`/`dtc`/`dtw`) are not kept because the
local Syzygy backend cannot produce them.
"""
alias Chesstrainer.Endgames.Tablebase
alias Chesstrainer.FEN
@type result :: :win | :draw | :loss | :unknown
@type t :: %__MODULE__{
category: result,
checkmate: boolean(),
moves: [Tablebase.Move.t()]
}
defstruct category: nil,
checkmate: false,
moves: nil
@doc """
Normalises a Lichess tablebase category string into a trainer result.
`cursed-win` and `blessed-loss` are wins/losses only when the 50-move rule is
ignored, so they are draws in play. Unrecognised values become `:unknown`
rather than minting arbitrary atoms.
"""
@spec normalize_category(term()) :: result()
def normalize_category(category) when category in ["win", "syzygy-win", "maybe-win"], do: :win
def normalize_category(category) when category in ["draw", "cursed-win", "blessed-loss"],
do: :draw
def normalize_category(category) when category in ["loss", "syzygy-loss", "maybe-loss"],
do: :loss
def normalize_category(_category), do: :unknown
@spec new(String.t()) ::
{:ok, t()}
| {:cooldown, non_neg_integer()}
| {:error, :invalid_endgame}
| {:error, term()}
def new(fen) do
key = FEN.position_key(fen)
case Tablebase.Cache.get(key) do
{:ok, tablebase} ->
{:ok, tablebase}
_ ->
case Tablebase.Router.probe(fen) do
{:error, reason} ->
{:error, reason}
{:cooldown, remaining_ms} ->
{:cooldown, remaining_ms}
{:ok, tablebase} when tablebase.category == :unknown ->
{:error, :invalid_endgame}
{:ok, tablebase} ->
Tablebase.Cache.put(key, tablebase)
{:ok, tablebase}
end
end
end
end