Repository navigation
perf(stats): speed up usage charts and Clash subscriptions - #1060
Conversation
…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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info
WalkthroughThe 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. ChangesUsage statistics queries
Subscription HWID validation
YAML serialization
Priority: ➖ Normal Estimated code review effort: 3 (Moderate) | ~25 minutes Change: Refactor Suggested reviewers: Merge Risk: ⚪ Minimal · up to
|
| _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]*") |
|
@coderabbitai review |
✅ Action performedReview finished.
|
…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.
…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.
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.
…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)
…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.
…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.
Summary
Clash and Clash Meta subscriptions render with libyaml while keeping the output byte-identical, the usage chart joins
usersonly 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_subscriptioncalledvalidate_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".user_subscription_with_client_typealready had this order.Clash YAML goes through the pure-Python emitter
yamltemplate filter (to_yaml, 3 calls per Clash render) used PyYAML's pure-PythonDumper, 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.to_yamlnow uses ayaml.CDumpersubclass. 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
usersget_all_users_usages(GET /api/users/usage) joined everynode_user_usagesrow in range tousers, only to drop rows of deleted users, which PostgreSQL, MySQL and MariaDB already delete throughON DELETE CASCADE. MySQL ran it as one primary-key lookup per history row.usersonly 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}andGET /api/node/user_counts/{metric}) rancount(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).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 keepcount(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_meta55.2 ms -> 35.0 ms,clash34.2 ms -> 27.1 ms.Behavior changes
X-HWID. If such a client also lacks a required HWID header, it now gets 406 "Client not supported" instead of 403.2a1176f0c666removed orphan rows and recreated both foreign keys withON DELETE CASCADE, so migrated installs cannot have them.Tests
tests/api/test_hwid.py::test_unsupported_client_does_not_register_hwid[None|block]: fails ondev(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 ondev: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}/clashand/sub/{token}/clash_metabodies 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 ondevon PostgreSQL ('join users' in usage_sql). 19 passed each on PostgreSQL 16, MySQL 8.4 and MariaDB 10.6.pytest tests --ignore=tests/api729 passed, 34 skipped;pytest tests/api498 passed.ruff checkandruff format --checkare clean.Related
Summary by CodeRabbit