inky-engine 3.0.3

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
//! Operator metrics: the scheduler's live counters, the periodic snapshot writer (`INK_METRICS_SNAPSHOT_SECS`)
//! and the OS memory readings both it and `GET /metrics` (`INK_OPERATOR_KEY_ENV`) report.
//! Both are internal `INK_*` diagnostics read at startup (`operator_metrics_env` in main.rs), undocumented for users.
//!
//! The scheduler only stores atomics here, and only while an operator surface is on; the snapshot thread reads
//! them on its own schedule and hands each line to a bounded, non-blocking recorder queue. Nothing here is ever
//! in `/health`, and every value is a number: no prompt text, card ids or keys.
//!
//! A file's epoch is complete only if it ends with a `sample_kind` 2 line. No final line means the process
//! died without one (SIGKILL, a crash, power): treat that epoch as incomplete, its last interval unknown. A final
//! line with `end_censored` 1 means requests were still in flight (`inflight_at_end`) when it stopped.
use serde_json::{Map, Value};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::Mutex;
use std::time::Duration;

use super::block_cache::CacheStats;

/// Version of the snapshot line and `/metrics` body. Bump on a renamed or re-meant field.
pub(super) const METRICS_SCHEMA_VERSION: u64 = 1;

/// How often the scheduler rescans the KV pools for slot occupancy while metrics are on (an O(slots) walk).
pub(super) const POOL_SCAN_EVERY: Duration = Duration::from_secs(1);

/// What a snapshot line marks: `sample_kind` 0 is the first line of a process epoch, 1 a periodic one and
/// 2 the last one, at scheduler drain or on SIGTERM / SIGINT.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SampleKind {
    Start = 0,
    Periodic = 1,
    Shutdown = 2,
}

/// A scheduler step class for call and wall accounting. A DSpark verify step is its own class.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum StepPhase {
    Prefill = 0,
    Decode = 1,
    Verify = 2,
    Mixed = 3,
}

impl StepPhase {
    pub(super) const ALL: [StepPhase; 4] = [
        StepPhase::Prefill,
        StepPhase::Decode,
        StepPhase::Verify,
        StepPhase::Mixed,
    ];

    fn name(self) -> &'static str {
        match self {
            StepPhase::Prefill => "prefill",
            StepPhase::Decode => "decode",
            StepPhase::Verify => "verify",
            StepPhase::Mixed => "mixed",
        }
    }
}

/// Classify a step's wall-time bucket from the surviving decode and prefill spans AFTER the KV pool check.
#[inline]
pub(super) fn classify_surviving_step_phase(n_dec: usize, n_pf_spans: usize) -> Option<StepPhase> {
    match (n_dec > 0, n_pf_spans > 0) {
        (false, false) => None,
        (true, false) => Some(StepPhase::Decode),
        (false, true) => Some(StepPhase::Prefill),
        (true, true) => Some(StepPhase::Mixed),
    }
}

/// Calls and untruncated host wall time of one step class, succeeded and failed counted apart.
#[derive(Default)]
pub(super) struct StepCounters {
    calls: AtomicU64,
    /// Rows the successful steps computed: ordinary decode rows, or verify target positions (`1 + k` per lane).
    rows: AtomicU64,
    wall_us: AtomicU64,
    failed_calls: AtomicU64,
    failed_wall_us: AtomicU64,
}

/// Counters the scheduler publishes for `/health` (pool deferrals, always) and for the operator surfaces
/// (everything else, only while `enabled`).
#[derive(Default)]
pub(super) struct LiveCounters {
    pub(super) admit_pool_deferrals: AtomicU64,
    pub(super) step_pool_deferrals: AtomicU64,
    /// The pool livelock escape (no lane could take its next block and none could free one): requests it took
    /// off a lane and queued to resume, preempted requests admitted again, and requests it failed (HTTP 500)
    /// because no lane could be preempted.
    pub(super) pool_preemptions: AtomicU64,
    pub(super) pool_resumes: AtomicU64,
    pub(super) pool_victims_failed: AtomicU64,
    pub(super) think_budget_hits: AtomicU64,
    /// Answer/tool body tokens emitted after a forced thinking close.
    pub(super) think_cap_answer_tokens: AtomicU64,
    /// Capped turns whose forced close was followed by a tool call.
    pub(super) think_cap_tool_calls: AtomicU64,
    /// Turns whose thinking budget was lowered to keep answer room inside `max_tokens`.
    pub(super) think_cap_room_clamped: AtomicU64,
    /// `/health`, summed over finished turns: `<|endoftext|>` masked out of a greedy argmax / a sampled top-k set,
    /// `<|endoftext|>` sent to a client (must stay 0), tool calls sent as `{"_unparsed": ...}`, and tool bodies a
    /// length stop cut off.
    pub(super) eot_masked_greedy: AtomicU64,
    pub(super) eot_masked_sampled: AtomicU64,
    pub(super) eot_emitted: AtomicU64,
    pub(super) tool_call_parse_fallback: AtomicU64,
    pub(super) tool_call_dropped_at_length: AtomicU64,
    /// The tool-header mask, summed over finished turns: masked header draws, those whose top token named no
    /// offered tool, and tool markers drawn away from an offered header by a path without a mask (rewritten).
    pub(super) tool_header_draws: AtomicU64,
    pub(super) tool_header_masked: AtomicU64,
    pub(super) tool_marker_rewritten: AtomicU64,
    /// Must stay 0: completed tool bodies under a name the request did not offer, calls sent under an offered
    /// name the model did not give consistently, and tool bodies cut by a role stop or another marker.
    pub(super) tool_call_unoffered_name: AtomicU64,
    pub(super) tool_call_malformed: AtomicU64,
    pub(super) tool_call_dropped_at_marker: AtomicU64,
    /// Always on: ready, dispatched and per-reason skipped lanes per step (`/health` `dispatch_waits`).
    pub(super) dispatch: super::dispatch_trace::DispatchCounters,
    /// `INK_DISPATCH_TRACE=1`: the buffered per-step trace into `--record-dir`.
    pub(super) dispatch_trace: std::sync::OnceLock<std::sync::Arc<super::dispatch_trace::DispatchTrace>>,
    /// A snapshot writer or `/metrics` is configured: the scheduler publishes the counters below.
    enabled: AtomicBool,
    pub(super) lanes_restoring: AtomicUsize,
    pub(super) lanes_prefilling: AtomicUsize,
    pub(super) lanes_decoding: AtomicUsize,
    /// Per lane slot, the ordinal (`Job::seq`) of the request it holds, 0 when empty. A reused slot shows its
    /// new request's ordinal.
    lane_seqs: Mutex<Vec<u64>>,
    steps: [StepCounters; 4],
    mixed_decode_rows: AtomicU64,
    mixed_prefill_rows: AtomicU64,
    batched_span_logits_steps: AtomicU64,
    mixed_tail_plans: AtomicU64,
    moe_decode_rg_passes: AtomicU64,
    parallel_cpu_sample_rows: AtomicU64,
    chunked_decode_steps: AtomicU64,
    mix_wave_dispatches: AtomicU64,
    prefill_span_keeps: AtomicU64,
    pub(super) retained_host_bytes: AtomicU64,
    pub(super) retained_host_budget_bytes: AtomicU64,
    pub(super) retained_starts: AtomicU64,
    pub(super) kv_window_slots_used: AtomicU64,
    pub(super) kv_window_slots_capacity: AtomicU64,
    pub(super) kv_full_slots_used: AtomicU64,
    pub(super) kv_full_slots_capacity: AtomicU64,
    cache_stats: Mutex<CacheStats>,
    /// This process epoch (Unix ms at serve start), the same on every snapshot line and `/metrics` body.
    pub(super) epoch: AtomicU64,
    /// The last power source seen: 0 unknown, 1 mains, 2 battery.
    last_power: AtomicU64,
    power_changes: AtomicU64,
}

impl LiveCounters {
    pub(super) fn enable(&self) {
        self.enabled.store(true, Ordering::Relaxed);
    }

    pub(super) fn on(&self) -> bool {
        self.enabled.load(Ordering::Relaxed)
    }

    /// Count one step of `phase` that took `elapsed` of host wall time (encode to completion, untruncated).
    pub(super) fn step(&self, phase: StepPhase, elapsed: Duration, failed: bool) {
        if !self.on() {
            return;
        }
        let c = &self.steps[phase as usize];
        let us = u64::try_from(elapsed.as_micros()).unwrap_or(u64::MAX);
        if failed {
            c.failed_calls.fetch_add(1, Ordering::Relaxed);
            c.failed_wall_us.fetch_add(us, Ordering::Relaxed);
        } else {
            c.calls.fetch_add(1, Ordering::Relaxed);
            c.wall_us.fetch_add(us, Ordering::Relaxed);
        }
    }

    /// Count `n` rows computed by a successful step of `phase` (decode rows that sampled a reply token, or verify
    /// target positions), apart from its calls and from the tokens it emitted.
    pub(super) fn rows(&self, phase: StepPhase, n: usize) {
        if self.on() {
            self.steps[phase as usize].rows.fetch_add(n as u64, Ordering::Relaxed);
        }
    }

    /// Conv states kept at start-point checkpoints inside prefill spans (spans through checkpoints, `INK_PREFILL_CKPT_SPLIT`): each is a split step not run.
    pub(super) fn add_prefill_span_keeps(&self, n: u64) {
        if self.on() {
            self.prefill_span_keeps.fetch_add(n, Ordering::Relaxed);
        }
    }

    /// Plain decode steps committed in chunks (`INK_CB_CHUNK`), as the engine counts them (published once a step).
    pub(super) fn set_chunked_decode_steps(&self, n: u64) {
        if self.on() {
            self.chunked_decode_steps.store(n, Ordering::Relaxed);
        }
    }

    /// Decode rows drawn on the parallel CPU sampler's threads (`INK_PARALLEL_CPU_SAMPLE`).
    pub(super) fn add_parallel_cpu_sample_rows(&self, n: u64) {
        if self.on() && n > 0 {
            self.parallel_cpu_sample_rows.fetch_add(n, Ordering::Relaxed);
        }
    }

    /// Layer passes whose grouped MoE decode ran the register-fed class-1 kernels (`k_moe_dec_rg*`, `INK_OLD_MOE_RG`), as the engine counts them (published once a step).
    pub(super) fn set_moe_decode_rg_passes(&self, n: u64) {
        if self.on() {
            self.moe_decode_rg_passes.store(n, Ordering::Relaxed);
        }
    }

    /// Mixer dispatches that ran several jobs as one `k_mix_wave` (`INK_DEC_FIXED_COST`), as the engine counts them (published once a step).
    pub(super) fn set_mix_wave_dispatches(&self, n: u64) {
        if self.on() {
            self.mix_wave_dispatches.store(n, Ordering::Relaxed);
        }
    }

    /// Mixed prefill+decode steps whose prefill spans took the last-layer tail trim (`mixed_tail_trim`,
    /// `INK_MIXED_TAIL_TRIM`), as the engine counts them (`Engine::mixed_tail_plans`, published once a step).
    pub(super) fn set_mixed_tail_plans(&self, n: u64) {
        if self.on() {
            self.mixed_tail_plans.store(n, Ordering::Relaxed);
        }
    }

    /// Prefill steps whose spans' logits rows ran through one batched LM-head pass (`batched_span_logits`, `INK_PER_SPAN_LOGITS`), as the engine counts them (published once a step).
    pub(super) fn set_batched_span_logits_steps(&self, n: u64) {
        if self.on() {
            self.batched_span_logits_steps.store(n, Ordering::Relaxed);
        }
    }

    /// Record surviving decode and prefill token rows executed in a `StepPhase::Mixed` step.
    pub(super) fn mixed_rows(&self, decode_rows: usize, prefill_rows: usize) {
        if self.on() {
            self.mixed_decode_rows.fetch_add(decode_rows as u64, Ordering::Relaxed);
            self.mixed_prefill_rows.fetch_add(prefill_rows as u64, Ordering::Relaxed);
        }
    }

    /// Publish each lane slot's request ordinal (0 empty) and phase counts.
    pub(super) fn publish_lanes(&self, lanes: impl Iterator<Item = LaneView>) {
        let (mut restoring, mut prefilling, mut decoding) = (0, 0, 0);
        let mut seqs = self.lane_seqs.lock().unwrap_or_else(|e| e.into_inner());
        seqs.clear();
        for lane in lanes {
            match lane {
                LaneView::Empty => seqs.push(0),
                LaneView::Restoring(seq) => {
                    restoring += 1;
                    seqs.push(seq);
                }
                LaneView::Prefilling(seq) => {
                    prefilling += 1;
                    seqs.push(seq);
                }
                LaneView::Decoding(seq) => {
                    decoding += 1;
                    seqs.push(seq);
                }
            }
        }
        drop(seqs);
        self.lanes_restoring.store(restoring, Ordering::Relaxed);
        self.lanes_prefilling.store(prefilling, Ordering::Relaxed);
        self.lanes_decoding.store(decoding, Ordering::Relaxed);
    }

    /// Note a power-source reading and return the AC-to-battery transitions seen so far. Readings are taken
    /// only at snapshots and `/metrics` requests, so a battery excursion between two of them is not seen.
    pub(super) fn note_power(&self, power: Option<Power>) -> u64 {
        if let Some(p) = power {
            let now = if p.on_ac { 1 } else { 2 };
            if self.last_power.swap(now, Ordering::Relaxed) == 1 && now == 2 {
                self.power_changes.fetch_add(1, Ordering::Relaxed);
            }
        }
        self.power_changes.load(Ordering::Relaxed)
    }

    pub(super) fn publish_cache_stats(&self, stats: CacheStats) {
        *self.cache_stats.lock().unwrap_or_else(|e| e.into_inner()) = stats;
    }

    pub(super) fn lane_seqs(&self) -> Vec<u64> {
        self.lane_seqs.lock().unwrap_or_else(|e| e.into_inner()).clone()
    }

    /// Step call and wall totals as snapshot fields.
    pub(super) fn insert_steps(&self, obj: &mut Map<String, Value>) {
        for phase in StepPhase::ALL {
            let c = &self.steps[phase as usize];
            let n = phase.name();
            put(obj, &format!("{n}_calls_total"), c.calls.load(Ordering::Relaxed));
            put(obj, &format!("{n}_host_wall_us_total"), c.wall_us.load(Ordering::Relaxed));
            put(obj, &format!("{n}_failed_calls_total"), c.failed_calls.load(Ordering::Relaxed));
            put(obj, &format!("{n}_failed_host_wall_us_total"), c.failed_wall_us.load(Ordering::Relaxed));
        }
        put(obj, "decode_rows_total", self.steps[StepPhase::Decode as usize].rows.load(Ordering::Relaxed));
        put(
            obj,
            "verify_target_positions_total",
            self.steps[StepPhase::Verify as usize].rows.load(Ordering::Relaxed),
        );
        put(obj, "mixed_decode_rows_total", self.mixed_decode_rows.load(Ordering::Relaxed));
        put(obj, "mixed_prefill_rows_total", self.mixed_prefill_rows.load(Ordering::Relaxed));
        put(obj, "batched_span_logits_steps_total", self.batched_span_logits_steps.load(Ordering::Relaxed));
        put(obj, "mixed_tail_plans_total", self.mixed_tail_plans.load(Ordering::Relaxed));
        put(obj, "moe_decode_rg_passes_total", self.moe_decode_rg_passes.load(Ordering::Relaxed));
        put(obj, "parallel_cpu_sample_rows_total", self.parallel_cpu_sample_rows.load(Ordering::Relaxed));
        put(obj, "chunked_decode_steps_total", self.chunked_decode_steps.load(Ordering::Relaxed));
        put(obj, "mix_wave_dispatches_total", self.mix_wave_dispatches.load(Ordering::Relaxed));
        put(obj, "prefill_span_keeps_total", self.prefill_span_keeps.load(Ordering::Relaxed));
    }

    /// Dynamic reuse totals: operator-only, never in `/health` (#187).
    pub(super) fn insert_reuse(&self, obj: &mut Map<String, Value>) {
        let cs = *self.cache_stats.lock().unwrap_or_else(|e| e.into_inner());
        for (k, v) in [
            ("reuse_start_matches_total", cs.start_matches),
            ("reuse_cached_tokens_total", cs.cached_tokens_total),
            ("reuse_singleflight_rebinds_total", cs.singleflight_rebinds),
            ("reuse_singleflight_saved_tokens_total", cs.singleflight_saved_tokens),
            ("reuse_approx_starts_saved_total", cs.approx_starts_saved),
            ("reuse_approx_start_matches_total", cs.approx_start_matches),
            ("reuse_approx_cached_tokens_total", cs.approx_cached_tokens_total),
            ("reuse_stitch_hits_total", cs.stitch_hits),
            ("reuse_stitched_tokens_total", cs.stitched_tokens_total),
            ("reuse_ikv_quarantined_total", cs.ikv_quarantined),
            ("reuse_starts_saved_total", cs.start_points_saved),
            ("reuse_starts_evicted_total", cs.start_points_evicted),
            ("reuse_evictions_pool_pressure_total", cs.evictions_pool_pressure),
            ("reuse_evictions_host_budget_total", cs.evictions_host_budget),
            ("reuse_evictions_approx_scope_cap_total", cs.evictions_approx_scope_cap),
            ("reuse_evictions_stale_invalid_total", cs.evictions_stale_invalid),
            ("reuse_evictions_shutdown_total", cs.evictions_shutdown),
            ("reuse_evictions_superseded_total", cs.evictions_superseded),
            ("reuse_evictions_ranked_over_lru_total", cs.evictions_ranked_over_lru),
            ("reuse_cache_activity_ticks_total", cs.activity_ticks),
            ("spill_restores_total", cs.starts_restored),
            ("spill_restores_failed_total", cs.restores_failed),
            ("spill_restore_wall_us_total", cs.restore_us_total),
            ("spill_starts_spilled_total", cs.starts_spilled),
        ] {
            put(obj, k, v);
        }
    }
}

/// One lane slot as the scheduler sees it, with its request ordinal.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum LaneView {
    Empty,
    Restoring(u64),
    Prefilling(u64),
    Decoding(u64),
}

pub(super) fn put(obj: &mut Map<String, Value>, key: &str, v: u64) {
    obj.insert(key.to_string(), Value::from(v));
}

/// The snapshot schedule of one process epoch on a monotonic millisecond clock that starts at the epoch:
/// sample `k` is due at `k * period_ms`. A sample taken late counts the due times it skipped.
#[derive(Debug)]
pub(super) struct Cadence {
    period_ms: u64,
    sample_seq: u64,
    last_mono_ms: Option<u64>,
    last_slot: u64,
    missed_total: u64,
}

/// The bookkeeping fields of one snapshot line.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Tick {
    pub(super) kind: SampleKind,
    pub(super) sample_seq: u64,
    pub(super) mono_ms: u64,
    pub(super) interval_ms: u64,
    pub(super) missed_samples_total: u64,
}

impl Cadence {
    pub(super) fn new(period: Duration) -> Self {
        let period_ms = u64::try_from(period.as_millis()).unwrap_or(u64::MAX).max(1);
        Self { period_ms, sample_seq: 0, last_mono_ms: None, last_slot: 0, missed_total: 0 }
    }

    /// Monotonic ms of the next periodic due time after the last sample.
    pub(super) fn next_due_ms(&self) -> u64 {
        self.last_slot.saturating_add(1).saturating_mul(self.period_ms)
    }

    /// Account one sample taken at `mono_ms` (ms since the epoch began).
    pub(super) fn take(&mut self, kind: SampleKind, mono_ms: u64) -> Tick {
        let interval_ms = self.last_mono_ms.map_or(0, |last| mono_ms.saturating_sub(last));
        if kind == SampleKind::Periodic {
            let slot = mono_ms / self.period_ms;
            // Due times strictly between the last sample's slot and this one never got a line.
            self.missed_total += slot.saturating_sub(self.last_slot).saturating_sub(1);
            self.last_slot = slot.max(self.last_slot);
        }
        self.last_mono_ms = Some(mono_ms);
        let tick = Tick { kind, sample_seq: self.sample_seq, mono_ms, interval_ms, missed_samples_total: self.missed_total };
        self.sample_seq += 1;
        tick
    }
}

/// Where a snapshot line goes: the metrics recorder in production, a fake in tests. `offer` never blocks.
pub(super) trait MetricsSink: Send + Sync {
    fn offer(&self, unix_ms: u64, line: &Value) -> bool;
    fn dropped_total(&self) -> u64;
    fn write_errors_total(&self) -> u64;
    /// Wait up to `wait` for offered lines to reach disk (the last line before exit).
    fn drain(&self, _wait: Duration) {}
}

impl MetricsSink for crate::record::Recorder {
    fn offer(&self, unix_ms: u64, line: &Value) -> bool {
        self.record_value(unix_ms, line)
    }

    fn dropped_total(&self) -> u64 {
        self.dropped_count() as u64
    }

    fn write_errors_total(&self) -> u64 {
        self.write_error_count() as u64
    }

    fn drain(&self, wait: Duration) {
        self.finish(wait);
    }
}

/// The header every snapshot line carries, ahead of the live counters.
pub(super) fn insert_header(obj: &mut Map<String, Value>, epoch: u64, unix_ms: u64, tick: Tick, sink: &dyn MetricsSink) {
    put(obj, "schema_version", METRICS_SCHEMA_VERSION);
    put(obj, "epoch", epoch);
    put(obj, "sample_kind", tick.kind as u64);
    put(obj, "sample_seq", tick.sample_seq);
    put(obj, "mono_ms", tick.mono_ms);
    put(obj, "unix_ms", unix_ms);
    put(obj, "interval_ms", tick.interval_ms);
    put(obj, "missed_samples_total", tick.missed_samples_total);
    put(obj, "dropped_lines_total", sink.dropped_total());
    put(obj, "write_errors_total", sink.write_errors_total());
}

/// OS memory readings, cumulative since boot where the OS keeps a counter. Absent fields could not be read.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct OsMemory {
    pub(super) page_size_bytes: Option<u64>,
    pub(super) swapins_total: Option<u64>,
    pub(super) swapouts_total: Option<u64>,
    pub(super) swap_used_bytes: Option<u64>,
    pub(super) memory_pressure_level: Option<u64>,
    /// The power source, when it could be read.
    pub(super) power: Option<Power>,
}

/// Where the machine draws power from. Timings taken off mains power are not valid M5 measurements (AGENTS.md
/// rule 1), so every line says.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Power {
    pub(super) on_ac: bool,
    /// The internal battery's charge in percent; `None` on a Mac without one.
    pub(super) battery_percent: Option<u64>,
}

/// Parse `pmset -g batt`: the first line names the source (`Now drawing from 'AC Power'` or `'Battery Power'`),
/// and a Mac with a battery adds a ` -InternalBattery-0 (id=...)\t87%; discharging; ...` line.
pub(super) fn parse_pmset_batt(text: &str) -> Option<Power> {
    let first = text.lines().next()?;
    let source = first.strip_prefix("Now drawing from '")?.split('\'').next()?;
    let on_ac = source == "AC Power";
    let battery_percent = text.lines().find(|l| l.contains("InternalBattery")).and_then(|l| {
        let before = &l[..l.find('%')?];
        let digits = before.rsplit(|c: char| !c.is_ascii_digit()).next()?;
        digits.parse::<u64>().ok().filter(|&p| p <= 100)
    });
    Some(Power { on_ac, battery_percent })
}

impl OsMemory {
    pub(super) fn insert(&self, obj: &mut Map<String, Value>) {
        for (k, v) in [
            ("os_page_size_bytes", self.page_size_bytes),
            ("os_swapins_pages_total", self.swapins_total),
            ("os_swapouts_pages_total", self.swapouts_total),
            ("os_swap_used_bytes", self.swap_used_bytes),
            ("os_memory_pressure_level", self.memory_pressure_level),
        ] {
            if let Some(v) = v {
                put(obj, k, v);
            }
        }
        // An unread power source is null (unknown), never a guessed 0 or 1.
        obj.insert("os_on_ac_power".into(), self.power.map_or(Value::Null, |p| Value::from(u64::from(p.on_ac))));
        obj.insert(
            "os_battery_percent".into(),
            self.power.and_then(|p| p.battery_percent).map_or(Value::Null, Value::from),
        );
    }

    /// Read on the snapshot thread or a `/metrics` request, never on the scheduler.
    #[cfg(target_os = "macos")]
    pub(super) fn read() -> Self {
        mac::read()
    }

    #[cfg(not(target_os = "macos"))]
    pub(super) fn read() -> Self {
        Self::default()
    }
}

/// How often the power watcher asks whether the machine is on mains power.
pub(super) const POWER_WATCH_EVERY: Duration = Duration::from_millis(250);

/// Watch the power source on its own thread while the operator metrics are on, so a short battery interval
/// between two snapshots still counts in `os_power_source_changes_total` (one excursion shorter than
/// [`POWER_WATCH_EVERY`] can still be missed). Off the scheduler; one cheap IOKit call per check.
#[cfg(target_os = "macos")]
pub(super) fn spawn_power_watch(live: std::sync::Weak<LiveCounters>) {
    let _ = std::thread::Builder::new().name("inky-power-watch".into()).spawn(move || loop {
        let Some(live) = live.upgrade() else { break };
        live.note_power(Some(Power { on_ac: mac::on_ac_power(), battery_percent: None }));
        drop(live);
        std::thread::sleep(POWER_WATCH_EVERY);
    });
}

#[cfg(not(target_os = "macos"))]
pub(super) fn spawn_power_watch(_live: std::sync::Weak<LiveCounters>) {}

#[cfg(target_os = "macos")]
mod mac {
    use super::OsMemory;

    extern "C" {
        // libc marks its own binding deprecated in favour of the mach2 crate; this is the same symbol.
        fn mach_host_self() -> libc::mach_port_t;
    }

    #[link(name = "IOKit", kind = "framework")]
    extern "C" {
        // `kIOPSTimeRemainingUnlimited` (-2.0) on mains power (and always on a Mac without a battery); the
        // seconds left, or `kIOPSTimeRemainingUnknown` (-1.0), on battery.
        fn IOPSGetTimeRemainingEstimate() -> f64;
    }

    pub(super) fn on_ac_power() -> bool {
        // SAFETY: no arguments and no preconditions; returns a plain double.
        let estimate = unsafe { IOPSGetTimeRemainingEstimate() };
        estimate == -2.0
    }

    fn sysctl<T: Copy>(name: &std::ffi::CStr) -> Option<T> {
        let mut out = std::mem::MaybeUninit::<T>::zeroed();
        let mut len = std::mem::size_of::<T>();
        // SAFETY: `out` is `len` writable bytes; the kernel writes at most `len` and reports the size it wrote.
        let rc = unsafe {
            libc::sysctlbyname(name.as_ptr(), out.as_mut_ptr().cast(), &mut len, std::ptr::null_mut(), 0)
        };
        // SAFETY: a zeroed `T` of these plain-integer types is valid even if the kernel wrote less.
        (rc == 0 && len == std::mem::size_of::<T>()).then(|| unsafe { out.assume_init() })
    }

    pub(super) fn read() -> OsMemory {
        let mut os = OsMemory::default();
        // SAFETY: sysconf has no preconditions.
        let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
        os.page_size_bytes = u64::try_from(page).ok().filter(|&p| p > 0);
        let mut vm = std::mem::MaybeUninit::<libc::vm_statistics64>::zeroed();
        let mut count = libc::HOST_VM_INFO64_COUNT;
        // SAFETY: `vm` holds HOST_VM_INFO64_COUNT integers, the count we pass; the kernel fills at most that many.
        let kr = unsafe {
            libc::host_statistics64(mach_host_self(), libc::HOST_VM_INFO64, vm.as_mut_ptr().cast(), &mut count)
        };
        if kr == libc::KERN_SUCCESS {
            // SAFETY: zero-initialised plain integers, filled by the kernel.
            let vm = unsafe { vm.assume_init() };
            os.swapins_total = Some(vm.swapins);
            os.swapouts_total = Some(vm.swapouts);
        }
        os.swap_used_bytes = sysctl::<libc::xsw_usage>(c"vm.swapusage").map(|x| x.xsu_used);
        os.memory_pressure_level =
            sysctl::<libc::c_int>(c"kern.memorystatus_vm_pressure_level").and_then(|v| u64::try_from(v).ok());
        // What `pmset` reads from IOKit's power sources, via pmset itself: no CoreFoundation FFI to keep. A child
        // process every snapshot interval, on the snapshot thread (std resets the signal mask in the child).
        os.power = std::process::Command::new("/usr/bin/pmset")
            .args(["-g", "batt"])
            .stdin(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .output()
            .ok()
            .filter(|o| o.status.success())
            .and_then(|o| super::parse_pmset_batt(&String::from_utf8_lossy(&o.stdout)));
        os
    }
}

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

    #[test]
    fn cadence_counts_a_missed_due_time_and_restarts_per_epoch() {
        let mut c = Cadence::new(Duration::from_secs(10));
        let start = c.take(SampleKind::Start, 0);
        assert_eq!((start.sample_seq, start.interval_ms, start.missed_samples_total), (0, 0, 0));
        assert_eq!(c.next_due_ms(), 10_000);
        let p1 = c.take(SampleKind::Periodic, 10_003);
        assert_eq!((p1.sample_seq, p1.interval_ms, p1.missed_samples_total), (1, 10_003, 0));
        assert_eq!(c.next_due_ms(), 20_000);
        // The thread wakes at 41 s: the 20 s and 30 s samples never happened.
        let p2 = c.take(SampleKind::Periodic, 41_000);
        assert_eq!((p2.sample_seq, p2.interval_ms, p2.missed_samples_total), (2, 30_997, 2));
        assert_eq!(c.next_due_ms(), 50_000);
        let end = c.take(SampleKind::Shutdown, 43_500);
        assert_eq!((end.kind, end.sample_seq, end.interval_ms, end.missed_samples_total), (SampleKind::Shutdown, 3, 2_500, 2));
        // A restart is a new epoch: its schedule and sequence begin again.
        let mut again = Cadence::new(Duration::from_secs(10));
        let s2 = again.take(SampleKind::Start, 0);
        assert_eq!((s2.sample_seq, s2.missed_samples_total), (0, 0));
    }


    #[test]
    fn mixed_step_counters_partition_wall_and_reclassify_pool_deferral() {
        assert_eq!(classify_surviving_step_phase(0, 0), None);
        assert_eq!(classify_surviving_step_phase(3, 0), Some(StepPhase::Decode));
        assert_eq!(classify_surviving_step_phase(0, 2), Some(StepPhase::Prefill));
        assert_eq!(classify_surviving_step_phase(3, 2), Some(StepPhase::Mixed));

        let live = LiveCounters::default();
        live.enable();
        live.step(StepPhase::Mixed, Duration::from_micros(1_250), false);
        live.step(StepPhase::Mixed, Duration::from_micros(300), true);
        live.mixed_rows(4, 192);
        let mut obj = Map::new();
        live.insert_steps(&mut obj);
        assert_eq!(obj["mixed_calls_total"], 1);
        assert_eq!(obj["mixed_host_wall_us_total"], 1_250);
        assert_eq!(obj["mixed_failed_calls_total"], 1);
        assert_eq!(obj["mixed_failed_host_wall_us_total"], 300);
        assert_eq!(obj["mixed_decode_rows_total"], 4);
        assert_eq!(obj["mixed_prefill_rows_total"], 192);
        // Zero contamination of homogeneous prefill/decode counters (SingleWallCharge):
        assert_eq!(obj["prefill_calls_total"], 0);
        assert_eq!(obj["prefill_host_wall_us_total"], 0);
        assert_eq!(obj["decode_calls_total"], 0);
        assert_eq!(obj["decode_host_wall_us_total"], 0);
        assert_eq!(obj["decode_rows_total"], 0);
    }

    #[test]
    fn step_counters_keep_failed_work_apart_and_stay_off_until_enabled() {
        let live = LiveCounters::default();
        live.step(StepPhase::Prefill, Duration::from_micros(500), false);
        let mut obj = Map::new();
        live.insert_steps(&mut obj);
        assert_eq!(obj["prefill_calls_total"], 0, "off: nothing counted");
        live.enable();
        live.step(StepPhase::Prefill, Duration::from_micros(500), false);
        live.step(StepPhase::Prefill, Duration::from_micros(700), true);
        live.step(StepPhase::Verify, Duration::from_micros(90), false);
        live.rows(StepPhase::Decode, 3);
        live.rows(StepPhase::Verify, 8);
        let mut obj = Map::new();
        live.insert_steps(&mut obj);
        assert_eq!(obj["prefill_calls_total"], 1);
        assert_eq!(obj["prefill_host_wall_us_total"], 500);
        assert_eq!(obj["prefill_failed_calls_total"], 1);
        assert_eq!(obj["prefill_failed_host_wall_us_total"], 700);
        assert_eq!(obj["verify_calls_total"], 1);
        assert_eq!(obj["decode_calls_total"], 0);
        assert_eq!(obj["decode_rows_total"], 3, "rows apart from calls");
        assert_eq!(obj["verify_target_positions_total"], 8);
    }

    #[test]
    fn a_reused_lane_slot_shows_its_new_request_ordinal() {
        let live = LiveCounters::default();
        live.publish_lanes([LaneView::Prefilling(7), LaneView::Empty].into_iter());
        assert_eq!(live.lane_seqs(), [7, 0]);
        live.publish_lanes([LaneView::Decoding(7), LaneView::Restoring(8)].into_iter());
        assert_eq!(live.lane_seqs(), [7, 8]);
        // Request 7 is cancelled mid-command; its slot is empty until request 9 takes it.
        live.publish_lanes([LaneView::Empty, LaneView::Prefilling(8)].into_iter());
        assert_eq!(live.lane_seqs(), [0, 8]);
        assert_eq!(live.lanes_decoding.load(Ordering::Relaxed), 0);
        live.publish_lanes([LaneView::Prefilling(9), LaneView::Decoding(8)].into_iter());
        assert_eq!(live.lane_seqs(), [9, 8]);
        assert_eq!(live.lanes_prefilling.load(Ordering::Relaxed), 1);
        assert_eq!(live.lanes_decoding.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn pmset_power_source_parses_mains_battery_and_no_battery() {
        let laptop_ac = "Now drawing from 'AC Power'\n -InternalBattery-0 (id=4653155)\t100%; charged; 0:00 remaining present: true\n";
        let laptop_batt = "Now drawing from 'Battery Power'\n -InternalBattery-0 (id=4653155)\t87%; discharging; 5:12 remaining present: true\n";
        let desktop = "Now drawing from 'AC Power'\n";
        assert_eq!(parse_pmset_batt(laptop_ac), Some(Power { on_ac: true, battery_percent: Some(100) }));
        assert_eq!(parse_pmset_batt(laptop_batt), Some(Power { on_ac: false, battery_percent: Some(87) }));
        assert_eq!(parse_pmset_batt(desktop), Some(Power { on_ac: true, battery_percent: None }));
        assert_eq!(parse_pmset_batt(""), None);
        assert_eq!(parse_pmset_batt("garbage\n"), None);

        let mut obj = Map::new();
        OsMemory { power: parse_pmset_batt(desktop), ..Default::default() }.insert(&mut obj);
        assert_eq!((obj["os_on_ac_power"].clone(), obj["os_battery_percent"].clone()), (Value::from(1), Value::Null));
        let mut unread = Map::new();
        OsMemory::default().insert(&mut unread);
        assert_eq!((unread["os_on_ac_power"].clone(), unread["os_battery_percent"].clone()), (Value::Null, Value::Null));

        // AC to battery counts once per transition; back to AC and unreadable readings count nothing.
        let live = LiveCounters::default();
        let ac = parse_pmset_batt(laptop_ac);
        let batt = parse_pmset_batt(laptop_batt);
        let seen: Vec<u64> = [batt, ac, batt, batt, None, ac, ac, batt].iter().map(|&p| live.note_power(p)).collect();
        assert_eq!(seen, [0, 0, 1, 1, 1, 1, 1, 2]);
    }

    #[test]
    fn os_memory_fields_are_numbers_and_absent_when_unread() {
        let mut obj = Map::new();
        OsMemory { page_size_bytes: Some(16_384), swapouts_total: Some(3), ..Default::default() }.insert(&mut obj);
        assert_eq!(obj["os_page_size_bytes"], 16_384);
        assert_eq!(obj["os_swapouts_pages_total"], 3);
        assert!(!obj.contains_key("os_swapins_pages_total"));
        #[cfg(target_os = "macos")]
        {
            let os = OsMemory::read();
            assert!(os.page_size_bytes.is_some_and(|p| p >= 4096));
            assert!(os.swapouts_total.is_some(), "host_statistics64 reads swapouts on macOS");
        }
    }
}