Skip to content

Overhaul stats: Persist all torrents downloads metric - #1540

Merged
josecelano merged 5 commits into
torrust:developfrom
josecelano:1539-overhaul-stats-persist-all-torrents-downloads-metric
May 27, 2025
Merged

josecelano merged 5 commits into
torrust:developfrom
josecelano:1539-overhaul-stats-persist-all-torrents-downloads-metric

Conversation

@josecelano

@josecelano josecelano commented May 27, 2025 •

Copy link
Copy Markdown
Member

Persist "all torrent downloads" metric.

Subtasks

  • Add new methods to the Database trait.
  • Make use of the new methods to persist the metric TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL.
  • Add an integration test.

…wnloads counter

It does not use the new methods in production yet.
@josecelano josecelano self-assigned this May 27, 2025
@josecelano
josecelano requested a review from da2ce7 May 27, 2025 09:39
@josecelano josecelano added the - User - Enjoyable to Use our Software label May 27, 2025
@codecov

codecov Bot commented May 27, 2025 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 66.66667% with 81 lines in your changes missing coverage. Please review.

Project coverage is 83.33%. Comparing base (3fce84b) to head (4febda4).
Report is 6 commits behind head on develop.

Files with missing lines Patch % Lines
...ackages/tracker-core/src/databases/driver/mysql.rs 0.00% 34 Missing ⚠️
...ckages/tracker-core/src/databases/driver/sqlite.rs 71.73% 4 Missing and 9 partials ⚠️
...s/tracker-core/src/statistics/persisted_metrics.rs 43.47% 10 Missing and 3 partials ⚠️
src/app.rs 33.33% 7 Missing and 1 partial ⚠️
...kages/tracker-core/src/statistics/event/handler.rs 36.36% 5 Missing and 2 partials ⚠️
packages/metrics/src/metric_collection.rs 85.00% 3 Missing ⚠️
...s/tracker-core/src/torrent/repository/persisted.rs 77.77% 1 Missing and 1 partial ⚠️
packages/tracker-core/src/statistics/repository.rs 93.33% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1540      +/-   ##
===========================================
- Coverage    83.52%   83.33%   -0.19%     
===========================================
  Files          273      274       +1     
  Lines        19317    19554     +237     
  Branches     19317    19554     +237     
===========================================
+ Hits         16134    16295     +161     
- Misses        2909     2969      +60     
- Partials       274      290      +16     

☔ View full report in Codecov by Sentry.
📢 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.

The total number of dowloads (for all torrents) is saved in the DB, but
not loaded yet.

todo: load the initial value when the tracker starts.
@josecelano
josecelano marked this pull request as ready for review May 27, 2025 11:55
@josecelano
josecelano marked this pull request as draft May 27, 2025 11:55
@josecelano

Copy link
Copy Markdown
Member Author

ACK 4febda4

@josecelano
josecelano marked this pull request as ready for review May 27, 2025 12:18
@josecelano josecelano linked an issue May 27, 2025 that may be closed by this pull request
@josecelano
josecelano merged commit 46df7eb into torrust:develop May 27, 2025

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

What still runs: the torrent_aggregate_metrics table from the 20250527093000 migrations (widened to BIGINT on MySQL and PostgreSQL by 20260409120000), the global-downloads logic now in packages/tracker-core/src/statistics/persisted/ (DatabaseDownloadsMetricRepository::increase_global_downloads, and load_persisted_metrics, which seeds the persistent and persisted download totals at startup), and the startup load in src/app.rs, which now returns a typed InitialPersistenceLoad error instead of panicking. The database driver code this pull request added has since been rewritten and is not reviewed here.

[Major] The tracker's own increment can push the stored global total past u32::MAX, and after that the total can no longer be read. increase_global_downloads (packages/tracker-core/src/statistics/persisted/downloads.rs:132) reads the row as NumberOfDownloads (u32) and then runs UPDATE torrent_aggregate_metrics SET value = value + 1 (for example packages/tracker-core/src/databases/driver/mysql/torrent_metrics_store.rs:120). The column is 64-bit (packages/tracker-core/migrations/mysql/20260409120000_torrust_tracker_widen_download_counters.sql:3), so nothing stops the update. Sequence: the row holds 4294967295. The next completed download reads Some(u32::MAX), and the update stores 4294967296. Every later completed download fails in the read with MalformedDatabaseRecord (the u32::try_from at packages/tracker-core/src/databases/driver/sqlite/mod.rs:59, and the same conversion in the MySQL and PostgreSQL drivers). The failure is logged, and the stored total stops moving. On the next restart, load_persisted_metrics (packages/tracker-core/src/statistics/persisted/mod.rs:26) returns that error and src/app.rs:384 turns it into InitialPersistenceLoad, so the tracker does not start until someone edits the row by hand. The type-alignment record (docs/issues/closed/1721-1525-07-align-rust-and-db-types/ISSUE.md:110) assumes the application cannot write a value above u32::MAX, but this increment runs inside the database, where the Rust type does not bound it. The in-memory totals are already u64. The smallest fix is to give the global aggregate its own u64 in TorrentMetricsStore::load_global_downloads and save_global_downloads (packages/tracker-core/src/databases/traits/torrent_metrics.rs:91 and :102), read with u64::try_from(i64). If the u32 has to stay, bound the update with AND value < 4294967295 in the three drivers. The per-torrent completed = completed + 1 path has the same shape, but a single torrent cannot realistically reach the limit.

[Nit] increase_global_downloads (packages/tracker-core/src/statistics/persisted/downloads.rs:133) reads the row before every increment and saves 1 when the row is absent. That costs a second query per completed download. Where two tracker processes share one database and both find no row, both store 1 and one download is lost. The read is also what turns the overflow above into a permanent stop. One statement per driver does the same work atomically: INSERT INTO torrent_aggregate_metrics (metric_name, value) VALUES (?, 1) ON CONFLICT(metric_name) DO UPDATE SET value = value + 1 (on MySQL, ON DUPLICATE KEY UPDATE value = value + 1), combined with the bound or the wider type from the finding above.

[Nit] The comment line this pull request added at packages/tracker-core/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql:7 uses #. MySQL accepts that, but packages/tracker-core/migrations/README.md:29 says # comments are not accepted on MySQL either. A contributor who follows the README and changes the line to -- changes the checksum recorded in _sqlx_migrations. Every MySQL database that has applied the migration would then fail at startup, which is the outcome the immutability rule at packages/tracker-core/migrations/README.md:37 exists to prevent. The smallest fix is one README sentence naming this file as an exception that must stay byte-identical.

Checked and found sound: the three 20250527093000 migrations agree across backends, and the UNIQUE on metric_name backs the drivers' upserts. The SQLite 20260409120000 no-op is correct, since SQLite integers are already 64-bit. The startup load runs before any event listener or service starts, so no download is counted before the seed. An absent row leaves both totals at zero. Enabling persistent_torrent_completed_stat without a database is still rejected, at src/app.rs:438. A failed database increment is logged and leaves the persisted total behind the persistent one, so the failure stays visible. The metric name is a constant bound as a query parameter. Defects that were present at merge and have since been fixed: the startup expect (now a typed error, 56ea1231f), the # comment in the SQLite migration (54677ee46), the 32-bit MySQL column (32b7e3395), and the integration test that simulated a restart without waiting for the listener to write (it now waits).

This branch was previously deployed

1 inactive deployment
coverage — 4febda49 Deployed May 27, 2025 by josecelano
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

- User - Enjoyable to Use our Software

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Overhaul stats: Persist all torrents downloads metric

2 participants