Implement tablebase move grading in the play view

#7: prefetch the tablebase at mount and grade a played move locally
against its moves list (optimal / winning / losing), blocking the
attempt when the tablebase is rate-limited or unavailable. The client
now reports prev_fen and promotion, and the trainer board locks after a
graded move until reset.

Fix the 429 clause ordering in the tablebase parser so the cooldown
actually fires, and use the HTTPS endpoint.

Add dialyxir to the dev/test deps.
This commit is contained in:
2026-11-01 21:37:27 +01:00
parent e5f9365ed7
commit 758629565b
5 changed files with 299 additions and 65 deletions
+15 -13
View File
@@ -44,7 +44,7 @@ export const ChessBoard = {
});
},
initBoard({ fen, orientation, player_color }) {
initBoard({ fen, orientation, player_color, blocked }) {
try {
this.chess.load(fen);
} catch (error) {
@@ -67,9 +67,9 @@ export const ChessBoard = {
orientation: orientation,
turnColor: turnColor,
movable: {
color: player_color,
color: blocked ? null : player_color,
free: false,
dests: this.getValidDests(),
dests: blocked ? new Map() : this.getValidDests(),
},
events: {
move: (orig, dest, _capturedPiece) => {
@@ -134,22 +134,25 @@ export const ChessBoard = {
},
executeMove(orig, dest, promotion) {
const move = this.chess.move({ from: orig, to: dest, promotion });
const prevFen = this.chess.fen();
const move = promotion
? this.chess.move({ from: orig, to: dest, promotion })
: this.chess.move({ from: orig, to: dest });
if (move) {
const eventName =
this.el.dataset && this.el.dataset.endgameId
? "endgame_move_played"
: "move_played";
const isTrainer = !!(this.el.dataset && this.el.dataset.endgameId);
const eventName = isTrainer ? "endgame_move_played" : "move_played";
const payload = {
from: orig,
to: dest,
prev_fen: prevFen,
fen: this.chess.fen(),
san: move.san,
promotion: promotion || null,
};
if (eventName === "endgame_move_played") {
if (isTrainer) {
payload.endgame_id = this.el.dataset.endgameId;
}
@@ -160,10 +163,9 @@ export const ChessBoard = {
this.ground.set({
turnColor: nextTurnColor,
fen: this.chess.fen(),
movable: {
color: nextTurnColor,
dests: this.getValidDests(),
},
movable: isTrainer
? { color: null, dests: new Map() }
: { color: nextTurnColor, dests: this.getValidDests() },
});
} else {
this.ground.set({ fen: this.chess.fen() });
@@ -11,7 +11,7 @@ defmodule Chesstrainer.Endgames.Tablebase.Parser do
import Chesstrainer.Ratelimiters
alias Chesstrainer.Endgames.Tablebase
@lichess_tablebase_url "http://tablebase.lichess.ovh/standard?fen="
@lichess_tablebase_url "https://tablebase.lichess.ovh/standard?fen="
@spec from_fen(String.t()) ::
{:ok, Tablebase.t()} | {:cooldown, non_neg_integer()} | {:error, term()}
@@ -72,21 +72,22 @@ defmodule Chesstrainer.Endgames.Tablebase.Parser do
}
end
defp parse_response(response) do
# exposed for testing
def parse_response(response) do
case response do
# Success
{:ok, %Req.Response{status: 200, body: body}} ->
{:ok, body}
# Client errors
{:ok, %Req.Response{status: status, body: body}} when status in 400..499 ->
{:error, {:client_error, status, body}}
# Rate limiting
# Rate limiting (must precede the generic 4xx clause, or 429 is swallowed)
{:ok, %Req.Response{status: 429, body: body}} ->
lichess_add_cooldown()
{:error, {:too_many_requests, 429, body}}
# Client errors
{:ok, %Req.Response{status: status, body: body}} when status in 400..499 ->
{:error, {:client_error, status, body}}
# Server errors
{:ok, %Req.Response{status: status, body: body}} when status in 500..599 ->
{:error, {:server_error, status, body}}
+162 -29
View File
@@ -2,6 +2,7 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
use ChesstrainerWeb, :live_view
alias Chesstrainer.Endgames
alias Chesstrainer.Endgames.Tablebase
@impl true
def render(assigns) do
@@ -30,6 +31,26 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
</div>
<div class="w-48 h-100 flex flex-col gap-3">
<div class="rounded-lg bg-white p-3 text-sm">
<%= cond do %>
<% @status == :loading -> %>
<p class="text-gray-500">Loading tablebase…</p>
<% @status == :blocked -> %>
<p class="font-semibold text-red-600">Tablebase unavailable</p>
<p class="text-red-500">{@blocked_reason}</p>
<% @last_grade == :optimal -> %>
<p class="font-semibold text-emerald-600">Optimal move</p>
<% @last_grade == :winning -> %>
<p class="font-semibold text-amber-600">Winning — but not the sharpest</p>
<% @last_grade == :losing -> %>
<p class="font-semibold text-red-600">Losing move — this throws away the win</p>
<% @last_grade == :unknown -> %>
<p class="font-semibold text-gray-600">Could not grade that move</p>
<% true -> %>
<p class="text-gray-500">Make a move to have it graded.</p>
<% end %>
</div>
<div class="flex-1 min-h-0 flex flex-col bg-white rounded-lg p-3">
<p class="text-sm text-gray-600 font-semibold mb-2">Moves:</p>
<div class="flex-1 overflow-y-auto">
@@ -49,8 +70,6 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
</div>
</div>
<div>Buttons</div>
<div>
<.button phx-click="reset" variant="primary">
<.icon name="hero-arrow-path" /> Reset
@@ -70,30 +89,36 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
socket
|> assign(:page_title, "Play endgame")
|> assign(:endgame, endgame)
|> assign(:fen, endgame.fen)
|> assign(:tablebase, nil)
|> assign(:status, :loading)
|> assign(:blocked_reason, nil)
|> assign(:move_list, [])
|> assign(:last_san, "None yet")
|> assign(:last_from_to, "None yet")
|> push_event("init_board", %{
fen: endgame.fen,
orientation: Atom.to_string(endgame.color),
player_color: Atom.to_string(endgame.color)
})
|> assign(:last_grade, nil)
{:ok, socket}
{:ok, load_attempt(socket)}
end
@impl true
def handle_event(
"endgame_move_played",
%{"from" => from, "to" => to, "san" => san},
socket
) do
# TODO: server-side legality check + tablebase evaluation when wired
{:noreply,
socket
|> assign(:last_from_to, "#{from} ➔ #{to}")
|> assign(:last_san, san)
|> assign(:move_list, socket.assigns.move_list ++ [san])}
def handle_event("endgame_move_played", params, socket) do
%{"from" => from, "to" => to, "san" => san} = params
promotion = params["promotion"]
prev_fen = params["prev_fen"] || socket.assigns.fen
cond do
socket.assigns.status != :playing ->
{:noreply,
put_flash(socket, :error, "The tablebase is unavailable, so this move cannot be graded.")}
not same_position?(prev_fen, socket.assigns.fen) ->
{:noreply,
put_flash(socket, :error, "That move is out of sequence. Press Reset to try again.")}
true ->
grade_and_record(socket, from, to, promotion, san)
end
end
def handle_event("chess_fen_invalid", %{"fen" => fen, "message" => message}, socket) do
@@ -106,16 +131,14 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
end
def handle_event("reset", _params, socket) do
{:noreply,
socket
|> assign(:move_list, [])
|> assign(:last_san, "None yet")
|> assign(:last_from_to, "None yet")
|> push_event("init_board", %{
fen: socket.assigns.endgame.fen,
orientation: Atom.to_string(socket.assigns.endgame.color),
player_color: Atom.to_string(socket.assigns.endgame.color)
})}
socket =
socket
|> assign(:move_list, [])
|> assign(:last_san, "None yet")
|> assign(:last_from_to, "None yet")
|> assign(:last_grade, nil)
{:noreply, load_attempt(socket)}
end
def format_move_pairs(move_list, color) do
@@ -125,4 +148,114 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|> Enum.chunk_every(2, 2, [nil])
|> Enum.with_index(1)
end
defp load_attempt(socket) do
fen = socket.assigns.endgame.fen
socket = assign(socket, :fen, fen)
if connected?(socket) do
case Tablebase.new(fen) do
{:ok, tablebase} ->
socket
|> assign(:tablebase, tablebase)
|> assign(:status, :playing)
|> assign(:blocked_reason, nil)
|> push_init_board(fen)
other ->
socket
|> assign(:tablebase, nil)
|> assign(:status, :blocked)
|> assign(:blocked_reason, blocked_reason(other))
|> push_init_board(fen)
end
else
assign(socket, :status, :loading)
end
end
defp push_init_board(socket, fen) do
push_event(socket, "init_board", %{
fen: fen,
orientation: Atom.to_string(socket.assigns.endgame.color),
player_color: Atom.to_string(socket.assigns.endgame.color),
blocked: socket.assigns.status == :blocked
})
end
defp blocked_reason({:cooldown, remaining_ms}) do
seconds = max(div(remaining_ms + 999, 1000), 1)
"The tablebase is rate-limited. Try again in about #{seconds}s."
end
defp blocked_reason({:error, {:too_many_requests, _, _}}) do
"The tablebase is rate-limited. Try again in a minute."
end
defp blocked_reason({:error, {:client_error, 404, _}}) do
"This position is not covered by the tablebase."
end
defp blocked_reason({:error, reason}) do
"The tablebase is unavailable (#{inspect(reason)})."
end
defp grade_and_record(socket, from, to, promotion, san) do
case find_move(socket.assigns.tablebase, from, to, promotion) do
nil ->
{:noreply, put_flash(socket, :error, "Could not identify that move in the tablebase.")}
move ->
{:noreply,
socket
|> assign(:last_from_to, "#{from} ➔ #{to}")
|> assign(:last_san, san)
|> assign(:last_grade, grade_move(socket.assigns.tablebase, move))
|> assign(:move_list, socket.assigns.move_list ++ [san])}
end
end
defp find_move(%Tablebase{moves: moves}, from, to, promotion) when is_list(moves) do
uci = "#{from}#{to}#{promotion || ""}"
Enum.find(moves, &(&1.uci == uci))
end
defp find_move(_tablebase, _from, _to, _promotion), do: nil
# Compare only the board and side to move: chess.js may normalise the rest
# (castling/en-passant/halfmove/fullmove) differently from the stored FEN.
defp same_position?(fen_a, fen_b), do: position_key(fen_a) == position_key(fen_b)
defp position_key(fen) do
case String.split(fen, " ") do
[board, active | _] -> {board, active}
_ -> fen
end
end
defp grade_move(%Tablebase{moves: []}, _move), do: :unknown
defp grade_move(%Tablebase{category: position_category, moves: [best | _]}, move) do
best_rank = outcome_rank(position_category)
move_rank = outcome_rank(mover_outcome(move.category))
cond do
is_nil(best_rank) or is_nil(move_rank) -> :unknown
move_rank < best_rank -> :losing
move.dtz == best.dtz -> :optimal
true -> :winning
end
end
# The mover's outcome is the flip of `category`, which is reported from the
# perspective of the side to move *after* the move.
defp mover_outcome(:loss), do: :win
defp mover_outcome(:win), do: :loss
defp mover_outcome(:draw), do: :draw
defp mover_outcome(_), do: :unknown
defp outcome_rank(:win), do: 2
defp outcome_rank(:draw), do: 1
defp outcome_rank(:loss), do: 0
defp outcome_rank(_), do: nil
end
@@ -4,6 +4,7 @@ defmodule Chesstrainer.Endgames.TablebaseTest do
alias Chesstrainer.Endgames.Tablebase
alias Chesstrainer.Endgames.Tablebase.Cache, as: TablebaseCache
alias Chesstrainer.Endgames.Tablebase.Parser
alias Chesstrainer.Ratelimiters
describe "normalize_category/1" do
test "maps winning categories to :win" do
@@ -68,6 +69,19 @@ defmodule Chesstrainer.Endgames.TablebaseTest do
end
end
describe "Parser.parse_response/1" do
test "a 429 sets the cooldown and returns a rate-limit error" do
Ratelimiters.lichess_reset_cooldown()
on_exit(fn -> Ratelimiters.lichess_reset_cooldown() end)
assert {:error, {:too_many_requests, 429, "rate limited"}} =
Parser.parse_response({:ok, %Req.Response{status: 429, body: "rate limited"}})
assert {:cooldown, remaining} = Ratelimiters.lichess_check_cooldown()
assert remaining > 0
end
end
describe "new/1" do
test "returns {:ok, tablebase} on a cache hit" do
fen = "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1"
@@ -4,6 +4,10 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
import Phoenix.LiveViewTest
import Chesstrainer.EndgamesFixtures
alias Chesstrainer.Endgames.Tablebase
alias Chesstrainer.Endgames.Tablebase.Cache, as: TablebaseCache
alias Chesstrainer.Ratelimiters
defp assert_init_board(view, expected_fen, expected_orientation, expected_player_color) do
%{proxy: {ref, _topic, _}} = view
@@ -14,9 +18,40 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
assert payload.player_color == expected_player_color
end
# Seed the tablebase cache so mount never touches the network in tests.
defp seed_tablebase(fen, opts \\ []) do
tablebase = %Tablebase{
category: Keyword.get(opts, :category, :win),
moves: Keyword.get(opts, :moves, [])
}
TablebaseCache.put(fen, tablebase)
on_exit(fn -> TablebaseCache.delete(fen) end)
end
defp grading_moves do
[
%Tablebase.Move{uci: "d1d7", san: "Qd7+", category: :loss, dtz: -1},
%Tablebase.Move{uci: "d1d5", san: "Qd5", category: :loss, dtz: -9},
%Tablebase.Move{uci: "d1d4", san: "Qd4", category: :draw, dtz: 0}
]
end
defp play_move(view, endgame, from, to, san) do
render_hook(view, "endgame_move_played", %{
"from" => from,
"to" => to,
"san" => san,
"prev_fen" => endgame.fen,
"fen" => endgame.fen,
"endgame_id" => endgame.id
})
end
describe "mount" do
test "renders the chessboard hook div and pushes init_board", %{conn: conn} do
endgame = endgame_fixture(color: :white)
seed_tablebase(endgame.fen)
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
@@ -26,6 +61,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
test "pushes black orientation when the endgame color is black", %{conn: conn} do
endgame = endgame_fixture(color: :black)
seed_tablebase(endgame.fen)
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
@@ -34,6 +70,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
test "shows endgame metadata in the header", %{conn: conn} do
endgame = endgame_fixture(key: "KQ v K", color: :white, result: :win, rating: 1800)
seed_tablebase(endgame.fen)
{:ok, _view, html} = live(conn, ~p"/endgames/#{endgame}/play")
@@ -49,9 +86,26 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
end
end
describe "tablebase availability" do
test "blocks the attempt when the tablebase is cooling down", %{conn: conn} do
endgame = endgame_fixture()
TablebaseCache.delete(endgame.fen)
Ratelimiters.lichess_add_cooldown()
on_exit(fn -> Ratelimiters.lichess_reset_cooldown() end)
{:ok, view, html} = live(conn, ~p"/endgames/#{endgame}/play")
assert html =~ "Tablebase unavailable"
play_move(view, endgame, "d1", "d7", "Qd7+")
assert render(view) =~ "cannot be graded"
end
end
describe "chess_fen_invalid" do
test "shows a flash when the chessground hook reports an unparseable FEN", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen)
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
@@ -68,45 +122,75 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
end
describe "endgame_move_played" do
test "appends the SAN move and updates last_san / last_from_to", %{conn: conn} do
test "grades the optimal move", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
view
|> render_hook("endgame_move_played", %{
play_move(view, endgame, "d1", "d7", "Qd7+")
html = render(view)
assert html =~ "Optimal move"
assert html =~ "Qd7+"
end
test "grades a winning but slower move as winning", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
play_move(view, endgame, "d1", "d5", "Qd5")
assert render(view) =~ "Winning — but not the sharpest"
end
test "grades a move that throws the win away as losing", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
play_move(view, endgame, "d1", "d4", "Qd4")
assert render(view) =~ "Losing move"
end
test "rejects a move that is out of sequence", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
render_hook(view, "endgame_move_played", %{
"from" => "d1",
"to" => "d7",
"san" => "Qd7+",
"prev_fen" => "8/8/8/8/8/8/8/8 w - - 0 1",
"fen" => endgame.fen,
"endgame_id" => endgame.id
})
html = render(view)
assert html =~ "Qd7+"
assert render(view) =~ "out of sequence"
end
end
describe "reset" do
test "clears move list and re-pushes init_board", %{conn: conn} do
test "clears the move list and grade, and re-pushes init_board", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
view
|> render_hook("endgame_move_played", %{
"from" => "d1",
"to" => "d7",
"san" => "Qd7+",
"fen" => endgame.fen,
"endgame_id" => endgame.id
})
play_move(view, endgame, "d1", "d7", "Qd7+")
assert render(view) =~ "Qd7+"
view |> element("button", "Reset") |> render_click()
assert render(view) =~ "No Moves"
html = render(view)
assert html =~ "No Moves"
refute html =~ "Optimal move"
assert_init_board(view, endgame.fen, "white", "white")
end
end