diff --git a/charts/sturnus/templates/bot-deployment.yaml b/charts/sturnus/templates/bot-deployment.yaml index c78af433..5e73d8c7 100644 --- a/charts/sturnus/templates/bot-deployment.yaml +++ b/charts/sturnus/templates/bot-deployment.yaml @@ -8,17 +8,9 @@ spec: # Fixed at 1, not a values knob: two instances would hold two Discord # gateway connections and record every session twice (Spec 4.1). # - # `STURNUS_SHARD_COUNT` (bot.env in values.yaml) does not relax this and - # is not a step towards relaxing it by itself. Shards are gateway - # connections *within* one process: N shards here is still one pod, one - # voice connection per guild, one RWO recording PVC. Two pods would each - # open the same shards and record every session twice exactly as before. - # - # Running one shard range per pod is a different deployment shape, not a - # larger `replicas`: it needs a StatefulSet (stable ordinals, so a pod - # knows which shard range it owns), a volumeClaimTemplate instead of the - # single shared PVC below, and an announcement sweep that speaks only for - # the guilds its own shards carry. See docs/operations.md section 3.6. + # Running more than one pod is a different deployment shape, not a larger + # `replicas`: each pod would need its own recording volume and its own share of + # the guilds. See docs/operations.md section 3.6. replicas: 1 # Recreate, not RollingUpdate: a rolling update briefly runs the old and # the new pod together, which is exactly the double-recording situation diff --git a/charts/sturnus/values.yaml b/charts/sturnus/values.yaml index 0c4fba43..6319de79 100644 --- a/charts/sturnus/values.yaml +++ b/charts/sturnus/values.yaml @@ -238,15 +238,10 @@ bot: # Deployment template hardcodes both `replicas: 1` and `strategy.type: # Recreate` for this reason, so nothing can turn it into a rolling update. # - # `STURNUS_SHARD_COUNT` below does NOT change this, and it is worth being - # blunt about that because the word "sharding" invites the opposite - # conclusion. Shards are gateway connections *inside* one process: four - # shards is still one pod, one voice connection per guild, one recording - # PVC. Two pods would still record every session twice, shard count or - # not, because both would identify as the same bot on overlapping shard - # ranges. Splitting shard ranges across pods is a different change -- - # a StatefulSet, a PVC per pod, a shard range per ordinal -- and - # docs/operations.md section 3.6 lists what it needs. + # Two pods would still record every session twice: both would identify as + # the same bot and receive the same gateway events. Splitting the work across + # pods is a different change, and docs/operations.md section 3.6 says what it + # would take. command: ["sturnus-bot"] env: STURNUS_RECORDING_DIR: /data/recordings @@ -259,22 +254,6 @@ bot: # talks to Discord. Set "Public Bot" off and GUILD_INSTALL only in the # Developer Portal as well (docs/first-deployment.md). STURNUS_GUILD_ID: "" - # How many gateway connections this one process opens. **Empty means - # "let Discord decide"**, which is the right answer for almost every - # deployment: `AutoShardedClient` asks `/gateway/bot` and takes the - # recommendation, and that recommendation grows with the guild count - # on its own where a number pinned here would not. - # - # Discord *requires* sharding above 2500 guilds; below that it is - # headroom and resilience -- one shard's reconnect no longer stalls - # every other guild's events behind it. Set it only if you know why - # (matching a `max_concurrency` bucket, reproducing a routing - # problem), and note that `/readyz` then requires *every* shard to be - # up: four shards with one reconnecting is a NotReady pod, on purpose. - # - # Values below 1 are refused at startup rather than at the gateway, - # so a typo names itself in the pod's first log line. - STURNUS_SHARD_COUNT: "" # Recordings themselves go straight to the PVC above; this only needs to # cover Python/library scratch writes to /tmp under readOnlyRootFilesystem. tmpSizeLimit: 256Mi diff --git a/docs/operations.md b/docs/operations.md index 31b48163..1d63cbc8 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -60,7 +60,6 @@ the Kubernetes `Secret` rather than from plain manifest text (see section | `STURNUS_OUTLINE_BASE_URL` | **yes** | no | Base URL of the Outline instance. The bot needs it only to build the authorization URL `/link` sends a user's browser to; it never calls Outline's API itself. | | `STURNUS_OUTLINE_CLIENT_ID` | **yes** | no | OAuth client id of the Sturnus application registered in Outline. Public by design — it travels in the query string of the authorization URL every user's browser opens. | | `STURNUS_OUTLINE_REDIRECT_URI` | **yes** | no | The callback URL that authorization returns to. Must be the same value `sturnus-link` is given, and must actually route to `link` — see section 1.5. | -| `STURNUS_SHARD_COUNT` | unset | no | How many Discord gateway connections this one process opens. Unset or empty — the chart's default — means **let Discord decide**: `AutoShardedClient` asks `/gateway/bot` and uses the recommendation, which grows with the guild count on its own. An explicit value is for an operator who knows why; anything below `1` is refused at startup. It does **not** make the bot horizontally scalable — every shard lives in this one process and the Deployment stays at one replica. See section 3.6. | | `STURNUS_HEALTH_PORT` | `8080` | no | Port the `/healthz`, `/readyz`, `/metrics`, `/version` HTTP endpoints listen on. `/metrics` answers **`501 Not Implemented`**: metrics are *pushed* over OTLP, not scraped — see section 7. | | `STURNUS_SENTRY_DSN` | unset | no | Sentry DSN for error reporting. Empty disables it entirely: `sentry_sdk.init()` is never called, so no instrumentation is installed and the process runs exactly as it does without Sentry. Supplied through the `Secret`, and required to be present even when blank; see section 1.4 for why a value that is not a credential is stored like one. | | `STURNUS_SENTRY_ENVIRONMENT` | `production` | no | Names the deployment in Sentry's environment filter **and** supplies OpenTelemetry's `deployment.environment.name`. One variable for both on purpose — `OtelSettings.environment` reads this exact name rather than adding a second one, so the environment filter in Sentry and the one in Grafana can never disagree. | @@ -537,118 +536,38 @@ is one constant (`MAX_CONCURRENT_SESSIONS_PER_GUILD`) that the code asks rather than assumes — but raising that constant without supplying the second identity breaks the bot instead of improving it. -### 3.6 Shards, and the four things they do not change +### 3.6 One gateway connection -A Discord bot's guilds are split across **shards**. A shard is one gateway -connection, and Discord routes a guild to shard `(guild_id >> 22) % -shard_count`. Sturnus's bot process holds all of them -(`discord.AutoShardedClient`), and `STURNUS_SHARD_COUNT` is the only knob. +The bot process holds a single Discord gateway connection. Discord asks for +sharding (several connections, each carrying a share of the guilds) only +above 2,500 guilds +(). An installation +serves one guild, so Sturnus does not shard, and there is no variable to set. +If `STURNUS_SHARD_COUNT` is still present in a deployment from before this +change, it is ignored and the bot logs `config.shard_count_ignored` once at +startup; unset it. -**Leave it unset.** Unset means the bot asks Discord `/gateway/bot` and -opens the number Discord recommends — which tracks the guild count by -itself, where a number pinned in a values file does not. Discord *requires* -sharding above 2500 guilds; below that, shards buy headroom and one -concrete piece of resilience: a shard that has to reconnect stalls only its -own guilds' events, instead of every guild's queueing behind one socket. - -Set it explicitly only with a reason — matching a `max_concurrency` bucket -during a large-bot rollout, or reproducing a routing problem on a known -shard layout. Values below `1` are refused when the process starts, naming -the variable, rather than producing a bot that opens no connection and sits -there looking alive. - -**What sharding changes about `/readyz`.** Readiness is now "every shard -this process holds is up", rather than one boolean set at startup and never -cleared. With four shards and one reconnecting, `/readyz` answers `503` -with a body naming the missing shard: +**What `/readyz` reports.** `discord_connected` is `true` while the gateway +connection is up and `database_reachable` while the database answers. A +dropped connection clears the first flag at once, and the connection +resuming sets it again: ```json -{"status": "not ready", "discord_connected": false, "database_reachable": true, - "shards_connected": 3, "shards_expected": 4, "shards_missing": [2]} -``` - -That is deliberate. Three shards up means a quarter of the servers Sturnus -is in cannot be recorded in at all, and a probe reporting perfect health -through that is worse than one that occasionally flaps. It does **not** -flap on a routine reconnect: the probe polls every 10 s with -`failureThreshold: 3`, so a shard has to be absent for 30 continuous -seconds before Kubernetes marks the pod NotReady, and an ordinary RESUME -takes a second or two. The bot's Service carries no traffic, so a NotReady -pod here is a signal to go and look, not a load-shedding action. - -**What sharding changes about the logs.** `bot.shard_ready`, -`bot.shard_resumed` and `bot.shard_disconnected` carry `shard_id` and -`shard_count`. Per-guild lines — the guild tick, the voice lifecycle, the -capture failures — carry `shard_id` **only when this process holds more -than one shard**: with one shard it would be `0` in every line for ever, -which is a key in every Loki stream that answers nothing. So, once a shard -count above one is in use: - -```logql -# Which guilds went with the shard that just dropped -{app="sturnus-bot"} | json | shard_id="2" +{"status": "not ready", "discord_connected": false, "database_reachable": true} ``` -**What sharding does not change.** All four are worth stating plainly, -because the word invites the opposite conclusion: - -1. **The Deployment stays at `replicas: 1`, with `strategy: Recreate`.** - Four shards is still one process. Two pods would each open the same - shards, hold two gateway connections to the same guilds, and record - every session twice — exactly the situation `replicas: 1` exists to - prevent, shard count or not. -2. **One voice connection per guild.** That is a platform limit and section - 3.5 is unaffected: a guild with three allowed channels still records one - of them at a time. -3. **One recording PVC.** In-progress recordings live on the pod's own - `ReadWriteOnce` volume, and the SIGTERM handler that flushes them is - still one handler in one process. -4. **One announcement sweep.** The poll that posts a finished session's - document link reads `sessions` rows for every guild there is. With one - process that is exactly right; it is the one sweep in the bot that would - stop being right otherwise. - -#### What running one shard range per pod would actually take - -Written down so that it stays a decision rather than becoming an -archaeology exercise. Sturnus has **not** built this. In rough dependency -order: - -1. **A StatefulSet, not a Deployment.** Each pod needs a stable ordinal to - derive its shard range from; a Deployment's pods are interchangeable and - have no such identity. `sturnus.application.sharding.shards_this_process_owns` - is the one function that would read it — it returns every shard today, - and would return `range(ordinal * per_pod, (ordinal + 1) * per_pod)`. -2. **`shard_ids` passed to `AutoShardedClient`** alongside `shard_count`. - discord.py requires both when shard ids are given by hand, and refuses - ids without a count outright. -3. **A `volumeClaimTemplate` instead of the single shared PVC.** The - recording volume is `ReadWriteOnce` and holds in-progress audio; two - pods cannot share it, and a pod that restarts must come back to *its - own* unflushed recordings for `recover_orphans` to find them. -4. **The announcement sweep scoped to the pod's shards.** Already asked: - `announce_ready_sessions` calls `process_serves_guild` for every - candidate session, so this half is a change to - `shards_this_process_owns` and nothing else. Without it, four pods post - the same document link four times. -5. **A PodDisruptionBudget that means something at N replicas.** - `minAvailable: 1` at one replica blocks every voluntary eviction, which - is the point today; at four it would permit three quarters of the bot to - be drained at once, mid-recording. -6. **Session-start rate limiting across pods.** Discord's `max_concurrency` - bounds how many shards may IDENTIFY per five seconds. One process - serialises its own launches; N pods starting together do not, so a - rollout would need `AutoShardedClient.fetch_session_start_limits` and a - `before_identity_hook` coordinating between them. -7. **The console's mirrors read as though they were complete.** The - administrator and directory mirrors are written per guild off each - process's own gateway cache, so they stay correct — but a pod that is - down leaves its guilds' rows stale with nothing saying so, and the API - currently has no way to express that. - -Items 1, 3, 5 and 6 are deployment work with no code in this repository to -change. Item 4 is one function body. Items 2 and 7 are small. The ordering -is the useful part: none of it is hard, and none of it happens by raising +It does **not** make the pod flap on a routine reconnect. The probe polls +every 10 s with `failureThreshold: 3`, so the connection has to be down for +30 continuous seconds before Kubernetes marks the pod NotReady, and an +ordinary RESUME takes a second or two. The bot's Service carries no traffic, +so a NotReady pod is a signal to go and look, not a load-shedding action. + +**Why the Deployment stays at one pod.** `replicas: 1` with +`strategy: Recreate` is unchanged. Two pods would each hold a gateway +connection to the same guilds and record every session twice. Each pod also +has its own `ReadWriteOnce` recording volume, and the SIGTERM handler that +flushes an in-progress recording runs in one process. Running more than one +pod would be a different deployment shape, with its own design, not a larger `replicas`. ## 4. First run diff --git a/src/sturnus/application/publishing.py b/src/sturnus/application/publishing.py index 52a1a427..4564e720 100644 --- a/src/sturnus/application/publishing.py +++ b/src/sturnus/application/publishing.py @@ -33,7 +33,6 @@ from jinja2.sandbox import SandboxedEnvironment -from sturnus.application.sharding import process_serves_guild from sturnus.observability.events import Event, log_event, log_exception log = logging.getLogger(__name__) @@ -178,13 +177,6 @@ async def candidates_for_announcement(self) -> list[dict[str, object]]: mention them. An implementation that omits the key still works: `announce_ready_sessions` falls back to no mentions rather than failing to post the link. - - Each row also carries `guild_id`, which is not used to render - anything: it is what lets `announce_ready_sessions` ask whether - this process serves that guild at all. This is the one sweep in - the bot whose input is the database rather than a gateway cache, - so it is the one that has to ask -- see - `sturnus.application.sharding`. """ ... @@ -202,8 +194,6 @@ async def announce_ready_sessions( announcer: Announcer, now: datetime, template_source: str = DEFAULT_ANNOUNCEMENT_TEMPLATE, - *, - shard_count: int | None = None, ) -> None: """Posts each documented session's link once and stamps `announced_at`. @@ -222,22 +212,10 @@ async def announce_ready_sessions( at all whenever the post itself is what fails, which is the more common failure mode (a flaky Discord API call) and the one this function exists to survive. - - **The one sweep in the bot that asks whether it serves a guild.** - Everything else the bot sweeps periodically is driven off its own - gateway cache and is therefore scoped to this process's shards for - free; this reads `sessions` rows for every guild there is. Today - `process_serves_guild` answers `True` for all of them -- one process - holds every shard -- and the call is there so that the day it does - not, four pods do not each post the same document link four times. - `shard_count` is `None` for a caller with no gateway (every test of - this function), which changes nothing today and is the honest value. """ for session in sessions_to_announce(await sessions.candidates_for_announcement()): session_id = cast(int, session["id"]) channel_id = cast(int, session["channel_id"]) - if not process_serves_guild(cast(int, session["guild_id"]), shard_count): - continue document_url = cast(str, session["document_url"]) # `.get`, not `[...]`: a reader that does not supply participants # loses the mentions, not the announcement itself. diff --git a/src/sturnus/application/sharding.py b/src/sturnus/application/sharding.py deleted file mode 100644 index 4e73d5e9..00000000 --- a/src/sturnus/application/sharding.py +++ /dev/null @@ -1,166 +0,0 @@ -"""How many gateway connections this process holds, and which guilds are its business. - -Discord splits a bot's guilds across *shards*: a shard is one gateway -connection, and a guild belongs to shard `(guild_id >> 22) % shard_count`. -Discord requires sharding above 2500 guilds; below that it is headroom and -resilience, because one shard's reconnect no longer stalls every other -guild's events behind it. - -**There are two different changes hiding under the word "sharding", and -this module exists to keep them apart.** - -*Stage one -- several shards in one process.* `discord.AutoShardedClient` -opens N gateway connections from a single process and routes each guild's -events down the connection that owns it. **It changes no deployment -invariant**, because there is still exactly one process: one voice -connection per guild, one PVC of in-progress recordings, one announcement -poll. That is what Sturnus does today, and `STURNUS_SHARD_COUNT` is its -only knob. - -*Stage two -- several processes, each owning a shard range.* That one does -break an invariant this repository states out loud. -`charts/sturnus/templates/bot-deployment.yaml` pins `replicas: 1` with -`strategy: Recreate` precisely because two bot processes would hold two -gateway connections to the same guilds and record every session twice. -Stage two makes that safe only by giving each process a *disjoint* shard -range -- plus a StatefulSet for stable ordinals, a per-pod PVC, and an -announcement poll that no longer speaks for guilds it cannot see. -**Sturnus has not built stage two.** `docs/operations.md` section 3.6 -lists what it would take. - -**The predicate below is the seam.** `process_serves_guild` is `True` for -every guild today because `shards_this_process_owns` returns every shard -there is. Stage two narrows that one function to this pod's range, and the -sweeps that ask the predicate start declining guilds that belong to another -pod -- rather than each pod posting the same document link. - -Which sweeps ask, and which do not, is itself a decision worth writing -down: - -- **The announcement poll asks** (`publishing.announce_ready_sessions`). - It reads `sessions` rows for *every* guild out of the database, which is - the only sweep in the bot whose input is not already scoped by what this - process's gateway cache holds. Under stage two, without the predicate, - four pods would each post the same link four times. -- **The guild tick, the administrator mirror and the directory mirror do - not need to ask.** They iterate `SturnusClient.guilds` -- the gateway - cache -- which under stage two already contains exactly this process's - shards' guilds and nothing else. Adding a guard there would be a check - that can never fail, which is worse than no check: it reads as though - something were being enforced. -- **Orphan recovery and the retention sweep do not need to ask either.** - Both work off this pod's own recording directory, and stage two gives - each pod its own. - -Standard library only, like every module under `sturnus.application` that -`sturnus.domain` neighbours: `tests/test_architecture.py` forbids reaching -into `sturnus.infrastructure` from here, and nothing in this file wants to. -""" - -from __future__ import annotations - -from typing import Final - -#: Discord's own routing rule shifts a snowflake right by this many bits -#: before taking the shard modulus: the low 22 bits are a snowflake's -#: worker, process and sequence counters, which carry no guild identity. -_SNOWFLAKE_SHARD_SHIFT: Final = 22 - -#: The smallest shard count that describes a running bot. Zero shards is -#: not a smaller deployment, it is a process that never connects, and -#: `sturnus.config.Settings` refuses it at startup rather than letting the -#: gateway reject it later. -MIN_SHARD_COUNT: Final = 1 - -#: Whether one bot process holds every shard Sturnus's identity has. -#: -#: `True`, and it is the assumption behind `replicas: 1`. It is written -#: here as a name rather than left implicit in a dozen sweeps for the same -#: reason `channel_choice.MAX_CONCURRENT_SESSIONS_PER_GUILD` is: the value -#: of making an assumption single-sited is that lifting it becomes a list -#: somebody can read. -#: -#: Note what it is *not*: it is not "there is only one shard". Sturnus may -#: run four shards today, and this stays `True` -- all four are in this -#: process. It is `False` only once shard ranges are split across pods. -PROCESS_HOLDS_EVERY_SHARD: Final[bool] = True - - -def shard_of(guild_id: int, shard_count: int | None) -> int: - """The shard id Discord routes this guild's events to. - - `(guild_id >> 22) % shard_count`, which is Discord's published rule and - the same arithmetic `discord.Guild.shard_id` performs. Reimplemented - here rather than read off a `Guild` object because the callers that - need it most -- a tick for a guild that has just left the cache, a log - line that has only an id -- have no `Guild` to ask. - - `None` means the gateway has not told this process its shard count yet - (`discord.Client.shard_count` before `launch_shards` has run). Every - guild is on shard 0 in that window, which is what `Guild.shard_id` - answers too. - """ - if shard_count is None or shard_count <= MIN_SHARD_COUNT: - return 0 - return (guild_id >> _SNOWFLAKE_SHARD_SHIFT) % shard_count - - -def shards_this_process_owns(shard_count: int | None) -> frozenset[int]: - """Every shard id this process holds a gateway connection for. - - **This is the one function stage two changes.** Today it returns all of - them, because `PROCESS_HOLDS_EVERY_SHARD`. Under stage two it would - return this pod's slice -- derived from a StatefulSet ordinal and the - cluster-wide shard count -- and `process_serves_guild` would start - answering `False` for guilds another pod owns without a single call - site changing. - """ - if not PROCESS_HOLDS_EVERY_SHARD: # pragma: no cover - stage two - raise NotImplementedError( - "Splitting shards across processes needs a shard range per pod; " - "see docs/operations.md section 3.6." - ) - if shard_count is None: - return frozenset({0}) - return frozenset(range(shard_count)) - - -def process_serves_guild(guild_id: int, shard_count: int | None) -> bool: - """Whether this process is the one responsible for `guild_id`. - - Asked by every sweep whose input is the *database* rather than this - process's gateway cache -- see the module docstring for which those - are and why the others deliberately do not ask. - - Always `True` today. That is not a reason to skip the call: the call - is what makes the assumption a thing the code states rather than a - thing it happens to get away with. - """ - return shard_of(guild_id, shard_count) in shards_this_process_owns(shard_count) - - -def shard_id_for_logging(guild_id: int, shard_count: int | None) -> int | None: - """This guild's shard id, or `None` while this process holds only one shard. - - Deliberately conditional. `shard_id` is a pure function of `guild_id` - and the shard count, so on a single-shard process it is `0` on every - line for ever: a key in every Loki stream that answers no question - anybody could ask, and cardinality spent on a constant. - - Once there is more than one shard it stops being a constant and starts - being the grouping an operator actually wants -- "shard 3 just - dropped, which guilds went with it" -- which LogQL cannot compute from - `guild_id`, because it has no `>>` and no `%`. So the field earns its - place exactly when there is more than one shard, and not before. - - `None` rather than an absent key because rule R3 in - `tests/test_logging_discipline.py` forbids `**kwargs` into a log event - -- every emitted field name must stay statically readable at its call - site -- and `sturnus.observability.redaction.scrub_fields` drops a - `None` value rather than writing `null`. Between them, a call site - names the field in source and the line carries it only when it says - something. - """ - if shard_count is None or shard_count <= MIN_SHARD_COUNT: - return None - return shard_of(guild_id, shard_count) diff --git a/src/sturnus/config.py b/src/sturnus/config.py index 35f14c8d..ca69186d 100644 --- a/src/sturnus/config.py +++ b/src/sturnus/config.py @@ -7,14 +7,14 @@ from __future__ import annotations +from collections.abc import Mapping from functools import lru_cache from pathlib import Path +from typing import Final from pydantic import Field, SecretStr, field_validator, model_validator from pydantic_settings import BaseSettings, SettingsConfigDict -from sturnus.application.sharding import MIN_SHARD_COUNT - class StrictSettings(BaseSettings): """Settings that refuse to start on a blank required value. @@ -195,18 +195,6 @@ class Settings(StrictSettings): #: never talks to Discord and does not need it. guild_id: int health_port: int = 8080 - # How many gateway connections this one process opens. **Unset means - # "let Discord decide"** -- `discord.AutoShardedClient` asks - # `/gateway/bot` and uses the recommendation, which grows with the - # guild count on its own. A number pinned in a values file does not, - # so an explicit value is for an operator who knows why they want one - # (matching a `max_concurrency` bucket, reproducing a routing problem) - # and is prepared to revisit it. - # - # It does **not** make the bot horizontally scalable: every shard here - # lives in this one process, and `replicas: 1` is unchanged. See - # `sturnus.application.sharding` for the two stages this distinguishes. - shard_count: int | None = None # Off by default, and meant to be turned on for one recording at a # time. Measures what Discord actually sends and what the Opus decoder # makes of it, which is the one thing a finished WAV cannot show -- @@ -214,38 +202,16 @@ class Settings(StrictSettings): # audio: packet sizes, packet shapes and three aggregate numbers. capture_diagnostics: bool = False - @field_validator("shard_count", mode="before") - @classmethod - def _blank_shard_count_is_absent(cls, value: object) -> object: - """A blank `STURNUS_SHARD_COUNT` means "let Discord decide", not a failure. - - The same load-bearing normalisation `OtelSettings` performs on its - endpoint, and for the same reason: the chart renders every optional - value, so a cluster that has not opted in supplies `""` rather than - omitting the variable. Pydantic would reject that as an unparseable - `int` and the pod would crash-loop on a setting nobody had touched. - """ - if isinstance(value, str) and not value.strip(): - return None - return value - @field_validator("shard_count", mode="after") - @classmethod - def _at_least_one_shard(cls, value: int | None) -> int | None: - """Refuses a shard count below one while an operator is still looking. - - Left to the gateway, zero would build an empty shard range: no - connection, `on_ready` never fires, and the process sits there - looking alive behind a readiness probe that never turns green and - no line saying why. Naming the variable at startup is the whole - point of `StrictSettings`. - """ - if value is not None and value < MIN_SHARD_COUNT: - raise ValueError( - f"STURNUS_SHARD_COUNT must be at least {MIN_SHARD_COUNT}. " - f"Leave it unset to let Discord choose the shard count." - ) - return value +#: The one variable a deployment may still set from before its gateway +#: connections were removed. Pydantic reads only declared fields, so setting +#: it changes nothing and does not stop startup; the entrypoint logs it. +SHARD_COUNT_VARIABLE: Final = "STURNUS_SHARD_COUNT" + + +def shard_count_is_configured(environ: Mapping[str, str]) -> bool: + """Whether a leftover `STURNUS_SHARD_COUNT` is present, blank or not.""" + return SHARD_COUNT_VARIABLE in environ @lru_cache(maxsize=1) diff --git a/src/sturnus/entrypoints/bot.py b/src/sturnus/entrypoints/bot.py index e1d88221..48cb1d83 100644 --- a/src/sturnus/entrypoints/bot.py +++ b/src/sturnus/entrypoints/bot.py @@ -14,6 +14,7 @@ import base64 import contextlib import logging +import os import signal from datetime import UTC, datetime @@ -25,7 +26,7 @@ from sturnus.application.ports import Clock from sturnus.application.publishing import SessionReader, announce_ready_sessions from sturnus.application.recovery import recover_orphans -from sturnus.config import get_settings +from sturnus.config import get_settings, shard_count_is_configured from sturnus.domain import settings as domain_settings from sturnus.infrastructure.db.admin_members import AdminMemberStore from sturnus.infrastructure.db.config_store import ConfigStore @@ -108,19 +109,10 @@ async def _publish_loop( """ await client.wait_until_ready() announcer = DiscordAnnouncer(client) - # Read once, outside the loop and outside the `try` below: the count is - # fixed for the life of the connection, and reading it inside a block - # that swallows every exception would turn "this attribute moved" into - # a sweep that quietly announces nothing. Taken from the client rather - # than from `Settings` because the setting may be unset, in which case - # Discord chose the number and only the client knows it -- - # `wait_until_ready()` above has returned, so `launch_shards` has - # already filled it in. - shard_count = client.shard_count while not stop.is_set(): now = datetime.now(UTC) try: - await announce_ready_sessions(sessions, announcer, now, shard_count=shard_count) + await announce_ready_sessions(sessions, announcer, now) except Exception as exc: log_exception( log, @@ -186,6 +178,14 @@ async def _wait_for_schema( async def _run() -> None: settings = get_settings() + if shard_count_is_configured(os.environ): + log_event( + log, + logging.WARNING, + Event.CONFIG_SHARD_COUNT_IGNORED, + "STURNUS_SHARD_COUNT is no longer read and has no effect; the bot holds " + "one gateway connection. Unset it.", + ) engine = create_async_engine(settings.database_url) session_factory = async_sessionmaker(engine, expire_on_commit=False) @@ -310,7 +310,6 @@ async def database_ping() -> bool: link_states=link_states, account_links=account_links, capture_diagnostics=settings.capture_diagnostics, - shard_count=settings.shard_count, ) stop = asyncio.Event() diff --git a/src/sturnus/entrypoints/worker.py b/src/sturnus/entrypoints/worker.py index 2b4b6cbd..3853e74f 100644 --- a/src/sturnus/entrypoints/worker.py +++ b/src/sturnus/entrypoints/worker.py @@ -662,10 +662,7 @@ async def _run() -> None: config_store = ConfigStore(session_factory) template_source = _load_template() - # This process holds no gateway connection, so it holds all zero of the - # shards it is supposed to hold -- which is what makes the gateway half - # of readiness satisfied here without a second flag meaning "ignore it". - readiness = ReadinessState(expected_shards=0) + readiness = ReadinessState(discord_connected=True) # this process has no gateway to wait on async def database_ping() -> bool: """Proves the database answers *and* samples the queue depth. diff --git a/src/sturnus/infrastructure/db/repositories.py b/src/sturnus/infrastructure/db/repositories.py index 3bc6d245..bc57efb5 100644 --- a/src/sturnus/infrastructure/db/repositories.py +++ b/src/sturnus/infrastructure/db/repositories.py @@ -376,12 +376,6 @@ async def candidates_for_announcement(self) -> list[dict[str, object]]: await session.execute( select( Session.id, - # Selected so `announce_ready_sessions` can ask - # whether this process serves the guild at all -- - # see `sturnus.application.sharding`. Always true - # today; the column is what makes it possible to - # stop being true without rewriting the sweep. - Session.guild_id, Session.channel_id, Session.status, Session.document_url, @@ -408,7 +402,6 @@ async def candidates_for_announcement(self) -> list[dict[str, object]]: return [ { "id": row.id, - "guild_id": row.guild_id, "channel_id": row.channel_id, "status": row.status, "document_url": row.document_url, diff --git a/src/sturnus/infrastructure/discord/client.py b/src/sturnus/infrastructure/discord/client.py index fad9c513..2c075b9e 100644 --- a/src/sturnus/infrastructure/discord/client.py +++ b/src/sturnus/infrastructure/discord/client.py @@ -72,7 +72,6 @@ plan_reconfigure, ) from sturnus.application.recording import JobQueue, RecordingService -from sturnus.application.sharding import shard_id_for_logging from sturnus.domain import settings from sturnus.domain.guild_scope import serves_guild from sturnus.domain.session import EndReason, SessionTimeouts @@ -310,40 +309,8 @@ def role_id(self) -> int: return self.config.role_id -class SturnusClient(commands.AutoShardedBot): - """The bot process's Discord connection, or connections. - - `commands.AutoShardedBot` rather than `commands.Bot`: one process, N - gateway connections, each carrying the guilds Discord routes to it. - **That changes no deployment invariant** -- there is still exactly one - bot process, one voice connection per guild, one recording directory -- - and `sturnus.application.sharding` is where the difference between - "several shards in one process" and "several processes" is written - down. Read it before concluding that this class can now be scaled to - three replicas; it cannot. - - Sharding does change three things about the gateway lifecycle, and each - is handled explicitly below rather than inherited by accident: - - 1. **`on_ready` stops being the recovery hook.** With a plain client it - fires again on every re-IDENTIFY, which is what made "reconcile - every guild in `on_ready`" a working repair for a gateway blip. - Under `AutoShardedClient` it fires only when the *whole set* of - shards becomes ready: `AutoShardedConnectionState._delay_ready` - clears `_ready_tasks` once it has fired, and `parse_ready` only - re-schedules it when every shard has a pending ready task again. - One shard re-IDENTIFYing therefore never re-fires it. The - reconcile lives in `on_shard_ready` now, where it fires per shard - and for exactly that shard's guilds. - 2. **Readiness stops being one boolean.** See `on_shard_ready`, - `on_shard_resumed`, `on_shard_disconnect` and - `infrastructure.health.ReadinessState`. - 3. **The tick loop must be started once, not once per connection.** - `setup_hook` still runs exactly once (discord.py calls it from - `login`, before any shard is launched), but the loop's creation is - behind `_ensure_tick_loop` so that being wrong about that would - cost nothing. - """ +class SturnusClient(commands.Bot): + """The bot process's single Discord connection.""" def __init__( self, @@ -382,11 +349,6 @@ def __init__( #: from settings inside the cogs, because this class is the #: composition root for everything the gateway serves. transcription_host: str = "", - #: How many gateway connections this one process opens. `None` - #: means "let Discord decide" -- `AutoShardedClient` asks - #: `/gateway/bot` and takes the recommendation, which tracks the - #: guild count on its own. See `sturnus.config.Settings`. - shard_count: int | None = None, ) -> None: intents = discord.Intents.default() # `members` is a privileged intent and must also be turned on for @@ -401,14 +363,7 @@ def __init__( # have to delete this line deliberately rather than lose voice # events by omission. There is no portal switch for this one. intents.voice_states = True - # `shard_count=None` is discord.py's own "ask the gateway", not a - # missing value: `launch_shards` fills it in from `/gateway/bot` - # before the first connection opens. - super().__init__( - command_prefix=commands.when_mentioned, - intents=intents, - shard_count=shard_count, - ) + super().__init__(command_prefix=commands.when_mentioned, intents=intents) self._clock = clock self._guild_id = guild_id @@ -516,27 +471,6 @@ def __init__( #: client) after `graceful_shutdown` has already left the channel. self._shutting_down = False - # -- Attributing a guild's line to the connection it arrived on --------- - - def _shard(self, guild_id: int) -> int | None: - """This guild's shard id, or `None` while this process holds only one shard. - - A one-line wrapper so no call site has to remember either half of - the decision -- which shard a guild is on, and whether saying so - is worth a key in every Loki stream. Both live in - `sturnus.application.sharding.shard_id_for_logging`; the reasoning - for the conditional is on that function and on the `shard_id` - entry in `sturnus.observability.fields`. - - `None` rather than an omitted keyword because rule R3 in - `tests/test_logging_discipline.py` forbids `**kwargs` into a log - event -- every field name must stay readable at its call site -- - and `redaction.scrub_fields` drops a `None` value rather than - writing `null`. So the field name is visible in the source and - still absent from the line. - """ - return shard_id_for_logging(guild_id, self.shard_count) - # -- The one-connection limit, in one place ----------------------------- def _recordings_of(self, guild_id: int) -> tuple[_ChannelRecording, ...]: @@ -662,7 +596,7 @@ async def setup_hook(self) -> None: # LICENSE file in the repository does not reach them — /about does. await self.add_cog(AboutCog(self._transcription_host)) await self._sync_commands() - self._ensure_tick_loop() + self._tick_task = asyncio.create_task(self._tick_loop()) async def _sync_commands(self) -> None: """Registers the commands for the served guild alone, and clears the old globals. @@ -714,130 +648,56 @@ def _refuses(self, guild_id: int) -> bool: ) return True - def _ensure_tick_loop(self) -> None: - """Starts the tick loop, once, however often this is called. - - `setup_hook` runs exactly once -- discord.py calls it from - `login()`, before `connect()` launches any shard -- so under - sharding this is still one loop for N connections and not one per - connection. The guard is here anyway because the cost of being - wrong about that is a second loop closing sessions on a `_recordings` - dict the first one is also iterating, and the cost of the guard is - one comparison at startup. - """ - if self._tick_task is not None and not self._tick_task.done(): - return - self._tick_task = asyncio.create_task(self._tick_loop()) - - async def on_shard_ready(self, shard_id: int) -> None: - """Reconciles the guilds this shard just handed over. Fires once per shard. - - **This, not `on_ready`, is the gateway-blip repair.** With a plain - client `on_ready` fired again on every re-IDENTIFY, which is what - made reconciling everything there a working recovery. Under - `AutoShardedClient` it does not: `AutoShardedConnectionState. - _delay_ready` empties `_ready_tasks` after firing, and `parse_ready` - only re-schedules the whole-bot ready when *every* shard has a - pending ready task again -- so one shard coming back on its own - never re-fires it. Left in `on_ready`, the reconcile would have - silently stopped happening for exactly the guilds that had just - lost and rebuilt their caches. - - Scoped to this shard's guilds, not all of them. `self.guilds` is - one cache across every connection, so the other shards' guilds are - sitting right there and reconciling them too would multiply the - startup database reads by the shard count for no gain -- their own - `shard_ready` is what covers them, exactly once each. - - Idempotent, like every other caller of `reconcile_guild`: a guild - whose configuration is unchanged is a no-op, which is what makes - re-running this on every re-IDENTIFY safe rather than destructive. + async def on_ready(self) -> None: + """Reconciles every guild. Re-entrant, because Discord re-fires this. + + discord.py raises `on_ready` again whenever a RESUME fails and the + client has to re-IDENTIFY -- a routine gateway blip. The old + one-shot `_configure_guild` unconditionally overwrote the guild's + entry in `self._recordings`, so that blip dropped a recording guild's + `RecordingService` (unflushed writers, an orphaned plaintext WAV) + and its `VoiceReceiveAdapter` (a live voice connection nothing + would ever disconnect). `reconcile_guild` is idempotent, so this + path is now a no-op for a guild whose configuration is unchanged. """ - reconciled = 0 for guild in self.guilds: - if guild.shard_id != shard_id: - continue await self.reconcile_guild(guild.id) - reconciled += 1 - # After the reconcile, not before. `on_shard_connect` fires the - # moment the READY payload lands -- before the guild caches are - # filled -- and marking readiness there would turn the probe green - # on a shard that cannot yet answer for a single guild. - self._readiness.shard_connected(shard_id, shard_count=self.shard_count) + self._readiness.discord_connected = True log_event( log, logging.INFO, - Event.BOT_SHARD_READY, - "A gateway shard is ready; reconciled the guilds it carries", - shard_id=shard_id, - shard_count=self.shard_count, - count=reconciled, + Event.BOT_CONNECTED, + "Connected to Discord", + count=len(self._recordings), ) - async def on_shard_resumed(self, shard_id: int) -> None: - """Marks a shard back up after a blip it resumed through. + async def on_disconnect(self) -> None: + """Clears the gateway flag, so `/readyz` stops reporting the bot as connected. - No reconcile: a RESUME replays the events missed and keeps the - guild cache, so there is nothing to rebuild. That is the whole - difference between this and `on_shard_ready`, and reconciling here - anyway would put a database read per guild behind every routine - gateway hiccup. + discord.py dispatches this for every RESUME too, so most of these are + followed by `on_resumed` within seconds. The probe's three-failure + threshold is what keeps that blip invisible to Kubernetes. """ - self._readiness.shard_connected(shard_id, shard_count=self.shard_count) - log_event( - log, - logging.INFO, - Event.BOT_SHARD_RESUMED, - "A gateway shard resumed after a disconnect", - shard_id=shard_id, - shard_count=self.shard_count, - ) - - async def on_shard_disconnect(self, shard_id: int) -> None: - """Marks a shard down, so `/readyz` stops speaking for its guilds. - - WARNING rather than ERROR: discord.py dispatches this for every - RESUME too, so most of these are followed by `bot.shard_resumed` - within seconds and nothing was ever wrong. What makes a genuine - outage visible is not the level of this line but the readiness - probe it feeds -- 10-second period, `failureThreshold: 3`, so a - shard has to stay down for half a minute before Kubernetes marks - the pod NotReady. A blip is invisible; a shard that is actually - gone is not. - """ - self._readiness.shard_disconnected(shard_id) + self._readiness.discord_connected = False log_event( log, logging.WARNING, - Event.BOT_SHARD_DISCONNECTED, - "A gateway shard disconnected; the guilds it carries are unreachable " - "until it comes back", - shard_id=shard_id, - shard_count=self.shard_count, + Event.BOT_DISCONNECTED, + "The gateway connection dropped; the bot is unreachable until it resumes", ) - async def on_ready(self) -> None: - """Says the whole set of shards is up. Deliberately does no work. - - The reconcile that used to live here moved to `on_shard_ready` -- - read that method for why, because the move is the substance of - sharding this client and not a tidy-up. `_delay_ready` fires this - only after every shard's own ready task has completed, so by the - time this runs each shard has already reconciled its guilds - exactly once; repeating the sweep here would be a second database - read per guild that could not change anything. - - Readiness is not touched here either. It is per shard now, and - four shards up is something this method cannot say more precisely - than the four `on_shard_ready` calls that preceded it. + async def on_resumed(self) -> None: + """Sets the gateway flag back after a RESUME. + + No reconcile: a RESUME replays the events missed and keeps the guild + cache, so there is nothing to rebuild. """ + self._readiness.discord_connected = True log_event( log, logging.INFO, - Event.BOT_CONNECTED, - "Connected to Discord", - count=len(self._recordings), - shard_count=self.shard_count, + Event.BOT_RESUMED, + "The gateway connection resumed after a disconnect", ) async def on_guild_join(self, guild: discord.Guild) -> None: @@ -1607,7 +1467,6 @@ async def _start_capture(self, recording: _ChannelRecording) -> None: channel_id=recording.channel_id, session_id=recording.service.session_id, end_reason=EndReason.CAPTURE_FAILURE.value, - shard_id=self._shard(recording.service.guild_id), # The one join failure whose type name says nothing # useful: `discord.ConnectionClosed` is what Discord # raises for "session no longer valid", "you were @@ -1657,7 +1516,6 @@ async def _return_to_idle(self, guild_id: int, recording: _ChannelRecording) -> guild_id=guild_id, channel_id=recording.channel_id, session_id=recording.service.session_id, - shard_id=self._shard(guild_id), ) recording.service.reset() @@ -1954,16 +1812,6 @@ async def _tick_all(self, now: datetime) -> None: Every guild's body is wrapped: this one task also carries the readiness heartbeat and every other guild's timeout enforcement, and one guild raising here must not take those with it. - - **This sweep does not ask whether it serves a guild, and that is a - decision rather than an omission.** Its input is `self.guilds` -- - the gateway cache -- which contains exactly the guilds this - process's shards carry and nothing else, today and under stage two - alike. The administrator mirror and the directory mirror inherit - that scoping by running inside it. `sturnus.application.sharding` - carries the full argument, and names the one sweep whose input is - the *database* instead and therefore does have to ask: the - announcement poll. """ guild_ids = {guild.id for guild in self.guilds} | { guild_id for guild_id, _channel_id in self._recordings @@ -1979,7 +1827,6 @@ async def _tick_all(self, now: datetime) -> None: "The periodic tick failed for this guild; every other guild is unaffected.", exc, guild_id=guild_id, - shard_id=self._shard(guild_id), ) async def _tick_guild(self, guild_id: int, now: datetime) -> None: @@ -2009,7 +1856,7 @@ async def _tick_guild(self, guild_id: int, now: datetime) -> None: recount it performs should use the configuration the reconcile above has just settled on rather than the one before it. """ - # Silent, unlike `reconcile_guild`: the join and the shard-ready + # Silent, unlike `reconcile_guild`: the join and the on_ready # reconcile have already reported this guild, and a line every ten # seconds would say nothing new. if not serves_guild(configured_guild_id=self._guild_id, guild_id=guild_id): @@ -2079,7 +1926,6 @@ async def _apply_setup_intents(self, guild_id: int, now: datetime) -> None: "configuration it already had", exc, guild_id=guild_id, - shard_id=self._shard(guild_id), ) async def _mirror_administrators(self, guild_id: int, now: datetime) -> None: @@ -2112,7 +1958,6 @@ async def _mirror_administrators(self, guild_id: int, now: datetime) -> None: "the membership it already had", exc, guild_id=guild_id, - shard_id=self._shard(guild_id), ) async def _mirror_directory(self, guild_id: int, now: datetime) -> None: @@ -2160,7 +2005,6 @@ async def _mirror_directory(self, guild_id: int, now: datetime) -> None: "keeps the names it already had", exc, guild_id=guild_id, - shard_id=self._shard(guild_id), ) async def _sweep_due_session( @@ -2231,7 +2075,6 @@ async def _sweep_due_session( exc, guild_id=guild_id, session_id=session_id, - shard_id=self._shard(guild_id), ) if not closed: return @@ -2276,7 +2119,6 @@ def _begin_capture_cooldown( channel_id=recording.channel_id, end_reason=reason.value, duration_seconds=REJOIN_COOLDOWN.total_seconds(), - shard_id=self._shard(recording.service.guild_id), ) async def _end_capture_cooldown(self, guild_id: int) -> None: diff --git a/src/sturnus/infrastructure/discord/voice.py b/src/sturnus/infrastructure/discord/voice.py index 8c4cd983..0a9db37f 100644 --- a/src/sturnus/infrastructure/discord/voice.py +++ b/src/sturnus/infrastructure/discord/voice.py @@ -54,7 +54,6 @@ from sturnus.application.ports import Clock from sturnus.application.recording import RecordingService -from sturnus.application.sharding import shard_id_for_logging from sturnus.domain import settings from sturnus.domain.session import EndReason from sturnus.infrastructure.db.config_store import ConfigStore @@ -174,25 +173,6 @@ def __init__( self._stopping = False self._message_errors = RateLimiter(_MESSAGE_ERROR_LOG_EVERY) - def _shard(self, guild_id: int | None) -> int | None: - """This guild's shard id, or `None` while this process holds only one shard. - - The voice lifecycle is where "which shard is the unhealthy one" - gets asked in anger: a shard whose gateway keeps re-IDENTIFYing - drops the voice connections of its guilds and nobody else's, so - `voice.joined`/`voice.left` grouped by shard is the line the - pattern shows up in. The same conditional - `SturnusClient._shard` applies, from the same one function, so - the two cannot disagree about when the field is worth emitting. - - `guild_id` is `None` only on a `leave()` for a connection that - never completed a `join()`, and a shard id for no guild is not a - fact -- the field is simply absent then. - """ - if guild_id is None: - return None - return shard_id_for_logging(guild_id, self._client.shard_count) - async def join(self, channel_id: int) -> None: """Connects to the voice channel and starts listening on a sink. @@ -264,7 +244,6 @@ async def join(self, channel_id: int) -> None: channel_id=channel_id, session_id=self._service.session_id, listening=True, - shard_id=self._shard(channel.guild.id), ) async def leave(self) -> None: @@ -310,7 +289,6 @@ async def leave(self) -> None: guild_id=guild_id, session_id=self._service.session_id, listening=False, - shard_id=self._shard(guild_id), ) # -- capture side: everything below runs on the extension's threads -- @@ -612,7 +590,6 @@ def _report_decode_failure(self) -> None: "No voice stream is decoding any longer; ending the session rather than " "recording silence.", guild_id=self._guild_id, - shard_id=self._shard(self._guild_id), session_id=self._service.session_id, end_reason=EndReason.DECODE_FAILURE.value, ) @@ -644,7 +621,6 @@ def _report_capture_stopped(self, message: CaptureStopped) -> None: "session rather than leaving it open with nothing arriving. This is the " "failure mode that silently ended a recording in production.", guild_id=self._guild_id, - shard_id=self._shard(self._guild_id), session_id=self._service.session_id, end_reason=EndReason.CAPTURE_FAILURE.value, listening=False, @@ -659,7 +635,6 @@ def _report_capture_stopped(self, message: CaptureStopped) -> None: "silently ended a recording in production.", message.error, guild_id=self._guild_id, - shard_id=self._shard(self._guild_id), session_id=self._service.session_id, end_reason=EndReason.CAPTURE_FAILURE.value, listening=False, diff --git a/src/sturnus/infrastructure/health.py b/src/sturnus/infrastructure/health.py index ef85420f..898f4226 100644 --- a/src/sturnus/infrastructure/health.py +++ b/src/sturnus/infrastructure/health.py @@ -9,12 +9,11 @@ from __future__ import annotations -from dataclasses import dataclass, field +from dataclasses import dataclass from aiohttp import web from sturnus import __version__ -from sturnus.application.sharding import shards_this_process_owns @dataclass @@ -25,91 +24,21 @@ class ReadinessState: inject exactly the state it wants to assert against, without a real gateway connection or a real database. - **What "ready" means when the bot holds several shards.** The gateway - half used to be one boolean, set in `on_ready` and never cleared: a - gateway lost an hour after startup left `/readyz` green for the rest - of the process's life, because nothing was watching. Sharding both - forces the question and supplies the answer, since `on_shard_connect` - / `on_shard_disconnect` are per-connection events there is no excuse - for ignoring. - - The rule chosen is **every shard this process is supposed to hold**. - The two alternatives are both worse: - - - *Any shard up.* With four shards and one down, a quarter of the - guilds Sturnus is in cannot be recorded in at all, and the probe - would report perfect health. A probe that lies in that direction is - worse than one that flaps -- nothing else in the stack would say so. - - *A fraction.* "Three quarters up is ready" needs a threshold nobody - can defend, and buys nothing: the pod is not load-balanced, so - failing readiness sheds no traffic. It is purely a signal, and the - truthful signal is "this process is not doing all of its job". - - **It does not flap on a routine reconnect**, and that is arithmetic - rather than hope. discord.py dispatches `shard_disconnect` for every - RESUME too, so a blip does clear a shard here -- for the second or - two until `shard_resumed`. The chart polls `/readyz` every 10s with - the default `failureThreshold: 3`, so a shard has to be down for - 30 continuous seconds before Kubernetes marks the pod NotReady. A - RESUME is invisible; a shard that is genuinely gone is not. - - `expected_shards` is `None` until the gateway has told this process - how many shards it will open, which keeps a four-shard process from - turning green the moment its first connection lands. `0` is the - honest value for a process that holds no gateway at all (`worker`, - `link`): it holds all zero of the shards it is supposed to hold. + `discord_connected` is set in `on_ready` and cleared in + `on_disconnect`, so a gateway lost hours after startup turns the probe + red until it resumes. It is not latched. The process holds one gateway + connection, so this is one flag; a process with no gateway (`worker`) + sets it once at startup to say the gateway half does not apply to it. + + It does not flap on a routine reconnect: the chart polls `/readyz` + every 10s with the default `failureThreshold: 3`, so the connection + has to be down for 30 continuous seconds before Kubernetes marks the + pod NotReady. A RESUME is invisible; a connection that is genuinely + gone is not. """ database_reachable: bool = False - #: How many shards this process must hold before it is doing its job. - #: `None` while the gateway has not said yet; `0` for a process with - #: no gateway connection at all. - expected_shards: int | None = None - #: The shard ids currently holding a live gateway connection. - connected_shards: set[int] = field(default_factory=set) - - def shard_connected(self, shard_id: int, *, shard_count: int | None = None) -> None: - """Records that one shard is up, and how many there are in total. - - `shard_count` arrives with every call rather than being set once - at startup because `discord.Client.shard_count` is only populated - once `launch_shards` has run -- which is after this object is - constructed and before the first shard reports in. Taking it from - whichever event happens to arrive first removes the ordering - question entirely. - """ - if shard_count is not None: - self.expected_shards = shard_count - self.connected_shards.add(shard_id) - - def shard_disconnected(self, shard_id: int) -> None: - """Records that one shard has dropped, whether or not it comes straight back.""" - self.connected_shards.discard(shard_id) - - @property - def missing_shards(self) -> list[int]: - """The shard ids this process should hold and does not, in order. - - Reported in the `/readyz` body so a 503 names *which* quarter of - the guilds is unreachable, rather than leaving an operator to - correlate log lines to find out. - - Which ids this process *should* hold is asked of - `sturnus.application.sharding` rather than assumed to be - `range(shard_count)`. Today they are the same set; stage two -- - one shard range per pod -- narrows that function, and this - property follows without being touched. - """ - if self.expected_shards is None: - return [] - return sorted(shards_this_process_owns(self.expected_shards) - self.connected_shards) - - @property - def discord_connected(self) -> bool: - """Whether every shard this process is supposed to hold is up.""" - if self.expected_shards is None: - return False - return not self.missing_shards + discord_connected: bool = False @property def ready(self) -> bool: @@ -129,19 +58,11 @@ async def healthz(_request: web.Request) -> web.Response: async def readyz(_request: web.Request) -> web.Response: if state.ready: return web.json_response({"status": "ready"}) - # The body names *which* shards are missing, not only that the - # gateway half is unsatisfied. With one shard that is the same - # statement; with four it is the difference between "the bot is - # down" and "a quarter of the guilds are", which are different - # incidents with different responses. return web.json_response( { "status": "not ready", "discord_connected": state.discord_connected, "database_reachable": state.database_reachable, - "shards_connected": len(state.connected_shards), - "shards_expected": state.expected_shards, - "shards_missing": state.missing_shards, }, status=503, ) diff --git a/src/sturnus/observability/events.py b/src/sturnus/observability/events.py index da241035..773054e6 100644 --- a/src/sturnus/observability/events.py +++ b/src/sturnus/observability/events.py @@ -65,23 +65,12 @@ class Event(StrEnum): GUILD_CONFIGURED = "guild.configured" GUILD_UNCONFIGURED = "guild.unconfigured" BOT_CONNECTED = "bot.connected" - #: One gateway connection finished its IDENTIFY and handed this process - #: its share of the guilds. Fires once per shard, and on every - #: re-IDENTIFY of that shard afterwards -- which is the *only* signal - #: that a shard came back, because `on_ready` does not fire again for - #: a single shard once the whole set has been ready once. See - #: `SturnusClient.on_shard_ready`. - BOT_SHARD_READY = "bot.shard_ready" - #: One gateway connection resumed after a blip, replaying the events it - #: missed. INFO rather than WARNING: a RESUME is the gateway working, - #: and no guild cache was lost, so nothing is re-reconciled. - BOT_SHARD_RESUMED = "bot.shard_resumed" - #: One gateway connection dropped. **WARNING**, not ERROR: discord.py - #: reconnects on its own and the overwhelming majority of these are - #: followed by `bot.shard_resumed` within seconds. It is ERROR-shaped - #: only if it stays -- which is what `/readyz` is for, and why - #: readiness is scoped to shards rather than to a single boolean. - BOT_SHARD_DISCONNECTED = "bot.shard_disconnected" + #: The gateway connection dropped. WARNING: discord.py reconnects on its own and + #: most of these are followed by `bot.resumed` within seconds, but a connection + #: that stays down is the outage `/readyz` reports, and this line is how it reads in Loki. + BOT_DISCONNECTED = "bot.disconnected" + #: The gateway connection resumed after a disconnect, replaying missed events. INFO. + BOT_RESUMED = "bot.resumed" VOICE_JOINED = "voice.joined" VOICE_LEFT = "voice.left" VOICE_JOIN_FAILED = "voice.join_failed" @@ -360,6 +349,9 @@ class Event(StrEnum): SHUTDOWN_BEGIN = "shutdown.begin" SHUTDOWN_COMPLETE = "shutdown.complete" SCHEMA_WAITING = "schema.waiting" + #: A leftover `STURNUS_SHARD_COUNT` is set. It is ignored: the bot holds one + #: gateway connection and nothing reads the variable any more. + CONFIG_SHARD_COUNT_IGNORED = "config.shard_count_ignored" #: The startup line that says a requested third-party log level was #: raised to `setup.THIRD_PARTY_FLOOR`. An operator who turned the knob #: up and sees nothing new needs to be told why, in the same place they diff --git a/src/sturnus/observability/fields.py b/src/sturnus/observability/fields.py index f6e6577e..c45bf98f 100644 --- a/src/sturnus/observability/fields.py +++ b/src/sturnus/observability/fields.py @@ -84,24 +84,6 @@ def service_name(component: str) -> str: "configured_key_id", "provider", "ssrc", - #: Which of this process's gateway connections a guild's events - #: arrive on -- Discord's `(guild_id >> 22) % shard_count`. An - #: identifier of a connection rather than of a row, and bounded by - #: the shard count, which is why it sits here rather than among - #: the measurements. - #: - #: **Emitted only when this process holds more than one shard.** - #: It is a pure function of `guild_id`, so on a single-shard - #: process it is `0` on every line for ever -- a key in every Loki - #: stream that answers nothing. `sturnus.application.sharding. - #: shard_fields` is the one place that decision is made; see its - #: docstring for why LogQL cannot recover it from `guild_id` - #: instead. - #: - #: Deliberately **not** in `METRIC_LABEL_FIELDS`. `guild_id` - #: already is, and a shard id adds no dimension a guild id does - #: not already carry -- it would only multiply series. - "shard_id", } ) @@ -257,13 +239,6 @@ def service_name(component: str) -> str: #: somebody who already knows which batch to count. "revoked", "refused", - #: How many gateway connections this one process holds. On the - #: shard lifecycle lines only -- `bot.connected`, - #: `bot.shard_ready`, `bot.shard_disconnected` -- where it is the - #: denominator that makes "shard 3 is down" mean something. Not on - #: per-guild lines: there it would be the same number on every one - #: of them, which is what `shard_id` is conditional to avoid. - "shard_count", } ) @@ -276,29 +251,6 @@ def service_name(component: str) -> str: _IDENTIFIERS | _SUBJECT_IDENTIFIERS | _LITERALS | _MEASUREMENTS | _CORRELATION ) -#: Fields whose `None` means "this does not apply here" rather than "we -#: looked, and there was none" -- dropped by `redaction.scrub_fields` -#: instead of being written as `null`. -#: -#: **The contrast that defines the set is `close_code`.** A -#: `voice.reader_stopped` line with `close_code: null` is a *finding*: the -#: adapter looked at the exception, it was an `OSError` rather than a -#: `discord.ConnectionClosed`, and there genuinely is no close code. That -#: null is worth a key, and `voice_close_code`'s docstring argues the case. -#: -#: `shard_id` is the other kind. On a process holding one shard it is not -#: "no shard"; the concept simply has nothing to say, and writing -#: `shard_id: null` into every guild line for ever is the noise the -#: registry exists to keep out. The distinction is registered here rather -#: than decided by `scrub_fields` for every field at once, precisely so -#: that adding a field to it is a deliberate act with a reason attached. -#: -#: This is also what lets a call site emit a field conditionally at all: -#: rule R3 in `tests/test_logging_discipline.py` forbids `**kwargs` into a -#: log event, so the field name must be written in the source and the -#: *value* is the only place the condition can live. -OMITTED_WHEN_NONE: Final[frozenset[str]] = frozenset({"shard_id"}) - #: Registered, logged, and deliberately kept out of spans and metrics. #: #: The checklist blesses a user id in a pod log, and this codebase already diff --git a/src/sturnus/observability/redaction.py b/src/sturnus/observability/redaction.py index 9de3fb7d..6f797d6c 100644 --- a/src/sturnus/observability/redaction.py +++ b/src/sturnus/observability/redaction.py @@ -52,12 +52,7 @@ from typing import Final from sturnus.domain.errors import DiagnosticSafeError -from sturnus.observability.fields import ( - ALLOWED_FIELDS, - CREDENTIAL_NAMES, - DENIED_NAMES, - OMITTED_WHEN_NONE, -) +from sturnus.observability.fields import ALLOWED_FIELDS, CREDENTIAL_NAMES, DENIED_NAMES REDACTED: Final = "" @@ -233,15 +228,6 @@ def scrub_fields(fields: Mapping[str, object], *, warn: bool = True) -> dict[str """ out: dict[str, object] = {} for key, value in fields.items(): - # A `None` in `OMITTED_WHEN_NONE` means "this field does not apply - # to this process", not "we looked and there was none" -- see the - # registry entry, which draws the contrast with `close_code` - # explicitly. It is what lets a call site emit a field - # *conditionally* without reaching for `**kwargs`, which rule R3 in - # `tests/test_logging_discipline.py` forbids outright so that every - # emitted field name stays statically visible at its call site. - if value is None and key in OMITTED_WHEN_NONE: - continue if key not in ALLOWED_FIELDS: if warn: log.warning( diff --git a/tests/application/test_publishing.py b/tests/application/test_publishing.py index c2ec44e3..9ea3864f 100644 --- a/tests/application/test_publishing.py +++ b/tests/application/test_publishing.py @@ -19,14 +19,12 @@ def session( announced: datetime | None = None, channel_id: int = 999, participant_ids: tuple[int, ...] = (), - guild_id: int = 7, ) -> dict[str, object]: return { "id": session_id, "status": status, "document_url": document_url, "announced_at": announced, - "guild_id": guild_id, "channel_id": channel_id, "participant_ids": participant_ids, } diff --git a/tests/application/test_sharding.py b/tests/application/test_sharding.py deleted file mode 100644 index 348afd11..00000000 --- a/tests/application/test_sharding.py +++ /dev/null @@ -1,110 +0,0 @@ -"""The one place the "one process, every guild" assumption is written down. - -These tests are deliberately about a *predicate that is always true today*. -That is the point: `sturnus.application.sharding` exists so that stage two --- several bot processes, each owning a range of shards -- is a change to -one function body and whatever the type checker then points at, rather than -an archaeology exercise across every sweep that reads rows for all guilds. -""" - -from __future__ import annotations - -import pytest - -from sturnus.application.sharding import ( - MIN_SHARD_COUNT, - PROCESS_HOLDS_EVERY_SHARD, - process_serves_guild, - shard_id_for_logging, - shard_of, - shards_this_process_owns, -) - -#: Snowflakes whose shard ids differ under a four-shard cluster. Discord's -#: own rule is `(guild_id >> 22) % shard_count`, so the low 22 bits are the -#: timestamp-internal part and change nothing. -FIRST_GUILD = 1 << 22 -SECOND_GUILD = 2 << 22 -FIFTH_GUILD = 5 << 22 - - -def test_a_guild_lands_on_the_shard_discord_would_route_it_to() -> None: - """`shard_of` must agree with Discord's own routing rule, or a log line lies. - - The whole value of a `shard_id` field is that an operator can join it - to what Discord and discord.py believe. `(guild_id >> 22) % shard_count` - is that rule, and it is the same arithmetic `discord.Guild.shard_id` - performs. - """ - assert shard_of(FIRST_GUILD, 4) == 1 - assert shard_of(SECOND_GUILD, 4) == 2 - assert shard_of(FIFTH_GUILD, 4) == 1 - - -def test_an_unlaunched_client_puts_every_guild_on_shard_zero() -> None: - """A shard count of `None` is "the gateway has not told us yet", not a crash. - - `discord.Client.shard_count` is `None` until `launch_shards` has run, - and `discord.Guild.shard_id` answers `0` in that window rather than - dividing by nothing. Anything derived from it here must do the same. - """ - assert shard_of(FIRST_GUILD, None) == 0 - assert shard_of(SECOND_GUILD, None) == 0 - - -def test_this_process_owns_every_shard_it_was_told_about() -> None: - """Stage one is one process holding all N shards, and this says so. - - Stage two makes this function return a *range* -- and it is the only - function that has to change for the predicate below to start refusing - guilds that belong to another pod. - """ - assert shards_this_process_owns(4) == frozenset({0, 1, 2, 3}) - assert shards_this_process_owns(1) == frozenset({0}) - assert shards_this_process_owns(None) == frozenset({0}) - - -@pytest.mark.parametrize("guild_id", [FIRST_GUILD, SECOND_GUILD, FIFTH_GUILD]) -@pytest.mark.parametrize("shard_count", [None, 1, 4, 16]) -def test_every_guild_is_served_by_this_process_today( - guild_id: int, shard_count: int | None -) -> None: - """The invariant itself: one process, so every guild is its business. - - A database sweep -- the announcement poll is the one that matters -- - reads rows for every guild there is, and today it is right to act on - all of them. This test is what turns "obviously" into "asserted", so - the day `PROCESS_HOLDS_EVERY_SHARD` stops being true, the sweeps that - depend on it fail here rather than double-posting in production. - """ - assert PROCESS_HOLDS_EVERY_SHARD is True - assert process_serves_guild(guild_id, shard_count) is True - - -def test_a_single_shard_process_adds_no_shard_field_to_a_log_line() -> None: - """One shard means `shard_id=0` on every line, which is noise, not signal. - - A field whose value never varies costs a key in every Loki stream and - answers no question anyone could ask. It earns its place only once - there is more than one shard to tell apart. `None` is how that absence - is expressed at a call site, because rule R3 forbids `**kwargs` into a - log event and `scrub_fields` drops a `None` rather than writing null. - """ - assert shard_id_for_logging(FIRST_GUILD, None) is None - assert shard_id_for_logging(FIRST_GUILD, 1) is None - - -def test_more_than_one_shard_attributes_a_guild_line_to_its_shard() -> None: - """With several shards, "which shard is stalling" becomes answerable. - - `shard_id` is derivable from `guild_id` and the shard count, but not - in LogQL -- so without the field the grouping an operator actually - wants cannot be expressed at query time. - """ - assert shard_id_for_logging(FIRST_GUILD, 4) == 1 - assert shard_id_for_logging(SECOND_GUILD, 4) == 2 - - -def test_the_smallest_meaningful_shard_count_is_one() -> None: - """Zero shards is not a smaller deployment; it is a bot that never connects.""" - assert MIN_SHARD_COUNT == 1 diff --git a/tests/entrypoints/test_bot_entrypoint.py b/tests/entrypoints/test_bot_entrypoint.py index 6fe74f8e..2ac57471 100644 --- a/tests/entrypoints/test_bot_entrypoint.py +++ b/tests/entrypoints/test_bot_entrypoint.py @@ -35,14 +35,6 @@ class _FakeClient: is constructed but never actually calls `get_channel`/`fetch_channel`. """ - #: The announce sweep is told how many shards this process holds, so it - #: can ask whether it serves each candidate's guild - #: (`sturnus.application.sharding`). `None` is what a client reports - #: before `launch_shards` has run. Without the attribute the sweep's - #: own `except Exception` would swallow the `AttributeError` and this - #: test would keep passing while announcing nothing at all. - shard_count: int | None = None - async def wait_until_ready(self) -> None: return None diff --git a/tests/infrastructure/discord/test_client.py b/tests/infrastructure/discord/test_client.py index 499a8bda..12b7d2f1 100644 --- a/tests/infrastructure/discord/test_client.py +++ b/tests/infrastructure/discord/test_client.py @@ -364,7 +364,6 @@ def _client( audio_store: AudioStore | None = None, directory_mirror: object | None = None, setup_intents: object | None = None, - shard_count: int | None = None, ) -> _TestClient: """A `SturnusClient` with every dependency these tests do not touch stubbed out. @@ -377,11 +376,6 @@ def _client( the console needs, and `setup_intents` for the ones that assert it applies what the console asked for -- both left `None` everywhere else, which is a client that neither mirrors nor is asked anything. - - `shard_count` is `None` -- discord.py's "let the gateway decide" -- - for everything except `test_client_shards`, which is the one suite - that has anything to say about how many connections this process - holds. """ client = _TestClient( clock=clock, @@ -405,7 +399,6 @@ def _client( outline_oauth=MagicMock(spec=OutlineOAuth), link_states=MagicMock(spec=LinkStateStore), account_links=MagicMock(spec=AccountLinkRepository), - shard_count=shard_count, ) client.voices = [] return client @@ -785,6 +778,64 @@ async def test_reconciling_twice_changes_nothing(tmp_path: Path) -> None: assert len(client.voices) == 1, "a second pipeline would leak a voice connection" +async def test_on_ready_reconciles_each_guild_it_holds_exactly_once( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """One `on_ready` is one reconcile pass over every guild in the cache.""" + clock = FakeClock(T0) + client = _client(clock, config_store=_configured_store()) + _in_guild(client, _guild(GUILD_ID, _voice_channel(CHANNEL_ID, members=[]))) + _in_guild(client, _guild(OTHER_GUILD_ID, _voice_channel(NEW_CHANNEL_ID, members=[]))) + reconciled: list[int] = [] + + async def record(guild_id: int) -> None: + reconciled.append(guild_id) + + monkeypatch.setattr(client, "reconcile_guild", record) + + await client.on_ready() + + assert sorted(reconciled) == [GUILD_ID, OTHER_GUILD_ID] + + +async def test_on_ready_marks_the_gateway_connected() -> None: + client = _client(FakeClock(T0), config_store=_configured_store()) + + await client.on_ready() + + assert client._readiness.discord_connected is True + + +async def test_a_disconnect_writes_one_warning_under_the_disconnect_event( + caplog: pytest.LogCaptureFixture, +) -> None: + """A real outage must stay visible in the logs, not only on the probe.""" + client = _client(FakeClock(T0), config_store=_configured_store()) + + with caplog.at_level(logging.INFO, logger=CLIENT_LOGGER): + await client.on_disconnect() + + matching = [ + record + for record in caplog.records + if record.name == CLIENT_LOGGER + and getattr(record, "sturnus_event", None) == Event.BOT_DISCONNECTED + ] + assert len(matching) == 1, "one disconnect is one line" + assert matching[0].levelno == logging.WARNING + + +async def test_a_disconnect_clears_the_gateway_flag_and_a_resume_sets_it_again() -> None: + client = _client(FakeClock(T0), config_store=_configured_store()) + await client.on_ready() + + await client.on_disconnect() + assert client._readiness.discord_connected is False + + await client.on_resumed() + assert client._readiness.discord_connected is True + + async def test_an_unparseable_value_neither_raises_nor_un_configures_a_guild( tmp_path: Path, ) -> None: diff --git a/tests/infrastructure/discord/test_client_shards.py b/tests/infrastructure/discord/test_client_shards.py deleted file mode 100644 index 6af8a01d..00000000 --- a/tests/infrastructure/discord/test_client_shards.py +++ /dev/null @@ -1,383 +0,0 @@ -"""What changes about the client's lifecycle when it holds several shards. - -`SturnusClient` extends `commands.AutoShardedBot`, so one process opens N -gateway connections instead of one. **No deployment invariant moves** -- -`sturnus.application.sharding` is where that is argued -- but three things -about the gateway lifecycle genuinely do, and each is pinned here rather -than left to be discovered in production: - -1. `on_ready` stops firing on a single shard's re-IDENTIFY, so the - "reconcile everything after a gateway blip" repair had to move to - `on_shard_ready` or silently stop happening. -2. Readiness stops being a boolean set once and never cleared. -3. The tick loop must be started once for N connections, not once each. - -The fakes come from `test_client`, which already builds a `SturnusClient` -entirely against ports -- there is no gateway connection anywhere in this -file. Guild ids are real snowflake shapes rather than `1` and `2`, because -Discord's routing rule is `(guild_id >> 22) % shard_count` and small -integers all land on shard 0, which would make every assertion below pass -for the wrong reason. -""" - -from __future__ import annotations - -import asyncio -import logging -from pathlib import Path -from unittest.mock import MagicMock - -import discord -import pytest - -from sturnus.application.reconfigure import ReconfigureResult -from sturnus.application.sharding import shard_of -from sturnus.domain import settings -from sturnus.observability.events import Event -from sturnus.observability.redaction import scrub_fields -from tests.infrastructure.discord.test_client import ( - CHANNEL_ID, - ROLE_ID, - T0, - FakeClock, - FakeConfigStore, - _client, - _guild, - _in_guild, - _voice_channel, -) - -CLIENT_LOGGER = "sturnus.infrastructure.discord.client" - -#: Two guilds Discord routes to different shards under a two-shard client: -#: `(1 << 22) >> 22 == 1` and `(2 << 22) >> 22 == 2`, which are 1 and 0 -#: modulo two. `test_client`'s `GUILD_ID = 1` would put both on shard 0. -GUILD_A = 1 << 22 -GUILD_B = 2 << 22 - - -def _sharded(client: discord.AutoShardedClient, shard_count: int) -> None: - """Tells the client and its cache how many shards this process holds. - - `discord.Client.shard_count` is an instance attribute `launch_shards` - fills in, and `discord.Guild.shard_id` reads the *connection state's* - copy of it -- two attributes discord.py keeps in step itself. A test - with no gateway has to set both, which is exactly what `launch_shards` - does. - """ - client.shard_count = shard_count - client._connection.shard_count = shard_count - - -def _guild_on_shard(guild_id: int, shard_count: int) -> MagicMock: - """A guild mock that answers `shard_id` the way a real `Guild` would. - - `MagicMock(spec=discord.Guild)` gives `shard_id` back as a mock rather - than an integer, because it is a property. Computing it here with the - same rule discord.py uses keeps the fixture honest instead of letting - a test pick whichever shard makes it pass. - """ - guild = _guild(guild_id, _voice_channel(CHANNEL_ID, members=[])) - guild.shard_id = shard_of(guild_id, shard_count) - return guild - - -def _store(*guild_ids: int) -> FakeConfigStore: - store = FakeConfigStore() - for guild_id in guild_ids: - store.write(guild_id, settings.VOICE_CHANNEL_IDS, str(CHANNEL_ID)) - store.write(guild_id, settings.CONSENT_ROLE_ID, str(ROLE_ID)) - return store - - -def _events(caplog: pytest.LogCaptureFixture, event: Event) -> list[logging.LogRecord]: - return [r for r in caplog.records if getattr(r, "sturnus_event", None) == str(event)] - - -def _emitted(record: logging.LogRecord) -> dict[str, object]: - """The fields as they reach a log line, not as the call site passed them. - - `log_event` attaches the call site's dict to the record untouched; the - registry is applied by `SturnusFilter` on the way to the formatter. - Anything asserting on *absence* has to run the same step, or it is - reading a stage earlier than the one that decides. - """ - return scrub_fields(getattr(record, "sturnus_fields", {})) - - -async def test_a_shard_coming_back_reconciles_only_the_guilds_it_carries( - monkeypatch: pytest.MonkeyPatch, -) -> None: - """A shard's ready is about that shard's guilds, not about all of them. - - `self.guilds` is one cache shared across every connection, so the other - shards' guilds are sitting right there and it would be easy -- and - wrong -- to sweep them too. Each shard's own ready covers its own - guilds exactly once; reconciling everything on every shard would - multiply the startup database reads by the shard count and buy nothing. - """ - client = _client(FakeClock(T0), config_store=_store(GUILD_A, GUILD_B)) - _sharded(client, 2) - first = _guild_on_shard(GUILD_A, 2) - second = _guild_on_shard(GUILD_B, 2) - assert first.shard_id != second.shard_id, ( - "the fixture must put the two guilds on different shards, or this asserts nothing" - ) - _in_guild(client, first) - _in_guild(client, second) - - reconciled: list[int] = [] - original = client.reconcile_guild - - async def recording_reconcile(guild_id: int) -> ReconfigureResult: - reconciled.append(guild_id) - return await original(guild_id) - - monkeypatch.setattr(client, "reconcile_guild", recording_reconcile) - - await client.on_shard_ready(first.shard_id) - - assert reconciled == [GUILD_A] - - -async def test_on_ready_does_no_reconciling_because_the_shards_already_did( - monkeypatch: pytest.MonkeyPatch, -) -> None: - """The move that sharding this client is actually about. - - With a plain client, `on_ready` fired again on every re-IDENTIFY, and - reconciling every guild there was a working repair for a gateway blip. - `AutoShardedConnectionState._delay_ready` empties `_ready_tasks` once - it has fired, and `parse_ready` only re-schedules the whole-bot ready - when *every* shard has a pending ready task again -- so one shard - coming back on its own never re-fires it. Left where it was, the - repair would have quietly stopped happening for exactly the guilds - that had just lost and rebuilt their caches. - - It is not merely moved: `on_ready` fires only after every shard's own - ready task has finished, so repeating the sweep here would be a second - database read per guild that could not change anything. - """ - client = _client(FakeClock(T0), config_store=_store(GUILD_A)) - _sharded(client, 1) - _in_guild(client, _guild_on_shard(GUILD_A, 1)) - - async def refuse(_guild_id: int) -> ReconfigureResult: - raise AssertionError("on_ready must not reconcile") - - monkeypatch.setattr(client, "reconcile_guild", refuse) - - await client.on_ready() - - -async def test_the_shard_lifecycle_drives_readiness_rather_than_on_ready() -> None: - """Four shards up is four statements, and one of them can stop being true. - - Readiness used to be a boolean set in `on_ready` and never cleared, so - a gateway lost an hour after startup left `/readyz` green for the rest - of the process's life. Per shard there is a disconnect event, so there - is no longer an excuse. - """ - client = _client(FakeClock(T0), config_store=_store(GUILD_A)) - _sharded(client, 2) - _in_guild(client, _guild_on_shard(GUILD_A, 2)) - client._readiness.database_reachable = True - - await client.on_shard_ready(0) - assert client._readiness.ready is False, "one of two shards is not the whole bot" - - await client.on_shard_ready(1) - assert client._readiness.ready is True - - await client.on_shard_disconnect(1) - assert client._readiness.ready is False - assert client._readiness.missing_shards == [1] - - await client.on_shard_resumed(1) - assert client._readiness.ready is True - - -async def test_a_shard_is_only_ready_once_its_guilds_have_been_reconciled( - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Readiness hangs off `shard_ready`, never off `shard_connect`. - - discord.py dispatches `shard_connect` the moment the READY payload - lands -- before the guild caches are filled and before this client has - read a single guild's configuration. Marking the shard ready there - would turn the probe green on a connection that cannot yet answer for - any of the servers it carries. - """ - client = _client(FakeClock(T0), config_store=_store(GUILD_A)) - _sharded(client, 1) - _in_guild(client, _guild_on_shard(GUILD_A, 1)) - client._readiness.database_reachable = True - - seen: list[bool] = [] - - async def reconcile_and_look(_guild_id: int) -> None: - seen.append(client._readiness.discord_connected) - - monkeypatch.setattr(client, "reconcile_guild", reconcile_and_look) - - await client.on_shard_ready(0) - - assert seen == [False], "the shard was marked up before its guilds were reconciled" - assert client._readiness.ready is True - - -async def test_a_resume_restores_a_shard_without_reconciling_its_guilds( - monkeypatch: pytest.MonkeyPatch, -) -> None: - """A RESUME keeps the guild cache, so there is nothing to rebuild. - - That is the whole difference between `on_shard_resumed` and - `on_shard_ready`. Reconciling here anyway would put a database read - per guild behind every routine gateway hiccup -- and discord.py - dispatches `shard_disconnect`/`shard_resumed` for exactly those. - """ - client = _client(FakeClock(T0), config_store=_store(GUILD_A)) - _sharded(client, 1) - _in_guild(client, _guild_on_shard(GUILD_A, 1)) - - async def refuse(_guild_id: int) -> ReconfigureResult: - raise AssertionError("a resume must not reconcile") - - monkeypatch.setattr(client, "reconcile_guild", refuse) - - await client.on_shard_resumed(0) - - assert client._readiness.discord_connected is True - - -async def test_the_tick_loop_is_started_once_however_often_it_is_asked_for() -> None: - """One loop for N connections, not one per connection. - - `setup_hook` runs exactly once -- discord.py calls it from `login()`, - before `connect()` launches any shard -- so this guard never fires - today. It is here because the cost of being wrong is two loops - sweeping the same `_recordings` dict and closing each other's - sessions, and the cost of the guard is one comparison at startup. - """ - client = _client(FakeClock(T0), config_store=_store()) - - client._ensure_tick_loop() - first = client._tick_task - client._ensure_tick_loop() - - assert first is not None - assert client._tick_task is first - first.cancel() - - -async def test_a_shard_ready_says_which_shard_and_how_many_there_are( - caplog: pytest.LogCaptureFixture, -) -> None: - """`shard_id` alone does not say whether "3 is down" is a third or a quarter.""" - client = _client(FakeClock(T0), config_store=_store()) - _sharded(client, 4) - - with caplog.at_level(logging.INFO, logger=CLIENT_LOGGER): - await client.on_shard_ready(2) - - (record,) = _events(caplog, Event.BOT_SHARD_READY) - fields = getattr(record, "sturnus_fields", {}) - assert fields["shard_id"] == 2 - assert fields["shard_count"] == 4 - - -async def test_a_disconnected_shard_is_reported_as_a_warning_naming_the_shard( - caplog: pytest.LogCaptureFixture, -) -> None: - """WARNING, not ERROR: discord.py dispatches this for every RESUME too. - - Most of these are followed by `bot.shard_resumed` within seconds and - nothing was ever wrong. What makes a genuine outage visible is the - readiness probe this feeds -- 10-second period, `failureThreshold: 3`, - so half a minute of continuous absence -- not the level of the line. - """ - client = _client(FakeClock(T0), config_store=_store()) - _sharded(client, 4) - - with caplog.at_level(logging.WARNING, logger=CLIENT_LOGGER): - await client.on_shard_disconnect(3) - - (record,) = _events(caplog, Event.BOT_SHARD_DISCONNECTED) - assert record.levelno == logging.WARNING - assert getattr(record, "sturnus_fields", {})["shard_id"] == 3 - - -async def test_a_guild_line_names_its_shard_only_when_there_is_more_than_one( - tmp_path: Path, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch -) -> None: - """The conditional field, exercised through a real failing tick. - - On a single-shard process `shard_id` would be `0` in every line for - ever, so it is absent. With four shards it is the grouping an operator - actually wants when one connection starts misbehaving, and LogQL - cannot derive it from `guild_id` -- it has no `>>` and no `%`. - - Asserted through `scrub_fields`, because that is the shape the line - actually reaches Loki in: `log_event` attaches the call site's dict to - the record untouched, and the registry -- including - `OMITTED_WHEN_NONE`, which is what turns the call site's `None` into - an absent key -- is applied on the way to the formatter. - """ - clock = FakeClock(T0) - client = _client(clock, config_store=_store(GUILD_A), recording_dir=tmp_path) - _in_guild(client, _guild_on_shard(GUILD_A, 4)) - - async def explode(_guild_id: int, _now: object) -> None: - raise RuntimeError("the tick could not run") - - monkeypatch.setattr(client, "_tick_guild", explode) - - _sharded(client, 1) - with caplog.at_level(logging.ERROR, logger=CLIENT_LOGGER): - await client._tick_all(clock.now()) - (single,) = _events(caplog, Event.GUILD_TICK_FAILED) - assert "shard_id" not in _emitted(single) - - caplog.clear() - _sharded(client, 4) - with caplog.at_level(logging.ERROR, logger=CLIENT_LOGGER): - await client._tick_all(clock.now()) - (sharded,) = _events(caplog, Event.GUILD_TICK_FAILED) - assert _emitted(sharded)["shard_id"] == shard_of(GUILD_A, 4) - - -async def test_an_explicit_shard_count_reaches_the_gateway_client() -> None: - """The setting is not decoration: it has to arrive where discord.py reads it.""" - client = _client(FakeClock(T0), config_store=_store(), shard_count=4) - assert client.shard_count == 4 - - -async def test_no_shard_count_leaves_the_choice_to_discord() -> None: - """`None` is discord.py's own "ask `/gateway/bot`", not a missing value.""" - client = _client(FakeClock(T0), config_store=_store()) - assert client.shard_count is None - - -async def test_the_client_is_auto_sharded_at_all() -> None: - """The one assertion the whole file rests on. - - A plain `commands.Bot` would make every handler above dead code: the - `shard_*` events are dispatched by `AutoShardedConnectionState` and by - nothing else, so they would simply never fire and readiness would - never turn green. - """ - client = _client(FakeClock(T0), config_store=_store()) - assert isinstance(client, discord.AutoShardedClient) - - -async def test_shutdown_still_cancels_the_one_tick_loop() -> None: - """Sharding adds connections, not loops; the shutdown path is unchanged.""" - client = _client(FakeClock(T0), config_store=_store()) - client._ensure_tick_loop() - task = client._tick_task - assert task is not None - - await client.graceful_shutdown() - await asyncio.sleep(0) - - assert task.cancelled() or task.done() diff --git a/tests/infrastructure/discord/test_voice_adapter.py b/tests/infrastructure/discord/test_voice_adapter.py index 14542b3b..2a858a0b 100644 --- a/tests/infrastructure/discord/test_voice_adapter.py +++ b/tests/infrastructure/discord/test_voice_adapter.py @@ -148,27 +148,13 @@ def recording_service(sessions: FakeSessions) -> RecordingService: ) -def _gateway_client() -> MagicMock: - """A stand-in `discord.Client` that answers `shard_count`. - - `shard_count` is an *instance* attribute discord.py assigns in - `Client.__init__`, not a class attribute, so `MagicMock(spec=...)` does - not know about it and raises on access. The adapter reads it to decide - whether a `shard_id` is worth putting on `voice.joined`/`voice.left` - (see `VoiceReceiveAdapter._shard`), so it has to be present. `None` - is what a client whose shards have not launched reports, and it is the - value that keeps these tests asserting the single-shard behaviour. - """ - return MagicMock(spec=discord.Client, shard_count=None) - - def adapter( *, service: RecordingService | None = None, clock: FakeClock | None = None, ) -> VoiceReceiveAdapter: voice = VoiceReceiveAdapter( - _gateway_client(), + MagicMock(spec=discord.Client), service or MagicMock(spec=RecordingService), MagicMock(spec=ConfigStore), clock or FakeClock(), @@ -408,7 +394,7 @@ async def test_join_refuses_to_enter_the_channel_when_libopus_is_missing() -> No channel = MagicMock(spec=discord.VoiceChannel) channel.guild = MagicMock(id=GUILD_ID) channel.connect = AsyncMock() - client = _gateway_client() + client = MagicMock(spec=discord.Client) client.get_channel = MagicMock(return_value=channel) def broken_factory() -> FrameDecoder: @@ -439,7 +425,7 @@ async def test_a_failed_connect_leaves_no_task_running_behind_it() -> None: channel = MagicMock(spec=discord.VoiceChannel) channel.guild = MagicMock(id=GUILD_ID) channel.connect = AsyncMock(side_effect=discord.ClientException("no voice")) - client = _gateway_client() + client = MagicMock(spec=discord.Client) client.get_channel = MagicMock(return_value=channel) voice = VoiceReceiveAdapter( @@ -468,7 +454,7 @@ def _joinable() -> tuple[MagicMock, MagicMock]: # are `AsyncMock`s too, so `listen()` would hand back an un-awaited # coroutine and the resulting warnings would drown the assertion. channel.connect = AsyncMock(return_value=MagicMock(disconnect=AsyncMock())) - client = _gateway_client() + client = MagicMock(spec=discord.Client) client.get_channel = MagicMock(return_value=channel) return client, channel diff --git a/tests/infrastructure/test_health.py b/tests/infrastructure/test_health.py index 27e4c869..d17d7395 100644 --- a/tests/infrastructure/test_health.py +++ b/tests/infrastructure/test_health.py @@ -24,88 +24,69 @@ async def test_readyz_is_503_before_the_injected_flags_are_set() -> None: assert response.status == 503 -async def test_readyz_is_200_once_every_shard_and_the_database_are_up() -> None: - state = ReadinessState(database_reachable=True) - state.shard_connected(0, shard_count=1) +async def test_readyz_is_200_once_the_gateway_and_the_database_are_up() -> None: + state = ReadinessState(database_reachable=True, discord_connected=True) async with TestClient(TestServer(health_app(state))) as client: response = await client.get("/readyz") assert response.status == 200 -async def test_readyz_stays_503_with_only_one_dependency_up() -> None: - state = ReadinessState(database_reachable=False) - state.shard_connected(0, shard_count=1) +async def test_readyz_stays_503_with_only_the_database_up() -> None: + state = ReadinessState(database_reachable=True, discord_connected=False) async with TestClient(TestServer(health_app(state))) as client: response = await client.get("/readyz") assert response.status == 503 -async def test_a_process_that_holds_no_gateway_is_ready_on_the_database_alone() -> None: - """`worker` and `link` have no shards to wait on, and must not wait for one. - - Readiness over shards is "every shard I am supposed to hold is up". - A process that holds none satisfies that vacuously, and saying so with - `expected_shards=0` is what lets one `ReadinessState` serve every - process without a second flag meaning "ignore the gateway". - """ - state = ReadinessState(database_reachable=True, expected_shards=0) - async with TestClient(TestServer(health_app(state))) as client: - assert (await client.get("/readyz")).status == 200 - - -async def test_a_partly_connected_cluster_of_shards_is_not_ready() -> None: - """Three of four shards up is a quarter of the guilds unreachable. - - The tempting alternative -- ready as soon as *any* shard is up -- - reports healthy while a quarter of the servers Sturnus is in cannot - be recorded in at all, and nothing anywhere else would say so. A probe - that lies in that direction is worse than one that flaps. - """ - state = ReadinessState(database_reachable=True) - for shard_id in (0, 1, 3): - state.shard_connected(shard_id, shard_count=4) +async def test_readyz_stays_503_with_only_the_gateway_up() -> None: + state = ReadinessState(database_reachable=False, discord_connected=True) async with TestClient(TestServer(health_app(state))) as client: response = await client.get("/readyz") assert response.status == 503 - body = await response.json() - assert body["shards_connected"] == 3 - assert body["shards_expected"] == 4 - assert body["shards_missing"] == [2] -async def test_the_first_shard_up_does_not_declare_the_whole_process_ready() -> None: - """The count of connected shards is meaningless without the expected one. +async def test_a_process_with_no_gateway_is_ready_on_the_database_alone() -> None: + """`worker` and `link` hold no gateway and must not wait for one. - `all(connected)` over a dict that only shard 0 has reached is - trivially true, which would turn a four-shard process green the - moment its first connection landed and leave it green while the other - three never arrived. + They set the gateway flag themselves, once, at startup, so one + `ReadinessState` serves every process without a second flag meaning + "ignore the gateway". """ - state = ReadinessState(database_reachable=True) - state.shard_connected(0, shard_count=4) + state = ReadinessState(database_reachable=True, discord_connected=True) async with TestClient(TestServer(health_app(state))) as client: - assert (await client.get("/readyz")).status == 503 + assert (await client.get("/readyz")).status == 200 -async def test_a_shard_that_drops_takes_readiness_with_it() -> None: +async def test_a_dropped_gateway_takes_readiness_with_it_and_a_resume_restores_it() -> None: """Readiness is a live statement, not a latch set once at startup. - Before shards it was set `True` in `on_ready` and never cleared, so a - gateway lost hours later left `/readyz` reporting green for the rest - of the process's life. With shards there is a `shard_disconnect` - event, so there is no longer an excuse for that. + A gateway lost hours after startup must turn `/readyz` red, and the + connection coming back must turn it green again. The tolerance for a + short blip is the probe's `failureThreshold` in the chart, not a + timer here: a RESUME clears the flag for seconds and Kubernetes only + acts after three consecutive failed polls. """ - state = ReadinessState(database_reachable=True) - state.shard_connected(0, shard_count=2) - state.shard_connected(1, shard_count=2) + state = ReadinessState(database_reachable=True, discord_connected=True) async with TestClient(TestServer(health_app(state))) as client: assert (await client.get("/readyz")).status == 200 - state.shard_disconnected(1) + state.discord_connected = False assert (await client.get("/readyz")).status == 503 - state.shard_connected(1, shard_count=2) + state.discord_connected = True assert (await client.get("/readyz")).status == 200 +async def test_readyz_body_reports_the_gateway_and_database_flags() -> None: + state = ReadinessState(database_reachable=True, discord_connected=False) + async with TestClient(TestServer(health_app(state))) as client: + response = await client.get("/readyz") + body = await response.json() + assert body == { + "status": "not ready", + "discord_connected": False, + "database_reachable": True, + } + + async def test_version_reports_the_installed_package_version() -> None: async with TestClient(TestServer(health_app(ReadinessState()))) as client: response = await client.get("/version") diff --git a/tests/observability/test_redaction.py b/tests/observability/test_redaction.py index e3a01d24..102acd30 100644 --- a/tests/observability/test_redaction.py +++ b/tests/observability/test_redaction.py @@ -123,33 +123,6 @@ def test_unregistered_fields_are_dropped_not_stripped() -> None: assert "Alice" not in str(out) -def test_a_field_registered_as_omittable_is_dropped_rather_than_written_as_null() -> None: - """`shard_id=None` means "this process has one shard", not "shard none". - - Writing it as `null` would put a key that says nothing into every guild - line of every single-shard deployment -- which is every deployment - today. The registry decides which fields work this way; see - `OMITTED_WHEN_NONE`. - """ - assert scrub_fields({"guild_id": 5, "shard_id": None}, warn=False) == {"guild_id": 5} - assert scrub_fields({"guild_id": 5, "shard_id": 3}, warn=False) == { - "guild_id": 5, - "shard_id": 3, - } - - -def test_a_null_that_is_a_finding_still_travels() -> None: - """The contrast that gives `OMITTED_WHEN_NONE` its shape. - - `close_code: null` on a `voice.reader_stopped` line is a fact somebody - established -- the adapter looked, and the exception was an `OSError` - rather than a `discord.ConnectionClosed`. Dropping every `None` - everywhere would have taken that with it, which is why the behaviour is - registered per field instead of applied to all of them. - """ - assert scrub_fields({"close_code": None}, warn=False) == {"close_code": None} - - def test_an_object_renders_as_its_type_never_its_repr() -> None: """A repr is how an object holding a transcript prints itself into a line.""" diff --git a/tests/test_config.py b/tests/test_config.py index 5ab418d3..586e02c1 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -3,7 +3,7 @@ import pytest from pydantic import ValidationError -from sturnus.config import SentrySettings, Settings +from sturnus.config import SentrySettings, Settings, shard_count_is_configured # KeyWrapper requires the master key to base64-decode to exactly 32 bytes, # which makes any valid fixture look like a real key to a secret scanner. @@ -176,56 +176,44 @@ def test_sentry_settings_do_not_require_the_rest_of_the_environment( assert SentrySettings().sentry_dsn is None -def test_the_shard_count_is_unset_by_default_so_discord_decides( - monkeypatch: pytest.MonkeyPatch, +@pytest.mark.parametrize("leftover", ["4", "0", "-1", ""]) +def test_a_leftover_shard_count_does_not_stop_the_bot_starting( + monkeypatch: pytest.MonkeyPatch, leftover: str ) -> None: - """No shard count means "ask the gateway how many to open", which is the - only answer that stays right as the bot is added to more servers. - Discord's own `/gateway/bot` recommendation grows with the guild count; - a number pinned in a Helm values file does not. - """ - for k, v in _env().items(): - monkeypatch.setenv(k, v) - monkeypatch.delenv("STURNUS_SHARD_COUNT", raising=False) - assert Settings().shard_count is None + """`STURNUS_SHARD_COUNT` was removed with per-shard gateway connections. - -@pytest.mark.parametrize("blank", ["", " "]) -def test_a_blank_shard_count_means_unset_rather_than_a_failure( - monkeypatch: pytest.MonkeyPatch, blank: str -) -> None: - """The chart renders every optional value, so "not configured" arrives as - an empty string rather than an absent variable -- exactly as it does for - `STURNUS_OTEL_EXPORTER_OTLP_ENDPOINT`. An empty string must mean "let - Discord decide", not "refuse to start". + An operator who has not yet unset it must not have a crash-looping pod + over a setting that now does nothing: pydantic-settings reads only the + fields it declares, so the variable is simply not looked at. Whether to + say so is the entrypoint's decision, tested below. """ for k, v in _env().items(): monkeypatch.setenv(k, v) - monkeypatch.setenv("STURNUS_SHARD_COUNT", blank) - assert Settings().shard_count is None + monkeypatch.setenv("STURNUS_SHARD_COUNT", leftover) + assert Settings().guild_id == 123456789012345678 -def test_an_explicit_shard_count_survives(monkeypatch: pytest.MonkeyPatch) -> None: - """An operator who knows why may pin it; nothing about that is discouraged.""" +def test_a_leftover_shard_count_changes_no_setting(monkeypatch: pytest.MonkeyPatch) -> None: for k, v in _env().items(): monkeypatch.setenv(k, v) + monkeypatch.delenv("STURNUS_SHARD_COUNT", raising=False) + without = Settings().model_dump() monkeypatch.setenv("STURNUS_SHARD_COUNT", "4") - assert Settings().shard_count == 4 + assert Settings().model_dump() == without -@pytest.mark.parametrize("value", ["0", "-1"]) -def test_a_shard_count_below_one_is_refused_at_startup( - monkeypatch: pytest.MonkeyPatch, value: str -) -> None: - """Zero shards is not a smaller deployment, it is a bot that never connects. +def test_the_settings_no_longer_declare_a_shard_count() -> None: + assert "shard_count" not in Settings.model_fields + - Refused here rather than left to the gateway: `discord.py` would build - an empty shard range, `on_ready` would never fire, and the process - would sit there looking alive with a readiness probe that never turns - green and no line saying why. +def test_a_set_shard_count_variable_is_reported_even_when_blank() -> None: + """A chart that still renders the variable as `""` should be named in the log. + + The hint is for an operator's leftover, so it fires on presence, not on + a useful value. """ - for k, v in _env().items(): - monkeypatch.setenv(k, v) - monkeypatch.setenv("STURNUS_SHARD_COUNT", value) - with pytest.raises(ValidationError, match="STURNUS_SHARD_COUNT"): - Settings() + assert shard_count_is_configured({"STURNUS_SHARD_COUNT": ""}) is True + + +def test_an_unset_shard_count_variable_is_not_reported() -> None: + assert shard_count_is_configured({"STURNUS_DISCORD_TOKEN": "x"}) is False