# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """Family E, the behavioural half: sittings, bursts and what goes together. These are the only questions that need a *trustworthy ordering in time*, so they are the only ones restricted to ``live`` rows plus the journald ones that carry a real hour. A ``daily_uses`` row is a count with a synthetic timestamp built from midnight; treating those as a sequence would invent a sitting in which somebody ran forty commands in forty milliseconds. A session is one person's run of commands with no gap longer than ``SESSION_GAP_MS``. It exists to make two things sayable: * **burstiness** -- how many commands a sitting contains. Three or four means somebody is re-rolling for a better photo, which is a fact about the pool rather than about them. * **co-occurrence** -- which commands turn up in the same sitting, which is what says whether two commands are alternatives or a habit. """ from __future__ import annotations from collections import Counter from dataclasses import dataclass from itertools import combinations from typing import TYPE_CHECKING, Final from signal_bot.analytics.scope import SESSION_GAP_MS if TYPE_CHECKING: import sqlite3 from signal_bot.analytics.scope import Scope # Only rows whose timestamp is a real moment. daily_uses rows are excluded # by local_hour, which is the one column that distinguishes them. ORDERED_SQL: Final = """ SELECT user_uuid, command, invoked_at_ms FROM command_events WHERE (:group IS NULL OR group_id = :group) AND local_hour >= 0 AND outcome != 'unknown_word' ORDER BY user_uuid, invoked_at_ms """ @dataclass(frozen=True, slots=True) class Sessions: """How the group actually uses the bot, sitting by sitting.""" count: int = 0 commands: int = 0 longest: int = 0 pairs: tuple[tuple[str, str, int], ...] = () repeats: tuple[tuple[str, int], ...] = () @property def average_length(self) -> float: """Commands per sitting. One means nobody re-rolls.""" return self.commands / self.count if self.count else 0.0 def _split(rows: list[tuple[str, str, int]]) -> list[list[str]]: """Cut one person's ordered commands into sittings on the idle gap.""" sittings: list[list[str]] = [] current: list[str] = [] last_uuid = "" last_at = 0 for uuid, command, at_ms in rows: broken = uuid != last_uuid or at_ms - last_at > SESSION_GAP_MS if broken and current: sittings.append(current) current = [] current.append(command) last_uuid = uuid last_at = at_ms if current: sittings.append(current) return sittings def collect(conn: sqlite3.Connection, scope: Scope) -> Sessions: """Split the history into sittings and describe what they contain.""" rows = [ (str(row["user_uuid"]), str(row["command"]), int(row["invoked_at_ms"])) for row in conn.execute(ORDERED_SQL, scope.params()) ] sittings = _split(rows) if not sittings: return Sessions() pairs: Counter[tuple[str, str]] = Counter() repeats: Counter[str] = Counter() for sitting in sittings: # Sorted and de-duplicated, so (cat, dog) and (dog, cat) are one # fact rather than two, and running !kot four times in a sitting # does not make it co-occur with itself. distinct = sorted(set(sitting)) for left, right in combinations(distinct, 2): pairs[(left, right)] += 1 for command, times in Counter(sitting).items(): if times > 1: repeats[command] += times - 1 return Sessions( count=len(sittings), commands=sum(len(sitting) for sitting in sittings), longest=max(len(sitting) for sitting in sittings), pairs=tuple( (left, right, count) for (left, right), count in sorted(pairs.items(), key=lambda p: (-p[1], p[0])) ), repeats=tuple(sorted(repeats.items(), key=lambda pair: (-pair[1], pair[0]))), )