signal-bot/signal_bot/stats/records.py
Krzysztof kuhy Rudnicki a9ffd02f33 feat: periods, records and the crown
The queries the statistics are made of, all derived rather than cached --
two sources of truth for one number is how a leaderboard comes to
disagree with itself, and this history is small enough that recomputing
is free.

Periods take an inclusive span of stored Warsaw day strings, never a
range of timestamps, so a daylight-saving change cannot move a boundary.
Trend reports None rather than 0 when there is no previous period:
"nothing to compare against yet" and "no change" are different
statements and the group will read them differently.

A tie shares the crown and keeps every tied run alive, per kuhy's call.
Streaks count *recorded* days, so a day nobody spoke does not end a run
-- there was no crown to lose -- and neither does a day the bot was
offline for, which it could not have judged.

Every record excludes the backfilled day. It is a 22-hour window filed
as a day, and leaving it in would hand somebody a personal best they
never set.

Two bugs found by running the code rather than reading it:

- current_streaks reported every streak as zero. Ending somebody's run
  dropped them from the tally along with the length they had already
  accumulated, so the surviving dict was empty by the time it returned.
  Now the run ends and the count it reached is kept.
- daily_winners depended on SQLite's grouping order to find a day's
  leader. It happened to work because uuids sorted conveniently in the
  fixtures. Ordering by messages DESC makes the first row per day the
  leader by construction, which is both correct and obviously so.

No suppressions: the period queries compare an exclusion parameter
against '' instead of pasting half a WHERE clause into an f-string,
which is a SQL-injection shape even when every input is a constant.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 19:38:54 +02:00

185 lines
5.4 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""All-time records: busiest days, quietest days, personal bests, silences.
Everything here is derived by query rather than kept in a cache table. Two
sources of truth for one number is how a leaderboard comes to disagree with
itself, and the history is small enough that recomputing is free.
The backfilled day is excluded from every record. It is a 22-hour window
filed as a day, so leaving it in would hand somebody a personal best they
never set -- see ``stats.backfill``.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from signal_bot.stats.periods import shift
if TYPE_CHECKING:
from signal_bot.stats.events import EventStore
PERSON_DAYS = """
SELECT day, COUNT(*) AS messages
FROM message_events
WHERE group_id = ? AND uuid = ? AND day <> ?
GROUP BY day
ORDER BY messages DESC, day ASC
"""
MEDIA_DAYS = """
SELECT day, SUM(media_count) AS media
FROM message_events
WHERE group_id = ? AND day <> ?
GROUP BY day
HAVING media > 0
ORDER BY media DESC, day ASC
"""
DAILY_LEADERS = """
SELECT day, uuid, display_name, COUNT(*) AS messages
FROM message_events
WHERE group_id = ? AND day <> ?
GROUP BY day, uuid
ORDER BY day ASC
"""
@dataclass(frozen=True, slots=True)
class DayRecord:
"""One day and the number that makes it a record."""
day: str
value: int
def busiest_day(days: dict[str, int]) -> DayRecord | None:
"""The day with the most messages, earliest day winning a tie."""
if not days:
return None
day = min(days, key=lambda d: (-days[d], d))
return DayRecord(day, days[day])
def quietest_day(days: dict[str, int]) -> DayRecord | None:
"""The quietest day on which anybody spoke at all.
Days with no messages are absent from the series rather than zero, and
that is the right reading: a day nobody spoke is a silence, which
``longest_silence`` measures. A "quietest day" of zero would just name
whichever day the bot happened to be offline.
"""
if not days:
return None
day = min(days, key=lambda d: (days[d], d))
return DayRecord(day, days[day])
def personal_best(
events: EventStore,
group_id: str,
uuid: str,
*,
exclude: str | None = None,
) -> DayRecord | None:
"""Somebody's busiest day ever, or None if they have never written."""
row = events.connection.execute(PERSON_DAYS, (group_id, uuid, exclude or "")).fetchone()
return DayRecord(row["day"], row["messages"]) if row else None
def previous_best(
events: EventStore,
group_id: str,
uuid: str,
before: str,
*,
exclude: str | None = None,
) -> DayRecord | None:
"""Somebody's best day *excluding* one day, for "poprzedni rekord".
Announcing "rekord życiowy: 76" is worth little without what it beat, and
the day being announced must not be its own previous best.
"""
rows = events.connection.execute(PERSON_DAYS, (group_id, uuid, exclude or "")).fetchall()
for row in rows:
if row["day"] != before:
return DayRecord(row["day"], row["messages"])
return None
def most_media_day(
events: EventStore,
group_id: str,
*,
exclude: str | None = None,
) -> DayRecord | None:
"""The day carrying the most photos and videos."""
row = events.connection.execute(MEDIA_DAYS, (group_id, exclude or "")).fetchone()
return DayRecord(row["day"], row["media"]) if row else None
@dataclass(frozen=True, slots=True)
class Silence:
"""A stretch of days on which nobody wrote anything."""
start: str
end: str
days: int
def longest_silence(days: dict[str, int], until: str) -> Silence | None:
"""The longest run of consecutive silent days, up to and including ``until``.
Walks the calendar rather than the recorded days, because the whole point
is the days that are *missing* from the series. Returns None when the
history is too short to contain a gap.
"""
if not days:
return None
spoke = set(days)
first = min(spoke)
best: Silence | None = None
run_start: str | None = None
day = first
while day <= until:
if day in spoke:
if run_start is not None:
run = _silence(run_start, shift(day, -1))
best = run if best is None or run.days > best.days else best
run_start = None
elif run_start is None:
run_start = day
day = shift(day, 1)
if run_start is not None:
run = _silence(run_start, until)
best = run if best is None or run.days > best.days else best
return best
def _silence(start: str, end: str) -> Silence:
"""Build a Silence, counting both ends."""
length = 1
day = start
while day < end:
day = shift(day, 1)
length += 1
return Silence(start, end, length)
def silent_since(days: dict[str, int], uuid_days: dict[str, int], until: str) -> int:
"""How many days somebody has gone without writing, as of ``until``.
Counts back from ``until`` to their last message. Zero means they wrote
today; the group's own recorded days bound it, so a person who joined
yesterday is not reported as silent for a year.
"""
if not days:
return 0
if not uuid_days:
return sum(1 for day in days if day <= until)
last = max(uuid_days)
return sum(1 for day in days if last < day <= until)