Skip to content

perf(stats): speed up usage charts and Clash subscriptions - #1060

Merged
T3ST3ST3R0N merged 4 commits into
devfrom
perf/stats-and-sub
Oct 22, 2026
Merged

T3ST3ST3R0N merged 4 commits into
devfrom
perf/stats-and-sub

Conversation

@T3ST3ST3R0N

@T3ST3ST3R0N T3ST3ST3R0N commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Clash and Clash Meta subscriptions render with libyaml while keeping the output byte-identical, the usage chart joins users only when it needs to, and the user-counts chart uses a query shape PostgreSQL can hash. Also one subscription fix: a blocked or unmatched client no longer registers its HWID before the 406.

Fixes

Unsupported clients use up an HWID slot

  • SubscriptionOperation.user_subscription called validate_and_register_hwid (which commits) before the client rule check. Opening a blocked app once used up a device slot, and the user's allowed app could then get 403 "Device limit reached".
  • The client rule check (block rule or no matching rule: 406) now runs first. user_subscription_with_client_type already had this order.

Clash YAML goes through the pure-Python emitter

  • The yaml template filter (to_yaml, 3 calls per Clash render) used PyYAML's pure-Python Dumper, about half of every Clash and Clash Meta render. Plain libyaml is several times faster but writes some input differently, most visibly emoji (escaped as "\U0001F1E9"), which are common in remarks.
  • With libyaml available, to_yaml now uses a yaml.CDumper subclass. Characters outside the Basic Multilingual Plane are swapped for unused private-use characters during the dump and swapped back after it. Input the two emitters would still write differently (U+0085, CR, lone surrogates, private-use characters, empty keys, keys of 123+ characters or 128+ bytes, top-level scalars, astral characters in double-quoted strings) falls back to the pure-Python dumper. The output is byte-identical except for double-quoted strings wider than 80 columns, which the two emitters fold at different points and which parse to the same value. The UUID representer is registered once at import instead of on every call.

Usage chart joins every history row to users

  • get_all_users_usages (GET /api/users/usage) joined every node_user_usages row in range to users, only to drop rows of deleted users, which PostgreSQL, MySQL and MariaDB already delete through ON DELETE CASCADE. MySQL ran it as one primary-key lookup per history row.
  • It joins users only for an admin filter, group_by_admin, or on SQLite (no foreign key enforcement, so orphan rows are possible).

User-counts chart sorts every history row on PostgreSQL

  • get_user_count_metric_stats (GET /api/users/counts/{metric} and GET /api/node/user_counts/{metric}) ran count(DISTINCT user_id) GROUP BY bucket. PostgreSQL cannot hash a DISTINCT aggregate, so it sorted every row in range (an external merge sort on disk for a few days of history).
  • On PostgreSQL it now selects DISTINCT (bucket, [node,] user) in a subquery and counts per bucket. A row the metric does not count keeps a NULL user id, so its bucket still shows with 0, as before. MySQL, MariaDB and SQLite keep count(DISTINCT), which is faster there (for hourly online counts the pair shape took 4.4 s instead of 1.7 s on MySQL, and 18.4 s instead of 1.6 s on MariaDB). The total query is unchanged.

Performance

  • Clash, 51 hosts with emoji remarks (SQLite, warm caches): 3 YAML dumps per render 27.9 ms -> 6.0 ms; request median clash_meta 55.2 ms -> 35.0 ms, clash 34.2 ms -> 27.1 ms.
  • Usage chart, 7 days (app call, best of 3): MySQL 8.4 with 1.15M rows in range 3.3 s -> 0.75 s; MariaDB 10.6, same data, 4.9 s -> 1.5 s; PostgreSQL 16 with 3.46M rows 512 ms -> 376 ms.
  • User-counts chart, PostgreSQL 16, 3.46M rows (including the unchanged total query): online 3 days by day 3.0 s -> 1.1 s, 7 days by day 3.8 s -> 1.9 s, expired 3 days by day 3.6 s -> 2.8 s, 1 day by hour unchanged.

Behavior changes

  • A client blocked by a rule, or matching no rule, no longer registers its X-HWID. If such a client also lacks a required HWID header, it now gets 406 "Client not supported" instead of 403.
  • Clash output does not change. Without libyaml (PyYAML wheels bundle it) the old path runs.
  • On a PostgreSQL/MySQL/MariaDB install whose foreign keys were disabled by hand and that holds history rows of deleted users, the usage chart would now count that traffic. Migration 2a1176f0c666 removed orphan rows and recreated both foreign keys with ON DELETE CASCADE, so migrated installs cannot have them.

Tests

  • tests/api/test_hwid.py::test_unsupported_client_does_not_register_hwid[None|block]: fails on dev (assert 1 == 0: the device was registered before the 406).
  • tests/test_yaml_filter.py: a 51-field Clash Meta document with flags, status emoji, Persian and Chinese text must match the pure dumper and must not fall back (fails on dev: fell back to the pure-Python dumper); a list of inputs libyaml writes differently (including keys of 123 and 127 characters); a 3,000-document seeded fuzz against the pure dumper.
  • tests/api/test_subscription_yaml.py::test_clash_subscriptions_match_pure_yaml_dumper: real /sub/{token}/clash and /sub/{token}/clash_meta bodies with emoji remarks must be byte-identical with both dumpers.
  • tests/api/test_usage_stats_query_shapes.py (19 tests): generated history (2 admins, users with and without an admin, expired and limited users, 2 nodes plus rows without a node, rows on local midnights and a month edge) over 3 time zones, 3 periods and several ranges and scopes. It compares the new usage query with the forced join and runs both user-count shapes on every database. The shape check fails on dev on PostgreSQL ('join users' in usage_sql). 19 passed each on PostgreSQL 16, MySQL 8.4 and MariaDB 10.6.
  • SQLite: pytest tests --ignore=tests/api 729 passed, 34 skipped; pytest tests/api 498 passed. ruff check and ruff format --check are clean.

Related

Summary by CodeRabbit

  • Bug Fixes
    • Unsupported subscription requests are now rejected before an HWID is registered, so blocked requests no longer add an HWID to the user’s account.
    • Usage charts and user-count metrics now handle different database systems and time zones more consistently.
  • Performance
    • Subscription YAML generation can use a faster serialization path while preserving compatible output, including emoji and other special characters.

…r HWID

A subscription request from a blocked or unmatched client registered its
X-HWID first and only then returned 406, so opening a blocked app once used
up a device slot and the user's allowed app could then get 403 "Device limit
reached". Check the client rule before the HWID registration.
…hanged

The `yaml` template filter used PyYAML's pure-Python dumper, which took
about half of every Clash and Clash Meta subscription render. libyaml's
emitter is several times faster but writes some input differently, most
visibly emoji (escaped as "\U0001F1E9" in double quotes), which are common
in remarks.

Use the C dumper when libyaml is available: characters outside the Basic
Multilingual Plane are swapped for unused private-use characters during the
dump and swapped back after it, and any input the two emitters would still
write differently (U+0085, CR, lone surrogates, empty keys, keys of 123 or
more characters or 128 or more bytes, top-level scalars, astral characters
in double-quoted strings) falls back to the pure-Python dumper. The output
is byte-identical except for double-quoted strings wider than 80 columns,
which the two emitters fold at different points and which parse to the
same value.

51 hosts with emoji remarks: 3 dumps per render 27.9 ms -> 6.0 ms,
clash_meta request median 55.2 ms -> 35.0 ms, clash 34.2 ms -> 27.1 ms.
get_all_users_usages (dashboard usage chart, GET /api/users/usage) joined
every node_user_usages row in range to users, even without an admin filter
or grouping by admin. The join only dropped history rows of deleted users,
which PostgreSQL, MySQL and MariaDB already remove through ON DELETE
CASCADE; MySQL ran it as one primary key lookup per history row.

Join users only for an admin filter, grouping by admin, or on SQLite, which
does not enforce foreign keys and can keep orphan rows. Results are
unchanged; the new test runs both shapes on the same generated history.

7-day chart, 1.15M rows in range: MySQL 8.4 3.3 s -> 0.75 s, MariaDB 10.6
4.9 s -> 1.5 s; 3.46M rows on PostgreSQL 16: 512 ms -> 376 ms.
…on PostgreSQL

The user counts chart (GET /api/users/counts/{metric}) ran
count(DISTINCT user_id) GROUP BY bucket over node_user_usages. PostgreSQL
cannot hash a DISTINCT aggregate, so it sorted every history row in range
(an external merge sort on disk for a few days of history).

On PostgreSQL, select DISTINCT (bucket, [node,] user) rows first and count
them per bucket, which it can hash. A row the metric does not count keeps a
NULL user id, so its bucket still shows with 0, as before. MySQL and MariaDB
keep count(DISTINCT), which is faster there (the pair shape took 4.4 s
instead of 1.7 s on MySQL and 18 s instead of 1.6 s on MariaDB for hourly
online counts). The new test runs both shapes on every database and expects
identical results.

PostgreSQL 16, 3.46M rows: online 3d/day 3.0 s -> 1.1 s, 7d/day
3.8 s -> 1.9 s, expired 3d/day 3.6 s -> 2.8 s, 1d/hour unchanged.
@coderabbitai

coderabbitai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 96915fad-09b9-4c47-9b9a-3e2e47e37c67
📥 Commits

Reviewing files that changed from the base of the PR and between f2f56cf and c02616b.

📒 Files selected for processing: 7
  • app/db/crud/user.py
  • app/operation/subscription.py
  • app/templates/filters.py
  • tests/api/test_hwid.py
  • tests/api/test_subscription_yaml.py
  • tests/api/test_usage_stats_query_shapes.py
  • tests/test_yaml_filter.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 0 remain after this review.

Walkthrough

The changes update usage-stat query behavior across database dialects, move unsupported-client rejection ahead of HWID registration, and add a libyaml-based YAML serialization path with fallback behavior. Tests cover these query, subscription, and serialization changes.

Changes

Usage statistics queries

Layer / File(s) Summary
Conditional user joins
app/db/crud/user.py, tests/api/test_usage_stats_query_shapes.py
Usage-history queries join users when admin filtering or grouping requires it, or when the dialect is SQLite. Tests compare results across query shapes and inspect generated SQL.
Distinct user-count buckets
app/db/crud/user.py, tests/api/test_usage_stats_query_shapes.py
PostgreSQL user-count metrics use distinct period-and-user rows, optionally including node ID. Tests compare results for both bucket-query shapes.

Subscription HWID validation

Layer / File(s) Summary
Reject unsupported clients before HWID registration
app/operation/subscription.py, tests/api/test_hwid.py
The operation rejects missing or blocked client targets before HWID validation and registration. Tests check the 406 response and confirm that no HWID was registered.

YAML serialization

Layer / File(s) Summary
Fast YAML output with compatible fallback
app/templates/filters.py, tests/test_yaml_filter.py, tests/api/test_subscription_yaml.py
The YAML filter uses a libyaml dumper for eligible dictionaries and lists, restores placeholders in successful output, and falls back to yaml.dump when needed. Tests compare output with the pure-Python dumper.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Refactor

Suggested reviewers: x0sina

Merge Risk: ⚪ Minimal · up to c0261

No actionable merge-blocking risk remains after normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 16.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 37 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly summarizes the primary performance changes to usage charts and Clash subscriptions. It is concise, specific, and related to the changeset.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

A rabbit checks the buckets bright,
Then guards the HWID from the night.
Fast YAML rolls, with fallback near,
While tests compare each result clear.
The rabbit hops, content and cheer.

Comment @coderabbitai help to get the list of available commands.

Comment thread app/templates/filters.py
_ASTRAL = re.compile("[\U00010000-\U0010ffff]")
# The pure-Python emitter writes astral characters as is only outside double quotes, so a string holding one
# must not contain anything that forces double quotes (control characters, line breaks, BOM, noncharacters).
_NO_DOUBLE_QUOTES = re.compile("[\x20-\x7e\xa0-\u2027\u202a-\ud7ff\ue000-\ufefe\uff00-\ufffd\U00010000-\U0010fffe]*")
@T3ST3ST3R0N

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@T3ST3ST3R0N
T3ST3ST3R0N merged commit e0bb112 into dev Oct 22, 2026
18 checks passed
@T3ST3ST3R0N
T3ST3ST3R0N deleted the perf/stats-and-sub branch October 22, 2026 12:34
Free-Guy-IR added a commit to Free-Guy-IR/panel that referenced this pull request Nov 2, 2026
…rd main's decisions

B7-ADV2 B2-3, B2-4, B2-6, B2-10 and main's rulings of 2026-10-28.

Decisions (Owner decisions):
- 2026-10-28-main-reclassified, until 2026-11-08: the entries now
  classified security: yes where the fork is affected, each ported as
  the fork's own increment: PasarGuard#1053 59c3b62 (format_map; the fork's
  address allowlist also passes width specs), PasarGuard#947 eb30578
  (webhook URLs logged at app/jobs/send_notifications.py:45 and :47),
  PasarGuard#1052 da27446 (inbound finalmask filter lists reach clients),
  e538dc1 (removes upstream's address check; the fork keeps its
  own and caps format specs with PasarGuard#1053), PasarGuard#1060 e0bb112 (HWID
  registered before the 406), e6ca015 (certifi 2026.10.19,
  already on main as 1c20204), PasarGuard#1065 80d855f (bridge 0.9.4: a
  rejected user stalled the node queue, so removals never arrived),
  PasarGuard#1059 0155c0e (MySQL DATEDIFF ends reset cycles a day early),
  and [email protected].
- 2026-10-28-main-hint-waivers, until 2026-11-27: the nine Waived
  entries the keyword hint flags, now security: yes; the seven
  notifier-workflow commits are covered only while they touch nothing
  but .github/workflows/github-notifications-bot.yml (deleted by the
  fork in 535c1aa), and the two UNMERGED-WIP entries keep failing at
  once if upstream merges them.

Classifications (B2-4): every port-queue security: no reason was
re-read against its diff by six non-author readers (233 entries) and
rewritten to say why the change has no security effect instead of
paraphrasing the subject; 64 readers' flags were adjudicated: the
held telemt entries 0373f09, 35b493c and 84e5416, the
AmneziaWG branch (unchecked fields rendered into subscriber .conf
files), certifi 2026.10.19 and 2026.10.23, docker/login-action 4.7.0
and the telemt link and validation commits are security: yes; the
rest are no with a reason. 0097556 stays no with its reason.

Reasons (B2-10): every Held and Waived security: no entry gives its
reason; the gate's unreasoned count is 0.

aiohttp (B2-6): 3.14.4 fixes eight advisories against 3.14.3 (OSV
2026-10-29): three high, four moderate, one low; item 0b ports aiohttp
3.14.5 and yarl 1.25.1 with trailers.

Bridge waiver: PasarGuard#27 is a security fix, so the 0.9.4 waiver is
security = "yes" under 2026-10-28-main-reclassified, until unchanged.

Held: PasarGuard#1120 8e92a12 (sse-starlette 3.5.1, upstream dev head) and
the new upstream branch feat/gzip-compression (8f48cd7,
769c296, 420d094); .upstream-refs records both heads.

Gate at HEAD with --today 2026-10-29: OK, not at parity, 181 owed.
Free-Guy-IR added a commit to Free-Guy-IR/panel that referenced this pull request Nov 2, 2026
…ords

B7-ADV2 B2-5 asks that the hint fire on PasarGuard#1053, PasarGuard#1060, PasarGuard#1052 and PasarGuard#947.
Reading the commit body catches PasarGuard#1060 ('escaped') and PasarGuard#947
('session'), but not PasarGuard#1053, whose body speaks of str.format_map, nor
PasarGuard#1052, whose subject keeps a server-only filter out of client configs.
The hint should also name format_map, server-only, and leak or expose
words.

RED on 4f040c5: all four cases fail.
Free-Guy-IR added a commit to Free-Guy-IR/panel that referenced this pull request Nov 2, 2026
B7-ADV2 B2-5: with the commit body read, the hint now fires on PasarGuard#1053
('format_map'), PasarGuard#1060 ('escaped'), PasarGuard#1052 ('server-only') and PasarGuard#947
('session'). The RED test's fourth case, 'exposes', is dropped: on the
real ledger it flagged only API wording ('expose online_users',
'expose core_config_id') and would have turned a waived unmerged
feature into an error; 'leak' covers the exposure wording that matters.
The real panel gate at HEAD on 2026-10-29 shows no new note.
Free-Guy-IR pushed a commit to Free-Guy-IR/panel that referenced this pull request Nov 4, 2026
…d#1060)

* fix(subscription): reject unsupported clients before registering their HWID

A subscription request from a blocked or unmatched client registered its
X-HWID first and only then returned 406, so opening a blocked app once used
up a device slot and the user's allowed app could then get 403 "Device limit
reached". Check the client rule before the HWID registration.

* perf(templates): dump Clash YAML with libyaml, keeping the output unchanged

The `yaml` template filter used PyYAML's pure-Python dumper, which took
about half of every Clash and Clash Meta subscription render. libyaml's
emitter is several times faster but writes some input differently, most
visibly emoji (escaped as "\U0001F1E9" in double quotes), which are common
in remarks.

Use the C dumper when libyaml is available: characters outside the Basic
Multilingual Plane are swapped for unused private-use characters during the
dump and swapped back after it, and any input the two emitters would still
write differently (U+0085, CR, lone surrogates, empty keys, keys of 123 or
more characters or 128 or more bytes, top-level scalars, astral characters
in double-quoted strings) falls back to the pure-Python dumper. The output
is byte-identical except for double-quoted strings wider than 80 columns,
which the two emitters fold at different points and which parse to the
same value.

51 hosts with emoji remarks: 3 dumps per render 27.9 ms -> 6.0 ms,
clash_meta request median 55.2 ms -> 35.0 ms, clash 34.2 ms -> 27.1 ms.

* perf(stats): join users in the usage chart query only when it is needed

get_all_users_usages (dashboard usage chart, GET /api/users/usage) joined
every node_user_usages row in range to users, even without an admin filter
or grouping by admin. The join only dropped history rows of deleted users,
which PostgreSQL, MySQL and MariaDB already remove through ON DELETE
CASCADE; MySQL ran it as one primary key lookup per history row.

Join users only for an admin filter, grouping by admin, or on SQLite, which
does not enforce foreign keys and can keep orphan rows. Results are
unchanged; the new test runs both shapes on the same generated history.

7-day chart, 1.15M rows in range: MySQL 8.4 3.3 s -> 0.75 s, MariaDB 10.6
4.9 s -> 1.5 s; 3.46M rows on PostgreSQL 16: 512 ms -> 376 ms.

* perf(stats): count distinct users per bucket from deduplicated pairs on PostgreSQL

The user counts chart (GET /api/users/counts/{metric}) ran
count(DISTINCT user_id) GROUP BY bucket over node_user_usages. PostgreSQL
cannot hash a DISTINCT aggregate, so it sorted every history row in range
(an external merge sort on disk for a few days of history).

On PostgreSQL, select DISTINCT (bucket, [node,] user) rows first and count
them per bucket, which it can hash. A row the metric does not count keeps a
NULL user id, so its bucket still shows with 0, as before. MySQL and MariaDB
keep count(DISTINCT), which is faster there (the pair shape took 4.4 s
instead of 1.7 s on MySQL and 18 s instead of 1.6 s on MariaDB for hourly
online counts). The new test runs both shapes on every database and expects
identical results.

PostgreSQL 16, 3.46M rows: online 3d/day 3.0 s -> 1.1 s, 7d/day
3.8 s -> 1.9 s, expired 3d/day 3.6 s -> 2.8 s, 1d/hour unchanged.

Fork adaptation: tests/api/test_hwid.py conflicted only because upstream's file already carried the PasarGuard#859 HWID tests the fork has not ported (ba4a0ab, owed); the fork keeps its own file and takes only this commit's test_unsupported_client_does_not_register_hwid, plus the asyncio import it needs. The usage chart drops the users join only without an admin filter or admin grouping: the fork's group scope (user_in_allowed_groups) filters on node_user_usages.user_id through users_groups, never on users, and node_user_usages.user_id is ON DELETE CASCADE, so no condition loses its table.

(cherry picked from commit e0bb112)
Free-Guy-IR added a commit to Free-Guy-IR/panel that referenced this pull request Nov 4, 2026
…oth query shapes of upstream e0bb112

The PasarGuard#1060 port drops the users join from the usage chart without an admin filter and counts PostgreSQL buckets from DISTINCT pairs. Both shapes are forced on the same history with a fork group scope (allowed_group_ids): the totals equal the in-group history rows, and the counts never exceed the in-group users. Dropping the scope in either cheap shape fails all 15 cases.
Free-Guy-IR added a commit to Free-Guy-IR/panel that referenced this pull request Nov 4, 2026
…rt queue; 1ccd86d waits for e0bb112

1ccd86d rewrites _build_user_count_buckets_from_distinct_pairs, which
upstream e0bb112 (PasarGuard#1060, owed by B-SUB) adds and fork main lacks.
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.

2 participants