Compare commits

...
7 Commits
Author SHA1 Message Date
owenrees c5989628bc End the attempt on solve or fail and count attempts
#9: solve the puzzle on checkmate or a winning promotion, fail
immediately on a losing move (revealing the missed best move), and
increment times_attempted when an attempt starts and times_solved when
it is solved. Terminal states lock play; reset starts a new attempt.
2026-11-01 22:01:19 +01:00
owenrees 248504cc58 Play the opponent's optimal defence after a passing move
#8: after a passing move, fetch the post-move position's tablebase and
reply with moves[0] (the defender's optimal defence). The client applies
and animates the reply, reports the resulting FEN, and the server fetches
that position's tablebase before resuming the user's turn.

Losing moves and terminal positions do not trigger a reply; a failed
post-reply fetch blocks the attempt. The board stays locked during the
reply round-trip so play cannot get out of sync.
2026-11-01 21:45:32 +01:00
owenrees cadc842010 update docs with static analysis tools 2026-11-01 21:40:29 +01:00
owenrees 758629565b 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.
2026-11-01 21:37:27 +01:00
owenrees e5f9365ed7 install dialyxir 2026-11-01 21:36:31 +01:00
owenrees 8b894465cc Implement tablebase parsing fixes and LFU cache
#5: normalise the full lichess tablebase category vocabulary (cursed-win
and blessed-loss classify as draws), return {:ok, tablebase} on a cache
hit, and unwrap the tablebase in game_from_fen.

#6: replace the LRU cache with an LFU cache storing
{key, value, frequency, last_access}, evicting the least-frequently-used
entry (LRU tie-break) and halving every frequency on a weekly sweep.
Persistence moves to a versioned v2 dets file, dropping the legacy
backup; the cache restores synchronously at startup.

Also updates stale tags enum and Play LiveView tests, and drops the
tracked legacy cache backup.
2026-11-01 21:24:51 +01:00
owenrees 6f08cdd10f add initial ADR and glossary 2026-11-01 21:18:07 +01:00
25 changed files with 1169 additions and 149 deletions
+3
View File
@@ -50,6 +50,9 @@ Read `CODING_STANDARDS.md` before writing code. Read the section for the layer y
Run `mix precommit` and fix what it flags.
Type-check risky changes with `mix dialyzer` (not part of `mix precommit`; the
first run builds a PLT and is slow).
## Agent skills
### Issue tracker
+14
View File
@@ -116,3 +116,17 @@ How to write code in this repo. Read the section for the layer you're touching.
## Precommit
`mix precommit` runs `compile --warnings-as-errors`, `deps.unlock --unused`, `format` and `test`.
## Type checking (Dialyzer)
`dialyxir` is available in dev/test; run:
mix dialyzer
It is intentionally **not** part of `mix precommit`: the first run builds a PLT
(several minutes), though subsequent runs are fast. The PLT lives under
`_build/` (gitignored).
Treat warnings as bugs — add `@spec`s or fix them. Only suppress with
`@dialyzer` or `.dialyzer_ignore.exs` when accompanied by a comment explaining
why.
+63
View File
@@ -0,0 +1,63 @@
# Chesstrainer
An endgame trainer: the user plays a stored endgame position against
tablebase-optimal defence and is graded on every move.
## Core model
**Endgame**:
A stored chess position (FEN) plus metadata — side to move, result, rating,
tags — that can be played as a puzzle.
_Avoid_: Position, puzzle
**Puzzle**:
A playable challenge derived from an endgame: play the winning (or drawing)
side correctly against tablebase-optimal defence.
_Avoid_: Endgame (the stored record), exercise
**Attempt**:
One playthrough of a puzzle by a user, ending solved or failed.
_Avoid_: Run, session, game
## Play
**Winning side**:
The side that can force a win from the position; the side the user plays in
win-type endgames.
**Drawing side**:
In draw endgames, the side that must hold the draw; the side the user plays.
_Avoid_: Defender
**Optimal move**:
The tablebase's best move for the side to move (sharpest win / hardest defence).
**Winning move**:
A move that keeps the win (the opponent is still lost). Passes.
_Avoid_: Good move, accurate move
**Losing move**:
A move that throws away the result (the position becomes drawn or lost).
Fails the puzzle.
_Avoid_: Blunder, mistake
**Conversion**:
The decisive zeroing move — a promotion — that ends a conversion-type puzzle.
**Cutoff**:
The terminal condition short of mate at which a puzzle counts as solved:
promotion (still winning) for conversion puzzles, mate otherwise.
## Infrastructure
**Tablebase**:
A database of precomputed optimal outcomes for every position with at most
seven pieces, queried via the lichess API and cached.
**Cooldown**:
Rate-limit state entered after a 429 from the lichess tablebase API, during
which the trainer blocks play.
**Cache sweep**:
The periodic halving of LFU cache frequencies (weekly) that lets rarely-used
entries age out.
+64 -13
View File
@@ -5,6 +5,7 @@ export const ChessBoard = {
mounted() {
this.chess = new Chess();
this.ground = null;
this.playerColor = "white";
this.handleEvent("init_board", (payload) => {
this.initBoard(payload);
@@ -37,6 +38,14 @@ export const ChessBoard = {
}
});
this.handleEvent("opponent_move", ({ from, to, promotion, san }) => {
this.applyOpponentMove({ from, to, promotion, san });
});
this.handleEvent("resume_board", () => {
this.resumeBoard();
});
this.initBoard({
fen: this.chess.fen(),
orientation: "white",
@@ -44,7 +53,7 @@ export const ChessBoard = {
});
},
initBoard({ fen, orientation, player_color }) {
initBoard({ fen, orientation, player_color, blocked }) {
try {
this.chess.load(fen);
} catch (error) {
@@ -56,6 +65,8 @@ export const ChessBoard = {
return;
}
this.playerColor = player_color;
if (this.ground) {
this.ground.destroy();
}
@@ -67,9 +78,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 +145,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,13 +174,50 @@ 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() });
}
},
applyOpponentMove({ from, to, promotion, san }) {
const move = promotion
? this.chess.move({ from, to, promotion })
: this.chess.move({ from, to });
if (!move) {
console.error("Opponent move rejected by chess.js", { from, to, promotion, san });
return;
}
const nextTurnColor = this.chess.turn() === "w" ? "white" : "black";
this.ground.set({
fen: this.chess.fen(),
turnColor: nextTurnColor,
movable: { color: null, dests: new Map() },
});
this.pushEvent("opponent_reply_applied", {
fen: this.chess.fen(),
san: move.san,
});
},
resumeBoard() {
const turnColor = this.chess.turn() === "w" ? "white" : "black";
this.ground.set({
fen: this.chess.fen(),
turnColor,
movable: {
color: this.playerColor || turnColor,
free: false,
dests: this.getValidDests(),
},
});
},
};
@@ -0,0 +1,8 @@
# Tablebase via the lichess API instead of self-hosting
The trainer grades moves against Syzygy tablebases, but self-hosting them is not
possible yet, so we query the lichess tablebase API (`tablebase.lichess.ovh`)
over HTTP and cache responses. This couples the core play loop to a remote
service with rate limits (mitigated by a cooldown and an LFU cache), but avoids
the multi-terabyte 7-piece dataset and hosting cost until local tablebases are
viable.
@@ -0,0 +1,8 @@
# Client-authoritative move legality; server grades via tablebase
Moves are validated by chess.js on the client (which also renders the board);
the server never applies moves and trusts the client's FEN, only grading the
move against the tablebase. We chose this over server-side validation with Chex
because Chex's move-legality logic is immature, and the app is single-user with
no auth, so client tampering is not a threat. Revisit once the Chex fork is
fixed.
+85
View File
@@ -0,0 +1,85 @@
# MVP: endgame trainer play loop
Goal: a user picks an endgame and plays it against tablebase-optimal defence,
with every move graded against the lichess tablebase, end-to-end.
## Definition of done
- On `/endgames/:id/play`, the seeded endgames (KR v K, KPPP v KPP) load and are
playable.
- The user plays `endgame.color`; a legal move is graded (optimal / winning /
losing) against the tablebase; the opponent auto-replies with optimal defence.
- A **losing move** fails the puzzle immediately; **checkmate or a winning
promotion** solves it.
- Draw endgames are playable: the user holds the draw (solves on chess.js
`isDraw()`), or fails on a losing move.
- Tablebase unavailability (429/network) blocks the session with a clear message.
- `times_attempted` / `times_solved` increment on finish.
## Decisions (see GLOSSARY.md, docs/adr/)
- Strict trainer; losing move fails. Optimal vs. winning-but-slower are two
feedback tiers; only losing moves fail.
- Client (chess.js) is authoritative for legality; server grades via tablebase
(ADR-0002). Tablebase via lichess API (ADR-0001).
- Server holds attempt state in `assigns`; the client is the only engine.
- Grading rule: a move passes iff its category ∈ {loss, syzygy-loss, maybe-loss}
(opponent still lost); `cursed-win`/`blessed-loss` normalise to draw.
- Cutoff: solve on checkmate or a winning promotion.
- LFU cache with weekly halving sweep.
## Work breakdown
### 0. Prerequisite bug fixes
- `Chesstrainer.Endgames.Tablebase.new/1`: return `{:ok, tablebase}` on a cache
hit (fix the `{:cache, _}` return + `@spec`); unwrap the tuple in
`Chesstrainer.Game.game_from_fen/2`.
- `Chesstrainer.Endgames.Tablebase.Parser`: normalise the full category
vocabulary to `:win | :draw | :loss | :unknown`
(`win/syzygy-win/maybe-win → :win`; `draw/cursed-win/blessed-loss → :draw`;
`loss/syzygy-loss/maybe-loss → :loss`).
- `assets/js/hooks/chessBoard.js`: add `promotion` (and `prev_fen`) to the
`endgame_move_played` payload for unambiguous UCI matching.
### 1. LFU cache rewrite
- `Chesstrainer.Cache`: store `{key, value, freq, last_access}`; on `put`, if
over `@max_size`, evict lowest frequency (LRU tie-break).
- `Chesstrainer.Cache.Evict`: replace timestamp-based eviction with frequency.
- Add a weekly sweep that halves every entry's frequency
(`Chesstrainer.Cache` `handle_info` timer, alongside the existing backup).
- `Chesstrainer.Cache.Persist`: the DETS tuple format changes; drop old backups
(tablebase data is re-fetchable).
### 2. Server attempt state + grading (`EndgameLive.Play`)
- `assigns`: `fen` (grading reference), `status` (`:playing | :solved | :failed
| :blocked`), `move_list`, `last_grade`.
- `handle_event("endgame_move_played", %{from, to, san, prev_fen, fen_after,
promotion})`:
1. grade the move against `prev_fen`'s tablebase (match UCI; pass/fail);
2. on fail → `status: :failed`, reveal the missed optimal move(s);
3. on pass → pick the opponent reply (`moves[0]`) from `fen_after`'s
tablebase, push it to the client, update `fen`;
4. detect solve (checkmate / winning promotion) and draw (for draw endgames).
- Block: when `Tablebase.new` returns `{:cooldown, _}` or `{:error, _}`,
set `status: :blocked` and surface a message.
### 3. Client hook (`assets/js/hooks/chessBoard.js`)
- Send `prev_fen` + `fen_after` + `promotion` on each move.
- Apply the opponent reply (from the server) via chess.js and animate it.
- Report draw/mate (chess.js `isDraw()` / `isCheckmate()`) for terminal
detection.
### 4. Feedback UI (`EndgameLive.Play` + components)
- Two-tier grade display (green "Best" vs. amber "Winning, but suboptimal"),
losing-move failure with the missed move, solved/failed banner, reset/retry.
### 5. Counters
- Increment `times_attempted` on start; `times_solved` on solve (via
`Chesstrainer.Endgames`).
## Out of scope (deferred)
- Auth / user accounts: #3
- Glicko rating for users and endgames (puzzle ELO): #4
- Draw via cursed-win 50-move defences; material-based cutoffs; per-endgame
`win_condition` field.
+66 -39
View File
@@ -1,6 +1,12 @@
defmodule Chesstrainer.Cache do
@moduledoc """
Generic LRU cache.
Generic LFU cache with a periodic frequency-decay sweep.
Entries are stored in ETS as `{key, value, frequency, last_access}`. Reads bump
the frequency; when the cache is over its maximum size the least frequently
used entry is evicted (ties broken by least recent use). A weekly sweep halves
every frequency so entries that were used heavily once but have not been used
since eventually age out.
## Examples
@@ -9,14 +15,21 @@ defmodule Chesstrainer.Cache do
use GenServer
@max_size 1000
@default_max_size 1000
@default_sweep_interval :timer.hours(24 * 7)
@backup_interval_minutes 60
def start_link(table), do: GenServer.start_link(__MODULE__, table, name: via_tuple(table))
def start_link(table), do: start_link(table, [])
def start_link(table, opts) when is_list(opts) do
GenServer.start_link(__MODULE__, {table, opts}, name: via_tuple(table))
end
def put(table, key, value), do: GenServer.call(via_tuple(table), {:put, key, value})
def get(table, key), do: GenServer.call(via_tuple(table), {:get, key})
def delete(table, key), do: GenServer.call(via_tuple(table), {:delete, key})
def backup(table), do: GenServer.cast(via_tuple(table), :backup)
def backup(table), do: GenServer.call(via_tuple(table), :backup)
def sweep(table), do: GenServer.call(via_tuple(table), :sweep)
def show(table) do
ensure_table(table)
@@ -26,66 +39,76 @@ defmodule Chesstrainer.Cache do
def size(table), do: :ets.info(table, :size)
@impl true
def init(table) do
{:ok, table, {:continue, :restore_and_backup}}
end
def init({table, opts}) do
state = %{
table: table,
max_size: Keyword.get(opts, :max_size, @default_max_size),
sweep_interval: Keyword.get(opts, :sweep_interval, @default_sweep_interval)
}
@impl true
def handle_continue(:restore_and_backup, table) do
# Create and restore synchronously so the cache is never observed empty
# between `start_link/1` returning and the restore finishing.
create_table(table)
__MODULE__.Persist.restore(table)
__MODULE__.Evict.evict(table, state.max_size)
:timer.send_interval(:timer.minutes(@backup_interval_minutes), :backup)
{:noreply, table}
:timer.send_interval(state.sweep_interval, :sweep)
{:ok, state}
end
@impl true
def handle_call({:put, key, value}, _from, table) do
ensure_table(table)
timestamp = System.system_time(:millisecond)
:ets.insert(table, {key, value, timestamp})
GenServer.cast(self(), :maybe_evict)
{:reply, :ok, table}
def handle_call({:put, key, value}, _from, state) do
ensure_table(state.table)
access = System.system_time(:microsecond)
:ets.insert(state.table, {key, value, 1, access})
__MODULE__.Evict.evict(state.table, state.max_size)
{:reply, :ok, state}
end
@impl true
def handle_call({:get, key}, _from, table) do
ensure_table(table)
def handle_call({:get, key}, _from, state) do
ensure_table(state.table)
case :ets.lookup(table, key) do
[{^key, value, _old_timestamp}] ->
timestamp = System.system_time(:millisecond)
:ets.insert(table, {key, value, timestamp})
{:reply, {:ok, value}, table}
case :ets.lookup(state.table, key) do
[{^key, value, frequency, _old_access}] ->
access = System.system_time(:microsecond)
:ets.insert(state.table, {key, value, frequency + 1, access})
{:reply, {:ok, value}, state}
[] ->
{:reply, :error, table}
{:reply, :error, state}
end
end
@impl true
def handle_call({:delete, key}, _from, table) do
:ets.delete(table, key)
{:reply, :ok, table}
def handle_call({:delete, key}, _from, state) do
:ets.delete(state.table, key)
{:reply, :ok, state}
end
@impl true
def handle_cast(:maybe_evict, table) do
__MODULE__.Evict.maybe_evict_oldest(table, @max_size)
{:noreply, table}
def handle_call(:backup, _from, state) do
__MODULE__.Persist.backup(state.table)
{:reply, :ok, state}
end
@impl true
def handle_cast(:backup, table) do
__MODULE__.Persist.backup(table)
{:noreply, table}
def handle_call(:sweep, _from, state) do
__MODULE__.Sweep.halve_frequencies(state.table)
{:reply, :ok, state}
end
@impl true
def handle_info(:backup, table) do
GenServer.cast(self(), :backup)
{:noreply, table}
def handle_info(:backup, state) do
__MODULE__.Persist.backup(state.table)
{:noreply, state}
end
@impl true
def handle_info(:sweep, state) do
__MODULE__.Sweep.halve_frequencies(state.table)
{:noreply, state}
end
defp via_tuple(table), do: {:via, Registry, {Chesstrainer.CacheRegistry, table}}
@@ -97,5 +120,9 @@ defmodule Chesstrainer.Cache do
end
end
defp create_table(table), do: :ets.new(table, [:named_table, :public, :set])
defp create_table(table) do
:ets.new(table, [:named_table, :public, :set])
rescue
ArgumentError -> table
end
end
+26 -11
View File
@@ -1,25 +1,40 @@
defmodule Chesstrainer.Cache.Evict do
@moduledoc """
Eviction functions for LRU cache
Eviction for the LFU cache.
"""
# O(n) time, not efficient
def maybe_evict_oldest(table, max_size) do
@doc """
Evicts least-frequently-used entries until `table` holds at most `max_size`
rows. Ties in frequency are broken by least recent use (`last_access`).
"""
def evict(table, max_size) do
if :ets.info(table, :size) > max_size do
case find_oldest_entry(table) do
{oldest_key, _} -> :ets.delete(table, oldest_key)
_ -> :ok
case find_least_used_entry(table) do
{key, _frequency, _last_access} ->
:ets.delete(table, key)
evict(table, max_size)
nil ->
:ok
end
else
:ok
end
end
defp find_oldest_entry(table) do
defp find_least_used_entry(table) do
:ets.foldl(
fn {k, _v, t}, acc ->
fn {k, _v, frequency, last_access}, acc ->
case acc do
nil -> {k, t}
{_, oldest_t} when t < oldest_t -> {k, t}
_ -> acc
nil ->
{k, frequency, last_access}
{_k, best_frequency, best_access}
when {frequency, last_access} < {best_frequency, best_access} ->
{k, frequency, last_access}
_ ->
acc
end
end,
nil,
+35 -6
View File
@@ -1,29 +1,58 @@
defmodule Chesstrainer.Cache.Persist do
@moduledoc """
Persistance for cache. Backup and restore functions.
Persistence for the cache. Backup and restore functions.
"""
@backup_path "priv/static/backups"
@format_version "v2"
def backup(table) do
File.mkdir_p!(@backup_path)
filename = Path.join(@backup_path, "#{table}.det") |> String.to_charlist()
{:ok, dets_table} = :dets.open_file(filename, type: :set)
name = backup_filename(table) |> String.to_charlist()
{:ok, dets_table} = :dets.open_file(name, type: :set)
:ets.to_dets(table, dets_table)
:dets.sync(dets_table)
:dets.close(dets_table)
end
def restore(table) do
File.mkdir_p!(@backup_path)
filename = Path.join(@backup_path, "#{table}.det") |> String.to_charlist()
drop_legacy_backup(table)
case :dets.open_file(table, file: filename, type: :set) do
path = backup_filename(table)
if File.exists?(path) do
name = String.to_charlist(path)
case :dets.open_file(table, file: name, type: :set) do
{:ok, ^table} ->
:dets.foldl(fn entry, _ -> :ets.insert(table, entry) end, :ok, table)
:dets.foldl(
fn
{key, value, frequency, last_access}, :ok when is_integer(frequency) ->
:ets.insert(table, {key, value, frequency, last_access})
:ok
_entry, :ok ->
:ok
end,
:ok,
table
)
:dets.close(table)
{:error, _} ->
:ok
end
end
:ok
end
defp backup_filename(table), do: Path.join(@backup_path, "#{table}.#{@format_version}.det")
defp drop_legacy_backup(table) do
legacy = Path.join(@backup_path, "#{table}.det")
if File.exists?(legacy), do: File.rm(legacy)
end
end
+25
View File
@@ -0,0 +1,25 @@
defmodule Chesstrainer.Cache.Sweep do
@moduledoc """
Frequency decay for the LFU cache.
Halving every frequency each week lets entries that were used heavily once but
have not been used since age out of the cache.
"""
@doc """
Halves the frequency of every entry in `table` with integer division, so an
entry used once decays from `1` to `0`.
"""
def halve_frequencies(table) do
:ets.foldl(
fn {key, value, frequency, last_access}, :ok ->
:ets.insert(table, {key, value, div(frequency, 2), last_access})
:ok
end,
:ok,
table
)
:ok
end
end
+16
View File
@@ -105,6 +105,22 @@ defmodule Chesstrainer.Endgames do
Endgame.changeset(endgame, attrs)
end
@doc """
Records the start of an attempt, incrementing `times_attempted`.
"""
def record_attempt(%Endgame{id: id}), do: increment(id, times_attempted: 1)
@doc """
Records a solved attempt, incrementing `times_solved`.
"""
def record_solve(%Endgame{id: id}), do: increment(id, times_solved: 1)
defp increment(id, increments) do
Repo.update_all(from(e in Endgame, where: e.id == ^id), inc: increments)
{:ok, Repo.get!(Endgame, id)}
end
def add_tag(endgame, tag) do
endgame
|> Repo.preload(:tags)
+20 -2
View File
@@ -27,6 +27,24 @@ defmodule Chesstrainer.Endgames.Tablebase do
insufficient_material: 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()}
@@ -34,8 +52,8 @@ defmodule Chesstrainer.Endgames.Tablebase do
| {:error, term()}
def new(fen) do
case Tablebase.Cache.get(fen) do
{_fen, tablebase} ->
{:cache, tablebase}
{:ok, tablebase} ->
{:ok, tablebase}
_ ->
case Tablebase.Parser.from_fen(fen) do
+1 -1
View File
@@ -3,7 +3,7 @@ defmodule Chesstrainer.Endgames.Tablebase.Move do
Moves struct for the tablebase
"""
@type result :: :win | :draw | :loss
@type result :: :win | :draw | :loss | :unknown
@type t :: %__MODULE__{
category: result,
+10 -9
View File
@@ -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()}
@@ -41,7 +41,7 @@ defmodule Chesstrainer.Endgames.Tablebase.Parser do
def from_map(map) do
{:ok,
%Tablebase{
category: map["category"] |> String.to_atom(),
category: Tablebase.normalize_category(map["category"]),
checkmate: map["checkmate"],
dtc: map["dtc"],
dtm: map["dtm"],
@@ -54,7 +54,7 @@ defmodule Chesstrainer.Endgames.Tablebase.Parser do
defp moves_from_map(map) do
%Tablebase.Move{
category: map["category"] |> String.to_atom(),
category: Tablebase.normalize_category(map["category"]),
checkmate: map["checkmate"],
conversion: map["conversion"],
dtc: map["dtc"],
@@ -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}}
+10 -6
View File
@@ -102,12 +102,7 @@ defmodule Chesstrainer.Game do
game_type: game_type,
fen: fen,
game_state: :continue,
tablebase:
if game_type === :endgame do
Endgames.Tablebase.new(fen)
else
nil
end
tablebase: tablebase_for(fen, game_type)
}
{:ok, game}
@@ -142,4 +137,13 @@ defmodule Chesstrainer.Game do
{:error, :invalid_fen, game}
end
end
defp tablebase_for(_fen, game_type) when game_type != :endgame, do: nil
defp tablebase_for(fen, :endgame) do
case Endgames.Tablebase.new(fen) do
{:ok, tablebase} -> tablebase
_ -> nil
end
end
end
+300 -25
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
@@ -10,7 +11,8 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
<.header>
Play endgame {@endgame.key}
<:subtitle>
{@endgame.color |> Atom.to_string() |> String.capitalize()} to move · Rating: {@endgame.rating}
{@endgame.color |> Atom.to_string() |> String.capitalize()} to move · Rating: {@endgame.rating} · Attempts: {@endgame.times_attempted ||
0} · Solved: {@endgame.times_solved || 0}
</:subtitle>
<:actions>
<.button navigate={~p"/endgames"}>
@@ -30,6 +32,36 @@ 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>
<% @status == :solved -> %>
<p class="font-semibold text-emerald-600">Solved!</p>
<% @status == :failed -> %>
<p class="font-semibold text-red-600">Failed</p>
<p class="text-red-500">That move throws away the win.</p>
<%= if @best_move do %>
<p class="text-gray-600">Best was: {@best_move}</p>
<% end %>
<% @awaiting_reply -> %>
<p class="text-gray-500">Opponent is replying…</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,11 +81,10 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
</div>
</div>
<div>Buttons</div>
<div>
<.button phx-click="reset" variant="primary">
<.icon name="hero-arrow-path" /> Reset
<.icon name="hero-arrow-path" />
{if @status in [:solved, :failed], do: "Try again", else: "Reset"}
</.button>
</div>
</div>
@@ -70,30 +101,67 @@ 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(:best_move, 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)
|> assign(:awaiting_reply, false)
{: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
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
fen_after = params["fen"] || socket.assigns.fen
cond do
socket.assigns.status == :blocked ->
{:noreply,
put_flash(socket, :error, "The tablebase is unavailable, so this move cannot be graded.")}
socket.assigns.status != :playing ->
{:noreply, socket}
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, fen_after)
end
end
def handle_event("opponent_reply_applied", %{"fen" => fen}, socket) do
if socket.assigns.awaiting_reply do
case Tablebase.new(fen) do
{:ok, tablebase} ->
{:noreply,
socket
|> assign(:last_from_to, "#{from} ➔ #{to}")
|> assign(:last_san, san)
|> assign(:move_list, socket.assigns.move_list ++ [san])}
|> assign(:fen, fen)
|> assign(:tablebase, tablebase)
|> assign(:awaiting_reply, false)
|> assign(:status, :playing)
|> assign(:blocked_reason, nil)
|> push_event("resume_board", %{})}
other ->
{:noreply,
socket
|> assign(:awaiting_reply, false)
|> assign(:status, :blocked)
|> assign(:blocked_reason, blocked_reason(other))}
end
else
{:noreply, socket}
end
end
def handle_event("chess_fen_invalid", %{"fen" => fen, "message" => message}, socket) do
@@ -106,16 +174,14 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
end
def handle_event("reset", _params, socket) do
{:noreply,
socket =
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)
})}
|> assign(:last_grade, nil)
{:noreply, load_attempt(socket)}
end
def format_move_pairs(move_list, color) do
@@ -125,4 +191,213 @@ 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 =
socket
|> assign(:fen, fen)
|> assign(:awaiting_reply, false)
|> assign(:best_move, nil)
if connected?(socket) do
case Tablebase.new(fen) do
{:ok, tablebase} ->
{:ok, endgame} = Endgames.record_attempt(socket.assigns.endgame)
socket
|> assign(:endgame, endgame)
|> 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, fen_after) 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 ->
grade = grade_move(socket.assigns.tablebase, move)
socket =
socket
|> assign(:last_from_to, "#{from} ➔ #{to}")
|> assign(:last_san, san)
|> assign(:last_grade, grade)
|> assign(:move_list, socket.assigns.move_list ++ [san])
cond do
grade == :losing ->
fail_attempt(socket)
grade in [:optimal, :winning] and not is_nil(promotion) ->
# Conversion cutoff: a promotion that keeps the win ends the puzzle.
solve_attempt(socket)
grade in [:optimal, :winning] and
not same_position?(fen_after, socket.assigns.fen) ->
start_opponent_reply(socket, fen_after)
true ->
{:noreply, socket}
end
end
end
defp start_opponent_reply(socket, fen_after) do
case Tablebase.new(fen_after) do
{:ok, %Tablebase{checkmate: true}} ->
solve_attempt(socket)
{:ok, %Tablebase{moves: [reply | _]}} ->
{:noreply,
socket
|> assign(:awaiting_reply, true)
|> push_event("opponent_move", reply_payload(reply))}
{:ok, %Tablebase{}} ->
# Terminal non-mate position (stalemate/insufficient): no reply to play.
{:noreply, socket}
other ->
{:noreply,
socket
|> assign(:status, :blocked)
|> assign(:blocked_reason, blocked_reason(other))}
end
end
defp solve_attempt(socket) do
{:ok, endgame} = Endgames.record_solve(socket.assigns.endgame)
{:noreply,
socket
|> assign(:status, :solved)
|> assign(:endgame, endgame)
|> assign(:awaiting_reply, false)
|> assign(:best_move, nil)}
end
defp fail_attempt(socket) do
{:noreply,
socket
|> assign(:status, :failed)
|> assign(:awaiting_reply, false)
|> assign(:best_move, best_move_text(socket.assigns.tablebase))}
end
defp best_move_text(%Tablebase{category: category, moves: [best | _] = moves}) do
best_rank = outcome_rank(category)
if is_nil(best_rank) do
nil
else
san =
moves
|> Enum.filter(fn move ->
outcome_rank(mover_outcome(move.category)) == best_rank and move.dtz == best.dtz
end)
|> Enum.map(& &1.san)
|> Enum.reject(&is_nil/1)
|> Enum.take(3)
|> Enum.join(", ")
if san == "", do: nil, else: san
end
end
defp best_move_text(_tablebase), do: nil
defp reply_payload(%Tablebase.Move{uci: uci, san: san}) do
%{
from: String.slice(uci, 0, 2),
to: String.slice(uci, 2, 2),
promotion: String.at(uci, 4),
san: san
}
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
+2 -1
View File
@@ -66,7 +66,8 @@ defmodule Chesstrainer.MixProject do
{:jason, "~> 1.2"},
{:dns_cluster, "~> 0.2.0"},
{:bandit, "~> 1.5"},
{:chex, git: "https://github.com/therealowenrees/chex.git", tag: "v0.2.0-alpha.2"}
{:chex, git: "https://github.com/therealowenrees/chex.git", tag: "v0.2.0-alpha.2"},
{:dialyxir, "~> 1.4", only: [:dev, :test], runtime: false}
]
end
+2
View File
@@ -4,10 +4,12 @@
"chex": {:git, "https://github.com/therealowenrees/chex.git", "655b5c3df6c5297689d7872bbce1e86c6c629d26", [tag: "v0.2.0-alpha.2"]},
"db_connection": {:hex, :db_connection, "2.10.1", "d5465f6bcc125c1b8981c1dbf23c193ca16f446ec0b25832dc174f74f18be510", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "18ed94c6e627b4bf452dbd4df61b69a35a1e768525140bc1917b7a685026a6a3"},
"decimal": {:hex, :decimal, "3.1.1", "430d87b04011ce6cbd4fd205be758311a81f87d552d40904abd00f015935b1d0", [:mix], [], "hexpm", "c5f25f2ced74a0587d03e6023f595db8e924c9d3922c8c8ffd9edfc4498cf1f6"},
"dialyxir": {:hex, :dialyxir, "1.4.8", "7ef671a8aff9948b091d8c30f09467fbb16e77305cda451bce48109a0f5e021c", [:mix], [{:erlex, ">= 0.2.8", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "cbd5a851571e5dfeb32aaf2e840bfa98b7864cb3071bf2ef5d95d1276b12e072"},
"dns_cluster": {:hex, :dns_cluster, "0.2.0", "aa8eb46e3bd0326bd67b84790c561733b25c5ba2fe3c7e36f28e88f384ebcb33", [:mix], [], "hexpm", "ba6f1893411c69c01b9e8e8f772062535a4cf70f3f35bcc964a324078d8c8240"},
"ecto": {:hex, :ecto, "3.14.0", "2fa64521eebfcb2670d907a86e4ad947290e9933706bb315e6fb5c21b172cb26", [:mix], [{:decimal, "~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "130d69ffb4285f9ce4792b65dfbb994fd13ea4cbc3cbea2524b199aa3de84af3"},
"ecto_sql": {:hex, :ecto_sql, "3.14.0", "06446ab8410d2f85bfbb80857ee224ab3b693700cbb38f6535d507449a627b2e", [:mix], [{:db_connection, "~> 2.9", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:ecto, "~> 3.14.0", [hex: :ecto, repo: "hexpm", optional: false]}, {:myxql, "~> 0.8", [hex: :myxql, repo: "hexpm", optional: true]}, {:postgrex, "~> 0.19 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}, {:tds, "~> 2.1.1 or ~> 2.2", [hex: :tds, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "f4d8d36faf294c9417b5a37ec7ac8217ee2abdef5fcf197ba690f361548d3949"},
"elixir_make": {:hex, :elixir_make, "0.9.0", "6484b3cd8c0cee58f09f05ecaf1a140a8c97670671a6a0e7ab4dc326c3109726", [:mix], [], "hexpm", "db23d4fd8b757462ad02f8aa73431a426fe6671c80b200d9710caf3d1dd0ffdb"},
"erlex": {:hex, :erlex, "0.2.9", "7debbbaa9f4f368b8cd648983e0f1d7963028508e9c59e9d4ed504e94ef52a55", [:mix], [], "hexpm", "8cfffc0ec7159e6d73de2ab28a588064de80f88b2798d5cbe4482cbbc200178b"},
"esbuild": {:hex, :esbuild, "0.10.0", "b0aa3388a1c23e727c5a3e7427c932d89ee791746b0081bbe56103e9ef3d291f", [:mix], [{:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "468489cda427b974a7cc9f03ace55368a83e1a7be12fba7e30969af78e5f8c70"},
"expo": {:hex, :expo, "1.1.1", "4202e1d2ca6e2b3b63e02f69cfe0a404f77702b041d02b58597c00992b601db5", [:mix], [], "hexpm", "5fb308b9cb359ae200b7e23d37c76978673aa1b06e2b3075d814ce12c5811640"},
"file_system": {:hex, :file_system, "1.1.1", "31864f4685b0148f25bd3fbef2b1228457c0c89024ad67f7a81a3ffbc0bbad3a", [:mix], [], "hexpm", "7a15ff97dfe526aeefb090a7a9d3d03aa907e100e262a0f8f7746b78f8f87a5d"},
Binary file not shown.
+82 -4
View File
@@ -3,20 +3,20 @@ defmodule Chesstrainer.CacheTest do
alias Chesstrainer.Cache
setup do
setup context do
table = :"test_#{System.unique_integer([:positive])}"
{:ok, pid} = Cache.start_link(table)
{:ok, pid} = Cache.start_link(table, Map.get(context, :cache_opts, []))
on_exit(fn -> if Process.alive?(pid), do: GenServer.stop(pid) end)
{:ok, %{pid: pid, table: table}}
end
describe "ChessTrainer.Cache function tests" do
describe "basic operations" do
test "cache is started", %{pid: pid, table: table} do
assert is_pid(pid)
assert 0 = Cache.size(table)
end
test "put/3", %{table: table} do
test "put/3 and get/2", %{table: table} do
assert :ok = Cache.put(table, "key1", "value1")
assert {:ok, "value1"} = Cache.get(table, "key1")
assert 1 = Cache.size(table)
@@ -36,4 +36,82 @@ defmodule Chesstrainer.CacheTest do
assert :error = Cache.get(table, "key1")
end
end
describe "frequency tracking" do
test "get/2 increments the entry frequency", %{table: table} do
Cache.put(table, "key", "value")
Cache.get(table, "key")
Cache.get(table, "key")
Cache.get(table, "key")
assert [{"key", "value", frequency, _last_access}] = Cache.show(table)
assert frequency == 4
end
end
describe "LFU eviction" do
@describetag cache_opts: [max_size: 2]
test "evicts the least-frequently-used entry on overflow", %{table: table} do
Cache.put(table, "hot", "value")
for _ <- 1..5, do: Cache.get(table, "hot")
Cache.put(table, "cold", "value")
Cache.put(table, "new", "value")
assert Cache.size(table) == 2
assert {:ok, "value"} = Cache.get(table, "hot")
assert :error = Cache.get(table, "cold")
assert {:ok, "value"} = Cache.get(table, "new")
end
test "breaks frequency ties by least-recently-used", %{table: table} do
Cache.put(table, "older", "value")
Cache.put(table, "newer", "value")
Cache.put(table, "newest", "value")
assert Cache.size(table) == 2
assert :error = Cache.get(table, "older")
assert {:ok, "value"} = Cache.get(table, "newer")
assert {:ok, "value"} = Cache.get(table, "newest")
end
end
describe "weekly sweep" do
test "halves every entry frequency", %{table: table} do
Cache.put(table, "busy", "value")
for _ <- 1..5, do: Cache.get(table, "busy")
Cache.put(table, "idle", "value")
Chesstrainer.Cache.Sweep.halve_frequencies(table)
frequencies = Map.new(Cache.show(table), fn {k, _v, f, _t} -> {k, f} end)
assert frequencies["busy"] == 3
assert frequencies["idle"] == 0
end
end
describe "persistence" do
test "backup and restore preserve frequencies" do
table = :"test_persist_#{System.unique_integer([:positive])}"
backup = Path.join("priv/static/backups", "#{table}.v2.det")
on_exit(fn -> File.rm(backup) end)
{:ok, pid} = Cache.start_link(table)
Cache.put(table, "key", "value")
Cache.get(table, "key")
Cache.get(table, "key")
assert :ok = Cache.backup(table)
assert :ok = GenServer.stop(pid)
{:ok, restored_pid} = Cache.start_link(table)
on_exit(fn -> if Process.alive?(restored_pid), do: GenServer.stop(restored_pid) end)
assert [{"key", "value", frequency, _last_access}] = Cache.show(table)
assert frequency == 3
end
end
end
@@ -0,0 +1,96 @@
defmodule Chesstrainer.Endgames.TablebaseTest do
use ExUnit.Case, async: false
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
for category <- ["win", "syzygy-win", "maybe-win"] do
assert Tablebase.normalize_category(category) == :win
end
end
test "maps 50-move-rule draws to :draw" do
for category <- ["draw", "cursed-win", "blessed-loss"] do
assert Tablebase.normalize_category(category) == :draw
end
end
test "maps losing categories to :loss" do
for category <- ["loss", "syzygy-loss", "maybe-loss"] do
assert Tablebase.normalize_category(category) == :loss
end
end
test "falls back to :unknown for anything else" do
for category <- ["unknown", "banana", nil] do
assert Tablebase.normalize_category(category) == :unknown
end
end
end
describe "Parser.from_map/1" do
test "normalises the position and move categories" do
assert {:ok, tablebase} =
Parser.from_map(%{
"category" => "cursed-win",
"checkmate" => false,
"dtc" => nil,
"dtm" => 20,
"dtw" => nil,
"dtz" => 3,
"insufficient_material" => false,
"moves" => [
%{
"category" => "blessed-loss",
"checkmate" => false,
"conversion" => false,
"dtc" => nil,
"dtm" => -19,
"dtw" => nil,
"dtz" => -2,
"insufficient_material" => false,
"precise_dtz" => -2,
"san" => "Kd7",
"stalemate" => false,
"uci" => "e8d7",
"variant_loss" => false,
"variant_win" => false,
"zeroing" => false
}
]
})
assert tablebase.category == :draw
assert [%Tablebase.Move{category: :draw, uci: "e8d7"}] = tablebase.moves
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"
tablebase = %Tablebase{category: :win, moves: []}
TablebaseCache.put(fen, tablebase)
on_exit(fn -> TablebaseCache.delete(fen) end)
assert {:ok, ^tablebase} = Tablebase.new(fen)
end
end
end
+4 -4
View File
@@ -21,11 +21,11 @@ defmodule Chesstrainer.TagsTest do
end
test "create_tag/1 with valid data creates a tag" do
valid_attrs = %{name: "some name", category: "some category"}
valid_attrs = %{name: "some name", category: :endgame}
assert {:ok, %Tag{} = tag} = Tags.create_tag(valid_attrs)
assert tag.name == "some name"
assert tag.category == "some category"
assert tag.category == :endgame
end
test "create_tag/1 with invalid data returns error changeset" do
@@ -34,11 +34,11 @@ defmodule Chesstrainer.TagsTest do
test "update_tag/2 with valid data updates the tag" do
tag = tag_fixture()
update_attrs = %{name: "some updated name", category: "some updated category"}
update_attrs = %{name: "some updated name", category: :opening}
assert {:ok, %Tag{} = tag} = Tags.update_tag(tag, update_attrs)
assert tag.name == "some updated name"
assert tag.category == "some updated category"
assert tag.category == :opening
end
test "update_tag/2 with invalid data returns error changeset" do
@@ -4,6 +4,11 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
import Phoenix.LiveViewTest
import Chesstrainer.EndgamesFixtures
alias Chesstrainer.Endgames
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 +19,41 @@ 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),
checkmate: Keyword.get(opts, :checkmate, false),
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 +63,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,12 +72,12 @@ 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")
assert html =~ "KQ v K"
assert html =~ "white to move"
assert html =~ "win"
assert html =~ "White to move"
assert html =~ "1800"
end
@@ -50,9 +88,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")
@@ -69,47 +124,193 @@ 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 "fails a move that throws the win away", %{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) =~ "Failed"
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
})
assert render(view) =~ "out of sequence"
end
end
describe "opponent reply" do
test "plays the opponent's optimal defence and resumes the user's turn", %{conn: conn} do
endgame = endgame_fixture()
fen_after = "8/8/8/8/8/8/8/8 b - - 0 1"
fen_after_reply = "8/8/8/8/8/8/8/8 w - - 0 1"
reply = %Tablebase.Move{uci: "e8e7", san: "Ke7", category: :loss, dtz: -3}
seed_tablebase(endgame.fen, moves: grading_moves())
seed_tablebase(fen_after, category: :loss, moves: [reply])
seed_tablebase(fen_after_reply, category: :win, 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" => endgame.fen,
"fen" => fen_after,
"endgame_id" => endgame.id
})
%{proxy: {ref, _topic, _}} = view
assert_receive {^ref, {:push_event, "opponent_move", payload}}, 100
assert payload == %{from: "e8", to: "e7", promotion: nil, san: "Ke7"}
render_hook(view, "opponent_reply_applied", %{"fen" => fen_after_reply})
assert_receive {^ref, {:push_event, "resume_board", _payload}}, 100
end
test "does not reply when the move throws the win away", %{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")
%{proxy: {ref, _topic, _}} = view
refute_receive {^ref, {:push_event, "opponent_move", _payload}}, 100
assert render(view) =~ "Failed"
end
end
describe "attempt outcome" do
test "records an attempt on start", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen)
{:ok, _view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
assert Endgames.get_endgame!(endgame.id).times_attempted == 1
end
test "solves on checkmate", %{conn: conn} do
endgame = endgame_fixture()
fen_after = "8/8/8/8/8/8/8/8 b - - 0 1"
seed_tablebase(endgame.fen, moves: grading_moves())
seed_tablebase(fen_after, checkmate: true, moves: [])
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
render_hook(view, "endgame_move_played", %{
"from" => "d1",
"to" => "d7",
"san" => "Qd7+",
"prev_fen" => endgame.fen,
"fen" => fen_after,
"endgame_id" => endgame.id
})
assert render(view) =~ "Solved!"
assert Endgames.get_endgame!(endgame.id).times_solved == 1
end
test "solves on a promotion that keeps the win", %{conn: conn} do
endgame = endgame_fixture()
moves = [%Tablebase.Move{uci: "a7a8q", san: "a8=Q", category: :loss, dtz: -1}]
seed_tablebase(endgame.fen, moves: moves)
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
render_hook(view, "endgame_move_played", %{
"from" => "a7",
"to" => "a8",
"san" => "a8=Q",
"promotion" => "q",
"prev_fen" => endgame.fen,
"fen" => endgame.fen,
"endgame_id" => endgame.id
})
assert render(view) =~ "Solved!"
assert Endgames.get_endgame!(endgame.id).times_solved == 1
end
test "fails on a losing move and reveals the best move", %{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")
html = render(view)
assert html =~ "Failed"
assert html =~ "Qd7+"
assert html =~ "d1 ➔ d7"
assert Endgames.get_endgame!(endgame.id).times_solved == 0
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")
assert Endgames.get_endgame!(endgame.id).times_attempted == 2
end
end
end
+1 -1
View File
@@ -16,7 +16,7 @@ defmodule Chesstrainer.TagsFixtures do
{:ok, tag} =
attrs
|> Enum.into(%{
category: "some category",
category: :endgame,
name: unique_tag_name()
})
|> Chesstrainer.Tags.create_tag()