Files
owenrees e0b446bbfb Weight puzzle selection and stop repeats inside a session (#183)
Selection took a hard rating band (medium = user rating ± 100), removed
everything attempted in the last 30 days, and drew uniformly from what was
left. Because the bulk importer gives every endgame in a batch the same
rating, the band held either the whole library or — once a user's rating
drifted past it — only the endgames that user had already played. With
`fresh` empty, the fallback re-drew from the same band ignoring recency, so
recently played puzzles came straight back. An empty band used a
deterministic nearest-match, alternating between the same two puzzles.

Difficulty is now a bias rather than a filter: candidates are weighted by
`exp(-|rating - target| / spread)` and drawn with an exponential race, so
the whole library stays reachable and a thin region around the user's rating
can never empty the pool. `easy` and `hard` keep one-sided guards so the
labels stay honest. When every candidate is excluded, selection serves the
least recently attempted endgame instead of a random recent one.

Sessions now carry the ids they have served, which fixes the observed
in-session repeat (only the current puzzle used to be excluded), and guest
training gets the same treatment. The 30-day window is configurable as the
repeat window and is now named in GLOSSARY.md, distinct from the rating
window and from the tablebase cooldown.

Difficulty copy is qualitative, since the band numbers no longer describe
how selection works.
2026-11-17 14:28:24 +01:00

127 lines
3.5 KiB
Elixir

defmodule Chesstrainer.Attempts do
@moduledoc """
The Attempts context: a per-user history of finished playthroughs.
"""
import Ecto.Query, warn: false
alias Chesstrainer.Repo
alias Chesstrainer.Accounts.{Scope, User}
alias Chesstrainer.Endgames.Endgame
alias Chesstrainer.Attempts.Attempt
@doc """
Records a finished attempt for the signed-in user in `scope`.
Anonymous scopes record nothing and return `:ignored`.
"""
def record_attempt(nil, _endgame, _outcome), do: :ignored
def record_attempt(%Scope{user: nil}, _endgame, _outcome), do: :ignored
def record_attempt(%Scope{user: %User{} = user}, %Endgame{} = endgame, outcome)
when outcome in [:solved, :failed] do
%Attempt{user_id: user.id, endgame_id: endgame.id}
|> Attempt.changeset(%{outcome: outcome})
|> Repo.insert()
end
@doc """
The timestamp of the most recent rated attempt for a user/endgame pair, or nil.
"""
def last_rated_at(user_id, endgame_id) do
Attempt
|> where([a], a.user_id == ^user_id and a.endgame_id == ^endgame_id)
|> rated()
|> select([a], max(a.rated_at))
|> Repo.one()
end
@doc """
The timestamp of the most recent rated attempt for a user, or nil.
"""
def last_rated_at_for_user(user_id) do
Attempt
|> where([a], a.user_id == ^user_id)
|> rated()
|> select([a], max(a.rated_at))
|> Repo.one()
end
@doc """
The timestamp of the most recent rated attempt on an endgame, or nil.
"""
def last_rated_at_for_endgame(endgame_id) do
Attempt
|> where([a], a.endgame_id == ^endgame_id)
|> rated()
|> select([a], max(a.rated_at))
|> Repo.one()
end
@doc """
Returns the number of users who have recorded at least one attempt.
A retry does not count twice: the count is over distinct users.
"""
def count_users_with_attempts do
Attempt
|> select([a], count(a.user_id, :distinct))
|> Repo.one()
end
@doc """
Aggregated attempt totals for `user_id`.
Returns a map with `:attempts`, `:solved`, `:failed` and `:endgames` (the
number of distinct puzzles tried).
"""
def stats_for_user(user_id) do
Attempt
|> where([a], a.user_id == ^user_id)
|> select([a], %{
attempts: count(a.id),
solved: filter(count(a.id), a.outcome == :solved),
failed: filter(count(a.id), a.outcome == :failed),
endgames: count(a.endgame_id, :distinct)
})
|> Repo.one()
end
@doc """
The attempts of `user_id`, newest first, with each endgame preloaded.
Pass `limit: n` to cap the history (the profile page shows a recent window;
exports pass no limit).
"""
def list_attempts_for_user(user_id, opts \\ []) do
Attempt
|> where([a], a.user_id == ^user_id)
|> order_by([a], desc: a.inserted_at)
|> maybe_limit(Keyword.get(opts, :limit))
|> preload(:endgame)
|> Repo.all()
end
@doc """
The distinct endgame ids `user_id` has attempted in the last `days` days.
Used by puzzle selection to skip puzzles inside the repeat window; a retry
still counts as an attempt, even though the rating window leaves it unrated.
"""
def recent_endgame_ids(user_id, days \\ 30) do
cutoff = DateTime.add(DateTime.utc_now(), -days, :day)
Attempt
|> where([a], a.user_id == ^user_id and a.inserted_at >= ^cutoff)
|> distinct(true)
|> select([a], a.endgame_id)
|> Repo.all()
end
defp rated(query), do: where(query, [a], not is_nil(a.rated_at))
defp maybe_limit(query, nil), do: query
defp maybe_limit(query, limit) when is_integer(limit), do: limit(query, ^limit)
end