1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
//! Token-based name normalization used by [`crate::ctprof_compare`]
//! to fold ephemeral digit/hex suffixes into pattern skeletons.
//!
//! Two callers feed this module:
//! - thread / process axes ([`super::GroupBy::Comm`] /
//! [`super::GroupBy::Pcomm`]) and the smaps_rollup keying use
//! [`pattern_key`] / [`pattern_counts_union`] /
//! [`pattern_display_label`].
//! - the cgroup axis applies a three-layer pipeline
//! ([`apply_systemd_template`] →
//! [`cgroup_skeleton_tokens`] → [`tighten_group`]) wrapped by
//! [`cgroup_normalize_skeleton`].
//!
//! The rules are pure (no kernel introspection, no IO) so they
//! sit in their own module without pulling the data-type or
//! compute layers along.
use BTreeMap;
use LazyLock;
use Regex;
use crate;
/// Placeholder for a pure-digit token (rule 1 of the token-based
/// normalizer). Replaces a token of all ASCII digits.
const TOKEN_DIGIT_PLACEHOLDER: &str = "{N}";
/// Placeholder for a hex-like token (rule 2 of the token-based
/// normalizer). Replaces a token whose chars are all in `[0-9a-f]`,
/// length ≥ 2, and contain at least one digit.
const TOKEN_HEX_PLACEHOLDER: &str = "{H}";
/// Placeholder for a systemd template instance whose value is an
/// opaque ID (rule applied by [`apply_systemd_template`] in cgroup
/// layer 1). For example, `user@0.service` and `user@1001.service`
/// both normalize to `user@{I}.service` because their instances
/// (`0`, `1001`) carry no `[._-]` separators that would suggest a
/// structured service name.
const TOKEN_INSTANCE_PLACEHOLDER: &str = "{I}";
/// Rule 1 pattern: pure ASCII digits.
static TOKEN_RULE_PURE_DIGITS: = new;
/// Rule 2 pattern: hex-like (all chars in `[0-9a-f]`, length ≥ 2).
/// The "must contain at least one digit" check is applied
/// separately because anchored character-class repetition does
/// not natively express that constraint.
static TOKEN_RULE_HEX_LIKE: =
new;
/// Rule 3 pattern: alpha prefix (length ≥ 1) followed by
/// trailing digits. Capture group 1 is the alpha prefix.
static TOKEN_RULE_ALPHA_PREFIX_DIGITS: =
new;
/// Rule 4 pattern: leading digits followed by an alpha suffix
/// (length ≥ 1). Capture group 1 is the alpha suffix. Catches
/// kworker high-priority bound workers (`1H`, `0H`, `2H` etc. —
/// the `H` suffix added by `format_worker_id` in
/// `kernel/workqueue.c` when the worker pool's nice value is
/// negative).
static TOKEN_RULE_DIGITS_ALPHA_SUFFIX: =
new;
/// Token-classification rule. The token-based normalizer
/// ([`pattern_key`]) walks segments produced by
/// [`split_into_segments`] and applies the first rule that
/// matches each token. Rules are checked in order; the first
/// match wins. Rule patterns are direct regex translations of
/// the thread-name normalization rules.
pub
/// One segment of a tokenized string: either a non-separator run
/// (a token) or a run of separator characters.
pub
/// Returns true for any character treated as a token separator by
/// the token-based normalizer. The set is `[.\-_/:@+\[\]\s]+` —
/// ASCII punctuation `.`, `-`, `_`, `/`, `:`, `@`, `+`, `[`, `]`
/// plus any Unicode whitespace. The `+` decoration kworker uses on
/// active workers (`kworker/<cpu>:<id>+<wq>` per `wq_worker_comm`
/// in `kernel/workqueue.c`) is a separator so the digit tokens on
/// either side normalize independently. Brackets appear in
/// process names set via `prctl(PR_SET_NAME)` (kernel threads in
/// userspace tooling render as `[ksoftirqd/0]`, etc.) AND in the
/// literal-mode smaps key shape `pcomm[tgid]` produced by
/// [`crate::ctprof_compare::collect_smaps_rollup`] under
/// [`crate::ctprof_compare::CompareOptions::no_thread_normalize`];
/// treating brackets as separators allows the digit / hex tokens
/// inside them to normalize independently from the surrounding
/// alpha tokens.
pub
/// Walk the input and emit alternating token / separator runs.
/// Empty input yields zero segments. Maximal runs are emitted —
/// `a..b` produces `[Token("a"), Separator(".."), Token("b")]`.
pub
/// Compute the token-normalized skeleton for a name string.
///
/// Consumed by [`crate::ctprof_compare::GroupBy::Comm`]
/// (thread-name grouping),
/// [`crate::ctprof_compare::GroupBy::Pcomm`] (process-name
/// grouping), and
/// [`crate::ctprof_compare::collect_smaps_rollup`] (per-pcomm
/// smaps aggregation) — each callsite passes a different field
/// (`t.comm`, `t.pcomm`, `t.pcomm` respectively) and applies its
/// own callsite-level policy on top of the skeleton this function
/// returns.
///
/// Splits the input on a separator class (`[.\-_/:@+\[\]\s]+`),
/// classifies each non-separator token by [`classify_token`], and
/// rejoins with the original separator runs preserved verbatim.
/// The first matching rule wins per token:
///
/// 1. Pure digits → `{N}` (e.g. `42` → `{N}`).
/// 2. Hex-like (all chars `[0-9a-f]`, length ≥ 2, contains at
/// least one digit) → `{H}` (e.g. `abc123def` → `{H}`).
/// 3. Alpha prefix + trailing digits (`^[A-Za-z]+\d+$`, alpha
/// prefix length ≥ 1) → `prefix{N}` (e.g. `worker7` →
/// `worker{N}`, `u8` → `u{N}`).
/// 4. Leading digits + alpha suffix (`^\d+[A-Za-z]+$`) →
/// `{N}suffix` (e.g. `1H` → `{N}H`, `100Hz` → `{N}Hz`).
/// 5. Otherwise: keep literal.
///
/// Two names that produce the same skeleton group together at
/// the bucket layer. The singleton-revert policy ("if only one
/// thread / process matches a skeleton, revert to literal") is a
/// callsite policy enforced by
/// [`crate::ctprof_compare::build_groups`] — `pattern_key` itself
/// always returns the skeleton, leaving callsites free to override
/// (and indeed [`crate::ctprof_compare::collect_smaps_rollup`]
/// does NOT singleton-revert; see its doc for why).
///
/// Examples:
/// - `whirly-gig-15` → `whirly-gig-{N}`.
/// - `kworker/0:0-wq_reclaim` → `kworker/{N}:{N}-wq_reclaim`.
/// - `kworker/u8:7` → `kworker/u{N}:{N}` (single-letter alpha
/// prefix `u` qualifies under rule 3).
/// - `session-a1234` → `session-{H}` (hex-like).
/// - `BPF_CUBIC` → `BPF_CUBIC` (pure alpha, no digits).
/// - `bloop-tangler` → `bloop-tangler` (pure alpha).
/// Cgroup layer 1: systemd `template@instance.service`
/// normalization. Walks the path, finding each
/// `@<instance>.service` segment (bounded by `/` or end-of-string).
/// If the instance contains any of `[._-]`, it is a structured
/// service name and the segment is kept verbatim. Otherwise, the
/// instance is treated as an opaque ID and the segment is rewritten
/// to `@{I}.service`.
///
/// Examples:
/// - `/user.slice/user-0.slice/user@0.service/boot.scope`
/// → `/user.slice/user-0.slice/user@{I}.service/boot.scope`
/// (`0` has no `[._-]`).
/// - `/critical.slice/launcher@foo.bar.baz.service`
/// → unchanged (instance `foo.bar.baz` has `.`).
pub
/// Cgroup layer 2: token-based normalization. Identical to
/// [`pattern_key`] but operates on a cgroup path string. Returns
/// the post-Layer-1 token list alongside the normalized skeleton —
/// the token list is consumed by [`tighten_group`] to revert
/// constant-across-members positions to literals (Layer 3).
pub
/// Cgroup layer 3 (tighten): for a multi-member group sharing the
/// same Layer-2 skeleton, revert any token position whose value is
/// identical across every member to its literal form. Positions
/// that vary across members keep their Layer-2 placeholder.
///
/// Members carry both their post-Layer-1 path (used to recover
/// separator runs verbatim from a representative member) and their
/// per-position token list (compared across members for the
/// position-by-position equality check). All members share the
/// same number of tokens and the same separator structure by
/// construction — they share a Layer-2 skeleton.
///
/// Returns the tightened skeleton; if every position varies
/// (nothing to tighten), the result equals the input skeleton.
pub
/// Compute the cgroup grouping key for a path under
/// [`crate::ctprof_compare::GroupBy::Cgroup`] aggregation. Applies
/// Layer 1 (systemd template) and Layer 2 (token normalization).
/// Layer 3 (tighten) runs separately on multi-member groups inside
/// [`crate::ctprof_compare::build_groups`].
///
/// Returns `(layer2_skeleton, post_l1_path, post_l1_tokens)`. The
/// skeleton is the join key; the post-L1 path and tokens feed
/// [`tighten_group`] for groups with ≥ 2 members.
pub
/// Compute the operator-facing display label for a pattern-aware
/// group, given the union of baseline+candidate member comms. For
/// buckets with ≥ 2 distinct member names, runs grex over the
/// sorted union to emit a regex that exactly matches the
/// constituent thread names. For singleton or all-identical
/// buckets, returns the join key unchanged so the rendered label
/// equals what would have shown under literal grouping.
///
/// Empty `members` returns `key` — defensive against synthetic
/// inputs; production builds populate `members` for every
/// bucket.
/// Build the union frequency map for pattern-aware grouping
/// ([`crate::ctprof_compare::GroupBy::Comm`] or
/// [`crate::ctprof_compare::GroupBy::Pcomm`]) across the
/// baseline + candidate snapshots. The frequency gate that
/// promotes a `pattern_key` from per-thread literal to a clustered
/// bucket must be evaluated against the UNION of both
/// snapshots' threads — otherwise a pattern that has 1 thread
/// in baseline + 3 threads in candidate would join under a
/// `worker-{N}` key in candidate but a literal `worker-7` key in
/// baseline, and `compare()` would surface the row as
/// only-in-candidate. Computing the count from the union ensures
/// the same key is used on both sides.
///
/// `field` selects which [`ThreadState`] string feeds the count:
/// `|t| t.comm.as_str()` for `Comm`, `|t| t.pcomm.as_str()` for
/// `Pcomm`. The two axes share the same union-frequency contract
/// so one helper covers both.
pub