Group WebGame's HLTB fields, serve rows flat

WebGame carries its HLTB times and poll counts in a WebHltb group;
dataset_to_payload inlines it, so the browser's row keys and order are
unchanged (new test).

Todo: 9b9342ba

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-12 08:37:51 +01:00
parent 7721b8716e
commit ce818db86c
6 changed files with 101 additions and 46 deletions

View File

@ -41,6 +41,7 @@ from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
from steam_backlog_enforcer._actions import allowed_app_ids from steam_backlog_enforcer._actions import allowed_app_ids
from steam_backlog_enforcer._flat_record import to_flat
from steam_backlog_enforcer._hltb_types import _read_raw_cache from steam_backlog_enforcer._hltb_types import _read_raw_cache
from steam_backlog_enforcer._scanning_confidence import ( from steam_backlog_enforcer._scanning_confidence import (
_MIN_COMP_100_POLLS, _MIN_COMP_100_POLLS,
@ -177,5 +178,7 @@ def build_web_dataset(state: State) -> WebDataset:
def dataset_to_payload(dataset: WebDataset) -> dict[str, Any]: def dataset_to_payload(dataset: WebDataset) -> dict[str, Any]:
"""Serialize a ``WebDataset`` to a JSON-ready dict.""" """Serialize a ``WebDataset`` to a JSON-ready dict; game rows stay flat."""
return asdict(dataset) payload = asdict(dataset)
payload["games"] = [to_flat(game) for game in dataset.games]
return payload

View File

@ -14,7 +14,7 @@ from steam_backlog_enforcer._scanning_confidence import (
_MIN_CONFIDENCE_SUM, _MIN_CONFIDENCE_SUM,
_MIN_COUNT_COMP, _MIN_COUNT_COMP,
) )
from steam_backlog_enforcer._web_models import DefaultSummary, WebGame from steam_backlog_enforcer._web_models import DefaultSummary, WebGame, WebHltb
from steam_backlog_enforcer.protondb import ( from steam_backlog_enforcer.protondb import (
ProtonDBRating, ProtonDBRating,
_load_cache, _load_cache,
@ -38,16 +38,17 @@ def _worst_hours(game: GameInfo, cache_hours: float, leisure: float) -> float:
def _passes_default_confidence(game: WebGame) -> bool: def _passes_default_confidence(game: WebGame) -> bool:
"""True if the game clears all three CLI HLTB-confidence thresholds.""" """True if the game clears all three CLI HLTB-confidence thresholds."""
if game.comp_100_count < _MIN_COMP_100_POLLS: if game.hltb.comp_100_count < _MIN_COMP_100_POLLS:
return False return False
if game.count_comp < _MIN_COUNT_COMP: if game.hltb.count_comp < _MIN_COUNT_COMP:
return False return False
return game.comp_100_count + game.count_comp >= _MIN_CONFIDENCE_SUM return game.hltb.comp_100_count + game.hltb.count_comp >= _MIN_CONFIDENCE_SUM
def _has_any_time(game: WebGame) -> bool: def _has_any_time(game: WebGame) -> bool:
"""True if the game has at least one positive time estimate.""" """True if the game has at least one positive time estimate."""
return game.worst_hours > 0 or game.rush_hours > 0 or game.leisure_hours > 0 hltb = game.hltb
return hltb.worst_hours > 0 or hltb.rush_hours > 0 or hltb.leisure_hours > 0
def _build_games(games: list[GameInfo], exclude: set[int]) -> list[WebGame]: def _build_games(games: list[GameInfo], exclude: set[int]) -> list[WebGame]:
@ -80,12 +81,14 @@ def _build_games(games: list[GameInfo], exclude: set[int]) -> list[WebGame]:
name=game.name, name=game.name,
completion_pct=round(game.completion_pct, 1), completion_pct=round(game.completion_pct, 1),
playtime_minutes=game.playtime_minutes, playtime_minutes=game.playtime_minutes,
rush_hours=rush, hltb=WebHltb(
leisure_hours=leisure, rush_hours=rush,
worst_hours=_worst_hours(game, cache_hours, leisure), leisure_hours=leisure,
count_comp=count_comp, worst_hours=_worst_hours(game, cache_hours, leisure),
comp_100_count=comp_100_count, count_comp=count_comp,
hltb_game_id=hltb_game_id, comp_100_count=comp_100_count,
hltb_game_id=hltb_game_id,
),
protondb_tier=rating.tier, protondb_tier=rating.tier,
protondb_trending_tier=rating.trending_tier, protondb_trending_tier=rating.trending_tier,
protondb_score=rating.score, protondb_score=rating.score,
@ -115,7 +118,7 @@ def _default_qualifying(rows: list[WebGame]) -> list[WebGame]:
def _sum_positive(rows: list[WebGame], attr: str) -> float: def _sum_positive(rows: list[WebGame], attr: str) -> float:
"""Sum a positive-only hour attribute across rows (matches ``_sum_hours``).""" """Sum a positive-only hour attribute across rows (matches ``_sum_hours``)."""
total = sum(getattr(g, attr) for g in rows if getattr(g, attr) > 0) total = sum(getattr(g.hltb, attr) for g in rows if getattr(g.hltb, attr) > 0)
return round(total, 1) return round(total, 1)

View File

@ -8,28 +8,41 @@ from __future__ import annotations
from dataclasses import dataclass, field from dataclasses import dataclass, field
from steam_backlog_enforcer._flat_record import flat_group
# Mirrors ``_stats._HOURS_PER_DAY_PRESETS`` but mutable/JSON-friendly. # Mirrors ``_stats._HOURS_PER_DAY_PRESETS`` but mutable/JSON-friendly.
HOURS_PER_DAY_PRESETS = [2.0, 4.0, 6.0, 8.0] HOURS_PER_DAY_PRESETS = [2.0, 4.0, 6.0, 8.0]
@dataclass @dataclass
class WebGame: class WebHltb:
"""One incomplete candidate game, with raw filterable fields. """A game's HLTB times and poll counts, as one :class:`WebGame` group.
Hour fields use ``-1`` to mean "no data" (matching the cache convention), Hour fields use ``-1`` to mean "no data" (matching the cache convention),
so the client can choose to include or exclude unknown-length games. so the client can choose to include or exclude unknown-length games.
""" """
app_id: int
name: str
completion_pct: float
playtime_minutes: int
rush_hours: float rush_hours: float
leisure_hours: float leisure_hours: float
worst_hours: float worst_hours: float
count_comp: int count_comp: int
comp_100_count: int comp_100_count: int
hltb_game_id: int hltb_game_id: int
@dataclass
class WebGame:
"""One incomplete candidate game, with raw filterable fields.
Served flat: :func:`~_flat_record.to_flat` inlines ``hltb`` so the browser
sees ``rush_hours`` etc. beside ``app_id``.
"""
app_id: int
name: str
completion_pct: float
playtime_minutes: int
hltb: WebHltb = field(metadata=flat_group(WebHltb))
protondb_tier: str protondb_tier: str
protondb_trending_tier: str protondb_trending_tier: str
protondb_score: float protondb_score: float

View File

@ -5,6 +5,7 @@ from __future__ import annotations
from dataclasses import replace from dataclasses import replace
from typing import Any from typing import Any
from steam_backlog_enforcer._flat_record import from_flat
from steam_backlog_enforcer._web_dataset import WebGame from steam_backlog_enforcer._web_dataset import WebGame
from steam_backlog_enforcer.steam_api import GameInfo from steam_backlog_enforcer.steam_api import GameInfo
@ -25,23 +26,23 @@ def _gi(**over: object) -> GameInfo:
def _wg(**over: object) -> WebGame: def _wg(**over: object) -> WebGame:
"""Build a WebGame with field overrides.""" """Build a WebGame with overrides named by its flat (served) keys."""
base = WebGame( base = {
app_id=1, "app_id": 1,
name="Game1", "name": "Game1",
completion_pct=0.0, "completion_pct": 0.0,
playtime_minutes=60, "playtime_minutes": 60,
rush_hours=10.0, "rush_hours": 10.0,
leisure_hours=20.0, "leisure_hours": 20.0,
worst_hours=25.0, "worst_hours": 25.0,
count_comp=20, "count_comp": 20,
comp_100_count=5, "comp_100_count": 5,
hltb_game_id=0, "hltb_game_id": 0,
protondb_tier="gold", "protondb_tier": "gold",
protondb_trending_tier="gold", "protondb_trending_tier": "gold",
protondb_score=0.8, "protondb_score": 0.8,
) }
return replace(base, **over) return from_flat(WebGame, base | over)
def _complete_game( def _complete_game(

View File

@ -68,12 +68,12 @@ class TestBuildGames:
rows = self._run([_gi(app_id=1, completionist_hours=0.0)], set(), raw, proton) rows = self._run([_gi(app_id=1, completionist_hours=0.0)], set(), raw, proton)
assert len(rows) == 1 assert len(rows) == 1
row = rows[0] row = rows[0]
assert row.rush_hours == 9.0 assert row.hltb.rush_hours == 9.0
assert row.leisure_hours == 22.0 assert row.hltb.leisure_hours == 22.0
assert row.worst_hours == 22.0 # max(cache 18, leisure 22) assert row.hltb.worst_hours == 22.0 # max(cache 18, leisure 22)
assert row.count_comp == 30 assert row.hltb.count_comp == 30
assert row.comp_100_count == 7 assert row.hltb.comp_100_count == 7
assert row.hltb_game_id == 555 assert row.hltb.hltb_game_id == 555
assert row.protondb_tier == "platinum" assert row.protondb_tier == "platinum"
assert row.protondb_trending_tier == "gold" assert row.protondb_trending_tier == "gold"
@ -82,9 +82,9 @@ class TestBuildGames:
rows = self._run([_gi(app_id=1, completionist_hours=12.0)], set()) rows = self._run([_gi(app_id=1, completionist_hours=12.0)], set())
assert len(rows) == 1 assert len(rows) == 1
row = rows[0] row = rows[0]
assert row.rush_hours == -1 assert row.hltb.rush_hours == -1
assert row.leisure_hours == -1 assert row.hltb.leisure_hours == -1
assert row.worst_hours == 12.0 # completionist only assert row.hltb.worst_hours == 12.0 # completionist only
assert row.protondb_tier == "" # no protondb entry assert row.protondb_tier == "" # no protondb entry

View File

@ -2,13 +2,17 @@
from __future__ import annotations from __future__ import annotations
from dataclasses import replace
from unittest.mock import patch from unittest.mock import patch
from steam_backlog_enforcer._web_dataset import ( from steam_backlog_enforcer._web_dataset import (
WebDataset,
WebGame,
build_web_dataset, build_web_dataset,
dataset_to_payload, dataset_to_payload,
) )
from steam_backlog_enforcer.config import State from steam_backlog_enforcer.config import State
from steam_backlog_enforcer.tests._web_dataset_factories import _wg
_PKG = "steam_backlog_enforcer._web_games" _PKG = "steam_backlog_enforcer._web_games"
# build_web_dataset itself did not move. # build_web_dataset itself did not move.
@ -36,3 +40,34 @@ class TestDatasetToPayload:
} }
assert isinstance(payload["games"], list) assert isinstance(payload["games"], list)
assert isinstance(payload["state"], dict) assert isinstance(payload["state"], dict)
def test_game_rows_are_served_flat(self) -> None:
"""The HLTB group is inlined: the browser's row keys do not change."""
dataset = build_web_dataset_with([_wg(rush_hours=3.0)])
row = dataset_to_payload(dataset)["games"][0]
assert list(row) == [
"app_id",
"name",
"completion_pct",
"playtime_minutes",
"rush_hours",
"leisure_hours",
"worst_hours",
"count_comp",
"comp_100_count",
"hltb_game_id",
"protondb_tier",
"protondb_trending_tier",
"protondb_score",
]
assert row["rush_hours"] == 3.0
def build_web_dataset_with(games: list[WebGame]) -> WebDataset:
"""An otherwise empty dataset carrying *games*."""
with (
patch(f"{_DATASET_PKG}.load_snapshot", return_value=None),
patch(f"{_PKG}._read_raw_cache", return_value={}),
patch(f"{_PKG}._load_cache", return_value={}),
):
return replace(build_web_dataset(State()), games=games)