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
+3
View File
@@ -15,6 +15,9 @@ Verdicts:
"Internal detail" means an exception term, an `inspect/1` result, a raw HTTP "Internal detail" means an exception term, an `inspect/1` result, a raw HTTP
status body, a stacktrace, or a raw FEN appearing in rendered HTML. status body, a stacktrace, or a raw FEN appearing in rendered HTML.
**Status:** #163 implements T1–T6, S1–S3 and S5. The rows below describe the
state before that change; #164 records what was verified afterwards.
## Play and tablebase ## Play and tablebase
| ID | State | Trigger | What the user sees today | Verdict | Action | | ID | State | Trigger | What the user sees today | Verdict | Action |
+27
View File
@@ -40,6 +40,18 @@ defmodule Chesstrainer.GuestLimits do
@doc "Clears every budget. Intended for tests." @doc "Clears every budget. Intended for tests."
def reset, do: GenServer.call(__MODULE__, :reset) 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." @doc "The daily puzzle allowance for a guest."
def limit, do: config() |> Keyword.get(:limit, @default_limit) def limit, do: config() |> Keyword.get(:limit, @default_limit)
@@ -67,6 +79,21 @@ defmodule Chesstrainer.GuestLimits do
@impl true @impl true
def handle_call({:take, nil, _today}, _from, state), do: {:reply, {:ok, nil}, state} 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 def handle_call({:take, address, today}, _from, state) do
day = Date.to_gregorian_days(today) day = Date.to_gregorian_days(today)
key = key(state.secret, day, address) key = key(state.secret, day, address)
@@ -14,14 +14,14 @@ defmodule ChesstrainerWeb.PlayComponents do
attr :endgame, :any, required: true attr :endgame, :any, required: true
attr :fen, :string, default: nil attr :fen, :string, default: nil
attr :status, :atom, required: true attr :status, :atom, required: true
attr :blocked_reason, :string, default: nil attr :blocked, :map, default: nil
attr :best_move, :string, default: nil attr :best_move, :string, default: nil
attr :plies, :list, required: true attr :plies, :list, required: true
attr :line, :list, required: true attr :line, :list, required: true
attr :reviewing, :boolean, required: true attr :reviewing, :boolean, required: true
attr :review_index, :integer, required: true attr :review_index, :integer, required: true
attr :review_tablebase, :any, default: nil 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 :awaiting_reply, :boolean, required: true
attr :last_grade, :atom, default: nil attr :last_grade, :atom, default: nil
attr :awaiting_best_line, :boolean, default: false attr :awaiting_best_line, :boolean, default: false
@@ -169,7 +169,23 @@ defmodule ChesstrainerWeb.PlayComponents do
> >
<.icon name="hero-eye" /> Review <.icon name="hero-eye" /> Review
</.button> </.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" /> <.icon name="hero-arrow-path" />
{if @status in [:solved, :failed], do: "Try again", else: "Reset"} {if @status in [:solved, :failed], do: "Try again", else: "Reset"}
</.button> </.button>
@@ -194,7 +210,7 @@ defmodule ChesstrainerWeb.PlayComponents do
<%= cond do %> <%= cond do %>
<% @review_blocked -> %> <% @review_blocked -> %>
<p class="text-muted">Best move unavailable here</p> <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 -> %> <% @review_tablebase -> %>
<p class="text-muted font-semibold mb-1">Best move:</p> <p class="text-muted font-semibold mb-1">Best move:</p>
<p class="text-success-text">{PlayCore.best_move_text(@review_tablebase) || "—"}</p> <p class="text-success-text">{PlayCore.best_move_text(@review_tablebase) || "—"}</p>
@@ -211,9 +227,9 @@ defmodule ChesstrainerWeb.PlayComponents do
<%= cond do %> <%= cond do %>
<% @status == :loading -> %> <% @status == :loading -> %>
<p class="text-muted">Loading tablebase…</p> <p class="text-muted">Loading tablebase…</p>
<% @status == :blocked -> %> <% @status == :blocked && @blocked -> %>
<p class="font-semibold text-error-text">Tablebase unavailable</p> <p class="font-semibold text-error-text">{@blocked.title}</p>
<p class="text-error-text">{@blocked_reason}</p> <p class="text-error-text">{@blocked.message}</p>
<% @status == :solved -> %> <% @status == :solved -> %>
<p class="font-semibold text-success-text"> <p class="font-semibold text-success-text">
{if @endgame.result == :draw, do: "Draw held!", else: "Solved!"} {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(:loading, _awaiting), do: "Loading the tablebase…"
defp move_hint(:blocked, _awaiting), defp move_hint(:blocked, _awaiting), do: "Moves are paused."
do: "The tablebase is unavailable, so moves cannot be entered."
defp move_hint(status, _awaiting) when status in [:solved, :failed], defp move_hint(status, _awaiting) when status in [:solved, :failed],
do: "This puzzle is finished. Reset or try again." do: "This puzzle is finished. Reset or try again."
@@ -488,7 +503,10 @@ defmodule ChesstrainerWeb.PlayComponents do
"Loading the tablebase." "Loading the tablebase."
assigns.status == :blocked -> 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 -> assigns.reviewing ->
review_announcement(assigns) review_announcement(assigns)
@@ -70,12 +70,12 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
</section> </section>
<PlayComponents.play_surface <PlayComponents.play_surface
:if={@endgame} :if={@endgame && @empty != :exhausted}
session={is_nil(@limit_reached)} session={is_nil(@limit_reached)}
endgame={@endgame} endgame={@endgame}
fen={@fen} fen={@fen}
status={@status} status={@status}
blocked_reason={@blocked_reason} blocked={@blocked}
best_move={@best_move} best_move={@best_move}
plies={@plies} plies={@plies}
line={@line} 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={@loading} class="text-base-content/70">Picking a random puzzle…</p>
<p <section
:if={not @loading and is_nil(@endgame) and is_nil(@limit_reached)} :if={@empty == :exhausted}
class="text-base-content/70" id="guest-pool-exhausted"
class="rounded-xl border border-hairline bg-canvas-raised p-6"
> >
No endgames are available yet. Please check back soon. <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> </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> </Layouts.app>
""" """
end end
@@ -120,6 +149,7 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
socket socket
|> assign(:loading, true) |> assign(:loading, true)
|> assign(:endgame, nil) |> assign(:endgame, nil)
|> assign(:empty, nil)
|> assign(:guest_remaining, nil) |> assign(:guest_remaining, nil)
|> assign(:limit_reached, nil) |> assign(:limit_reached, nil)
|> assign(:guest_address, nil)} |> assign(:guest_address, nil)}
@@ -127,29 +157,14 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
end end
@impl true @impl true
def handle_event("next_puzzle", _params, socket) do def handle_event("next_puzzle", _params, socket), do: {:noreply, next_puzzle(socket)}
case GuestLimits.take(socket.assigns.guest_address) do
{:ok, remaining} ->
endgame =
Endgames.random_endgame(exclude_ids: [socket.assigns.endgame.id]) ||
Endgames.random_endgame()
case endgame do def handle_event("retry_pool", _params, socket) do
nil -> if socket.assigns.empty == :exhausted do
{:noreply, put_flash(socket, :info, "No more puzzles are available right now.")} {:noreply, next_puzzle(socket)}
else
endgame -> {:ok, socket} = take_puzzle(socket, socket.assigns.guest_address)
{:noreply, {:noreply, socket}
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)}
end end
end end
@@ -193,34 +208,73 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
def handle_event("back_to_game", _params, socket), do: PlayCore.back_to_game(socket) def handle_event("back_to_game", _params, socket), do: PlayCore.back_to_game(socket)
defp next_puzzle(socket) do
case GuestLimits.remaining(socket.assigns.guest_address) do
{:limit_reached, retry_ms} ->
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 take_puzzle(socket, address) do 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 case GuestLimits.take(address) do
{:ok, remaining} -> {:ok, remaining} ->
socket =
socket socket
|> assign(:loading, false) |> assign(:loading, false)
|> assign(:guest_address, address) |> assign(:guest_address, address)
|> assign(:guest_remaining, remaining) |> assign(:guest_remaining, remaining)
|> assign(:limit_reached, nil) |> assign(:limit_reached, nil)
|> assign(:empty, nil)
{:ok, load_random_endgame(socket)} |> PlayCore.init(endgame, page_title: "Train")
{:limit_reached, retry_ms} -> {:limit_reached, retry_ms} ->
{:ok, 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 socket
|> assign(:loading, false) |> assign(:loading, false)
|> assign(:guest_address, address) |> assign(:guest_address, address)
|> assign(:guest_remaining, nil) |> assign(:guest_remaining, nil)
|> assign(:limit_reached, retry_ms) |> assign(:limit_reached, retry_ms)
|> assign(:endgame, nil)} |> assign(:endgame, nil)
end |> assign(:empty, nil)
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")
end
end end
defp signed_in?(socket) do defp signed_in?(socket) do
@@ -48,7 +48,7 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
endgame={@endgame} endgame={@endgame}
fen={@fen} fen={@fen}
status={@status} status={@status}
blocked_reason={@blocked_reason} blocked={@blocked}
best_move={@best_move} best_move={@best_move}
plies={@plies} plies={@plies}
line={@line} line={@line}
@@ -21,8 +21,23 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
alias Chesstrainer.Ratings alias Chesstrainer.Ratings
alias ChesstrainerWeb.RatingComponents alias ChesstrainerWeb.RatingComponents
require Logger
@uci_pattern ~r/^[a-h][1-8][a-h][1-8][qrbn]?$/ @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 """ @doc """
Loads `endgame` and starts an attempt on it. Loads `endgame` and starts an attempt on it.
@@ -39,7 +54,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|> assign(:fen, endgame.fen) |> assign(:fen, endgame.fen)
|> assign(:tablebase, nil) |> assign(:tablebase, nil)
|> assign(:status, :loading) |> assign(:status, :loading)
|> assign(:blocked_reason, nil) |> assign(:blocked, nil)
|> assign(:best_move, nil) |> assign(:best_move, nil)
|> assign(:plies, []) |> assign(:plies, [])
|> assign(:reviewing, false) |> assign(:reviewing, false)
@@ -164,7 +179,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|> snapshot(fen, tablebase) |> snapshot(fen, tablebase)
|> assign(:awaiting_reply, false) |> assign(:awaiting_reply, false)
|> assign(:status, :playing) |> assign(:status, :playing)
|> assign(:blocked_reason, nil) |> assign(:blocked, nil)
|> assign(:move_input_error, nil) |> assign(:move_input_error, nil)
|> push_event("resume_board", %{})} |> push_event("resume_board", %{})}
@@ -173,7 +188,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
socket socket
|> assign(:awaiting_reply, false) |> assign(:awaiting_reply, false)
|> assign(:status, :blocked) |> assign(:status, :blocked)
|> assign(:blocked_reason, blocked_reason(other))} |> assign(:blocked, blocked(other))}
end end
end end
else else
@@ -359,14 +374,14 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
|> assign(:tablebase, tablebase) |> assign(:tablebase, tablebase)
|> snapshot(fen, tablebase) |> snapshot(fen, tablebase)
|> assign(:status, :playing) |> assign(:status, :playing)
|> assign(:blocked_reason, nil) |> assign(:blocked, nil)
|> push_init_board(fen) |> push_init_board(fen)
other -> other ->
socket socket
|> assign(:tablebase, nil) |> assign(:tablebase, nil)
|> assign(:status, :blocked) |> assign(:status, :blocked)
|> assign(:blocked_reason, blocked_reason(other)) |> assign(:blocked, blocked(other))
|> push_init_board(fen) |> push_init_board(fen)
end end
else else
@@ -383,25 +398,54 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
}) })
end 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) 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 end
defp blocked_reason({:error, {:too_many_requests, _, _}}) do def blocked({:error, {:too_many_requests, _, _}}) do
"The tablebase is rate-limited. Try again in a minute." %{
kind: :rate_limited,
title: "Tablebase rate-limited",
message: "The tablebase is rate-limited. Try again in a minute.",
retry: true
}
end end
defp blocked_reason({:error, {:client_error, 404, _}}) do def blocked({:error, {:client_error, 404, _}}), do: not_covered()
"This position is not covered by the tablebase." 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 end
defp blocked_reason({:error, :not_covered}) do defp not_covered do
"This position is not covered by the tablebase." %{
end kind: :not_covered,
title: "Position not covered",
defp blocked_reason({:error, reason}) do message: "This position isn't in the tablebase, so it can't be graded.",
"The tablebase is unavailable (#{inspect(reason)})." retry: false
}
end end
defp grade_and_record(socket, from, to, promotion, san, fen_after, draw, check, checkmate) do 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, {:noreply,
socket socket
|> assign(:status, :blocked) |> assign(:status, :blocked)
|> assign(:blocked_reason, blocked_reason(other))} |> assign(:blocked, blocked(other))}
end end
end end
@@ -727,7 +771,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayCore do
:error -> :error ->
case Tablebase.new(fen) do case Tablebase.new(fen) do
{:ok, tablebase} -> {:ok, tablebase, snapshot(socket, fen, tablebase)} {:ok, tablebase} -> {:ok, tablebase, snapshot(socket, fen, tablebase)}
other -> {:unavailable, blocked_reason(other), socket} other -> {:unavailable, blocked(other), socket}
end end
end end
end end
+96 -45
View File
@@ -77,11 +77,12 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
</div> </div>
<PlayComponents.play_surface <PlayComponents.play_surface
:if={is_nil(@pool)}
session={true} session={true}
endgame={@endgame} endgame={@endgame}
fen={@fen} fen={@fen}
status={@status} status={@status}
blocked_reason={@blocked_reason} blocked={@blocked}
best_move={@best_move} best_move={@best_move}
plies={@plies} plies={@plies}
line={@line} line={@line}
@@ -99,6 +100,26 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
rating={@user_rating} rating={@user_rating}
rating_delta={@last_rating_delta} 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 %> <% else %>
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"> <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"> <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"> <div class="mt-4">
<.rating_guide rating={@user_rating} deviation={@user_deviation} /> <.rating_guide rating={@user_rating} deviation={@user_deviation} />
</div> </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"> <div class="mt-4 grid gap-2">
<%= for {difficulty, label, description} <- difficulty_options(@user_rating) do %> <%= for {difficulty, label, description} <- difficulty_options(@user_rating) do %>
<.button <.button
@@ -188,63 +222,33 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
|> assign(:last_session, nil) |> assign(:last_session, nil)
|> assign(:puzzle_started_mono, nil) |> assign(:puzzle_started_mono, nil)
|> assign(:puzzle_counted, false) |> assign(:puzzle_counted, false)
|> assign(:pool, nil)
|> assign(:user_rating, socket.assigns.current_scope.user.rating) |> assign(:user_rating, socket.assigns.current_scope.user.rating)
|> assign(:user_deviation, socket.assigns.current_scope.user.rating_deviation)} |> assign(:user_deviation, socket.assigns.current_scope.user.rating_deviation)}
end end
@impl true @impl true
def handle_event("start_session", %{"difficulty" => difficulty}, socket) do def handle_event("start_session", %{"difficulty" => difficulty}, socket) do
difficulty = parse_difficulty(difficulty) {:noreply, start_session(socket, parse_difficulty(difficulty))}
end
case Puzzles.next_endgame(selection_user(socket), difficulty) do def handle_event("next_puzzle", _params, socket), do: {:noreply, next_puzzle(socket)}
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
}
def handle_event("retry_pool", _params, socket) do
socket = socket =
socket case socket.assigns.session do
|> 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
end
def handle_event("next_puzzle", _params, 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 -> 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 -> _session ->
socket = next_puzzle(socket)
socket end
|> 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} {:noreply, socket}
end end
else
{:noreply, socket}
end
end
def handle_event("stop_session", _params, socket) do def handle_event("stop_session", _params, socket) do
socket = socket =
@@ -253,7 +257,7 @@ defmodule ChesstrainerWeb.EndgameLive.Train do
session -> assign(socket, :last_session, summarise(session, socket.assigns.user_rating)) session -> assign(socket, :last_session, summarise(session, socket.assigns.user_rating))
end end
{:noreply, assign(socket, :session, nil)} {:noreply, socket |> assign(:session, nil) |> assign(:pool, nil)}
end end
def handle_event("endgame_move_played", params, socket) do 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) 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 # A completed puzzle contributes one first-attempt time to the average. A
# retry happens after this point and is deliberately ignored. # retry happens after this point and is deliberately ignored.
defp account_completion(socket) do defp account_completion(socket) do
+12
View File
@@ -37,9 +37,21 @@ defmodule Chesstrainer.GuestLimitsTest do
assert {:ok, 4} = GuestLimits.take(@other, @today) assert {:ok, 4} = GuestLimits.take(@other, @today)
end end
test "remaining reports the budget without consuming it" do
assert {:ok, 5} = GuestLimits.remaining(@address, @today)
assert {:ok, 5} = GuestLimits.remaining(@address, @today)
assert {:ok, 4} = GuestLimits.take(@address, @today)
assert {:ok, 4} = GuestLimits.remaining(@address, @today)
for _ <- 1..4, do: assert({:ok, _} = GuestLimits.take(@address, @today))
assert {:limit_reached, _} = GuestLimits.remaining(@address, @today)
end
test "does not limit a missing address" do test "does not limit a missing address" do
assert {:ok, nil} = GuestLimits.take(nil, @today) assert {:ok, nil} = GuestLimits.take(nil, @today)
assert {:ok, nil} = GuestLimits.take(nil, @today) assert {:ok, nil} = GuestLimits.take(nil, @today)
assert {:ok, nil} = GuestLimits.remaining(nil, @today)
end end
test "reset clears spent budgets" do test "reset clears spent budgets" do
@@ -80,11 +80,21 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrainTest do
end end
describe "without puzzles" do describe "without puzzles" do
test "shows an empty state", %{conn: conn} do test "shows an empty state with a retry that does not spend a puzzle", %{conn: conn} do
{:ok, view, _html} = live(conn, ~p"/guest-train") {:ok, view, _html} = live(conn, ~p"/guest-train")
assert render(view) =~ "No endgames are available yet" assert has_element?(view, "#guest-pool-empty")
assert has_element?(view, "#retry-pool")
refute has_element?(view, "#endgame-board") refute has_element?(view, "#endgame-board")
assert {:ok, 5} = GuestLimits.remaining(@guest_address)
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
view |> element("#retry-pool") |> render_click()
assert has_element?(view, "#endgame-board")
assert :sys.get_state(view.pid).socket.assigns.guest_remaining == 4
end end
end end
@@ -133,6 +143,31 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrainTest do
assert :sys.get_state(view.pid).socket.assigns.guest_remaining == 4 assert :sys.get_state(view.pid).socket.assigns.guest_remaining == 4
end end
test "shows an in-page state when no puzzles are left, and retry loads one", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/guest-train")
solve_current(view)
Repo.delete!(endgame)
view |> element("#next-puzzle-button") |> render_click()
assert has_element?(view, "#guest-pool-exhausted")
assert has_element?(view, "#retry-pool")
refute has_element?(view, "#endgame-board")
assert :sys.get_state(view.pid).socket.assigns.guest_remaining == 4
new_endgame = endgame_fixture()
seed_tablebase(new_endgame.fen, moves: grading_moves())
view |> element("#retry-pool") |> render_click()
assert :sys.get_state(view.pid).socket.assigns.endgame.id == new_endgame.id
assert :sys.get_state(view.pid).socket.assigns.guest_remaining == 3
end
end end
describe "daily budget" do describe "daily budget" do
@@ -12,6 +12,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
alias Chesstrainer.FEN alias Chesstrainer.FEN
alias Chesstrainer.Ratelimiters alias Chesstrainer.Ratelimiters
alias Chesstrainer.Repo alias Chesstrainer.Repo
alias ChesstrainerWeb.EndgameLive.PlayCore
defp assert_init_board(view, expected_fen, expected_orientation, expected_player_color) do defp assert_init_board(view, expected_fen, expected_orientation, expected_player_color) do
%{proxy: {ref, _topic, _}} = view %{proxy: {ref, _topic, _}} = view
@@ -266,10 +267,22 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
{:ok, view, html} = live(conn, ~p"/endgames/#{endgame.public_code}/play") {:ok, view, html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
assert html =~ "Tablebase unavailable" assert html =~ "Tablebase cooling down"
refute html =~ "inspect("
refute html =~ "too_many_requests"
play_move(view, endgame, "d1", "d7", "Qd7+") play_move(view, endgame, "d1", "d7", "Qd7+")
assert render(view) =~ "cannot be graded" assert render(view) =~ "cannot be graded"
# Retry re-fetches: with the cache seeded and the cooldown cleared, the
# same puzzle becomes playable in one click.
seed_tablebase(endgame.fen)
Ratelimiters.lichess_reset_cooldown()
view |> element("#retry-blocked") |> render_click()
assert :sys.get_state(view.pid).socket.assigns.status == :playing
refute render(view) =~ "Tablebase cooling down"
end end
test "blocks an out-of-range endgame as not covered", %{conn: conn} do test "blocks an out-of-range endgame as not covered", %{conn: conn} do
@@ -278,8 +291,37 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
html = render(view) html = render(view)
assert html =~ "Tablebase unavailable" assert html =~ "Position not covered"
assert html =~ "not covered by the tablebase" assert html =~ "can&#39;t be graded"
refute has_element?(view, "#retry-blocked")
refute html =~ "not_covered"
refute html =~ "inspect("
end
@tag capture_log: true
test "classifies every failure class without exposing the reason" do
cases = [
{{:cooldown, 30_000}, :cooldown, true},
{{:error, {:too_many_requests, 429, "upstream body"}}, :rate_limited, true},
{{:error, {:client_error, 404, "upstream body"}}, :not_covered, false},
{{:error, :not_covered}, :not_covered, false},
{{:error, :invalid_endgame}, :not_covered, false},
{{:error, {:server_error, 500, "upstream body"}}, :unavailable, true},
{{:error, :econnrefused}, :unavailable, true}
]
for {input, kind, retry?} <- cases do
blocked = PlayCore.blocked(input)
assert blocked.kind == kind
assert blocked.retry == retry?
refute blocked.message =~ "inspect"
refute blocked.message =~ "server_error"
refute blocked.message =~ "econnrefused"
refute blocked.message =~ "upstream"
refute blocked.message =~ "500"
refute blocked.message =~ "429"
end
end end
end end
@@ -225,6 +225,63 @@ defmodule ChesstrainerWeb.EndgameLive.TrainTest do
end end
end end
describe "empty pools" do
setup :register_and_log_in_user
test "shows an in-page state when a difficulty has no puzzles", %{conn: conn} do
{:ok, view, _html} = live(conn, ~p"/train")
view |> element("#difficulty-medium") |> render_click()
assert has_element?(view, "#pool-empty")
assert has_element?(view, "#retry-pool")
assert has_element?(view, "#difficulty-picker")
refute has_element?(view, "#session-bar")
endgame = endgame_fixture(rating: 1500)
seed_tablebase(endgame.fen)
view |> element("#retry-pool") |> render_click()
assert has_element?(view, "#session-bar")
refute has_element?(view, "#pool-empty")
end
test "shows an in-page end-of-run state when the difficulty is exhausted", %{conn: conn} do
{view, [_endgame]} = start_medium_session(conn, 1)
solve_current(view)
view |> element("#next-puzzle-button") |> render_click()
assert has_element?(view, "#pool-exhausted")
assert has_element?(view, "#retry-pool")
assert has_element?(view, "#change-difficulty")
refute has_element?(view, "#endgame-board")
view |> element("#change-difficulty") |> render_click()
assert has_element?(view, "#difficulty-picker")
assert :sys.get_state(view.pid).socket.assigns.session == nil
end
test "retry loads a puzzle once the pool grows", %{conn: conn} do
{view, [_endgame]} = start_medium_session(conn, 1)
solve_current(view)
view |> element("#next-puzzle-button") |> render_click()
assert has_element?(view, "#pool-exhausted")
rating = :sys.get_state(view.pid).socket.assigns.user_rating
new_endgame = endgame_fixture(fen: "4k3/8/8/8/8/8/8/4K3 w - - 0 1", rating: round(rating))
seed_tablebase(new_endgame.fen)
view |> element("#retry-pool") |> render_click()
assert :sys.get_state(view.pid).socket.assigns.endgame.id == new_endgame.id
refute has_element?(view, "#pool-exhausted")
end
end
defp elapsed_id(view) do defp elapsed_id(view) do
:sys.get_state(view.pid).socket.assigns.session.started_at_ms :sys.get_state(view.pid).socket.assigns.session.started_at_ms
end end