signal-bot/signal_bot/stats/queries_period.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

174 lines
5.1 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Weeks, months, years, and the per-weekday picture.
Every query takes an inclusive span of stored Warsaw day strings, so a
daylight-saving change cannot move a boundary -- see ``stats.periods``.
Several of them take ``exclude``: the one day carried over from the pre-0.1.0
counter has real totals but no hours, no lengths, and a 22-hour window
pretending to be a day. It belongs in a total and nowhere near an average.
The exclusion is a bound parameter compared against ``''`` rather than a
clause pasted into the statement. No real day is the empty string, so one
static query serves both cases -- and the alternative, an f-string holding
half a WHERE clause, is a SQL-injection shape even when every input is a
module constant.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from signal_bot.stats.periods import weekday_of
from signal_bot.stats.queries_day import DayRow
if TYPE_CHECKING:
from signal_bot.stats.events import EventStore
from signal_bot.stats.periods import Period
PERIOD_ROWS = """
SELECT uuid,
display_name,
COUNT(*) AS messages,
SUM(media_count) AS media,
SUM(is_command) AS commands,
SUM(char_len) AS chars
FROM message_events
WHERE group_id = ? AND day BETWEEN ? AND ? AND day <> ?
GROUP BY uuid
ORDER BY messages DESC, display_name ASC
"""
DAILY_SERIES = """
SELECT day, COUNT(*) AS messages
FROM message_events
WHERE group_id = ? AND day BETWEEN ? AND ? AND day <> ?
GROUP BY day
ORDER BY day
"""
EVERY_DAY = """
SELECT day, COUNT(*) AS messages
FROM message_events
WHERE group_id = ? AND day <> ?
GROUP BY day
ORDER BY day
"""
def period_rows(
events: EventStore,
group_id: str,
period: Period,
*,
exclude: str | None = None,
) -> list[DayRow]:
"""Everyone who wrote during a period, most talkative first."""
rows = events.connection.execute(
PERIOD_ROWS, (group_id, period.start, period.end, exclude or "")
).fetchall()
return [
DayRow(
uuid=r["uuid"],
display_name=r["display_name"],
messages=r["messages"],
media=r["media"],
commands=r["commands"],
chars=r["chars"],
)
for r in rows
]
def daily_series(
events: EventStore,
group_id: str,
start: str,
end: str,
*,
exclude: str | None = None,
) -> dict[str, int]:
"""Messages per day across a span, missing days absent rather than zero.
The caller decides what a missing day means: for a streak it is silence,
for an average it is a day nobody was there to record.
"""
rows = events.connection.execute(DAILY_SERIES, (group_id, start, end, exclude or "")).fetchall()
return {r["day"]: r["messages"] for r in rows}
def every_day(
events: EventStore,
group_id: str,
*,
exclude: str | None = None,
) -> dict[str, int]:
"""Messages per day across the whole history."""
rows = events.connection.execute(EVERY_DAY, (group_id, exclude or "")).fetchall()
return {r["day"]: r["messages"] for r in rows}
def weekday_buckets(days: dict[str, int]) -> dict[int, list[int]]:
"""Bucket a day series by weekday, 0=Monday through 6=Sunday.
Returns the days themselves rather than a mean, so a caller can see how
many a figure rests on: "wtorki mają średnio 74" off a single Tuesday is a
number that should not be said out loud.
"""
buckets: dict[int, list[int]] = {}
for day, messages in days.items():
buckets.setdefault(weekday_of(day), []).append(messages)
return buckets
def total_for(
events: EventStore,
group_id: str,
start: str,
end: str,
*,
exclude: str | None = None,
) -> int:
"""How many messages a span holds."""
return sum(daily_series(events, group_id, start, end, exclude=exclude).values())
@dataclass(frozen=True, slots=True)
class Trend:
"""One period measured against the one before it."""
now: int
before: int
@property
def delta(self) -> int:
"""Absolute change, which may be negative."""
return self.now - self.before
@property
def percent(self) -> int | None:
"""Rounded percentage change, or None when there is no baseline.
None rather than 0: "nothing to compare against yet" is a different
statement from "no change", and the renderers say each differently.
"""
if not self.before:
return None
return round(self.delta / self.before * 100)
@property
def arrow(self) -> str:
"""An arrow, or "" when there is nothing to compare against."""
if self.percent is None or self.delta == 0:
return ""
return "↑" if self.delta > 0 else "↓"
def share_of_voice(rows: list[DayRow]) -> list[tuple[str, int]]:
"""Each person's percentage of the messages, largest first."""
total = sum(row.messages for row in rows)
if not total:
return []
return [(row.display_name, round(row.messages / total * 100)) for row in rows]