Skip to content

fix(events): [#2414] drain listener queues on shutdown - #2578

Merged
josecelano merged 20 commits into
torrust:developfrom
josecelano:2414-drain-listener-queues-on-shutdown
Oct 20, 2026
Merged

josecelano merged 20 commits into
torrust:developfrom
josecelano:2414-drain-listener-queues-on-shutdown

Conversation

@josecelano

Copy link
Copy Markdown
Member

Fixes the shutdown race where completed downloads queued on the swarm event bus were lost because every event listener returned as soon as it was cancelled, without handling the events already queued for it. This is sub-issue 2 of 4 of sub-EPIC #2410 (EPIC #1488).

Summary

Each of the seven event listeners now drains the events already queued for it when it is cancelled, within an injected drain timeout, logs what it did with one shared format, and returns Cancelled. The drain policy is shared in packages/events: Receiver::try_recv, Receiver::len, a default Receiver::is_empty, TryRecvError, the drain helper, DrainReport, DEFAULT_DRAIN_TIMEOUT (5 s), and the log_drain_report! macro. The macro is a macro and not a function because tracing needs a constant target (confirmed by compile error E0435; design record entry 28).

The drain handles each event it takes to completion, checks the timeout only between events, counts Lagged(n) as lost and keeps going, yields to the scheduler after each event, and never expires when the timeout is too large to add to the clock (design record entry 29, from the independent review). Counts in the logs are events of every type on the bus, not completions.

The seven it_should_prioritize_* tests, which asserted the old behavior, are replaced: each listener has a test that a queued event is handled and Cancelled is returned, and a zero timeout test; http-core, udp-core, and the udp-server statistics listener have a third test that the metrics policy applies to a drained event. The tracker-core TestEnv now owns, stops, and joins its listeners, and the regression tests for the lost completions were seen red before the fix and green after it.

Important caveat: the drain bounds admission, it does not drain a full buffer

The release-build measurement (task T4b) falsified the design's premise for the default timeout: a full 65,536-event buffer takes 12.5 to 14.4 s on tmpfs and 158 to 188 s on NVMe with SQLite (about 350 to 415 events/s), more than the 10 s shared shutdown deadline. The 5 s default is therefore a policy that bounds admission, not a time derived from the buffer. When it expires, the listener logs a warning with unread_when_timed_out. The maintainer agreed to this on 2026-10-20 (design record entry 28). Persistence batching, which would raise the rate, is #2418. MySQL and PostgreSQL drain rates were not measured.

Real-binary results

With the sub-EPIC reproduce-lost-completions.sh and the T0 parameters, on the final code before the last rebase:

  • Control run, PEERS=500: 500 of 500 completions persisted (on develop before the fix: 467, 33 lost).
  • Race runs, PEERS=2000 SIGTERM_DELAY=0.5: 665 of 665 and 641 of 641 persisted (on develop: 790 and 775 lost).
  • With an HTTP and a UDP tracker, all seven listeners logged their drain line with the same fields.
  • Large race, PEERS=10000 SIGTERM_DELAY=3: a warning after 5 s with outcome="timed_out" processed=2020 unread_when_timed_out=6464.

Commands, toolchain, build profile, and outcomes are in manual-verification-evidence.md (V10, V11).

Packages touched

packages/events (the helper), packages/tracker-core, packages/swarm-coordination-registry, packages/http-core, packages/udp-core, packages/udp-server, the bootstrap jobs and src/app.rs that pass DEFAULT_DRAIN_TIMEOUT, the HTTP and UDP test environments, and the issue folder, sub-EPIC design record, and adr-draft.md under docs/issues/. Cargo.lock is unchanged from develop.

Validation

  • Every code commit tests green on its own tree; the last code commit: cargo test --workspace 3,167 passed and cargo test --workspace --all-targets 3,120 passed, 0 failed.
  • On the rebased branch: the pre-push checks, linter all, cargo machete --with-metadata, cargo deny check bans, and nightly cargo fmt --check all exit 0. The real-binary runs above were on the tree before the rebase and were not repeated after it.
  • Every new test was mutation-checked against the code it guards (V5, V7, V9, V11); mutations that did not compile are recorded as non-results.
  • Independent Task Reviewer report before push (REVIEW PASSED, two should-fix items and six nits, all resolved as the maintainer decided) and a re-review of the fixes (REVIEW PASSED WITH FINDINGS, three nits fixed) are in agent-review-reports.md. The implementation retrospective is implementation-retrospective.md.
  • The acceptance criteria in the spec are left unticked for the pull request reviewer.
  • The open-pull-request check for PR-branch commit ids in changed files printed nothing. No temporary local-only patches are included.

Not in this PR

Producer ordering, per-component cancellation tokens, and the shutdown deadline abort belong to sub-issues 3 and 4 (#2415 and #2416). A handler that panics during a drain is a non-goal.

Closes #2414

Related to #2410, #1488, #2418

Copilot AI balanced review requested due to automatic review settings October 20, 2026 16:48
@josecelano josecelano self-assigned this Oct 20, 2026
@josecelano
josecelano requested a review from da2ce7 October 20, 2026 16:49

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

3 open issues
What changed in this PR

This PR fixes a shutdown race where event listeners previously dropped already-queued events when cancelled, by introducing a shared drain policy and applying it across all listener components.

Changes:

  • Added a shared draining API in packages/events (Receiver::try_recv, len, TryRecvError, drain, DrainReport, DEFAULT_DRAIN_TIMEOUT, and log_drain_report!).
  • Updated all seven listeners to drain queued events on cancellation (within a configurable timeout) and to log standardized drain outcomes.
  • Reworked/added unit and integration tests to assert drained-on-cancel behavior and updated test environments to own and join listener tasks.
File Description
src/​bootstrap/​jobs/​udp_tracker_server.rs Plumbs DEFAULT_DRAIN_TIMEOUT into UDP server listeners at startup.
src/​bootstrap/​jobs/​udp_tracker_core.rs Plumbs DEFAULT_DRAIN_TIMEOUT into UDP core listener at startup.
src/​bootstrap/​jobs/​tracker_core.rs Plumbs DEFAULT_DRAIN_TIMEOUT into tracker-core listeners at startup.
src/​bootstrap/​jobs/​torrent_repository.rs Plumbs DEFAULT_DRAIN_TIMEOUT into swarm-coordination registry listener at startup.
src/​bootstrap/​jobs/​http_tracker_core.rs Plumbs DEFAULT_DRAIN_TIMEOUT into HTTP core listener at startup.
src/​app.rs Updates app test wiring to pass the drain timeout.
project-words.txt Adds tmpfs to spelling allowlist to satisfy linters/docs tooling.
packages/​udp-server/​src/​testing/​environment.rs Passes drain timeout through UDP server test environment listener setup.
packages/​udp-server/​src/​statistics/​event/​listener.rs Adds drain-on-cancel behavior + logging + updated tests for UDP server statistics listener.
packages/​udp-server/​src/​banning/​event/​listener.rs Adds drain-on-cancel behavior + logging + updated tests for UDP server banning listener.
packages/​udp-core/​src/​statistics/​event/​listener.rs Adds drain-on-cancel behavior + logging + updated tests for UDP core statistics listener.
packages/​tracker-core/​tests/​integration.rs Adds integration coverage for listener receiver release/cancellation and persistence on drained cancel.
packages/​tracker-core/​tests/​common/​test_env.rs Makes TestEnv own cancellation + listener JoinHandles; adds stop() that cancels and joins.
packages/​tracker-core/​src/​statistics/​event/​listener.rs Adds drain-on-cancel behavior for in-memory + persistent listeners and replaces old priority tests.
packages/​swarm-coordination-registry/​src/​statistics/​event/​listener.rs Adds drain-on-cancel behavior + logging + updated tests.
packages/​http-core/​src/​statistics/​event/​listener.rs Adds drain-on-cancel behavior + logging, re-exports drain timeout for downstream tests, updates tests.
packages/​http-core/​src/​services/​announce.rs Updates test helper listener startup call to pass drain timeout.
packages/​http-core/​benches/​helpers/​util.rs Updates benchmark setup to pass drain timeout.
packages/​events/​src/​receiver.rs Extends Receiver with non-blocking try_recv + len + TryRecvError.
packages/​events/​src/​lib.rs Exposes new drain module.
packages/​events/​src/​drain.rs Introduces shared drain implementation, reporting, and standardized drain logging macro + tests.
packages/​events/​src/​broadcaster.rs Implements try_recv/len + TryRecvError mapping for tokio broadcast receivers; adds tests.
packages/​events/​Cargo.toml Adds tokio test-util for drain tests using paused time.
packages/​axum-http-server/​src/​v1/​handlers/​announce.rs Uses DEFAULT_DRAIN_TIMEOUT re-export when starting listener in tests.
packages/​axum-http-server/​src/​testing/​environment.rs Uses DEFAULT_DRAIN_TIMEOUT re-export when starting listener in test environment.
packages/​axum-http-server/​src/​server.rs Uses DEFAULT_DRAIN_TIMEOUT re-export when starting listener in tests.
docs/​issues/​open/​2414-2410-si-22-2-drain-listener-queues-on-shutdown/​manual-verification-evidence.md Adds detailed validation evidence and measurements supporting the drain policy.
docs/​issues/​open/​2414-2410-si-22-2-drain-listener-queues-on-shutdown/​implementation-retrospective.md Documents implementation learnings and follow-ups.
docs/​issues/​open/​2414-2410-si-22-2-drain-listener-queues-on-shutdown/​evidence/​run_m1.py Adds a harness script used to produce manual verification evidence.
docs/​issues/​open/​2414-2410-si-22-2-drain-listener-queues-on-shutdown/​evidence/​m1-tracker.toml Adds sample config used for manual verification runs.
docs/​issues/​open/​2414-2410-si-22-2-drain-listener-queues-on-shutdown/​agent-review-reports.md Records independent review findings and follow-up actions.
docs/​issues/​open/​2414-2410-si-22-2-drain-listener-queues-on-shutdown/​ISSUE.md Updates task statuses/verification plan/AC evidence as work progressed.
docs/​issues/​open/​2410-1488-si-22-process-queued-events-before-listeners-stop/​adr-draft.md Updates ADR draft with finalized drain policy constraints and logging details.
docs/​issues/​open/​2410-1488-si-22-process-queued-events-before-listeners-stop/​EPIC.md Updates epic record entries with #2414’s agreed design decisions and findings.

Review effort: Lite

Comment thread packages/events/src/drain.rs Resolved
josecelano and others added 20 commits October 20, 2026 18:23
…ts listeners

TestEnv created a local CancellationToken and dropped the handles of its
three listeners, so no test could stop or wait for them. It now keeps the
token (behind a DropGuard, since dropping a token does not cancel it) and the
named handles. stop() cancels the token and joins every handle under one
absolute deadline, reports failures only after all handles are joined, and
aborts a handle that misses the deadline. Dropping the environment without
stop() cancels the listeners, but cannot wait for them.

Two tests cover it: the environment releases every swarm-bus listener when
stopped, and when dropped without stop(). Each was shown to fail when stop()
does not cancel, when it does not join, and when the drop guard is on another
token (V1 and V2 in manual-verification-evidence.md).

The startup sleep, yield_now, and the persistence polling stay: stop() still
discards the queue until the listener drain exists.

Co-authored-by: Copilot <[email protected]>
…3c regression tests

The two regression tests fail against the cancel-first listener loop, so they
are not committed until the T4c fix makes them pass. Their code is embedded
verbatim in manual-verification-evidence.md (V3 and V4) with the failing
command, the output, and the tree they ran on.

- T3a: a ready completed-download event with a pre-cancelled token is not
  persisted (left None, right Some(1)).
- T3c, N = 3: three queued completions with an already-cancelled listener are
  not persisted (left None, right Some(3)). A temporary uncancelled control
  persisted all three, so the cancellation causes the red.

The torrust#2414 and sub-EPIC progress logs record it; T3a and T3c are IN_PROGRESS.

Co-authored-by: Copilot <[email protected]>
… shared listener drain helper

The Receiver trait gains a non-blocking try_recv, len (the unread-position
count), a default is_empty, and a TryRecvError (Empty, Closed, Lagged) that
maps tokio's broadcast errors. Buffered events are delivered before Closed,
and len includes events already overwritten until a Lagged result advances the
receiver.

packages/events/src/drain.rs adds drain(receiver, timeout, handler): after a
listener is cancelled it takes the queued events with try_recv until the queue
is empty or the timeout expires. The timeout is an admission budget checked
only between events; an event that was taken is awaited to completion. Lagged
results are counted and the drain continues. It returns a DrainReport
(outcome, processed, lost_to_lag, unread_when_timed_out) and does not log.
DEFAULT_DRAIN_TIMEOUT (5 s) and the log_drain_report! macro give every listener
one policy and one log format; a macro, because tracing needs a constant target
and each package has its own.

The scripted test receivers of the six listener packages implement the new
methods, so the whole workspace compiles in this commit. The helper has seven
tests and the broadcast implementation four; each was shown to fail under a
mutation of the code it guards (V5 in manual-verification-evidence.md).

No listener uses the helper yet; the persistent listener does in the next
commit.

Co-authored-by: Copilot <[email protected]>
…ue when it is cancelled

The persistent completed-statistics listener checked its cancellation token
before reading its receiver, so a cancelled listener dropped every event
already queued for it: completed downloads the tracker had answered were never
written to the database. On cancellation it now takes the queued events with
the shared drain helper, persists each one, logs what it did, and returns
Cancelled. A closed receiver still returns Completed.

The drain timeout is injected through the listener's constructor functions and
passed from the application bootstrap as DEFAULT_DRAIN_TIMEOUT. It bounds how
long the listener keeps admitting events, not how long a handler runs. A drain
that is cut short, or that counts lag, logs a warning with the listener name and
the counts; the counts are events of every type on the swarm bus, not only
completions. The drain is its own function to keep the dispatch function under
the cognitive-complexity limit.

The two regression tests of the bug, red against the cancel-first loop and
recorded as such, are green: a queued completed download is persisted when
cancellation is already pending (replacing the test that asserted the bug), and
three completions queued before the listener is cancelled are all persisted
(package test, TestEnv::new, a real database). Two further tests check that the
listener returns Cancelled after draining and that an expired timeout leaves the
queue unprocessed. The tracker-core scripted receiver is now lazy like a real
receiver, because select! creates the recv future even when the cancellation
branch wins and an eager pop consumed the event before the drain. Each listener
test was shown to fail under a mutation (V7).

Co-authored-by: Copilot <[email protected]>
…ain design changes

The T4 design review (maintainer, 2026-10-20) agreed to the changes the T4
measurement and implementation called for, so the design record and the ADR
draft are updated in the same change (D14).

- manual-verification-evidence.md: V5 (the drain helper and the trait, with
  nine mutations), V6 (the release measurement: a full buffer of 65,536 events
  takes 12.5 to 14.4 s on tmpfs and 158 to 188 s on NVMe with SQLite), V7 (the
  listener drain, its mutations, and the findings), V8 (the real binary: the T0
  control run persists 500 of 500, the structured drain line, and the warning
  after a 5 s timeout), and the commits and corrections.
- Sub-EPIC: record entry 28; D9 (default 5 s, not derived from the time to
  drain a full buffer), D13 (the log macro, is_empty), and the Chosen Design
  (counts are events, not completions).
- adr-draft.md section 7: the same changes.
- torrust#2414 spec: T3a, T3c, T4a to T4c done, the T4 checkpoint ticked, and the
  progress logs.

Co-authored-by: Copilot <[email protected]>
…ener's queue when it is cancelled

The in-memory completed-downloads listener checked its cancellation token
before reading its receiver, so a cancelled listener dropped every queued
event. On cancellation it now handles the queued events with the shared drain
helper, within an injected drain timeout, logs what it did through
log_drain_report!, and returns Cancelled.

The timeout is a parameter of the listener's constructor functions and the
callers (the bootstrap job, the package test environment, and the application
test) pass DEFAULT_DRAIN_TIMEOUT. The drain is its own function.

The test that asserted the bug (it_should_prioritize_a_pre_cancelled_token_over_a_ready_in_memory_event)
is replaced by two: a queued event is counted and the listener returns
Cancelled, and an expired timeout leaves the event unprocessed and still
returns Cancelled. Each was shown to fail when the timeout is forced to zero,
never expires, the listener returns Completed, or the drain never runs (V9).

Co-authored-by: Copilot <[email protected]>
… listener's queue when it is cancelled

The swarm-coordination-registry statistics listener checked its cancellation
token before reading its receiver, so a cancelled listener dropped every queued
event. On cancellation it now handles the queued events with the shared drain
helper, within an injected drain timeout, logs what it did through
log_drain_report!, and returns Cancelled.

The timeout is a parameter of the listener's constructor functions; the
bootstrap job and the tracker-core test environment pass DEFAULT_DRAIN_TIMEOUT.
The drain is its own function, and the package's scripted receiver is now lazy
like a real receiver, because select! creates the recv future even when the
cancellation branch wins.

The test that asserted the bug (it_should_prioritize_pre_cancelled_token_over_a_ready_event)
is replaced by two: a queued event is counted and the listener returns
Cancelled, and an expired timeout leaves it unprocessed and still returns
Cancelled. Each was shown to fail when the timeout is forced to zero, never
expires, the listener returns Completed, or the drain never runs (V9).

Co-authored-by: Copilot <[email protected]>
…when it is cancelled

The HTTP tracker core statistics listener checked its cancellation token
before reading its receiver, so a cancelled listener dropped every queued
event. On cancellation it now handles the queued events with the shared drain
helper, within an injected drain timeout, logs what it did through
log_drain_report!, and returns Cancelled. The metrics policy applies to a
drained event as to a live one.

The timeout is a parameter of the listener's constructor functions. The
bootstrap job, the HTTP test environment, the announce handler and server
tests, the announce service test, and the benchmark helper pass
DEFAULT_DRAIN_TIMEOUT; axum-http-server gains a direct dependency on
torrust-tracker-events for it. The drain is its own function, and the
package's scripted receiver is now lazy like a real receiver.

The test that asserted the bug (it_should_prioritize_cancellation_over_a_ready_event)
is replaced by two: a queued scrape is counted and the listener returns
Cancelled, and an expired timeout leaves it unprocessed and still returns
Cancelled. A third checks that the metrics policy applies to a drained event.
Each was shown to fail under a mutation: the timeout forced to zero or never
expiring, the policy bypassed, Completed returned, or the drain never running
(V9).

Co-authored-by: Copilot <[email protected]>
…hen it is cancelled

The UDP tracker core statistics listener checked its cancellation token before
reading its receiver, so a cancelled listener dropped every queued event. On
cancellation it now handles the queued events with the shared drain helper,
within an injected drain timeout, logs what it did through log_drain_report!,
and returns Cancelled. The metrics policy applies to a drained event as to a
live one.

The timeout is a parameter of the listener's constructor functions. The
bootstrap job and the UDP server test environment's call to this listener pass
DEFAULT_DRAIN_TIMEOUT. The drain is its own function, and the package's
scripted receiver is now lazy like a real receiver.

The test that asserted the bug (it_should_prioritize_cancellation_over_a_ready_event)
is replaced by two: a queued connect event is counted and the listener returns
Cancelled, and an expired timeout leaves it unprocessed and still returns
Cancelled. A third checks that the metrics policy applies to a drained event.
Each was shown to fail under a mutation: the timeout forced to zero or never
expiring, the policy bypassed, Completed returned, or the drain never running
(V9).

Co-authored-by: Copilot <[email protected]>
…eners' queues when they are cancelled

The UDP tracker server statistics listener and its banning listener checked
their cancellation token before reading their receiver, so a cancelled
listener dropped every queued event. On cancellation each now handles the
queued events with the shared drain helper, within an injected drain timeout,
logs what it did through log_drain_report!, and returns Cancelled. The
statistics listener applies its metrics policy to a drained event as to a live
one; the banning listener, which has no such policy, counts every
connection-cookie error it drains.

The timeout is a parameter of both listeners' constructor functions. The
bootstrap jobs and the UDP test environment pass DEFAULT_DRAIN_TIMEOUT. Each
drain is its own function. Both scripted receivers popped their queue eagerly in
recv(); they are lazy now, like a real receiver, and the call count is taken
when the future is polled.

The two tests that asserted the bug (it_should_prioritize_cancellation_over_a_ready_event
in each listener) are replaced: a queued event is counted and the listener
returns Cancelled, and an expired timeout leaves it unprocessed and still
returns Cancelled; the statistics listener has a third test for the metrics
policy. Each was shown to fail under a mutation: the timeout forced to zero or
never expiring, the policy bypassed, Completed returned, or the drain never
running (V9). This completes T5: all seven listeners drain.

Co-authored-by: Copilot <[email protected]>
…to M3 recheck

- manual-verification-evidence.md: V9 (the six other listeners, one row of
  mutations per package) and V10, the like-for-like recheck of the original
  symptom on the real binary after the last production change. The T0 control
  run now persists 500 of 500 (T0: 467), both race runs persist everything they
  answered (T0: 790 and 775 lost), all seven listeners log their drain with the
  same fields, and a drain cut short logs the warning after 5 s. The harness and
  configuration of the run with a UDP tracker are in the evidence folder; two
  slips (a UDP client argument and ports) are recorded.
- torrust#2414 spec: T5 done, M1 to M3 done, the Acceptance Verification table filled
  in (the criteria stay unticked for the reviewer), and the progress log.
- Sub-EPIC progress log.

Co-authored-by: Copilot <[email protected]>
…, and yield between events

Two defects the independent review of torrust#2414 found in the shared drain helper.

- Overflow: drain added its timeout to the current time with `+`, which panics
  for a Duration the clock cannot hold (verified: tokio's Instant + Duration::MAX
  gives "overflow when adding duration to instant"). A large configured timeout,
  which SI-20 will allow, would have panicked during shutdown. The deadline is
  now computed with checked_add, and a timeout too large to represent never
  expires.
- Starvation: a handler that never waits kept the drain running until its
  timeout expired, holding the worker thread (the spec asks for cooperative
  scheduling to be tested). The drain now yields to the runtime after each
  handled event.

Each has a regression test that was red before the fix: it panicked with the
overflow message, and no other task ran during a drain of 100 ready events.
Receiver::is_empty, a default method nobody tested, has a test too (shown to fail
when the default is inverted).

The new yield changed the drop-path test of the package TestEnv: its helper
published a probe event on every turn, so a draining listener kept finding a new
event until its 5 s timeout. The probe is now published at spaced intervals; the
drop guard mutation still fails the test (V11).

Co-authored-by: Copilot <[email protected]>
…ut instead of adding a dependency

axum-http-server gained a direct dependency on torrust-tracker-events only so its
test environment and two test modules could pass DEFAULT_DRAIN_TIMEOUT to the
HTTP statistics listener. http-core already depends on events and owns that
listener, so it now re-exports the constant from its listener module, and the
new dependency edge (the manifest line and its Cargo.lock entry) is removed.

The maintainer chose this over keeping the edge when the independent review of
torrust#2414 flagged it as an unrecorded design change (D14).

Co-authored-by: Copilot <[email protected]>
…add causal assertion messages

Two nits of the independent review of torrust#2414.

- The six scripted test receivers imported TryRecvError inside their try_recv
  function; the repository keeps imports at the top of the module, so they
  import it next to RecvError.
- The metric assertions of the new listener tests said only that two numbers
  differed. They now name what was counted (or left at zero) and after what,
  as do the two shared helpers behind the in-memory and swarm tests.

No behavior changes.

Co-authored-by: Copilot <[email protected]>
…er report, and the retrospective

Add the independent Task Reviewer report and the implementation
retrospective, the final real-binary recheck (V11), design record entry 29,
and the progress-log entries.

Co-authored-by: Copilot <[email protected]>
… yield

Record the cost of yielding after every drained event (V12), keep the
behavior, and say why in the drain comment and the ADR draft. Set the
spec's related-pr to 2578.

Co-authored-by: Copilot <[email protected]>
@josecelano
josecelano force-pushed the 2414-drain-listener-queues-on-shutdown branch from af933a7 to 147a22c Compare October 20, 2026 17:28
@josecelano

Copy link
Copy Markdown
Member Author

ACK 147a22c

@josecelano
josecelano merged commit f8e3bb2 into torrust:develop Oct 20, 2026
36 checks passed
josecelano added a commit that referenced this pull request Oct 20, 2026
…ssues/closed

5782782 chore(issues): archive closed issue #2414 spec to docs/issues/closed (Jose Celano)

Pull request description:

  Archives the spec of issue #2414 (SI-22.2, drain listener queues on shutdown) from `docs/issues/open/` to `docs/issues/closed/`, after PR #2578 merged on 2026-10-20 and the issue was closed on GitHub. This is a documentation-only change.

  - Verified before starting: issue #2414 is `CLOSED`, PR #2578 is `MERGED`, and no review arrived after the merge (the only review is Copilot's, whose three threads were replied to and resolved before the merge).
  - The spec frontmatter is `status: done` with the new `spec-path` and `last-updated-utc`, and the workflow checkpoint is ticked. At the maintainer's instruction the acceptance criteria AC1 to AC7 and the `linter all` criterion are ticked, counting his review and merge as the acceptance review; the qualifications stay in the Acceptance Verification table. The spec's progress log records both.
  - The relative links of the moved files to the sub-EPIC now point at `../../open/2410-...`, and the supplementary files' `related-artifacts` use the new path. All relative links in the moved folder resolve (checked by script, because `docs/issues/closed/` is not covered by the link checker).
  - The sub-EPIC's Subissues row 2 links the archived spec and is `DONE`, with a progress-log entry. The `related-artifacts` path in the archived #1348 refactor plan is updated.
  - Deliberately retained: the old path in the archived #2536 spec, line 594. It records which specs were open when #2536 was written.
  - No source, test, or configuration file changes. `linter all` and the pre-commit and pre-push checks pass.

  Related to #2414, #2410, #1488

ACKs for top commit:
  josecelano:
    ACK 5782782

Tree-SHA512: 00bbb8c8e3c6f5efc146ffcddb78c450a557aa5008b5538b22bd505d899b3873c6593e7e9864f287c2bb7d1356733b7c3033ff9cbee247b98780f796b14497ad
josecelano added a commit that referenced this pull request Oct 24, 2026
…its spec to docs/issues/closed

c19fca7 chore(issues): [#2410] close sub-EPIC SI-22 and archive its spec to docs/issues/closed (Jose Celano)

Pull request description:

  ## Summary

  Closes #2410

  All four sub-issues of sub-EPIC #2410 (SI-22, process queued events before listeners stop) are merged and archived: #2413 in PR #2553, #2414 in PR #2578, #2415 in PR #2591, and #2416 in PR #2623. This PR closes the sub-EPIC itself, which was still open on GitHub with its acceptance criteria and workflow checkpoints unticked and its completion review unassessed. It follows the precedent of PR #2557 (EPIC #2243): the archive and the closing keyword travel together.

  ## What changed

  - Moved `docs/issues/open/2410-1488-si-22-process-queued-events-before-listeners-stop/` to `docs/issues/closed/` with `git mv`, set the EPIC to `status: done` with the new `spec-path`, and kept `reproduce-lost-completions.sh` in the folder (the maintainer decided to keep it at the #2416 checkpoint).
  - Filled the Acceptance Verification table (AC1 to AC13) with the artifact behind each criterion, ticked the criteria and workflow checkpoints, marked M2 and M3 done with their evidence, and filled the Implementation Completion Review. Qualifications are kept, not dropped: the 5 s drain default is a policy choice and not derived from the measurement, the race runs do not prove loss window (b), a shared-deadline abort leaves an in-progress outcome unknown, the UDP environment's red is by mutation, and bus retention through listener join is read from source and not run.
  - Added `agent-review-reports.md` with the independent Task Reviewer review of this close-out (verdict `REVIEW PASSED WITH FINDINGS`, 3 should-fix and 4 nits, all fixed in this commit).
  - Repaired every live link to the old folder (the four archived sub-issue specs and their retrospectives and evidence files, the #2412 and #2448 specs, the glossary, and the promoted ADR) and bumped `last-updated-utc` on each touched document that carries it.
  - Set row 15 of the EPIC #1488 roadmap to `Done` and updated the three SI-22 statements in that spec that still described it as pending.
  - Repointed the draft-ADR reference in the #2418 spec to the promoted ADR.

  ## Acceptance

  The criteria and checkpoints are ticked in advance of the merge, as in #2557, and the progress-log entry says so: the maintainer's review and merge of this PR are the acceptance review, as for #2414 to #2416. If the review changes any criterion, it should be unticked before the merge.

  ## Deliberately retained references

  The old folder path remains only in historical records: two recorded commands in the sub-EPIC and #2414 evidence files, the "moved to" checkpoint text in the EPIC, and the review audits under `docs/pr-reviews/` (`pr-2421-review`, `pr-2553-review`).

  ## Not part of this PR

  Follow-ups #2418 (batch persisted download writes) and #2411 (spam and abuse EPIC) stay open and do not block this close-out. #2406 and #2417 are already closed. No sub-EPIC-level implementation retrospective was written, and the completion review gives the reason.

  ## Validation

  - `linter all` exits 0, including the local link and fragment check, which skips `docs/issues/closed/`, so the archived files were also checked with lychee and an empty config: 100 links OK, 0 errors.
  - The signed commit passed the pre-commit hook, including the frontmatter validator and `cargo test --doc --workspace`.
  - `git merge-tree` against `torrust/develop` shows a clean merge.
  - Documentation only: no code changed. No tests were re-run beyond the hook's doc tests; the acceptance claims about tests cite the sub-issues' recorded runs and the test names found on the tree (read from source, not run).

ACKs for top commit:
  josecelano:
    ACK c19fca7

Tree-SHA512: de784fead66e0eb1b6b9b7bf7e7aea9d29a2a3dbd297740752d23eca6fbaa700f20926e81033fdc06d31b72ff0f00302f522df7bce8354de87a3c9d48a0c7121

@da2ce7 da2ce7 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a post-merge review of the change from #2578 as it stands at 39d6d7e1b on the default branch.

What still runs: packages/events keeps Receiver::try_recv, Receiver::len, TryRecvError, the drain helper, DrainReport and log_drain_report!, unchanged since the merge apart from documentation (805dc65). All seven statistics and banning listeners still drain their queue through drain when cancelled, with the same handler as the live path, and then return Completion::Cancelled. Since f693ca6 and 41bb8c6 the application passes the configured application.shutdown.event_listener_drain_in_secs instead of DEFAULT_DRAIN_TIMEOUT, and since 59c9ce8 every producer stops before the listeners of the buses it publishes on, so the drain now runs on a bus that no longer grows. The drain racing live producers at the merge is therefore history. #3043 (70fcad0) changed how the http-core, udp-core and udp-server statistics listeners log an event their metrics policy skips; drained events take the same path, and the drain itself is untouched.

[Minor] A listener drain that runs out of budget is reported as a clean stop. Each listener logs the DrainReport, discards it and returns Completion::Cancelled unconditionally (for the persistent completed-downloads listener, packages/tracker-core/src/statistics/event/listener.rs:136-144 and :173-189; the other six listeners have the same shape, for example packages/http-core/src/statistics/event/listener.rs:75-80). component_runner maps that to ComponentCompletion::Cancelled (src/app.rs:586-590), which shutdown_exit_code counts as graceful (src/bootstrap/jobs/manager.rs:96-110). A server whose drain budget expires is mapped to a component error instead (src/bootstrap/jobs/token_aware_server.rs:86), and the exit-code decision Q3 in docs/features/shutdown-process/questions.md states that a timeout is not a successful graceful shutdown and that supervisors and automation must detect it. Concrete sequence: the tracker stops with SQLite on disk while more completed downloads are queued on the swarm bus than the budget can admit (the description of #2578 measures about 350 to 415 events/s, so roughly 2,000 for the 5-second default). The persistent listener logs outcome=timed_out with unread_when_timed_out above zero, the remaining completions never reach the database, and the process still exits 0, so a restart-on-failure policy or any other exit-code check sees a clean shutdown. Smallest fix: return the report from the drain_* helpers and, when outcome == DrainOutcome::TimedOut, return a distinct terminal state (for example a new Completion variant) that component_runner maps to a ComponentError, as token_aware_server.rs:86 does for servers. At least the persistent listener should do this, because the events it drops are persisted data.

[Minor] log_drain_report! is exported by a published crate but expands to bare tracing::warn! and tracing::info! (packages/events/src/drain.rs:142 and :152), while torrust-tracker-events does not depend on tracing (packages/events/Cargo.toml:20-22). The macro therefore compiles only in a crate that itself depends on tracing under that name: a downstream crate without it gets an unresolved-crate error at the call site. The doc example is marked ignore, so no doctest catches this. Smallest fix: add tracing to the crate's dependencies, re-export it under a hidden path (for example #[doc(hidden)] pub use tracing as __tracing;) and call $crate::__tracing::warn! and $crate::__tracing::info! in the macro.

[Nit] The doc comment on the re-export at packages/http-core/src/statistics/event/listener.rs:8 still calls DEFAULT_DRAIN_TIMEOUT the drain timeout the application gives every listener. Since 41bb8c6 the application passes the configured event_listener_drain(), and the constant is the default for standalone listeners and the test environments, as the updated text at packages/events/src/drain.rs:20-29 says. Smallest fix: reword the comment to match.

[Nit] In the tracker-core test environment, LISTENERS_STOP_TIMEOUT is 5 s (packages/tracker-core/tests/common/test_env.rs:24), the same as the DEFAULT_DRAIN_TIMEOUT the environment passes to every listener (:159, :167, :188). In a test that queues more events than a drain admits in 5 s, stop() reports that a listener did not stop within 5 s and aborts it mid-handler, instead of the drain reporting its own timeout. The application avoids this by requiring the drain budgets to stay below the shutdown deadline (packages/configuration/src/v3_0_0/shutdown.rs:221). Smallest fix: derive the stop timeout from DEFAULT_DRAIN_TIMEOUT plus a margin.

Checked and found sound: the drain checks its admission budget before each take and never races a taken event against it, yields after each handled event, counts Lagged as lost and keeps going, delivers buffered events before Closed, and treats a budget too large for the clock as unbounded; the try_recv and len mappings onto the tokio broadcast receiver follow tokio's semantics; each listener's biased select! builds its recv future lazily from a cancel-safe receive, so taking the cancellation branch drops no event; every drained event goes through the live handler, metrics policy included; every bootstrap site passes the configured budget, which a source-level test in src/bootstrap/jobs/mod.rs pins; and the regression test at packages/tracker-core/tests/integration.rs:396 checks both the per-torrent and the global database counts after three completions queued before cancellation.

This branch was previously deployed

1 inactive deployment
coverage — 147a22cf Deployed Oct 20, 2026 by josecelano via Generate Coverage Report #2642
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Drain listener queues on shutdown

3 participants