perf-sentinel-core 0.8.13

Core library for perf-sentinel: polyglot performance anti-pattern detector
Documentation
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Seeded synthetic trace generator for benchmarks and large-input fixtures.
//!
//! Deterministic: the same [`SynthSpec`] always yields the same events, so
//! criterion baselines and `bench --synthetic` runs are reproducible.
//! Hidden from the public API surface, the shapes mirror the demo dataset
//! and the detector fixtures (one anti-pattern per trace plus clean noise).

use std::sync::Arc;

use crate::event::{EventSource, EventType, SpanEvent};
use crate::time::millis_to_iso8601;

/// Relative weights of the per-trace patterns drawn by [`generate`].
#[derive(Debug, Clone)]
pub struct PatternMix {
    pub n_plus_one: u32,
    pub redundant: u32,
    pub chatty: u32,
    pub fanout: u32,
    pub slow: u32,
    pub clean: u32,
}

impl Default for PatternMix {
    /// Realistic fleet mix: mostly clean traffic, N+1 as the dominant
    /// anti-pattern, the rest as a long tail.
    fn default() -> Self {
        Self {
            n_plus_one: 30,
            redundant: 10,
            chatty: 10,
            fanout: 5,
            slow: 5,
            clean: 40,
        }
    }
}

impl PatternMix {
    fn total(&self) -> u32 {
        self.n_plus_one + self.redundant + self.chatty + self.fanout + self.slow + self.clean
    }
}

/// Specification for one deterministic synthetic dataset.
#[derive(Debug, Clone)]
pub struct SynthSpec {
    /// Number of distinct `service.name` values to spread traces over.
    pub services: usize,
    /// Number of traces to generate.
    pub traces: usize,
    /// Event count target for clean traces (patterns have their own shapes).
    pub spans_per_trace: usize,
    pub mix: PatternMix,
    pub seed: u64,
}

impl Default for SynthSpec {
    fn default() -> Self {
        Self {
            services: 8,
            traces: 100,
            spans_per_trace: 6,
            mix: PatternMix::default(),
            seed: 42,
        }
    }
}

/// xorshift64* PRNG: tiny, deterministic, no `rand` dependency.
struct Rng(u64);

impl Rng {
    fn new(seed: u64) -> Self {
        // Avoid the all-zero fixed point.
        Self(seed.wrapping_mul(2_685_821_657_736_338_717).max(1))
    }

    fn next_u64(&mut self) -> u64 {
        let mut x = self.0;
        x ^= x >> 12;
        x ^= x << 25;
        x ^= x >> 27;
        self.0 = x;
        x.wrapping_mul(2_685_821_657_736_338_717)
    }

    /// Uniform pick in `[0, n)`. `n` must be nonzero.
    fn pick(&mut self, n: usize) -> usize {
        usize::try_from(self.next_u64() % n.max(1) as u64).unwrap_or(0)
    }
}

/// Base instant for all generated timestamps (2025-07-10T14:32:01Z).
const BASE_MS: u64 = 1_752_157_921_000;

const REGIONS: [&str; 3] = ["eu-west-3", "us-east-1", "eu-central-1"];

const SQL_TABLES: [&str; 8] = [
    "orders",
    "order_item",
    "users",
    "payments",
    "inventory",
    "audit_log",
    "sessions",
    "products",
];

const HTTP_ROUTES: [&str; 6] = [
    "http://user-svc:5000/api/users",
    "http://product-svc:5000/api/products",
    "http://stock-svc:5000/api/stock",
    "http://billing-svc:5000/api/invoices",
    "http://auth-svc:5000/api/tokens",
    "http://geo-svc:5000/api/locations",
];

const ENDPOINTS: [&str; 5] = [
    "POST /api/orders/{id}/submit",
    "GET /api/orders/{id}",
    "GET /api/users/{id}/profile",
    "POST /api/payments",
    "GET /api/catalog/search",
];

/// Generate the deterministic dataset described by `spec`.
#[must_use]
pub fn generate(spec: &SynthSpec) -> Vec<SpanEvent> {
    let mut rng = Rng::new(spec.seed);
    let services: Vec<Arc<str>> = (0..spec.services.max(1))
        .map(|i| Arc::from(format!("synth-svc-{i:04}")))
        .collect();
    let regions: Vec<Arc<str>> = REGIONS.iter().map(|r| Arc::from(*r)).collect();

    // Rough mean of the per-pattern event counts under the default mix,
    // good enough to avoid Vec regrowth.
    let mut events = Vec::with_capacity(spec.traces.saturating_mul(9));
    for trace_idx in 0..spec.traces {
        let svc_idx = rng.pick(services.len());
        let ctx = TraceCtx {
            trace_id: format!("synth-{}-{trace_idx}", spec.seed),
            service: Arc::clone(&services[svc_idx]),
            region: Arc::clone(&regions[svc_idx % regions.len()]),
            endpoint: ENDPOINTS[rng.pick(ENDPOINTS.len())],
            // Spread traces 15 ms apart so per-trace windows stay tight
            // while the dataset spans a realistic time range.
            base_ms: BASE_MS + (trace_idx as u64) * 15,
        };
        let draw = u32::try_from(rng.next_u64() % u64::from(spec.mix.total().max(1))).unwrap_or(0);
        let m = &spec.mix;
        if draw < m.n_plus_one {
            push_n_plus_one(&mut events, &ctx, &mut rng);
        } else if draw < m.n_plus_one + m.redundant {
            push_redundant(&mut events, &ctx, &mut rng);
        } else if draw < m.n_plus_one + m.redundant + m.chatty {
            push_chatty(&mut events, &ctx);
        } else if draw < m.n_plus_one + m.redundant + m.chatty + m.fanout {
            push_fanout(&mut events, &ctx, &mut rng);
        } else if draw < m.n_plus_one + m.redundant + m.chatty + m.fanout + m.slow {
            push_slow(&mut events, &ctx, &mut rng);
        } else {
            push_clean(&mut events, &ctx, spec.spans_per_trace, &mut rng);
        }
    }
    events
}

/// Generate at least `target_events` events by growing the trace count.
///
/// Used by `bench --synthetic` so callers think in event counts (the unit
/// of the published throughput numbers) rather than trace counts.
#[must_use]
pub fn generate_target_events(
    target_events: usize,
    services: usize,
    mix: &PatternMix,
    seed: u64,
) -> Vec<SpanEvent> {
    // Under-ask first, then top up using the measured mean events per
    // trace: a fixed low divisor over-asked by ~37% under the default
    // mix (~8.2 events per trace), building events only to truncate.
    let mut spec = SynthSpec {
        services,
        traces: target_events / 9 + 1,
        spans_per_trace: 6,
        mix: mix.clone(),
        seed,
    };
    let mut events = generate(&spec);
    let mut traces_done = spec.traces;
    while events.len() < target_events {
        let mean = (events.len() / traces_done.max(1)).max(1);
        spec.traces = (target_events - events.len()) / mean + 1;
        spec.seed = seed.wrapping_add(events.len() as u64);
        traces_done += spec.traces;
        events.extend(generate(&spec));
    }
    events.truncate(target_events);
    events
}

/// Benchmark shim over the crate-private timestamp parser, so the
/// criterion suite can measure it without widening `time`'s visibility.
#[must_use]
pub fn parse_ts_ms(ts: &str) -> Option<u64> {
    crate::time::parse_iso8601_utc_to_ms(ts).ok()
}

/// Per-trace generation context shared by the pattern builders.
struct TraceCtx {
    trace_id: String,
    service: Arc<str>,
    region: Arc<str>,
    endpoint: &'static str,
    base_ms: u64,
}

impl TraceCtx {
    fn event(
        &self,
        idx: usize,
        offset_ms: u64,
        event_type: EventType,
        operation: &str,
        target: String,
        duration_us: u64,
    ) -> SpanEvent {
        SpanEvent {
            timestamp: millis_to_iso8601(self.base_ms + offset_ms),
            trace_id: self.trace_id.clone(),
            span_id: format!("{}-s{idx}", self.trace_id),
            parent_span_id: None,
            service: Arc::clone(&self.service),
            cloud_region: Some(Arc::clone(&self.region)),
            event_type,
            operation: operation.to_string(),
            target,
            duration_us,
            source: EventSource {
                endpoint: self.endpoint.to_string(),
                method: "Handler::handle".to_string(),
            },
            status_code: None,
            response_size_bytes: None,
            code_function: None,
            code_filepath: None,
            code_lineno: None,
            code_namespace: None,
            instrumentation_scopes: Vec::new(),
        }
    }

    fn sql(&self, idx: usize, offset_ms: u64, target: String, duration_us: u64) -> SpanEvent {
        self.event(
            idx,
            offset_ms,
            EventType::Sql,
            "SELECT",
            target,
            duration_us,
        )
    }

    fn http(&self, idx: usize, offset_ms: u64, target: String, duration_us: u64) -> SpanEvent {
        let mut e = self.event(
            idx,
            offset_ms,
            EventType::HttpOut,
            "GET",
            target,
            duration_us,
        );
        e.status_code = Some(200);
        e.response_size_bytes = Some(2_048);
        e
    }
}

/// One lookup repeated with distinct literals: the classic N+1 loop.
fn push_n_plus_one(events: &mut Vec<SpanEvent>, ctx: &TraceCtx, rng: &mut Rng) {
    let table = SQL_TABLES[rng.pick(SQL_TABLES.len())];
    let count = 6 + rng.pick(4);
    for i in 0..count {
        let id = 1000 + rng.pick(9000);
        events.push(ctx.sql(
            i,
            (i as u64) * 5,
            format!("SELECT * FROM {table} WHERE parent_id = {id}"),
            700 + (rng.pick(400) as u64),
        ));
    }
}

/// The same query with the same literal repeated verbatim.
fn push_redundant(events: &mut Vec<SpanEvent>, ctx: &TraceCtx, rng: &mut Rng) {
    let table = SQL_TABLES[rng.pick(SQL_TABLES.len())];
    let id = 1000 + rng.pick(9000);
    let target = format!("SELECT * FROM {table} WHERE id = {id}");
    for i in 0..5 {
        events.push(ctx.sql(i, (i as u64) * 4, target.clone(), 600));
    }
}

/// Many outbound HTTP calls from one trace (chatty service).
fn push_chatty(events: &mut Vec<SpanEvent>, ctx: &TraceCtx) {
    for i in 0..16 {
        let route = HTTP_ROUTES[i % HTTP_ROUTES.len()];
        events.push(ctx.http(i, (i as u64) * 3, format!("{route}/{}", 100 + i), 8_000));
    }
}

/// One parent span with an excessive number of children.
fn push_fanout(events: &mut Vec<SpanEvent>, ctx: &TraceCtx, rng: &mut Rng) {
    let parent = ctx.http(0, 0, format!("{}/batch", HTTP_ROUTES[0]), 90_000);
    let parent_id = parent.span_id.clone();
    events.push(parent);
    let route = HTTP_ROUTES[rng.pick(HTTP_ROUTES.len())];
    for i in 1..=25 {
        let mut child = ctx.http(i, 1 + (i as u64), format!("{route}/{}", 200 + i), 6_000);
        child.parent_span_id = Some(parent_id.clone());
        events.push(child);
    }
}

/// A recurring query far above the slow threshold.
fn push_slow(events: &mut Vec<SpanEvent>, ctx: &TraceCtx, rng: &mut Rng) {
    let table = SQL_TABLES[rng.pick(SQL_TABLES.len())];
    for i in 0..3 {
        events.push(ctx.sql(
            i,
            (i as u64) * 10,
            format!("SELECT * FROM {table} ORDER BY created_at DESC LIMIT 50"),
            800_000 + (rng.pick(400_000) as u64),
        ));
    }
}

/// Varied, non-repeating I/O: no finding expected.
fn push_clean(events: &mut Vec<SpanEvent>, ctx: &TraceCtx, count: usize, rng: &mut Rng) {
    for i in 0..count.max(2) {
        let offset = (i as u64) * 7;
        if i % 3 == 2 {
            let route = HTTP_ROUTES[rng.pick(HTTP_ROUTES.len())];
            events.push(ctx.http(i, offset, format!("{route}/{}", 300 + i), 9_000));
        } else {
            let table = SQL_TABLES[(i + rng.pick(3)) % SQL_TABLES.len()];
            let id = 1000 + rng.pick(9000);
            events.push(ctx.sql(
                i,
                offset,
                format!("SELECT id, status FROM {table} WHERE id = {id} AND tenant = 'a{i}'"),
                900,
            ));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn generation_is_deterministic() {
        let spec = SynthSpec::default();
        let a = generate(&spec);
        let b = generate(&spec);
        assert_eq!(a.len(), b.len());
        assert_eq!(a[0].trace_id, b[0].trace_id);
        assert_eq!(a[a.len() - 1].target, b[b.len() - 1].target);
    }

    #[test]
    fn different_seeds_differ() {
        let a = generate(&SynthSpec::default());
        let b = generate(&SynthSpec {
            seed: 43,
            ..SynthSpec::default()
        });
        // Trace ids embed the seed, content draws differ.
        assert_ne!(a[0].trace_id, b[0].trace_id);
    }

    #[test]
    fn target_events_is_exact() {
        let events = generate_target_events(10_000, 16, &PatternMix::default(), 7);
        assert_eq!(events.len(), 10_000);
    }

    #[test]
    fn services_are_bounded_and_used() {
        let spec = SynthSpec {
            services: 4,
            traces: 200,
            ..SynthSpec::default()
        };
        let events = generate(&spec);
        let distinct: std::collections::HashSet<&str> =
            events.iter().map(|e| e.service.as_ref()).collect();
        assert!(distinct.len() <= 4);
        assert!(distinct.len() >= 2, "expected several services in use");
    }

    #[test]
    fn pipeline_detects_planted_patterns() {
        // End-to-end sanity: the default mix must produce findings of the
        // planted kinds when run through the real pipeline.
        let spec = SynthSpec {
            services: 4,
            traces: 300,
            ..SynthSpec::default()
        };
        let events = generate(&spec);
        let config = crate::config::Config::default();
        let report = crate::pipeline::analyze(events, &config);
        assert!(
            report.analysis.traces_analyzed >= 290,
            "traces should flow through, got {}",
            report.analysis.traces_analyzed
        );
        let types: std::collections::HashSet<&str> = report
            .findings
            .iter()
            .map(|f| f.finding_type.as_str())
            .collect();
        for expected in ["n_plus_one_sql", "redundant_sql", "slow_sql"] {
            assert!(
                types.contains(expected),
                "expected planted {expected} findings, got types {types:?}"
            );
        }
    }
}