perf-sentinel-core 0.7.2

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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Shared timestamp conversion helpers.
//!
//! This module is the **single source of truth** for civil-calendar
//! arithmetic in the crate. Both directions are here: epoch → ISO 8601
//! (via [`nanos_to_iso8601`] / [`micros_to_iso8601`]) and ISO 8601 →
//! epoch ms (via [`parse_iso8601_utc_to_ms`]). Do not reimplement the
//! Howard-Hinnant `days_from_civil` formulas anywhere else, call these
//! helpers so a single bug fix propagates to every call site.

/// Convert nanoseconds since epoch to an ISO 8601 timestamp string.
///
/// Format: `YYYY-MM-DDTHH:MM:SS.mmmZ` (always UTC, 3 fractional digits).
#[must_use]
pub(crate) fn nanos_to_iso8601(nanos: u64) -> String {
    const NANOS_PER_SEC: u64 = 1_000_000_000;
    const SECS_PER_MIN: u64 = 60;
    const SECS_PER_HOUR: u64 = 3600;
    const SECS_PER_DAY: u64 = 86400;

    let total_secs = nanos / NANOS_PER_SEC;
    let millis = (nanos % NANOS_PER_SEC) / 1_000_000;

    // Days since epoch
    let mut days = total_secs / SECS_PER_DAY;
    let day_secs = total_secs % SECS_PER_DAY;

    let hours = day_secs / SECS_PER_HOUR;
    let minutes = (day_secs % SECS_PER_HOUR) / SECS_PER_MIN;
    let seconds = day_secs % SECS_PER_MIN;

    // Convert days since epoch to year/month/day
    // Algorithm from https://howardhinnant.github.io/date_algorithms.html
    days += 719_468; // shift to 0000-03-01
    let era = days / 146_097;
    let doe = days - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };

    format!("{y:04}-{m:02}-{d:02}T{hours:02}:{minutes:02}:{seconds:02}.{millis:03}Z")
}

/// Convert microseconds since epoch to an ISO 8601 timestamp string.
#[must_use]
pub(crate) fn micros_to_iso8601(micros: u64) -> String {
    nanos_to_iso8601(micros.saturating_mul(1000))
}

/// Convert epoch milliseconds to ISO 8601 UTC string.
pub(crate) fn millis_to_iso8601(ms: u64) -> String {
    nanos_to_iso8601(ms.saturating_mul(1_000_000))
}

/// Extract the UTC hour (0-23) from an ISO 8601 timestamp string.
///
/// Accepts the canonical `YYYY-MM-DDTHH:MM:SS[.fff]Z` form and the
/// space-separated `YYYY-MM-DD HH:MM:SS[.fff]Z` form. Returns `None` for:
/// - strings shorter than 13 bytes
/// - strings without a `T` or space at position 10
/// - non-numeric hour digits at positions 11-12
/// - hours outside `0..24`
/// - strings that do not end with `Z` (non-UTC offsets like `+02:00`
///   are rejected rather than silently shifted, the embedded hourly
///   carbon profile table is UTC-anchored, so naive offset handling
///   would poison CO₂ estimates)
///
/// Used by the hourly carbon profile path in
/// `score::compute_carbon_report`. Callers that receive `None` should
/// fall back to the flat annual intensity for the region (no sentinel
/// hour, a wrong hour would silently skew the estimate).
#[must_use]
pub(crate) fn parse_utc_hour(ts: &str) -> Option<u8> {
    // Strict ASCII-only parsing. If the string contains non-ASCII bytes
    // the indexing into `bytes` below would misalign with character
    // boundaries, but ASCII is all we need for ISO 8601.
    if !ts.is_ascii() {
        return None;
    }
    let bytes = ts.as_bytes();
    if bytes.len() < 13 {
        return None;
    }
    // Position 10 must be the date/time separator: 'T' (canonical) or
    // ' ' (space-separated variant used by some loggers).
    if bytes[10] != b'T' && bytes[10] != b' ' {
        return None;
    }
    // Positions 11-12 are the two-digit hour. Manually validate each
    // digit so `"1a"` or `"  "` produce `None` instead of silently
    // landing on hour 0.
    let h1 = bytes[11].checked_sub(b'0').filter(|&d| d <= 9)?;
    let h2 = bytes[12].checked_sub(b'0').filter(|&d| d <= 9)?;
    let hour = h1 * 10 + h2;
    if hour >= 24 {
        return None;
    }
    // Must end with 'Z' to be UTC. This rejects the `+HH:MM` / `-HH:MM`
    // offset forms deliberately, they would require a proper offset
    // subtraction that we don't support yet and silently treating
    // local hours as UTC would bias the carbon estimate systematically.
    if !ts.ends_with('Z') {
        return None;
    }
    Some(hour)
}

/// Extract the UTC month (0-indexed: 0 = January, 11 = December) from
/// an ISO 8601 timestamp string.
///
/// Parses positions 5-6 of `YYYY-MM-DD...` (the `MM` field). Same
/// ASCII-only and UTC-only constraints as [`parse_utc_hour`], but with
/// a lower minimum length (7 bytes vs 13). In practice, always called
/// alongside `parse_utc_hour` which provides the stricter check.
///
/// Returns `None` for strings shorter than 7 bytes, non-numeric month
/// digits or months outside 01..=12. The returned value is 0-indexed
/// for direct use as an array index into `[[f64; 24]; 12]`.
#[must_use]
pub(crate) fn parse_utc_month(ts: &str) -> Option<u8> {
    if !ts.is_ascii() {
        return None;
    }
    let bytes = ts.as_bytes();
    if bytes.len() < 7 {
        return None;
    }
    // Position 4 must be '-' (YYYY-MM).
    if bytes[4] != b'-' {
        return None;
    }
    let m1 = bytes[5].checked_sub(b'0').filter(|&d| d <= 9)?;
    let m2 = bytes[6].checked_sub(b'0').filter(|&d| d <= 9)?;
    let month = m1 * 10 + m2;
    if !(1..=12).contains(&month) {
        return None;
    }
    // Same UTC check as parse_utc_hour.
    if !ts.ends_with('Z') {
        return None;
    }
    Some(month - 1) // 0-indexed
}

/// Parse an ISO 8601 UTC timestamp into milliseconds since epoch.
///
/// Accepts the same forms as [`parse_utc_hour`] plus the full
/// `YYYY-MM-DDTHH:MM:SS[.fff]Z` variant:
///
/// - `T` or space between date and time
/// - fractional seconds with 1 to 9 digits (truncated to 3 for ms)
/// - must end with `Z` (UTC); non-UTC offsets are rejected
///
/// Uses Howard Hinnant's civil-date algorithm (the inverse of
/// [`nanos_to_iso8601`]) so both directions share the same source of
/// truth for leap-year handling and month-length arithmetic.
///
/// # Errors
///
/// Returns `Err` with a short human-readable message for non-UTC
/// timestamps, unparseable fields, out-of-range values or years before
/// 1970.
pub(crate) fn parse_iso8601_utc_to_ms(s: &str) -> Result<u64, String> {
    let s = s.trim();
    if !s.ends_with('Z') {
        return Err("only UTC timestamps (ending with 'Z') are supported".to_string());
    }
    let without_z = &s[..s.len() - 1];
    let (date_part, time_part) = split_date_time(without_z)?;
    let (year, month, day) = parse_date_ymd(date_part)?;
    let (hours, minutes, seconds, millis) = parse_time_hms(time_part)?;
    let days = civil_date_to_days(year, month, day);
    Ok(days * 86_400_000 + hours * 3_600_000 + minutes * 60_000 + seconds * 1_000 + millis)
}

/// Split the pre-`Z`-stripped timestamp into its date and time halves.
/// Accepts both `T` and space as the separator. Private helper for
/// [`parse_iso8601_utc_to_ms`].
fn split_date_time(without_z: &str) -> Result<(&str, &str), String> {
    if let Some(pos) = without_z.find('T') {
        Ok((&without_z[..pos], &without_z[pos + 1..]))
    } else if let Some(pos) = without_z.find(' ') {
        Ok((&without_z[..pos], &without_z[pos + 1..]))
    } else {
        Err("expected 'T' or space between date and time".to_string())
    }
}

/// Parse the `YYYY-MM-DD` half into its numeric components. Rejects
/// years before 1970 and out-of-range month/day values.
fn parse_date_ymd(date_part: &str) -> Result<(u64, u64, u64), String> {
    let date_parts: Vec<&str> = date_part.split('-').collect();
    if date_parts.len() != 3 {
        return Err("expected date format YYYY-MM-DD".to_string());
    }
    let year: u64 = date_parts[0]
        .parse()
        .map_err(|_| "invalid year".to_string())?;
    let month: u64 = date_parts[1]
        .parse()
        .map_err(|_| "invalid month".to_string())?;
    let day: u64 = date_parts[2]
        .parse()
        .map_err(|_| "invalid day".to_string())?;
    if year < 1970 {
        return Err("year must be >= 1970".to_string());
    }
    if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
        return Err("month or day out of range".to_string());
    }
    Ok((year, month, day))
}

/// Parse the `HH:MM:SS[.fff]` half into its numeric components. Fractional
/// seconds shorter than 3 digits are left-padded; longer ones are truncated.
fn parse_time_hms(time_part: &str) -> Result<(u64, u64, u64, u64), String> {
    let (time_no_frac, millis) = parse_fractional_seconds(time_part)?;
    let time_parts: Vec<&str> = time_no_frac.split(':').collect();
    if time_parts.len() != 3 {
        return Err("expected time format HH:MM:SS".to_string());
    }
    let hours: u64 = time_parts[0]
        .parse()
        .map_err(|_| "invalid hours".to_string())?;
    let minutes: u64 = time_parts[1]
        .parse()
        .map_err(|_| "invalid minutes".to_string())?;
    let seconds: u64 = time_parts[2]
        .parse()
        .map_err(|_| "invalid seconds".to_string())?;
    if hours >= 24 || minutes >= 60 || seconds >= 60 {
        return Err("time values out of range".to_string());
    }
    Ok((hours, minutes, seconds, millis))
}

/// Split `HH:MM:SS[.fff]` at the decimal point and return the seconds
/// part along with the normalized millisecond value.
fn parse_fractional_seconds(time_part: &str) -> Result<(&str, u64), String> {
    let Some(dot_pos) = time_part.find('.') else {
        return Ok((time_part, 0u64));
    };
    let frac = &time_part[dot_pos + 1..];
    // 1-digit → tenths, 2-digit → hundredths, 3-digit → ms, >3 → truncate.
    let digits = frac.len().min(3);
    let ms: u64 = frac[..digits]
        .parse::<u64>()
        .map_err(|_| "invalid fractional seconds".to_string())?;
    let normalized = ms * 10u64.pow(3 - digits as u32);
    Ok((&time_part[..dot_pos], normalized))
}

/// Howard Hinnant's `days_from_civil` (inverse of the epoch-to-ISO path
/// in [`nanos_to_iso8601`]). Shifts the year so March is month 0, then
/// computes era / yoe / doy / doe. See
/// <https://howardhinnant.github.io/date_algorithms.html>.
///
/// Assumes `parse_date_ymd` has already validated ranges.
fn civil_date_to_days(year: u64, month: u64, day: u64) -> u64 {
    let (y, m) = if month <= 2 {
        (year - 1, month + 9)
    } else {
        (year, month - 3)
    };
    let era = y / 400;
    let yoe = y - era * 400;
    let doy = (153 * m + 2) / 5 + day - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

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

    #[test]
    fn nanos_basic() {
        let ts = nanos_to_iso8601(1_720_621_921_123_000_000);
        assert_eq!(ts, "2024-07-10T14:32:01.123Z");
    }

    #[test]
    fn micros_basic() {
        let ts = micros_to_iso8601(1_720_621_921_123_000);
        assert_eq!(ts, "2024-07-10T14:32:01.123Z");
    }

    #[test]
    fn zero_epoch() {
        assert_eq!(nanos_to_iso8601(0), "1970-01-01T00:00:00.000Z");
    }

    // --- parse_utc_hour ---

    #[test]
    fn parse_utc_hour_canonical() {
        assert_eq!(parse_utc_hour("2025-07-10T14:32:01.123Z"), Some(14));
        assert_eq!(parse_utc_hour("2025-07-10T00:00:00.000Z"), Some(0));
        assert_eq!(parse_utc_hour("2025-07-10T23:59:59.999Z"), Some(23));
    }

    #[test]
    fn parse_utc_hour_no_fraction() {
        // "2025-07-10T09:30:00Z", no millisecond fraction is still valid.
        assert_eq!(parse_utc_hour("2025-07-10T09:30:00Z"), Some(9));
    }

    #[test]
    fn parse_utc_hour_space_separator() {
        // Some loggers emit a space instead of 'T' between date and time.
        assert_eq!(parse_utc_hour("2025-07-10 14:32:01.123Z"), Some(14));
    }

    #[test]
    fn parse_utc_hour_rejects_nonutc_offset() {
        // +02:00 offset must NOT be silently treated as UTC.
        assert_eq!(parse_utc_hour("2025-07-10T14:32:01.123+02:00"), None);
        assert_eq!(parse_utc_hour("2025-07-10T14:32:01-05:00"), None);
    }

    #[test]
    fn parse_utc_hour_rejects_truncated_string() {
        assert_eq!(parse_utc_hour(""), None);
        assert_eq!(parse_utc_hour("2025-07-10"), None);
        assert_eq!(parse_utc_hour("2025-07-10T14"), None); // len 13 but no Z
    }

    #[test]
    fn parse_utc_hour_rejects_invalid_separator() {
        // Position 10 must be 'T' or ' '. An underscore or hyphen there
        // is not a valid ISO 8601 variant we support.
        assert_eq!(parse_utc_hour("2025-07-10_14:32:01Z"), None);
        assert_eq!(parse_utc_hour("2025-07-10-14:32:01Z"), None);
    }

    #[test]
    fn parse_utc_hour_rejects_non_numeric_hour() {
        assert_eq!(parse_utc_hour("2025-07-10Tab:32:01Z"), None);
        assert_eq!(parse_utc_hour("2025-07-10T  :32:01Z"), None);
    }

    #[test]
    fn parse_utc_hour_rejects_hour_24_or_above() {
        // Hour 24 is not a valid ISO 8601 value (use 00 next day instead).
        assert_eq!(parse_utc_hour("2025-07-10T24:00:00Z"), None);
        assert_eq!(parse_utc_hour("2025-07-10T99:00:00Z"), None);
    }

    #[test]
    fn parse_utc_hour_rejects_missing_trailing_z() {
        // Must end with 'Z'. This rules out naked local-time strings.
        assert_eq!(parse_utc_hour("2025-07-10T14:32:01.123"), None);
    }

    #[test]
    fn parse_utc_hour_rejects_non_ascii() {
        // Multi-byte characters would misalign the byte indexing above.
        // The function returns None instead of panicking.
        assert_eq!(parse_utc_hour("2025-07-10T14\u{00E9}:32:01Z"), None);
    }

    // --- parse_utc_month ---

    #[test]
    fn parse_utc_month_canonical() {
        assert_eq!(parse_utc_month("2025-01-10T14:32:01.123Z"), Some(0)); // Jan
        assert_eq!(parse_utc_month("2025-06-15T00:00:00.000Z"), Some(5)); // Jun
        assert_eq!(parse_utc_month("2025-07-10T14:32:01.123Z"), Some(6)); // Jul
        assert_eq!(parse_utc_month("2025-12-31T23:59:59.999Z"), Some(11)); // Dec
    }

    #[test]
    fn parse_utc_month_all_months() {
        for m in 1..=12_u8 {
            let ts = format!("2025-{m:02}-10T12:00:00Z");
            assert_eq!(parse_utc_month(&ts), Some(m - 1), "month {m:02}");
        }
    }

    #[test]
    fn parse_utc_month_rejects_month_00() {
        assert_eq!(parse_utc_month("2025-00-10T14:32:01Z"), None);
    }

    #[test]
    fn parse_utc_month_rejects_month_13() {
        assert_eq!(parse_utc_month("2025-13-10T14:32:01Z"), None);
    }

    #[test]
    fn parse_utc_month_rejects_truncated() {
        assert_eq!(parse_utc_month(""), None);
        assert_eq!(parse_utc_month("2025-0"), None);
        assert_eq!(parse_utc_month("2025"), None);
    }

    #[test]
    fn parse_utc_month_rejects_non_utc() {
        assert_eq!(parse_utc_month("2025-07-10T14:32:01+02:00"), None);
        assert_eq!(parse_utc_month("2025-07-10T14:32:01-05:00"), None);
    }

    #[test]
    fn parse_utc_month_rejects_non_ascii() {
        assert_eq!(parse_utc_month("2025\u{00E9}07-10T14:32:01Z"), None);
    }

    #[test]
    fn parse_utc_month_rejects_non_numeric() {
        assert_eq!(parse_utc_month("2025-ab-10T14:32:01Z"), None);
    }

    #[test]
    fn parse_utc_month_rejects_missing_dash() {
        assert_eq!(parse_utc_month("2025007-10T14:32:01Z"), None);
    }

    // --- parse_iso8601_utc_to_ms ---

    #[test]
    fn parse_iso8601_round_trips_with_nanos_to_iso8601() {
        // Round-trip: nanos → ISO → ms → verify consistency. This is
        // the critical cross-function invariant: both directions must
        // agree on day counting and leap-year handling.
        let nanos = 1_720_621_921_123_000_000u64; // 2024-07-10T14:32:01.123Z
        let iso = nanos_to_iso8601(nanos);
        let ms = parse_iso8601_utc_to_ms(&iso).unwrap();
        assert_eq!(ms, nanos / 1_000_000);
    }

    #[test]
    fn parse_iso8601_epoch_zero() {
        let ms = parse_iso8601_utc_to_ms("1970-01-01T00:00:00.000Z").unwrap();
        assert_eq!(ms, 0);
    }

    #[test]
    fn parse_iso8601_without_fractional_seconds() {
        let ms = parse_iso8601_utc_to_ms("2025-07-10T14:32:01Z").unwrap();
        assert_eq!(ms % 1000, 0);
    }

    #[test]
    fn parse_iso8601_space_separator() {
        let ms_t = parse_iso8601_utc_to_ms("2025-07-10T14:32:01.123Z").unwrap();
        let ms_sp = parse_iso8601_utc_to_ms("2025-07-10 14:32:01.123Z").unwrap();
        assert_eq!(ms_t, ms_sp);
    }

    #[test]
    fn parse_iso8601_rejects_non_utc() {
        assert!(parse_iso8601_utc_to_ms("2025-07-10T14:32:01.123+02:00").is_err());
        assert!(parse_iso8601_utc_to_ms("2025-07-10T14:32:01.123").is_err());
    }

    #[test]
    fn parse_iso8601_rejects_pre_epoch() {
        assert!(parse_iso8601_utc_to_ms("1969-12-31T23:59:59Z").is_err());
    }

    #[test]
    fn parse_iso8601_rejects_invalid_month_day() {
        assert!(parse_iso8601_utc_to_ms("2025-13-01T00:00:00Z").is_err());
        assert!(parse_iso8601_utc_to_ms("2025-00-01T00:00:00Z").is_err());
        assert!(parse_iso8601_utc_to_ms("2025-06-32T00:00:00Z").is_err());
    }

    #[test]
    fn parse_iso8601_rejects_invalid_time() {
        assert!(parse_iso8601_utc_to_ms("2025-06-01T24:00:00Z").is_err());
        assert!(parse_iso8601_utc_to_ms("2025-06-01T12:60:00Z").is_err());
        assert!(parse_iso8601_utc_to_ms("2025-06-01T12:00:60Z").is_err());
    }

    #[test]
    fn parse_iso8601_rejects_malformed_date_field_count() {
        assert!(parse_iso8601_utc_to_ms("2025/07/10T14:32:01Z").is_err());
    }
}