signal-bot/tests/test_dispatcher_recording.py
Krzysztof kuhy Rudnicki 0717df646a
Some checks are pending
CI / check (push) Waiting to run
CI / web (push) Waiting to run
Rebuild the command table on demand, and survive a tag whose file is gone
The registry used to be built once, inline in build_bot, so every change to
the data behind it -- a person tagged in the web UI, an alias, soon a command
switched off from the management page -- meant restarting the unit. That is
cheap and lossless, but it is a deploy step somebody has to remember, and a
21:37 report can land in the middle of it.

Now the registration sequence lives in wiring.build_registry, and
RegistryHolder runs it again on POST /_reload: the new table is built whole
and swapped in with one assignment, never patched in place, so a duplicate
trigger is found before anything the dispatcher reads has changed. Bad data
(ConfigError, DuplicateTriggerError) keeps the previous table and answers
409 with the reason; a programming error still surfaces as a 500.
scripts/reload.sh wraps it, with --code for the restart a Python change
needs, and an optional command to type in testbot so "reloaded" means
"answered". No Python hot-reload on purpose.

The loader change is what makes deploying this safe: two rows in the live
tags.json name files that are no longer in media/, and load_pack refused
them, so the next restart would have looped on ConfigError. A stale tag is
drift in a file a page edits mid-session, not a broken album -- it is now
skipped with a warning naming it. A tag that reaches outside the album is
still refused. pack_load.py split at the 250-line cap; pack_tags.py is the
half whose checks are not all fatal.

Proven offline in scripts/e2e.sh: !delta is unknown, a fifth person is
tagged into the synthetic pack, scripts/reload.sh runs, and the same
process posts delta's photo.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-04 10:14:39 +02:00

135 lines
4.1 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Every attempt becomes a row, and a refusal still does not move the cooldown.
The second half is the one that matters. ``CommandRefusedError``'s docstring
records the bug: recording a refused run slid the cooldown window forward
every time somebody was told to wait, so waiting the stated time never
helped. The command history now takes refusals *and* crashes, which makes
merging the two writes look like an obvious simplification. It is not, and
test_a_refusal_does_not_move_the_cooldown is what says so.
"""
from __future__ import annotations
import datetime as dt
from typing import TYPE_CHECKING, Any
import pytest
from signal_bot.analytics import probe
from signal_bot.dispatcher import Dispatcher
from signal_bot.registry import CommandRegistry
from signal_bot.registry_holder import RegistryHolder
from tests.conftest import WATCHED_GROUP, envelope
if TYPE_CHECKING:
from signal_bot.config import Config
from signal_bot.context import CommandContext
from signal_bot.discovery import GroupDirectory
from signal_bot.store import Store
from signal_bot.transport_fake import FakeTransport
NOW = dt.datetime(2026, 8, 29, 12, 0, tzinfo=dt.UTC)
SENDER = "uuid-alice"
def history(store: Store) -> list[dict[str, Any]]:
"""Every recorded attempt, oldest first."""
return [
dict(row)
for row in store.commands.connection.execute(
"SELECT * FROM command_events ORDER BY invoked_at_ms"
)
]
def calls(store: Store) -> list[dict[str, Any]]:
"""Every recorded upstream call."""
return [
dict(row)
for row in store.commands.connection.execute("SELECT * FROM upstream_calls ORDER BY seq")
]
def build(
config: Config,
directory: GroupDirectory,
registry: CommandRegistry,
store: Store,
transport: FakeTransport,
) -> Dispatcher:
"""A dispatcher over one caller-supplied registry."""
return Dispatcher(
config=config,
directory=directory,
holder=RegistryHolder(lambda: registry),
store=store,
transport=transport,
clock=lambda: NOW,
)
@pytest.fixture
def ok_registry() -> CommandRegistry:
"""One command that succeeds and reports what it did on the way."""
async def handler(_ctx: CommandContext) -> None:
probe.note_upstream("api.example.test", 200, 40)
probe.note_send(120)
probe.note_item("Q42")
reg = CommandRegistry()
reg.register("cat", ["!cat"], handler, "kot")
return reg
async def test_a_success_is_recorded_with_what_it_cost(
config: Config,
directory: GroupDirectory,
ok_registry: CommandRegistry,
store: Store,
transport: FakeTransport,
) -> None:
"""The row nothing wrote before: outcome, item, and where the time went."""
dispatcher = build(config, directory, ok_registry, store, transport)
await dispatcher.handle(envelope(text="!cat"))
(row,) = history(store)
assert row["command"] == "cat"
assert row["outcome"] == "ok"
assert row["item_id"] == "Q42"
assert row["send_ms"] == 120
assert row["source"] == "live"
assert row["handler_ms"] >= 0
assert calls(store) == [
{
"group_id": WATCHED_GROUP,
"invoked_at_ms": row["invoked_at_ms"],
"command": "cat",
"host": "api.example.test",
"status": 200,
"duration_ms": 40,
"seq": 0,
}
]
async def test_the_history_and_the_message_share_a_key(
config: Config,
directory: GroupDirectory,
ok_registry: CommandRegistry,
store: Store,
transport: FakeTransport,
) -> None:
"""Both tables key on the envelope's own timestamp, or nothing joins."""
dispatcher = build(config, directory, ok_registry, store, transport)
await dispatcher.handle(envelope(text="!cat"))
(event,) = history(store)
row = store.events.connection.execute(
"SELECT sent_at_ms, local_hour, day FROM message_events WHERE is_command = 1"
).fetchone()
assert event["invoked_at_ms"] == row["sent_at_ms"]
assert event["local_hour"] == row["local_hour"]
assert event["day"] == row["day"]