inky-engine 3.0.0

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
// Operator metrics: snapshot lines (`INK_METRICS_SNAPSHOT_SECS`) and `GET /metrics` (`INK_OPERATOR_KEY_ENV`).
// Every clock here is passed in: no sleeps, sockets or network.

/// A sink that records what it was offered and can be set full, standing in for the metrics recorder.
#[derive(Default)]
struct FakeSink {
    lines: Mutex<Vec<Value>>,
    full: AtomicBool,
    dropped: AtomicU64,
    write_errors: AtomicU64,
}

impl live::MetricsSink for FakeSink {
    fn offer(&self, _unix_ms: u64, line: &Value) -> bool {
        if self.full.load(Ordering::Relaxed) {
            self.dropped.fetch_add(1, Ordering::Relaxed);
            return false;
        }
        self.lines.lock().unwrap().push(line.clone());
        true
    }

    fn dropped_total(&self) -> u64 {
        self.dropped.load(Ordering::Relaxed)
    }

    fn write_errors_total(&self) -> u64 {
        self.write_errors.load(Ordering::Relaxed)
    }
}

/// The field names of a snapshot line with no spill and no DSpark (Stella's scoreboard reads these).
const SNAPSHOT_FIELDS: &[&str] = &[
    "schema_version",
    "epoch",
    "sample_kind",
    "sample_seq",
    "mono_ms",
    "unix_ms",
    "interval_ms",
    "missed_samples_total",
    "dropped_lines_total",
    "write_errors_total",
    "lanes_configured",
    "lanes_admitted",
    "lanes_active",
    "lanes_restoring",
    "lanes_prefilling",
    "lanes_decoding",
    "queue_waiting",
    "queue_scheduler",
    "request_seq_last",
    "lane_seqs",
    "prompt_rows_prefill_step_total",
    "prompt_rows_decode_step_total",
    "output_tokens_enqueued_total",
    "output_tokens_failed_total",
    "lane_occupied_us_total",
    "prefill_calls_total",
    "prefill_host_wall_us_total",
    "prefill_failed_calls_total",
    "prefill_failed_host_wall_us_total",
    "decode_calls_total",
    "decode_host_wall_us_total",
    "decode_failed_calls_total",
    "decode_failed_host_wall_us_total",
    "verify_calls_total",
    "verify_host_wall_us_total",
    "verify_failed_calls_total",
    "verify_failed_host_wall_us_total",
    "decode_rows_total",
    "verify_target_positions_total",
    "contended_prefill_host_wall_us_total",
    "contended_decode_host_wall_us_total",
    "forced_prefill_steps_total",
    "forced_prefill_host_wall_us_total",
    "forced_decode_steps_total",
    "forced_decode_host_wall_us_total",
    "admit_deferrals_total",
    "step_deferrals_total",
    "think_budget_hits_total",
    "tool_call_dropped_at_length_total",
    "process_footprint_bytes",
    "retained_host_bytes",
    "retained_host_budget_bytes",
    "retained_starts",
    "kv_window_slots_used",
    "kv_window_slots_capacity",
    "kv_full_slots_used",
    "kv_full_slots_capacity",
    "reuse_start_matches_total",
    "reuse_cached_tokens_total",
    "reuse_singleflight_rebinds_total",
    "reuse_singleflight_saved_tokens_total",
    "reuse_approx_starts_saved_total",
    "reuse_approx_start_matches_total",
    "reuse_approx_cached_tokens_total",
    "reuse_stitch_hits_total",
    "reuse_stitched_tokens_total",
    "reuse_ikv_quarantined_total",
    "reuse_starts_saved_total",
    "reuse_starts_evicted_total",
    "reuse_evictions_pool_pressure_total",
    "reuse_evictions_host_budget_total",
    "reuse_evictions_approx_scope_cap_total",
    "reuse_evictions_stale_invalid_total",
    "reuse_evictions_shutdown_total",
    "reuse_evictions_superseded_total",
    "spill_restores_total",
    "spill_restores_failed_total",
    "spill_restore_wall_us_total",
    "spill_starts_spilled_total",
    "os_page_size_bytes",
    "os_swapins_pages_total",
    "os_swapouts_pages_total",
    "os_swap_used_bytes",
    "os_memory_pressure_level",
    "os_on_ac_power",
    "os_battery_percent",
    "os_power_source_changes_total",
];

fn fixed_os() -> live::OsMemory {
    live::OsMemory {
        page_size_bytes: Some(16_384),
        swapins_total: Some(10),
        swapouts_total: Some(20),
        swap_used_bytes: Some(0),
        memory_pressure_level: Some(1),
        power: Some(live::Power { on_ac: true, battery_percent: None }),
    }
}

fn metrics_ctx() -> (Ctx, Arc<FakeServeClock>, Instant) {
    let clock = FakeServeClock::auto_advancing();
    let (mut cx, _rx) = admission_test_ctx_with_clock(2, 2, QUEUE_WAIT_TIMEOUT, 4, clock.clone());
    let t0 = clock.now();
    cx.health = Arc::new(SchedulerHealth::new(t0));
    cx.metrics = Arc::new(Mutex::new(Counters::new(t0)));
    cx.live.enable();
    cx.live.epoch.store(1_795_000_000_000, Ordering::Relaxed);
    (cx, clock, t0)
}

#[test]
fn snapshot_line_carries_every_field_as_numbers_and_cumulative_totals() {
    let (cx, _clock, t0) = metrics_ctx();
    let sink = FakeSink::default();
    let mut cadence = live::Cadence::new(Duration::from_secs(10));
    let start = snapshot_line(&cx, &mut cadence, live::SampleKind::Start, t0, 1_795_000_000_000, fixed_os(), &sink);
    let obj = start.as_object().unwrap();
    let mut names: Vec<&str> = obj.keys().map(String::as_str).collect();
    let mut want = SNAPSHOT_FIELDS.to_vec();
    if !obj.contains_key("process_footprint_bytes") {
        want.retain(|&f| f != "process_footprint_bytes");
    }
    names.sort_unstable();
    want.sort_unstable();
    assert_eq!(names, want);
    for (k, v) in obj {
        let numeric = v.is_u64()
            || v.as_array().is_some_and(|a| a.iter().all(Value::is_u64))
            || (k == "os_battery_percent" && v.is_null());
        assert!(numeric, "{k} must be a number: {v}");
    }
    assert_eq!(obj["schema_version"], live::METRICS_SCHEMA_VERSION);
    assert_eq!(obj["epoch"], 1_795_000_000_000u64);
    assert_eq!(obj["sample_kind"], 0);
    assert_eq!(obj["sample_seq"], 0);
    assert_eq!(obj["mono_ms"], 0);
    assert_eq!(obj["interval_ms"], 0);
    assert_eq!(obj["prompt_rows_prefill_step_total"], 0);
    assert!(!obj.contains_key("end_censored"), "only the last line says how the epoch ended");

    // Ten seconds of work: two lanes busy for 4 s, one prefill step and a failed decode step.
    {
        let mut m = cx.metrics.lock().unwrap();
        let _ = m.admit(t0 + Duration::from_secs(2), t0);
        let _ = m.admit(t0 + Duration::from_secs(2), t0);
        m.add_input(128, RowPhase::PrefillStep);
        m.add_input(2, RowPhase::DecodeStep);
        m.add_output(9, 1);
        m.release(t0 + Duration::from_secs(6));
        m.release(t0 + Duration::from_secs(6));
    }
    cx.live.step(StepPhase::Prefill, Duration::from_micros(1_500), false);
    cx.live.step(StepPhase::Decode, Duration::from_micros(400), true);
    cx.live.publish_lanes([LaneView::Decoding(41), LaneView::Empty].into_iter());
    cx.seq.store(41, Ordering::Relaxed);
    let t1 = t0 + Duration::from_secs(10);
    let p1 = snapshot_line(&cx, &mut cadence, live::SampleKind::Periodic, t1, 1_795_000_010_000, fixed_os(), &sink);
    assert_eq!(p1["sample_kind"], 1);
    assert_eq!(p1["sample_seq"], 1);
    assert_eq!(p1["mono_ms"], 10_000);
    assert_eq!(p1["interval_ms"], 10_000);
    assert_eq!(p1["missed_samples_total"], 0);
    assert_eq!(p1["prompt_rows_prefill_step_total"], 128);
    assert_eq!(p1["prompt_rows_decode_step_total"], 2);
    assert_eq!(p1["output_tokens_enqueued_total"], 9);
    assert_eq!(p1["output_tokens_failed_total"], 1);
    assert_eq!(p1["lane_occupied_us_total"], 8_000_000, "two lanes for 4 s");
    assert_eq!(p1["prefill_calls_total"], 1);
    assert_eq!(p1["prefill_host_wall_us_total"], 1_500);
    assert_eq!(p1["decode_calls_total"], 0);
    assert_eq!(p1["decode_failed_calls_total"], 1);
    assert_eq!(p1["decode_failed_host_wall_us_total"], 400);
    assert_eq!(p1["lanes_decoding"], 1);
    assert_eq!(p1["lane_seqs"], json!([41, 0]));
    assert_eq!(p1["request_seq_last"], 41);
    assert_eq!(p1["os_swapouts_pages_total"], 20);
    assert_eq!((p1["os_on_ac_power"].as_u64(), p1["os_power_source_changes_total"].as_u64()), (Some(1), Some(0)));

    // The periodic summary log resets its own counts; the snapshot totals never go back.
    let _ = cx.metrics.lock().unwrap().summarize(t1, 0);
    cx.metrics.lock().unwrap().add_input(64, RowPhase::PrefillStep);
    let t2 = t0 + Duration::from_secs(20);
    let p2 = snapshot_line(&cx, &mut cadence, live::SampleKind::Periodic, t2, 1_795_000_020_000, fixed_os(), &sink);
    assert_eq!(p2["prompt_rows_prefill_step_total"], 192);
    assert_eq!(p2["lane_occupied_us_total"], 8_000_000);
}

#[test]
fn snapshots_count_a_missing_sample_a_full_recorder_and_restart_in_a_new_epoch() {
    let (cx, clock, t0) = metrics_ctx();
    let cx = Arc::new(cx);
    let sink = Arc::new(FakeSink::default());
    let snapshots = Snapshots::new(&cx, sink.clone(), Duration::from_secs(10));
    assert!(snapshots.take(live::SampleKind::Start, t0, 1, fixed_os()));
    assert!(snapshots.take(live::SampleKind::Periodic, t0 + Duration::from_secs(10), 2, fixed_os()));
    // The recorder is full for the 20 s sample: it is dropped, never waited on.
    sink.full.store(true, Ordering::Relaxed);
    assert!(snapshots.take(live::SampleKind::Periodic, t0 + Duration::from_secs(20), 3, fixed_os()));
    sink.full.store(false, Ordering::Relaxed);
    // The thread wakes at 51 s: the 30 s and 40 s samples were never taken.
    sink.write_errors.store(1, Ordering::Relaxed);
    assert!(snapshots.take(live::SampleKind::Periodic, t0 + Duration::from_secs(51), 4, fixed_os()));
    assert!(snapshots.take(live::SampleKind::Shutdown, t0 + Duration::from_secs(52), 5, fixed_os()));
    assert!(!snapshots.take(live::SampleKind::Periodic, t0 + Duration::from_secs(60), 6, fixed_os()), "nothing after the last line");
    let lines = sink.lines.lock().unwrap().clone();
    let col = |k: &str| lines.iter().map(|l| l[k].as_u64().unwrap()).collect::<Vec<_>>();
    assert_eq!(col("sample_kind"), [0, 1, 1, 2]);
    assert_eq!(col("sample_seq"), [0, 1, 3, 4], "the dropped line leaves a gap in sample_seq");
    assert_eq!(col("missed_samples_total"), [0, 0, 2, 2]);
    assert_eq!(col("dropped_lines_total"), [0, 0, 1, 1]);
    assert_eq!(col("write_errors_total"), [0, 0, 1, 1]);
    assert_eq!(col("interval_ms"), [0, 10_000, 31_000, 1_000]);

    // A restart is a new process: a new epoch whose sequence and schedule start again.
    let (cx2, _clock2, t0b) = metrics_ctx();
    cx2.live.epoch.store(1_795_000_100_000, Ordering::Relaxed);
    let cx2 = Arc::new(cx2);
    let sink2 = Arc::new(FakeSink::default());
    let again = Snapshots::new(&cx2, sink2.clone(), Duration::from_secs(10));
    assert!(again.take(live::SampleKind::Start, t0b, 7, fixed_os()));
    let first = sink2.lines.lock().unwrap()[0].clone();
    assert_eq!((first["sample_seq"].as_u64(), first["sample_kind"].as_u64()), (Some(0), Some(0)));
    assert_ne!(first["epoch"], lines[0]["epoch"]);
    drop(clock);
}

#[test]
fn metrics_route_opens_only_to_the_operator_key() {
    let clock = FakeServeClock::auto_advancing();
    let (mut cx, _jrx) = admission_test_ctx_with_clock(2, 2, QUEUE_WAIT_TIMEOUT, 4, clock.clone());
    cx.key = Some("api-key".into());
    cx.live.enable();
    let cfg = test_conn_config(clock.clone());
    let get = |cx: &Ctx, path: &str, auth: &str| {
        let head = format!("GET {path} HTTP/1.1\r\nHost: 127.0.0.1:8090\r\n{auth}\r\n");
        let (io, st) = ScriptedConnIo::new(head, Vec::new(), clock.clone());
        serve_one_connection(cx, io, &cfg);
        let raw = String::from_utf8(st.lock().unwrap().written.clone()).unwrap();
        let status = raw.get(9..12).unwrap_or_default().to_string();
        (status, raw.split_once("\r\n\r\n").map(|(_, b)| b.to_string()).unwrap_or_default())
    };
    // Without INK_OPERATOR_KEY_ENV there is no /metrics: the API key gets the same 404 as any unknown route.
    let health_before = get(&cx, "/health", "");
    assert_eq!(get(&cx, "/metrics", "Authorization: Bearer api-key\r\n").0, "404");
    assert_eq!(get(&cx, "/metrics", "").0, "401");

    cx.operator_key = Some("operator-key".into());
    for auth in [
        "",
        "Authorization: Bearer api-key\r\n",
        "x-api-key: api-key\r\n",
        "Authorization: Bearer wrong\r\n",
        "Authorization: Basic operator-key\r\n",
    ] {
        let (status, body) = get(&cx, "/metrics", auth);
        assert_eq!(status, "401", "{auth:?}: {body}");
        assert!(!body.contains("lanes_admitted"), "{auth:?} leaked metrics: {body}");
    }
    for auth in ["Authorization: Bearer operator-key\r\n", "x-api-key: operator-key\r\n"] {
        let (status, body) = get(&cx, "/metrics", auth);
        assert_eq!(status, "200", "{auth:?}: {body}");
        let v: Value = serde_json::from_str(&body).unwrap();
        for k in ["schema_version", "epoch", "mono_ms", "lanes_admitted", "prompt_rows_prefill_step_total", "reuse_stitch_hits_total"] {
            assert!(v[k].is_u64(), "{k} missing from /metrics: {body}");
        }
    }
    // The operator key opens nothing else, and /health is unchanged by the flag.
    assert_eq!(get(&cx, "/v1/models", "Authorization: Bearer operator-key\r\n").0, "401");
    let health_after = get(&cx, "/health", "");
    assert_eq!(health_after.0, health_before.0);
    let keys = |b: &str| serde_json::from_str::<Value>(b).unwrap().as_object().unwrap().keys().cloned().collect::<Vec<_>>();
    assert_eq!(keys(&health_after.1), keys(&health_before.1));
    assert!(!health_after.1.contains("reuse_") && !health_after.1.contains("lane_seqs"));

    // An unkeyed loopback server: /metrics still needs the operator key.
    cx.key = None;
    assert_eq!(get(&cx, "/metrics", "").0, "401");
    assert_eq!(get(&cx, "/metrics", "Authorization: Bearer operator-key\r\n").0, "200");
    cx.operator_key = None;
    assert_eq!(get(&cx, "/metrics", "").0, "404");
}


#[test]
fn a_closed_client_counts_its_token_failed_not_enqueued() {
    let (tx, rx) = job_events();
    let (mut sent, mut failed) = (0, 0);
    assert!(!emit_token(&tx, 7, &mut sent, &mut failed), "the first token reaches a live request");
    drop(rx);
    assert!(emit_token(&tx, 8, &mut sent, &mut failed), "the client is gone");
    assert_eq!((sent, failed), (1, 1));
}

#[test]
fn a_last_line_with_requests_in_flight_is_marked_censored() {
    let (cx, _clock, t0) = metrics_ctx();
    let sink = FakeSink::default();
    let mut cadence = live::Cadence::new(Duration::from_secs(10));
    let _ = snapshot_line(&cx, &mut cadence, live::SampleKind::Start, t0, 1, fixed_os(), &sink);
    let drained = snapshot_line(&cx, &mut cadence, live::SampleKind::Shutdown, t0, 2, fixed_os(), &sink);
    assert_eq!((drained["end_censored"].as_u64(), drained["inflight_at_end"].as_u64()), (Some(0), Some(0)));
    cx.active_lanes.store(2, Ordering::Relaxed);
    let mut cadence = live::Cadence::new(Duration::from_secs(10));
    let cut = snapshot_line(&cx, &mut cadence, live::SampleKind::Shutdown, t0, 3, fixed_os(), &sink);
    assert_eq!((cut["end_censored"].as_u64(), cut["inflight_at_end"].as_u64()), (Some(1), Some(2)));
}


#[test]
fn snapshot_and_metrics_expose_eviction_causes_budget_and_spill_io_without_touching_health() {
    let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("target")
        .join(format!("metrics-spill-io-{}-{}", std::process::id(), startup_nonce()));
    let _ = std::fs::remove_dir_all(&dir);
    {
        let (mut cx, clock, t0) = metrics_ctx();
        let health_before_keys = {
            let (_, b) = health_response_with_auth(&cx, t0, true);
            let mut k: Vec<String> = serde_json::from_str::<Value>(&b).unwrap().as_object().unwrap().keys().cloned().collect();
            k.sort();
            k
        };

        let mut pools = crate::blocks::BlockPools::with_capacities(8, 8, 2).unwrap();
        let max_spill_bytes = 64 * 1024 * 1024u64;
        let store = crate::spill::SpillStore::open_with_kvb(&dir, max_spill_bytes, pools.full.kvb()).unwrap();
        let mut cache = ServeBlockCache::with_spill_compat_sparse(store, None, None, 0, 0xBEEF);
        cache.set_approx_retain(true);
        cache.set_max_approx_starts_per_scope(1);
        cache.set_max_retained_host_bytes(512 * 1024);

        // 1. Spill an exact 256-token start (cs + 4 Full + 4 Window = 9 .blk writes), delete one window .blk,
        //    and run async restore so early block reads hit disk while start restore itself fails.
        let p_spill: Vec<u32> = (0..256u32).map(|i| 70_000 + i).collect();
        let mut tbl_s1 = crate::blocks::BlockTable::new(16).unwrap();
        let mut st_s1 = LaneBlockState::default();
        let _ = admit_reuse_bind(&mut cache, &mut pools, 0, &mut tbl_s1, &mut st_s1, 9, &p_spill);
        cache.ensure_span_blocks(&mut pools, &mut tbl_s1, 0, 256).unwrap();
        cache.finish_prefill_span(&mut pools, &mut tbl_s1, &mut st_s1, &p_spill, 0, 256, || vec![0x51; 64]);
        cache.release_lane(&mut pools, &mut tbl_s1, &mut st_s1);
        assert_eq!(cache.evict_all_starts_for_test(&mut pools), 1);

        let mut win_blks: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok().map(|x| x.path()))
            .filter(|p| {
                p.file_name()
                    .and_then(|n| n.to_str())
                    .is_some_and(|n| n.starts_with("blk-w-") && n.ends_with(".blk"))
            })
            .collect();
        win_blks.sort();
        assert_eq!(win_blks.len(), 4);
        std::fs::remove_file(win_blks.last().unwrap()).unwrap();

        let mut p_restore = p_spill.clone();
        p_restore.extend(71_000u32..71_032);
        let mut tbl_s2 = crate::blocks::BlockTable::new(16).unwrap();
        let mut st_s2 = LaneBlockState::default();
        let b_res = admit_reuse_bind(&mut cache, &mut pools, 0, &mut tbl_s2, &mut st_s2, 9, &p_restore);
        assert_eq!(b_res.restoring_target, Some(256));
        let done = poll_restore_lane_0_until_done(&mut cache, &mut pools, &mut tbl_s2, &mut st_s2);
        assert!(done.matched.is_none());
        cache.release_lane(&mut pools, &mut tbl_s2, &mut st_s2);

        // 2. Trigger ApproxScopeCap (1), HostBudget (2), and Shutdown (1) evictions on approximate starts.
        for (idx, card) in [(0u32, "mc1"), (1u32, "mc2")] {
            let owner = block_cache::approx_twin("msalt", 1, Some(card));
            let p: Vec<u32> = (0..64u32).map(|i| 72_000 + idx * 1000 + i).collect();
            let mut tbl = crate::blocks::BlockTable::new(8).unwrap();
            let mut st = LaneBlockState { owner, ..Default::default() };
            let _ = admit_reuse_bind(&mut cache, &mut pools, 0, &mut tbl, &mut st, 1, &p);
            st.stitched_approx = true;
            cache.enter_approx_path(&pools, &tbl, &mut st, &p);
            cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &p, 0, 64, || vec![0x61; 512]);
            cache.release_lane(&mut pools, &mut tbl, &mut st);
        }
        cache.set_max_retained_host_bytes(0);
        {
            let owner = block_cache::approx_twin("msalt", 2, Some("mc3"));
            let p: Vec<u32> = (0..64u32).map(|i| 75_000 + i).collect();
            let mut tbl = crate::blocks::BlockTable::new(8).unwrap();
            let mut st = LaneBlockState { owner, ..Default::default() };
            let _ = admit_reuse_bind(&mut cache, &mut pools, 0, &mut tbl, &mut st, 2, &p);
            st.stitched_approx = true;
            cache.enter_approx_path(&pools, &tbl, &mut st, &p);
            cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &p, 0, 64, || vec![0x62; 512]);
            cache.release_lane(&mut pools, &mut tbl, &mut st);
        }
        cache.set_max_retained_host_bytes(512 * 1024);
        {
            let owner = block_cache::approx_twin("msalt", 1, Some("mc4"));
            let p: Vec<u32> = (0..64u32).map(|i| 76_000 + i).collect();
            let mut tbl = crate::blocks::BlockTable::new(8).unwrap();
            let mut st = LaneBlockState { owner, ..Default::default() };
            let _ = admit_reuse_bind(&mut cache, &mut pools, 0, &mut tbl, &mut st, 1, &p);
            st.stitched_approx = true;
            cache.enter_approx_path(&pools, &tbl, &mut st, &p);
            cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 64).unwrap();
            cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &p, 0, 64, || vec![0x63; 512]);
            cache.release_lane(&mut pools, &mut tbl, &mut st);
        }
        cache.shutdown(&mut pools);

        cx.live.retained_host_budget_bytes.store(cache.max_retained_host_bytes(), Ordering::Relaxed);
        cx.live.publish_cache_stats(cache.stats());

        // Without spill_telemetry, /health key set is 100% identical to baseline.
        let health_after_no_spill_keys = {
            let (_, b) = health_response_with_auth(&cx, t0, true);
            let mut k: Vec<String> = serde_json::from_str::<Value>(&b).unwrap().as_object().unwrap().keys().cloned().collect();
            k.sort();
            k
        };
        assert_eq!(health_after_no_spill_keys, health_before_keys);

        let sp = Arc::new(SpillTelemetry::default());
        sp.sync_from(&cache);
        cx.spill_telemetry = Some(sp);
        cx.operator_key = Some("operator-secret".into());

        // Check both snapshot_line (metrics-YYYYMMDD.jsonl) and GET /metrics.
        let sink = FakeSink::default();
        let mut cadence = live::Cadence::new(Duration::from_secs(10));
        let snap = snapshot_line(&cx, &mut cadence, live::SampleKind::Periodic, t0 + Duration::from_secs(10), 1_795_000_010_000, fixed_os(), &sink);

        let cfg = test_conn_config(clock.clone());
        let head = "GET /metrics HTTP/1.1\r\nHost: 127.0.0.1:8090\r\nAuthorization: Bearer operator-secret\r\n\r\n".to_string();
        let (io, st_io) = ScriptedConnIo::new(head, Vec::new(), clock);
        serve_one_connection(&cx, io, &cfg);
        let raw_http = String::from_utf8(st_io.lock().unwrap().written.clone()).unwrap();
        assert!(raw_http.starts_with("HTTP/1.1 200"), "unexpected /metrics status: {raw_http}");
        let http_body = raw_http.split_once("\r\n\r\n").unwrap().1;
        let http_metrics: Value = serde_json::from_str(http_body).unwrap();

        for (label, doc) in [("snapshot_line", &snap), ("GET /metrics", &http_metrics)] {
            let obj = doc.as_object().unwrap();
            for (k, v) in obj {
                let numeric = v.is_u64()
                    || v.as_array().is_some_and(|a| a.iter().all(Value::is_u64))
                    || (matches!(k.as_str(), "os_on_ac_power" | "os_battery_percent") && v.is_null());
                assert!(numeric, "{label}: {k} must be numeric, got {v}");
            }
            assert_eq!(obj["retained_host_budget_bytes"], 512 * 1024, "{label}");
            assert_eq!(obj["reuse_evictions_pool_pressure_total"], 1, "{label}");
            assert_eq!(obj["reuse_evictions_host_budget_total"], 2, "{label}");
            assert_eq!(obj["reuse_evictions_approx_scope_cap_total"], 1, "{label}");
            assert_eq!(obj["reuse_evictions_stale_invalid_total"], 0, "{label}");
            assert_eq!(obj["reuse_evictions_shutdown_total"], 1, "{label}");
            assert_eq!(obj["reuse_evictions_superseded_total"], 0, "{label}");
            assert_eq!(obj["spill_starts_spilled_total"], 1, "{label}");
            assert_eq!(obj["spill_restores_total"], 0, "{label}: start restore did not complete");
            assert_eq!(obj["spill_restores_failed_total"], 1, "{label}: failed restore counted distinctly");
            assert!(obj["spill_restore_wall_us_total"].is_u64(), "{label}");
            assert_eq!(obj["spill_bytes_max"], max_spill_bytes, "{label}");
            assert!(obj["spill_bytes_used"].is_u64(), "{label}");
            assert_eq!(obj["spill_writes_total"], 9, "{label}");
            assert!(obj["spill_bytes_written_total"].as_u64().unwrap() > 0, "{label}");
            assert!(obj["spill_write_wall_us_total"].is_u64(), "{label}");
            assert!(
                obj["spill_reads_hit_total"].as_u64().unwrap() >= 5,
                "{label}: early .blk reads hit disk while spill_restores_total == 0"
            );
            assert_eq!(obj["spill_reads_miss_total"], 1, "{label}");
            assert!(obj["spill_bytes_read_total"].as_u64().unwrap() > 0, "{label}");
            assert!(obj["spill_read_wall_us_total"].is_u64(), "{label}");
        }

        // /health must remain completely untouched by the new operator metrics fields.
        for authed in [false, true] {
            let (_, hbody) = health_response_with_auth(&cx, t0, authed);
            let hobj = serde_json::from_str::<Value>(&hbody).unwrap();
            let hmap = hobj.as_object().unwrap();
            for forbidden in [
                "retained_host_budget_bytes",
                "reuse_evictions_pool_pressure_total",
                "reuse_evictions_host_budget_total",
                "reuse_evictions_approx_scope_cap_total",
                "reuse_evictions_stale_invalid_total",
                "reuse_evictions_shutdown_total",
                "reuse_evictions_superseded_total",
                "spill_restores_failed_total",
                "spill_restore_wall_us_total",
                "spill_bytes_max",
                "spill_writes_total",
                "spill_write_wall_us_total",
                "spill_reads_hit_total",
                "spill_reads_miss_total",
                "spill_bytes_read_total",
                "spill_read_wall_us_total",
            ] {
                assert!(
                    !hmap.contains_key(forbidden),
                    "/health (authed={authed}) must not expose operator metric {forbidden}: {hbody}"
                );
            }
        }
    }
    let _ = std::fs::remove_dir_all(&dir);
}