Make tablebase and empty-pool failures recoverable (#163) (#170)

Tablebase failures now render one message per class, with a Retry action
when fetching again can help. The generic class no longer interpolates
inspect(reason) into the page; the reason goes to the log instead.
Positions outside the tablebase offer the next puzzle (in a session) or the
existing back link, rather than a futile retry.

Train's no-puzzles and exhausted-difficulty flashes become in-page states
with Retry and Change difficulty. The guest pool gets the same treatment,
and GuestLimits.remaining/1 lets a guest see the wall, or the empty pool,
without spending a puzzle.
This commit is contained in:
2026-11-13 15:36:59 +01:00
committed by GitHub
parent 0563b5aca2
commit 021e412167
11 changed files with 476 additions and 133 deletions
+27
View File
@@ -40,6 +40,18 @@ defmodule Chesstrainer.GuestLimits do
@doc "Clears every budget. Intended for tests."
def reset, do: GenServer.call(__MODULE__, :reset)
@doc """
Returns the puzzles left today without consuming one.
Mirrors `take/2`'s result shape so a caller can show the wall before doing
work that would otherwise spend a puzzle.
"""
@spec remaining(address, Date.t()) ::
{:ok, non_neg_integer | nil} | {:limit_reached, non_neg_integer}
def remaining(address, today \\ Date.utc_today()) do
GenServer.call(__MODULE__, {:remaining, address, today})
end
@doc "The daily puzzle allowance for a guest."
def limit, do: config() |> Keyword.get(:limit, @default_limit)
@@ -67,6 +79,21 @@ defmodule Chesstrainer.GuestLimits do
@impl true
def handle_call({:take, nil, _today}, _from, state), do: {:reply, {:ok, nil}, state}
def handle_call({:remaining, nil, _today}, _from, state), do: {:reply, {:ok, nil}, state}
def handle_call({:remaining, address, today}, _from, state) do
day = Date.to_gregorian_days(today)
key = key(state.secret, day, address)
case count(key, day) do
used when used >= state.limit ->
{:reply, {:limit_reached, ms_until_utc_midnight()}, state}
used ->
{:reply, {:ok, state.limit - used}, state}
end
end
def handle_call({:take, address, today}, _from, state) do
day = Date.to_gregorian_days(today)
key = key(state.secret, day, address)
@@ -14,14 +14,14 @@ defmodule ChesstrainerWeb.PlayComponents do
attr :endgame, :any, required: true
attr :fen, :string, default: nil
attr :status, :atom, required: true
attr :blocked_reason, :string, default: nil
attr :blocked, :map, default: nil
attr :best_move, :string, default: nil
attr :plies, :list, required: true
attr :line, :list, required: true
attr :reviewing, :boolean, required: true
attr :review_index, :integer, required: true
attr :review_tablebase, :any, default: nil
attr :review_blocked, :string, default: nil
attr :review_blocked, :map, default: nil
attr :awaiting_reply, :boolean, required: true
attr :last_grade, :atom, default: nil
attr :awaiting_best_line, :boolean, default: false
@@ -169,7 +169,23 @@ defmodule ChesstrainerWeb.PlayComponents do
>
<.icon name="hero-eye" /> Review
</.button>
<.button phx-click="reset" variant="primary">
<.button
:if={@status == :blocked && @blocked && @blocked.retry}
id="retry-blocked"
phx-click="reset"
variant="primary"
>
<.icon name="hero-arrow-path" /> Retry
</.button>
<.button
:if={@status == :blocked && @blocked && !@blocked.retry && @session}
id="next-after-blocked"
phx-click="next_puzzle"
variant="primary"
>
Next puzzle
</.button>
<.button :if={@status != :blocked} phx-click="reset" variant="primary">
<.icon name="hero-arrow-path" />
{if @status in [:solved, :failed], do: "Try again", else: "Reset"}
</.button>
@@ -194,7 +210,7 @@ defmodule ChesstrainerWeb.PlayComponents do
<%= cond do %>
<% @review_blocked -> %>
<p class="text-muted">Best move unavailable here</p>
<p class="text-muted">{@review_blocked}</p>
<p class="text-muted">{@review_blocked.message}</p>
<% @review_tablebase -> %>
<p class="text-muted font-semibold mb-1">Best move:</p>
<p class="text-success-text">{PlayCore.best_move_text(@review_tablebase) || "—"}</p>
@@ -211,9 +227,9 @@ defmodule ChesstrainerWeb.PlayComponents do
<%= cond do %>
<% @status == :loading -> %>
<p class="text-muted">Loading tablebase…</p>
<% @status == :blocked -> %>
<p class="font-semibold text-error-text">Tablebase unavailable</p>
<p class="text-error-text">{@blocked_reason}</p>
<% @status == :blocked && @blocked -> %>
<p class="font-semibold text-error-text">{@blocked.title}</p>
<p class="text-error-text">{@blocked.message}</p>
<% @status == :solved -> %>
<p class="font-semibold text-success-text">
{if @endgame.result == :draw, do: "Draw held!", else: "Solved!"}
@@ -460,8 +476,7 @@ defmodule ChesstrainerWeb.PlayComponents do
defp move_hint(:loading, _awaiting), do: "Loading the tablebase…"
defp move_hint(:blocked, _awaiting),
do: "The tablebase is unavailable, so moves cannot be entered."
defp move_hint(:blocked, _awaiting), do: "Moves are paused."
defp move_hint(status, _awaiting) when status in [:solved, :failed],
do: "This puzzle is finished. Reset or try again."
@@ -488,7 +503,10 @@ defmodule ChesstrainerWeb.PlayComponents do
"Loading the tablebase."
assigns.status == :blocked ->
"Tablebase unavailable. #{assigns.blocked_reason || "Moves cannot be graded."}"
case assigns.blocked do
%{title: title, message: message} -> "#{title}. #{message}"
_ -> "Tablebase unavailable."
end
assigns.reviewing ->
review_announcement(assigns)
@@ -70,12 +70,12 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
</section>
<PlayComponents.play_surface
:if={@endgame}
:if={@endgame && @empty != :exhausted}
session={is_nil(@limit_reached)}
endgame={@endgame}
fen={@fen}
status={@status}
blocked_reason={@blocked_reason}
blocked={@blocked}
best_move={@best_move}
plies={@plies}
line={@line}
@@ -94,12 +94,41 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
<p :if={@loading} class="text-base-content/70">Picking a random puzzle…</p>
<p
:if={not @loading and is_nil(@endgame) and is_nil(@limit_reached)}
class="text-base-content/70"
<section
:if={@empty == :exhausted}
id="guest-pool-exhausted"
class="rounded-xl border border-hairline bg-canvas-raised p-6"
>
No endgames are available yet. Please check back soon.
</p>
<h2 class="text-lg font-semibold">No more puzzles are available right now</h2>
<p class="mt-1 text-sm text-muted">
Try again in a moment, or create a free account to train at your level.
</p>
<div class="mt-4 flex flex-wrap gap-2">
<.button id="retry-pool" phx-click="retry_pool" variant="primary">
<.icon name="hero-arrow-path" /> Retry
</.button>
<.button navigate={~p"/users/register"}>Sign up free</.button>
<.button navigate={~p"/users/log-in"}>Log in</.button>
</div>
</section>
<section
:if={not @loading and is_nil(@endgame) and is_nil(@limit_reached)}
id="guest-pool-empty"
class="rounded-xl border border-hairline bg-canvas-raised p-6"
>
<h2 class="text-lg font-semibold">No endgames are available yet</h2>
<p class="mt-1 text-sm text-muted">
Please check back soon, or create a free account to be ready when they land.
</p>
<div class="mt-4 flex flex-wrap gap-2">
<.button id="retry-pool" phx-click="retry_pool" variant="primary">
<.icon name="hero-arrow-path" /> Retry
</.button>
<.button navigate={~p"/users/register"}>Sign up free</.button>
<.button navigate={~p"/users/log-in"}>Log in</.button>
</div>
</section>
</Layouts.app>
"""
end
@@ -120,6 +149,7 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
socket
|> assign(:loading, true)
|> assign(:endgame, nil)
|> assign(:empty, nil)
|> assign(:guest_remaining, nil)
|> assign(:limit_reached, nil)
|> assign(:guest_address, nil)}
@@ -127,29 +157,14 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
end
@impl true
def handle_event("next_puzzle", _params, socket) do
case GuestLimits.take(socket.assigns.guest_address) do
{:ok, remaining} ->
endgame =
Endgames.random_endgame(exclude_ids: [socket.assigns.endgame.id]) ||
Endgames.random_endgame()
def handle_event("next_puzzle", _params, socket), do: {:noreply, next_puzzle(socket)}
case endgame do
nil ->
{:noreply, put_flash(socket, :info, "No more puzzles are available right now.")}
endgame ->
{:noreply,
socket
|> assign(:guest_remaining, remaining)
|> PlayCore.init(endgame, page_title: "Train")}
end
{:limit_reached, retry_ms} ->
{:noreply,
socket
|> assign(:guest_remaining, nil)
|> assign(:limit_reached, retry_ms)}
def handle_event("retry_pool", _params, socket) do
if socket.assigns.empty == :exhausted do
{:noreply, next_puzzle(socket)}
else
{:ok, socket} = take_puzzle(socket, socket.assigns.guest_address)
{:noreply, socket}
end
end
@@ -193,36 +208,75 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
def handle_event("back_to_game", _params, socket), do: PlayCore.back_to_game(socket)
defp take_puzzle(socket, address) do
case GuestLimits.take(address) do
{:ok, remaining} ->
socket =
socket
|> assign(:loading, false)
|> assign(:guest_address, address)
|> assign(:guest_remaining, remaining)
|> assign(:limit_reached, nil)
{:ok, load_random_endgame(socket)}
defp next_puzzle(socket) do
case GuestLimits.remaining(socket.assigns.guest_address) do
{:limit_reached, retry_ms} ->
{:ok,
socket
|> assign(:loading, false)
|> assign(:guest_address, address)
|> assign(:guest_remaining, nil)
|> assign(:limit_reached, retry_ms)
|> assign(:endgame, nil)}
socket
|> assign(:guest_remaining, nil)
|> assign(:empty, nil)
|> assign(:limit_reached, retry_ms)
{:ok, _remaining} ->
endgame =
Endgames.random_endgame(exclude_ids: [socket.assigns.endgame.id]) ||
Endgames.random_endgame()
case endgame do
nil -> assign(socket, :empty, :exhausted)
endgame -> start_guest_puzzle(socket, socket.assigns.guest_address, endgame)
end
end
end
defp load_random_endgame(socket) do
case Endgames.random_endgame() do
nil -> assign(socket, :endgame, nil)
endgame -> PlayCore.init(socket, endgame, page_title: "Train")
defp take_puzzle(socket, address) do
case GuestLimits.remaining(address) do
{:limit_reached, retry_ms} ->
{:ok, limit_wall(socket, address, retry_ms)}
{:ok, _remaining} ->
case Endgames.random_endgame() do
nil -> {:ok, empty_pool(socket, address)}
endgame -> {:ok, start_guest_puzzle(socket, address, endgame)}
end
end
end
defp start_guest_puzzle(socket, address, endgame) do
case GuestLimits.take(address) do
{:ok, remaining} ->
socket
|> assign(:loading, false)
|> assign(:guest_address, address)
|> assign(:guest_remaining, remaining)
|> assign(:limit_reached, nil)
|> assign(:empty, nil)
|> PlayCore.init(endgame, page_title: "Train")
{:limit_reached, retry_ms} ->
limit_wall(socket, address, retry_ms)
end
end
defp empty_pool(socket, address) do
socket
|> assign(:loading, false)
|> assign(:guest_address, address)
|> assign(:endgame, nil)
|> assign(:empty, nil)
|> assign(:guest_remaining, nil)
|> assign(:limit_reached, nil)
end
defp limit_wall(socket, address, retry_ms) do
socket
|> assign(:loading, false)
|> assign(:guest_address, address)
|> assign(:guest_remaining, nil)
|> assign(:limit_reached, retry_ms)
|> assign(:endgame, nil)
|> assign(:empty, nil)
end
defp signed_in?(socket) do
case socket.assigns.current_scope do
%{user: %{}} -> true
@@ -48,7 +48,7 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
endgame={@endgame}
fen={@fen}
status={@status}
blocked_reason={@blocked_reason}
blocked={@blocked}
best_move={@best_move}
plies={@plies}
line={@line}
@@ -21,8 +21,23 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
alias Chesstrainer.Ratings
alias ChesstrainerWeb.RatingComponents
require Logger
@uci_pattern ~r/^[a-h][1-8][a-h][1-8][qrbn]?$/
@typedoc """
A blocked puzzle's user-facing state.
`kind` names the failure class, `title` and `message` are the only copy shown
to the player, and `retry` says whether fetching again can plausibly help.
"""
@type blocked :: %{
kind: :cooldown | :rate_limited | :not_covered | :unavailable,
title: String.t(),
message: String.t(),
retry: boolean()
}
@doc """
Loads `endgame` and starts an attempt on it.
@@ -39,7 +54,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|> assign(:fen, endgame.fen)
|> assign(:tablebase, nil)
|> assign(:status, :loading)
|> assign(:blocked_reason, nil)
|> assign(:blocked, nil)
|> assign(:best_move, nil)
|> assign(:plies, [])
|> assign(:reviewing, false)
@@ -164,7 +179,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|> snapshot(fen, tablebase)
|> assign(:awaiting_reply, false)
|> assign(:status, :playing)
|> assign(:blocked_reason, nil)
|> assign(:blocked, nil)
|> assign(:move_input_error, nil)
|> push_event("resume_board", %{})}
@@ -173,7 +188,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
socket
|> assign(:awaiting_reply, false)
|> assign(:status, :blocked)
|> assign(:blocked_reason, blocked_reason(other))}
|> assign(:blocked, blocked(other))}
end
end
else
@@ -359,14 +374,14 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|> assign(:tablebase, tablebase)
|> snapshot(fen, tablebase)
|> assign(:status, :playing)
|> assign(:blocked_reason, nil)
|> assign(:blocked, nil)
|> push_init_board(fen)
other ->
socket
|> assign(:tablebase, nil)
|> assign(:status, :blocked)
|> assign(:blocked_reason, blocked_reason(other))
|> assign(:blocked, blocked(other))
|> push_init_board(fen)
end
else
@@ -383,25 +398,54 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
})
end
defp blocked_reason({:cooldown, remaining_ms}) do
@doc """
Classifies a failed tablebase fetch into the copy the player sees.
One message per failure class; the underlying reason never reaches the page.
"""
@spec blocked(term()) :: blocked()
def blocked({:cooldown, remaining_ms}) do
seconds = max(div(remaining_ms + 999, 1000), 1)
"The tablebase is rate-limited. Try again in about #{seconds}s."
%{
kind: :cooldown,
title: "Tablebase cooling down",
message: "The tablebase is rate-limited. Try again in about #{seconds}s.",
retry: true
}
end
defp blocked_reason({:error, {:too_many_requests, _, _}}) do
"The tablebase is rate-limited. Try again in a minute."
def blocked({:error, {:too_many_requests, _, _}}) do
%{
kind: :rate_limited,
title: "Tablebase rate-limited",
message: "The tablebase is rate-limited. Try again in a minute.",
retry: true
}
end
defp blocked_reason({:error, {:client_error, 404, _}}) do
"This position is not covered by the tablebase."
def blocked({:error, {:client_error, 404, _}}), do: not_covered()
def blocked({:error, :not_covered}), do: not_covered()
def blocked({:error, :invalid_endgame}), do: not_covered()
def blocked({:error, reason}) do
Logger.warning("tablebase.unavailable", reason: inspect(reason))
%{
kind: :unavailable,
title: "Tablebase unavailable",
message: "The tablebase is unavailable right now. Try again in a moment.",
retry: true
}
end
defp blocked_reason({:error, :not_covered}) do
"This position is not covered by the tablebase."
end
defp blocked_reason({:error, reason}) do
"The tablebase is unavailable (#{inspect(reason)})."
defp not_covered do
%{
kind: :not_covered,
title: "Position not covered",
message: "This position isn't in the tablebase, so it can't be graded.",
retry: false
}
end
defp grade_and_record(socket, from, to, promotion, san, fen_after, draw, check, checkmate) do
@@ -464,7 +508,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
{:noreply,
socket
|> assign(:status, :blocked)
|> assign(:blocked_reason, blocked_reason(other))}
|> assign(:blocked, blocked(other))}
end
end
@@ -727,7 +771,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
:error ->
case Tablebase.new(fen) do
{:ok, tablebase} -> {:ok, tablebase, snapshot(socket, fen, tablebase)}
other -> {:unavailable, blocked_reason(other), socket}
other -> {:unavailable, blocked(other), socket}
end
end
end
+97 -46
View File
@@ -77,11 +77,12 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
</div>
<PlayComponents.play_surface
:if={is_nil(@pool)}
session={true}
endgame={@endgame}
fen={@fen}
status={@status}
blocked_reason={@blocked_reason}
blocked={@blocked}
best_move={@best_move}
plies={@plies}
line={@line}
@@ -99,6 +100,26 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
rating={@user_rating}
rating_delta={@last_rating_delta}
/>
<section
:if={@pool}
id="pool-exhausted"
class="rounded-xl border border-hairline bg-canvas-raised p-6"
>
<h2 class="text-lg font-semibold">You've finished every puzzle at this difficulty</h2>
<p class="mt-1 text-sm text-muted">
There are no more {difficulty_label(@session.difficulty)} puzzles right now.
Try again, or pick another difficulty.
</p>
<div class="mt-4 flex flex-wrap gap-2">
<.button id="retry-pool" phx-click="retry_pool" variant="primary">
<.icon name="hero-arrow-path" /> Retry
</.button>
<.button id="change-difficulty" phx-click="stop_session">
Change difficulty
</.button>
</div>
</section>
<% else %>
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
<div id="difficulty-picker" class="w-full max-w-md rounded-xl bg-base-100 p-6 shadow-xl">
@@ -155,6 +176,19 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
<div class="mt-4">
<.rating_guide rating={@user_rating} deviation={@user_deviation} />
</div>
<div
:if={@pool}
id="pool-empty"
class="mt-4 rounded-lg border border-warning/30 bg-warning/10 p-3 text-sm"
>
<p class="font-semibold">No puzzles available right now</p>
<p class="mt-1 text-muted">
There are no {difficulty_label(@pool.difficulty)} puzzles yet. Try again, or choose another difficulty.
</p>
<.button id="retry-pool" phx-click="retry_pool" class="mt-3">
<.icon name="hero-arrow-path" /> Retry
</.button>
</div>
<div class="mt-4 grid gap-2">
<%= for {difficulty, label, description} <- difficulty_options(@user_rating) do %>
<.button
@@ -188,62 +222,32 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|> assign(:last_session, nil)
|> assign(:puzzle_started_mono, nil)
|> assign(:puzzle_counted, false)
|> assign(:pool, nil)
|> assign(:user_rating, socket.assigns.current_scope.user.rating)
|> assign(:user_deviation, socket.assigns.current_scope.user.rating_deviation)}
end
@impl true
def handle_event("start_session", %{"difficulty" => difficulty}, socket) do
difficulty = parse_difficulty(difficulty)
case Puzzles.next_endgame(selection_user(socket), difficulty) do
nil ->
{:noreply, put_flash(socket, :error, "No puzzles are available right now.")}
endgame ->
session = %{
difficulty: difficulty,
started_at_ms: System.system_time(:millisecond),
baseline: socket.assigns.user_rating,
count: 0,
sum_ms: 0
}
socket =
socket
|> assign(:session, session)
|> assign(:puzzle_started_mono, System.monotonic_time(:millisecond))
|> assign(:puzzle_counted, false)
|> assign(:last_rating_delta, nil)
|> PlayCore.init(endgame, page_title: "Train")
{:noreply, socket}
end
{:noreply, start_session(socket, parse_difficulty(difficulty))}
end
def handle_event("next_puzzle", _params, socket) do
session = socket.assigns.session
def handle_event("next_puzzle", _params, socket), do: {:noreply, next_puzzle(socket)}
if session do
case Puzzles.next_endgame(selection_user(socket), session.difficulty,
exclude_ids: [socket.assigns.endgame.id]
) do
def handle_event("retry_pool", _params, socket) do
socket =
case socket.assigns.session do
nil ->
{:noreply, put_flash(socket, :info, "No more puzzles at this difficulty.")}
case socket.assigns.pool do
%{difficulty: difficulty} -> start_session(socket, difficulty)
_ -> socket
end
endgame ->
socket =
socket
|> assign(:puzzle_started_mono, System.monotonic_time(:millisecond))
|> assign(:puzzle_counted, false)
|> assign(:last_rating_delta, nil)
|> PlayCore.init(endgame, page_title: "Train")
{:noreply, socket}
_session ->
next_puzzle(socket)
end
else
{:noreply, socket}
end
{:noreply, socket}
end
def handle_event("stop_session", _params, socket) do
@@ -253,7 +257,7 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
session -> assign(socket, :last_session, summarise(session, socket.assigns.user_rating))
end
{:noreply, assign(socket, :session, nil)}
{:noreply, socket |> assign(:session, nil) |> assign(:pool, nil)}
end
def handle_event("endgame_move_played", params, socket) do
@@ -300,6 +304,53 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
def handle_event("back_to_game", _params, socket), do: PlayCore.back_to_game(socket)
defp start_session(socket, difficulty) do
case Puzzles.next_endgame(selection_user(socket), difficulty) do
nil ->
assign(socket, :pool, %{difficulty: difficulty})
endgame ->
session = %{
difficulty: difficulty,
started_at_ms: System.system_time(:millisecond),
baseline: socket.assigns.user_rating,
count: 0,
sum_ms: 0
}
socket
|> assign(:session, session)
|> assign(:pool, nil)
|> assign(:puzzle_started_mono, System.monotonic_time(:millisecond))
|> assign(:puzzle_counted, false)
|> assign(:last_rating_delta, nil)
|> PlayCore.init(endgame, page_title: "Train")
end
end
defp next_puzzle(socket) do
session = socket.assigns.session
if session do
case Puzzles.next_endgame(selection_user(socket), session.difficulty,
exclude_ids: [socket.assigns.endgame.id]
) do
nil ->
assign(socket, :pool, %{difficulty: session.difficulty})
endgame ->
socket
|> assign(:pool, nil)
|> assign(:puzzle_started_mono, System.monotonic_time(:millisecond))
|> assign(:puzzle_counted, false)
|> assign(:last_rating_delta, nil)
|> PlayCore.init(endgame, page_title: "Train")
end
else
socket
end
end
# A completed puzzle contributes one first-attempt time to the average. A
# retry happens after this point and is deliberately ignored.
defp account_completion(socket) do