Skip to content

Fix per-instance event metrics policy - #2064

Merged
josecelano merged 17 commits into
torrust:developfrom
josecelano:2039-normalize-per-instance-event-metrics-policy
Aug 19, 2026
Merged

josecelano merged 17 commits into
torrust:developfrom
josecelano:2039-normalize-per-instance-event-metrics-policy

Conversation

@josecelano

Copy link
Copy Markdown
Member

Summary

Normalizes tracker_usage_statistics as a per-listener aggregate-metrics policy while preserving policy-neutral event publication and UDP banning.

  • Propagates canonical ConfigurationInstanceId through HTTP, UDP core, and UDP server event contexts.
  • Keeps shared event streams enabled; filters aggregate repositories in the corresponding metrics listeners instead.
  • Preserves UDP cookie-error delivery to banning independently of metrics policy.
  • Adds explicit nested integration targets with isolated port-zero error and banning scenarios.
  • Records reproducible baseline/final evidence, including the tracked forged-cookie probe.

Fixes #2039.

Validation

  • linter all
  • Pre-commit and pre-push hooks
  • HTTP/UDP core and UDP server tests
  • Explicit aggregate-policy integration targets:
    • metrics-fixed-ports
    • metrics-port-zero
    • metrics-udp-error-enabled-port-zero
    • metrics-udp-error-disabled-port-zero
    • banning-udp-metrics-disabled-port-zero

Notes

The implementation keeps one shared aggregate repository per layer. Listener identity is a filter key only; it is not introduced as a public metric label.

Copilot AI lite review requested due to automatic review settings August 19, 2026 11:24
@josecelano josecelano self-assigned this Aug 19, 2026
@codecov

codecov Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.45308% with 19 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.66%. Comparing base (d00bd1b) to head (a62953b).
⚠️ Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
packages/udp-server/src/server/launcher.rs 72.54% 14 Missing ⚠️
...ckages/udp-server/src/statistics/event/listener.rs 96.36% 2 Missing ⚠️
...ackages/http-core/src/statistics/event/listener.rs 98.00% 1 Missing ⚠️
packages/test-helpers/src/udp.rs 98.00% 0 Missing and 1 partial ⚠️
packages/udp-core/src/statistics/event/listener.rs 98.03% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #2064      +/-   ##
===========================================
+ Coverage    82.24%   82.66%   +0.42%     
===========================================
  Files          349      349              
  Lines        25142    25732     +590     
  Branches     25142    25732     +590     
===========================================
+ Hits         20677    21271     +594     
+ Misses        4154     4151       -3     
+ Partials       311      310       -1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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.

Pull request overview

This PR implements per-listener metrics policy (tracker_usage_statistics) by always publishing HTTP/UDP objective events with canonical ConfigurationInstanceId, then applying listener-side filtering in the aggregate metrics listeners (while keeping UDP banning independent of metrics policy). It also adds focused application-level integration tests and supporting evidence artifacts to validate the policy across fixed ports, port-zero duplicates, and UDP cookie-error / banning scenarios.

Changes:

  • Propagate ConfigurationInstanceId through HTTP core, UDP core, and UDP server event contexts so consumers can identify the originating listener reliably (including repeated 0.0.0.0:0 blocks).
  • Replace producer-side stats gating with consumer-side filtering (run_event_listener_with_metrics_policy) for shared aggregate repositories, while keeping banning fed by the unfiltered UDP server event stream.
  • Add/reshape integration tests (explicit [[test]] targets) plus documentation/evidence artifacts to validate enabled/disabled metrics behavior and banning independence.

Reviewed changes

Copilot reviewed 45 out of 45 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
tests/metrics/udp_error_enabled_port_zero.rs New integration test asserting UDP cookie errors are counted when metrics are enabled for a port-zero listener.
tests/metrics/udp_error_disabled_port_zero.rs New integration test asserting UDP cookie errors are not counted when metrics are disabled for a port-zero listener.
tests/metrics/port_zero.rs Updates port-zero integration coverage to enabled/disabled filtering using canonical identity (expects aggregate count 1).
tests/metrics/fixed_ports.rs Updates fixed-port integration coverage to enabled/disabled filtering and adds UDP operational counter assertions.
tests/common/workspace.rs Adds identity-based UDP socket address discovery helper for integration tests.
tests/common/statistics.rs Extends partial stats struct to include UDP operational/banning counters used by new tests.
tests/common/mod.rs Refactors common test re-exports; introduces shared configuration fixture and uses test-helper UDP functions.
tests/common/configuration.rs Adds shared TOML fixture + canonical IDs for port-zero enabled/disabled listener scenarios.
tests/common/announce.rs Removes local announce wrappers (now delegated via torrust_tracker_test_helpers).
tests/banning/udp_metrics_disabled_port_zero.rs New integration test ensuring banning still updates shared ban metrics even when listener metrics are disabled.
tests/AGENTS.md Updates integration-test guidance and references for the new test layout (YAML metadata updated).
src/container.rs Passes canonical instance IDs into HTTP/UDP core container initialization.
src/bootstrap/jobs/udp_tracker_server.rs Always starts UDP server stats listener and injects immutable per-instance metrics policy map; banning listener remains unfiltered.
src/bootstrap/jobs/udp_tracker_core.rs Always starts UDP core stats listener with per-instance metrics policy map.
src/bootstrap/jobs/http_tracker_core.rs Always starts HTTP core stats listener with per-instance metrics policy map.
packages/udp-server/src/statistics/event/listener.rs Adds metrics-policy-aware listener entry point and filters aggregate updates by configuration instance ID.
packages/udp-server/src/server/processor.rs Publishes UDP server events with canonical configuration instance ID in the connection context.
packages/udp-server/src/server/launcher.rs Refactors request discard/ban early-exit logic and publishes UDP server events with canonical configuration instance ID.
packages/udp-server/src/handlers/scrape.rs Publishes scrape accept/error events with canonical configuration instance ID.
packages/udp-server/src/handlers/mod.rs Threads configuration instance ID into error handling entrypoints.
packages/udp-server/src/handlers/error.rs Publishes UDP error events with canonical configuration instance ID.
packages/udp-server/src/handlers/connect.rs Publishes connect accept events with canonical configuration instance ID.
packages/udp-server/src/handlers/announce.rs Publishes announce accept/error events with canonical configuration instance ID.
packages/udp-server/src/container.rs Ensures UDP server event bus sender is always enabled (metrics policy no longer gates publication).
packages/udp-core/src/statistics/event/listener.rs Adds metrics-policy-aware listener entry point and filters aggregate updates by configuration instance ID.
packages/udp-core/src/services/scrape.rs Adds per-instance identity to emitted UDP core scrape events.
packages/udp-core/src/services/connect.rs Adds per-instance identity to emitted UDP core connect events.
packages/udp-core/src/services/announce.rs Adds per-instance identity to emitted UDP core announce events.
packages/udp-core/src/event.rs Extends UDP core ConnectionContext to carry canonical configuration instance identity.
packages/udp-core/src/container.rs Ensures UDP core event bus sender is always enabled; wires per-instance IDs into services.
packages/test-helpers/src/udp.rs Adds UDP invalid-connection-id helpers for cookie-error and ban enforcement testing.
packages/http-core/src/statistics/event/listener.rs Adds metrics-policy-aware listener entry point and filters aggregate updates by configuration instance ID.
packages/http-core/src/services/scrape.rs Adds per-instance identity to emitted HTTP core scrape events.
packages/http-core/src/services/announce.rs Adds per-instance identity to emitted HTTP core announce events.
packages/http-core/src/event.rs Extends HTTP core ConnectionContext to carry canonical configuration instance identity.
packages/http-core/src/container.rs Ensures HTTP core event bus sender is always enabled; wires per-instance IDs into services.
packages/events/src/bus.rs Clarifies SenderStatus semantics and updates related test name/docs.
docs/issues/open/2039-normalize-per-instance-event-metrics-policy/ISSUE.md Updates issue spec status, tasks, acceptance criteria, and links to new tests/artifacts.
docs/issues/open/2039-normalize-per-instance-event-metrics-policy/evidence.md Records baseline/final evidence and automation commands for per-instance metrics + banning verification.
docs/issues/open/2039-normalize-per-instance-event-metrics-policy/evidence-artifacts/port-zero-manual.toml Adds reproducible manual port-zero configuration artifact.
docs/issues/open/2039-normalize-per-instance-event-metrics-policy/evidence-artifacts/invalid_cookie_probe.py Adds reproducible manual invalid-cookie probe script for banning scenario.
docs/issues/open/2039-normalize-per-instance-event-metrics-policy/evidence-artifacts/fixed-port-manual.toml Adds reproducible manual fixed-port configuration artifact.
docs/issues/open/2035-fix-duplicate-port-zero-tracker-instance-bootstrap/ISSUE.md Updates references to renamed/moved metrics integration tests.
docs/events-architecture.md Updates event architecture doc to reflect objective-facts publication + consumer-side policy filtering.
Cargo.toml Registers explicit named integration test targets for the new metrics/banning test binaries.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread tests/AGENTS.md Resolved
@josecelano
josecelano requested a review from a team as a code owner August 19, 2026 11:36
@josecelano
josecelano force-pushed the 2039-normalize-per-instance-event-metrics-policy branch from 085be2c to 9a4de2a Compare August 19, 2026 18:23
@josecelano
josecelano requested a lite review from Copilot August 19, 2026 18:24

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.

Pull request overview

Copilot reviewed 74 out of 74 changed files in this pull request and generated no new comments.

Suppressed comments (6)

tests/AGENTS.md:10

  • The YAML frontmatter related-artifacts list is accidentally nested under tests/metrics/fixed_ports.rs due to indentation, which makes the frontmatter invalid / changes its meaning.
    packages/http-core/src/statistics/event/listener.rs:62
  • Metrics-disabled listeners are an expected configuration, but the event listener logs them at WARN and also conflates them with truly unknown configuration IDs. This can spam logs and create false-positive alerts in deployments that intentionally disable metrics per listener.
                    Ok(event) => {
                        tracing::warn!(
                            target: HTTP_TRACKER_LOG_TARGET,
                            configuration_instance_id = ?event_connection_id(&event),
                            "Ignoring HTTP tracker event from an unknown or metrics-disabled listener"
                        );
                    }

packages/udp-core/src/statistics/event/listener.rs:62

  • Metrics-disabled UDP listeners are a valid configuration, but this listener logs every ignored event at WARN and also treats disabled listeners the same as unknown IDs. That can flood logs and makes it harder to spot real misconfiguration (unknown IDs).
    packages/udp-server/src/statistics/event/listener.rs:63
  • Metrics-disabled UDP listeners are expected, but this stats listener logs every ignored event at WARN and conflates metrics-disabled with unknown configuration IDs. That can produce noisy logs and hides the important case (unknown ID) among expected traffic.
    docs/issues/open/2039-normalize-per-instance-event-metrics-policy/evidence-artifacts/invalid_cookie_probe.py:71
  • socket.settimeout() raises socket.timeout on receive, which is not guaranteed to be caught by except TimeoutError across Python versions. This can make the probe fail even when the tracker correctly bans the request.
        client.send(invalid_announce(12, source_port))
        try:
            client.recv(2048)
        except TimeoutError:
            print("PASS: the twelfth invalid request timed out after shared ban enforcement")
            return

tests/common/configuration.rs:52

  • send_invalid_connection_ids_until_banned assumes the ban threshold behavior driven by max_connection_id_errors_per_ip, but this shared port-zero fixture relies on the configuration default instead of setting the value explicitly. Making it explicit in the fixture keeps the integration tests deterministic if the default changes.

@josecelano

Copy link
Copy Markdown
Member Author

ACK a62953b

@josecelano
josecelano merged commit 7bd2dad into torrust:develop Aug 19, 2026
19 checks passed
josecelano added a commit that referenced this pull request Oct 16, 2026
… SI-24 alongside SI-22

#2039 was closed on 2026-08-19 after PR #2064 implemented it, so the #1419
follow-up no longer waits on it. The maintainer agreed on 2026-10-15 that
SI-23 and SI-24 may run alongside SI-22.

Co-authored-by: Copilot <[email protected]>
josecelano added a commit that referenced this pull request Oct 16, 2026
…nment when dropped without stop()

af3e157 docs(pr-reviews): [#2544] record the second review round in the audit (Jose Celano)
b174608 docs(pr-reviews): [#2544] correct the audit's head citation and its F4, F5 and F7 entries (Jose Celano)
afdbbc9 docs(issues): [#2471] record that the REST and health-check legacy drops do not stop the server either (Jose Celano)
c7a721e docs(issues): [#2471] mark V1's hypothesis as disproved (Jose Celano)
43a13a2 docs(issues): [#2471] cite review findings by their review-finding reference (Jose Celano)
3115012 docs(pr-reviews): add the PR #2544 review audit (Jose Celano)
0e7ed96 docs(issues): [#1488] keep roadmap row 14 Planned until the #2471 spec is archived (Jose Celano)
bbac249 docs(issues): [#2471] leave the acceptance criteria to the reviewer and mark the spec in progress (Jose Celano)
7e78178 docs(issues): [#2471] record the passed pre-commit and pre-push checks in the spec (Jose Celano)
37aa086 docs(issues): [#2471] correct the history: the HTTP drop gap predates SI-16 (Jose Celano)
eaa2401 docs(axum-http-server): [#2471] say that dropping the test environment requests cancellation (Jose Celano)
75c7be0 docs(issues): [#1488] mark #2471 done in the shutdown roadmap (Jose Celano)
096fb8f fix(axum-http-server): [#2471] stop the HTTP test environment when dropped without stop() (Jose Celano)
44eb6bb docs(issues): [#1488] refresh the #1419 follow-up and allow SI-23 and SI-24 alongside SI-22 (Jose Celano)

Pull request description:

  Closes #2471

  Part of EPIC #1488 (Overhaul: Tracker Shutdown), roadmap row 14.

  ## Summary

  Dropping a running `axum-http-server` test environment without calling `stop()` left its HTTP server running and its address bound, because dropping a `CancellationToken` does not cancel it. The gap predates SI-16 (#2412): before it, dropping the halt sender only made the shutdown task panic, so the server kept serving too (checked by running the drop test on the tree before SI-16). The UDP test environment was fixed during the SI-17 review, and this aligns HTTP with it. An earlier version of this description and of the spec called it a regression from SI-16; the review showed that was wrong and the records are corrected.

  The running state now holds the token as a `DropGuard`, and `stop()` disarms it before cancelling and joining exactly as before. Dropping a running environment cancels the token, so the binding is released shortly after the drop. The impact was test-only: each `#[tokio::test]` has its own runtime, so the leak lasted until the end of the test.

  ## Commits

  1. `docs(issues): [#1488] refresh the #1419 follow-up and allow SI-23 and SI-24 alongside SI-22`: removes the stale statement that #1419 still waits on #2039 (closed after PR #2064), and records the maintainer's agreement of 2026-10-15 that SI-23 and SI-24 may run alongside SI-22.
  2. `fix(axum-http-server): [#2471] stop the HTTP test environment when dropped without stop()`: the fix and the regression test, with the #2471 spec and evidence.
  3. `docs(issues): [#1488] mark #2471 done in the shutdown roadmap`: superseded by commit 8, which restores Planned.

  Review-round commits:

  4. `docs(axum-http-server): [#2471] say that dropping the test environment requests cancellation`
  5. `docs(issues): [#2471] correct the history: the HTTP drop gap predates SI-16`: corrects the spec, the evidence (new V4), the EPIC roadmap and the SI-23 and SI-24 specs, and the GitHub issue body.
  6. `docs(issues): [#2471] record the passed pre-commit and pre-push checks in the spec`
  7. `docs(issues): [#2471] leave the acceptance criteria to the reviewer and mark the spec in progress`
  8. `docs(issues): [#1488] keep roadmap row 14 Planned until the #2471 spec is archived`
  9. `docs(pr-reviews): add the PR #2544 review audit`: the audit record `docs/pr-reviews/pr-2544-review/PR-REVIEW.md`.

  Second review round (non-blocking findings):

  10. `docs(issues): [#2471] cite review findings by their review-finding reference`
  11. `docs(issues): [#2471] mark V1's hypothesis as disproved`
  12. `docs(issues): [#2471] record that the REST and health-check legacy drops do not stop the server either`
  13. `docs(pr-reviews): [#2544] correct the audit's head citation and its F4, F5 and F7 entries`
  14. `docs(pr-reviews): [#2544] record the second review round in the audit`

  ## Files and packages touched

  - `packages/axum-http-server/src/testing/environment.rs`
  - `docs/issues/open/2471-1488-fix-http-environment-drop-path/` (spec, `manual-verification-evidence.md`, `evidence/`)
  - `docs/issues/open/1488-overhaul-tracker-shutdown/ISSUE.md`
  - `docs/issues/open/2449-1488-si-23-migrate-rest-api-test-environment/ISSUE.md` and `docs/issues/open/2450-1488-si-24-migrate-health-check-api-test-environment/ISSUE.md` (drop-path note)
  - `docs/pr-reviews/pr-2544-review/PR-REVIEW.md`

  ## Validation

  - Regression test `it_should_release_the_http_binding_when_dropped_without_being_stopped` was recorded red before the fix (the binding was still taken after 10.02 s) and green after (evidence V2 and V3). The same drop test on the tree before SI-16 also times out (V4).
  - The 7 environment tests, the 44 unit tests and the 62 integration tests of `torrust-tracker-axum-http-server` pass, and clippy with `-D warnings` is clean.
  - The pre-commit hook passed on every commit, and the pre-push checks (nightly fmt, check and docs, plus the full stable test suite) passed on each push.
  - The design-review checkpoint is recorded in the #2471 progress log.

  Not done yet: the acceptance criteria are left for the reviewer, and the issue close-out and the move of the spec to `docs/issues/closed/` follow after review.

ACKs for top commit:
  da2ce7:
    ACK af3e157 — the six round-2 findings recomputed as resolved, the commit-id check empty, and the audit record's new rows F10–F15 checked against their comments, replies and threads.
  josecelano:
    ACK af3e157

Tree-SHA512: 407294cfbab53fbbb7f6bf6ef5297e143d8feaf603f903db35d218c58d810fbde8d27e623e583e9c64d774239cc6a1fc3517c1c137f88e2443fa38e1304868f9

@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 #2064 as it stands at a94c3ced8 on the default branch.

What still runs: the HTTP core, UDP core and UDP server event buses are always enabled (packages/http-core/src/container.rs:127, packages/udp-core/src/container.rs:187, packages/udp-server/src/container.rs:52), and every event carries the ConfigurationInstanceId of the tracker block that produced it. The three statistics listeners receive an immutable instance-to-policy map built from each tracker block's own tracker_usage_statistics (src/bootstrap/jobs/http_tracker_core.rs:17, src/bootstrap/jobs/udp_tracker_core.rs:17, src/bootstrap/jobs/udp_tracker_server.rs:26). They drop events from disabled instances before those events reach the shared repository (packages/http-core/src/statistics/event/listener.rs:136, packages/udp-core/src/statistics/event/listener.rs:133, packages/udp-server/src/statistics/event/listener.rs:132). The UDP banning listener reads the same unfiltered stream, so cookie errors through a statistics-disabled listener still count towards the shared ban. The change logged a WARN line for each event it ignored; commit 70fcad0 (#3043) replaced that with a trace! line, so that is history and not raised here.

[Minor] The global core.tracker_usage_statistics key no longer controls the HTTP and UDP request counters, but its documentation and the default container template still treat it as if it did. Since #2064 those counters follow only the per-tracker tracker_usage_statistics, which defaults to false (packages/configuration/src/v3_0_0/http_tracker.rs:74, packages/configuration/src/v3_0_0/udp_tracker.rs:63). The doc comment at packages/configuration/src/v3_0_0/core.rs:51 still says the core key collects "the number of connections handled, the number of announce requests handled". share/default/config/tracker.container.no-persistence.toml is the template that share/container/entry_script_sh:61 installs when no database driver is chosen. It sets tracker_usage_statistics = true under [core] (line 13) but leaves its [[udp_trackers]] and [[http_trackers]] blocks (lines 34 and 37) at the per-tracker default. A container started from that template therefore reports tcp4_announces_handled, udp4_connections_handled, udp4_announces_handled and the other request counters as 0 whatever traffic it serves, although its configuration reads as statistics on. A configuration written before #2064 that sets only the core key loses these counters in the same way after an upgrade. Smallest fix: make the doc comment of Core::tracker_usage_statistics say which statistics it still governs (the swarm and tracker-core statistics) and point to the per-tracker key for request counters. If the template is meant to collect request counters, also add tracker_usage_statistics = true to its two tracker blocks.

[Nit] tests/metrics/udp_error_disabled_port_zero.rs:33 checks that udp4_errors_handled is unchanged as soon as the error response arrives, but the UDP server statistics listener handles the error event in a separate task. With the filter removed, the test would still pass whenever the REST read ran before that task handled the event, so it shows less than its name claims. Smallest fix: after the request to the disabled listener, send one invalid connection ID through the enabled listener of the same configuration, poll until udp4_errors_handled rises, then assert that it rose by exactly one. Both events pass through one broadcast channel in order, so once the second one is counted the first has already been handled.

[Nit] The change left three public constructors with parameters they no longer read: UdpTrackerServerContainer::initialize(_core_config) at packages/udp-server/src/container.rs:23, HttpTrackerCoreServices::initialize_from(_tracker_core_container) at packages/http-core/src/container.rs:117, and UdpTrackerCoreServices::initialize_from(_tracker_core_container, ..) at packages/udp-core/src/container.rs:176. Callers still build and pass these values, and the parameter lists suggest that the core configuration still decides whether the buses publish. Smallest fix: remove the parameters while the crates are unpublished.

Checked and found sound:

  • Instance identity is fixed once per configuration block (src/container.rs:206, src/container.rs:232). Repeated 0.0.0.0:0 blocks get distinct ids.
  • The identity is threaded into every HTTP and UDP producer: the received, discarded, banned and aborted events in packages/udp-server/src/server/launcher.rs:285-409, the response events in packages/udp-server/src/server/processor.rs, and the error event in packages/udp-server/src/handlers/error.rs:148.
  • The policy map covers every instance that can publish, so its unknown-instance arm is an alarm for a wiring defect, not a traffic path.
  • The identity is not added to any metric label set, so the description's claim that it is only a filter key holds.
  • Ban admission still applies only under strict connection-ID validation (packages/udp-server/src/server/launcher.rs:389).
  • The cancellation drain applies the same policy as the live path.
  • The HTTP announce service keeps its disabled peer-IP selection policy.
  • Each explicit [[test]] target in Cargo.toml points to a file that exists.

This branch was previously deployed

1 inactive deployment
coverage — a62953b4 Deployed Aug 19, 2026 by josecelano via Generate Coverage Report #1775
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.

Normalize per-instance event metrics policy

3 participants