reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
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
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
#![cfg(test)]

use super::session::{
    EmptyInputBatchError, InputBatch, InputMailbox, InputTarget, LeaseError, Session,
    hold_mailbox_lock, install_admit_before_control, install_admit_with_control,
    install_commit_overlap, install_release_probe, install_transaction_arrival,
};
use crate::redact_tests::{SECRET, assert_redacted, assert_states};
use crate::state::session_state::{Key, SnapshotValue, WriteError};
use crate::transcript::item::{Item, ModelVisibility, System};
use crate::transcript::store::{self, Snapshot, Version};
use std::error::Error;
use std::sync::mpsc::{self, TryRecvError};
use std::sync::{Arc, Barrier};
use std::thread;

fn item(text: &str) -> Item {
    Item::System(System::new(
        "test".into(),
        text.into(),
        ModelVisibility::Visible,
    ))
}

fn text(item: &Item) -> &str {
    match item {
        Item::System(system) => system.text(),
        _ => panic!("test fixture must remain a system item"),
    }
}

fn batch(target: InputTarget, value: &str) -> InputBatch {
    InputBatch::new(target, vec![item(value)]).unwrap()
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct StateSnapshotValue(Vec<u8>);

// Trust contract: Vec owns its bytes and Clone performs no callback, I/O, or shared mutation.
impl SnapshotValue for StateSnapshotValue {}

#[test]
fn batch_and_error_surfaces_are_closed_and_owned() {
    assert!(matches!(
        InputBatch::new(InputTarget::NextStep, Vec::new()),
        Err(EmptyInputBatchError)
    ));
    assert_eq!(
        EmptyInputBatchError.to_string(),
        "input batch must not be empty"
    );
    let frozen = batch(InputTarget::NextTurn, "owned");
    assert_eq!(frozen.target(), InputTarget::NextTurn);
    assert_eq!(text(&frozen.items()[0]), "owned");
    let rendered = format!("{frozen:?}");
    assert!(rendered.starts_with("InputBatch { target: NextTurn, items: ["));
    assert!(
        !rendered.contains("enqueue_sequence"),
        "the private mailbox position must not enter the public Debug contract"
    );
    let (target, items) = frozen.into_parts();
    assert_eq!(target, InputTarget::NextTurn);
    assert_eq!(text(&items[0]), "owned");

    let errors = [
        LeaseError::Released,
        LeaseError::AlreadyAdmitted,
        LeaseError::Transcript(store::Error::Poisoned),
    ];
    assert_eq!(errors[0].to_string(), "session lease released");
    assert_eq!(errors[1].to_string(), "session lease already admitted");
    assert_eq!(errors[2].to_string(), "transcript store lock poisoned");

    // Only the transcript rejection wraps another failure, and it hands that
    // failure back rather than collapsing it into the rendered message.
    assert_eq!(
        errors[2]
            .source()
            .and_then(|cause| cause.downcast_ref::<store::Error>())
            .copied(),
        Some(store::Error::Poisoned)
    );
    for leaf in &errors[..2] {
        assert!(leaf.source().is_none(), "{leaf} is its own whole content");
    }
}

#[test]
fn mailbox_claims_target_fifo_and_moves_owned_batches() {
    let mailbox = InputMailbox::new();
    assert!(mailbox.is_empty());
    assert!(mailbox.claim(InputTarget::NextStep).is_none());
    mailbox.push(batch(InputTarget::NextTurn, "turn-1"));
    mailbox.push(batch(InputTarget::NextStep, "step-1"));
    mailbox.push(batch(InputTarget::NextTurn, "turn-2"));
    mailbox.push(batch(InputTarget::NextStep, "step-2"));
    assert_eq!(mailbox.len(), 4);
    assert!(!mailbox.is_empty());

    let claimed = mailbox.claim(InputTarget::NextStep).unwrap();
    assert_eq!(text(&claimed.items()[0]), "step-1");
    let remaining = mailbox.drain();
    let values: Vec<_> = remaining
        .iter()
        .map(|entry| (entry.target(), text(&entry.items()[0])))
        .collect();
    assert_eq!(
        values,
        [
            (InputTarget::NextTurn, "turn-1"),
            (InputTarget::NextTurn, "turn-2"),
            (InputTarget::NextStep, "step-2"),
        ]
    );
    assert!(mailbox.drain().is_empty());
}

fn queued(mailbox: &InputMailbox) -> Vec<(InputTarget, String)> {
    mailbox
        .drain()
        .iter()
        .map(|entry| (entry.target(), text(&entry.items()[0]).to_owned()))
        .collect()
}

/// An unsettled claim restores its batch at the position it was enqueued in,
/// not at the front: claims are target-selective, so a `push_front` would move
/// it ahead of an older batch of the other target.
#[test]
fn an_unsettled_claim_restores_its_batch_at_its_enqueue_position() {
    let mailbox = InputMailbox::new();
    mailbox.push(batch(InputTarget::NextTurn, "turn-1"));
    mailbox.push(batch(InputTarget::NextStep, "step-1"));
    mailbox.push(batch(InputTarget::NextTurn, "turn-2"));

    let claim = mailbox.claim_conserved(InputTarget::NextStep).unwrap();
    assert_eq!(text(&claim.batch().items()[0]), "step-1");
    assert_eq!(mailbox.len(), 2, "an in-flight claim is in no queue slot");
    mailbox.push(batch(InputTarget::NextStep, "step-2"));
    drop(claim);

    assert_eq!(
        queued(&mailbox),
        [
            (InputTarget::NextTurn, "turn-1".to_owned()),
            (InputTarget::NextStep, "step-1".to_owned()),
            (InputTarget::NextTurn, "turn-2".to_owned()),
            (InputTarget::NextStep, "step-2".to_owned()),
        ]
    );
}

/// Restoring behind batches claimed after it, and into an otherwise drained
/// queue, still lands by enqueue order.
#[test]
fn restores_interleave_by_enqueue_order_whatever_order_they_drop_in() {
    let mailbox = InputMailbox::new();
    mailbox.push(batch(InputTarget::NextStep, "first"));
    mailbox.push(batch(InputTarget::NextStep, "second"));
    mailbox.push(batch(InputTarget::NextStep, "third"));
    let first = mailbox.claim_conserved(InputTarget::NextStep).unwrap();
    let second = mailbox.claim_conserved(InputTarget::NextStep).unwrap();
    assert!(mailbox.drain().len() == 1, "only the third remains queued");
    drop(second);
    drop(first);
    assert_eq!(
        queued(&mailbox),
        [
            (InputTarget::NextStep, "first".to_owned()),
            (InputTarget::NextStep, "second".to_owned()),
        ]
    );
}

/// A settled claim hands its original batch over and restores nothing.
#[test]
fn a_settled_claim_restores_nothing() {
    let mailbox = InputMailbox::new();
    mailbox.push(batch(InputTarget::NextTurn, "settled"));
    let mut claim = mailbox.claim_conserved(InputTarget::NextTurn).unwrap();
    let settled = claim.settle();
    assert_eq!(text(&settled.items()[0]), "settled");
    drop(claim);
    assert!(mailbox.is_empty());
    assert!(mailbox.claim_conserved(InputTarget::NextTurn).is_none());
}

/// An unwind through an unsettled claim restores it too.
#[test]
fn an_unwinding_claim_restores_its_batch() {
    let mailbox = InputMailbox::new();
    mailbox.push(batch(InputTarget::NextTurn, "unwound"));
    let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let _claim = mailbox.claim_conserved(InputTarget::NextTurn).unwrap();
        panic!("admission unwound");
    }));
    assert!(caught.is_err());
    assert_eq!(
        queued(&mailbox),
        [(InputTarget::NextTurn, "unwound".to_owned())]
    );
}

#[test]
fn session_seed_identity_shared_handles_and_state_are_owned() {
    let seed = Snapshot::new(Version::from_u64(7), vec![item("seed")]);
    let session = Session::new("session-id".into(), Some(seed.clone()));
    assert_eq!(session.id(), "session-id");
    assert_eq!(
        session.transcript().version().unwrap(),
        Version::from_u64(7)
    );
    assert_eq!(
        text(&session.transcript().snapshot().unwrap().items()[0]),
        "seed"
    );
    assert_eq!(text(&seed.items()[0]), "seed");

    let first = session.input_mailbox();
    let second = session.input_mailbox();
    first.push(batch(InputTarget::NextStep, "shared"));
    assert_eq!(
        text(&second.claim(InputTarget::NextStep).unwrap().items()[0]),
        "shared"
    );

    let key = Key::<StateSnapshotValue>::new();
    let lease = session.try_acquire().unwrap();
    assert!(!lease.is_admitted());
    lease
        .state()
        .set(&key, &StateSnapshotValue(vec![1]))
        .unwrap();
    lease.admit().unwrap();
    assert!(lease.is_admitted());
    lease.release();
    assert!(!lease.is_admitted());
    assert_eq!(
        session.state().load(&key),
        Some(StateSnapshotValue(vec![1]))
    );
    assert_eq!(
        lease.state().set(&key, &StateSnapshotValue(vec![2])),
        Err(WriteError::LeaseReleased)
    );
}

#[test]
fn admission_is_once_per_lease_and_resets_for_each_successor() {
    let session = Session::new("admission".into(), None);
    let first = session.try_acquire().unwrap();
    assert!(session.try_acquire().is_none());
    assert!(!first.is_admitted());
    first.admit().unwrap();
    assert!(first.is_admitted());
    assert!(matches!(first.admit(), Err(LeaseError::AlreadyAdmitted)));
    first.release();
    first.release();
    assert!(!first.is_admitted());
    assert!(matches!(first.admit(), Err(LeaseError::Released)));

    let successor = session.try_acquire().unwrap();
    assert!(!first.is_admitted());
    assert!(!successor.is_admitted());
    successor.admit().unwrap();
    assert!(successor.is_admitted());
}

#[test]
fn transcript_authority_is_cas_only_and_release_bound() {
    let session = Session::new("transcript".into(), None);
    let lease = session.try_acquire().unwrap();
    lease.admit().unwrap();
    assert_eq!(
        lease
            .append_batch_if_version(vec![item("first")], Version::ZERO)
            .unwrap(),
        Version::from_u64(1)
    );
    let conflict = lease
        .append_batch_if_version(vec![item("stale")], Version::ZERO)
        .unwrap_err();
    assert!(matches!(
        conflict,
        LeaseError::Transcript(store::Error::VersionConflict { .. })
    ));
    assert_eq!(
        lease
            .replace_if_version(vec![item("replacement")], Version::from_u64(1))
            .unwrap(),
        Version::from_u64(2)
    );
    lease.release();
    let saved = lease.transcript_snapshot().unwrap();
    assert_eq!(saved.version(), Version::from_u64(2));
    assert_eq!(text(&saved.items()[0]), "replacement");
    assert!(matches!(
        lease.replace_if_version(Vec::new(), Version::from_u64(2)),
        Err(LeaseError::Released)
    ));
}

#[test]
fn admitted_transcript_commit_linearizes_before_release_and_successor() {
    let session = Session::new("linear".into(), None);
    let lease = Arc::new(session.try_acquire().unwrap());
    lease.admit().unwrap();
    let overlap = install_commit_overlap(&session);
    let arrival = install_transaction_arrival(&session);
    let writer = Arc::clone(&lease);
    let commit =
        thread::spawn(move || writer.append_batch_if_version(vec![item("winner")], Version::ZERO));
    overlap.wait_until_reached();
    overlap.assert_control_is_locked();

    let releaser = Arc::clone(&lease);
    let (released_tx, released_rx) = mpsc::channel();
    arrival.arm();
    let release = thread::spawn(move || {
        releaser.release();
        released_tx.send(()).unwrap();
    });
    // The releaser has reached the held transaction lock, so it is parked rather
    // than merely slow: release cannot revoke the authority mid-commit.
    arrival.wait_until_blocked();
    assert_eq!(released_rx.try_recv(), Err(TryRecvError::Empty));
    overlap.proceed();
    assert_eq!(commit.join().unwrap().unwrap(), Version::from_u64(1));
    release.join().unwrap();
    released_rx.recv().unwrap();

    let successor = session.try_acquire().unwrap();
    successor.admit().unwrap();
    assert_eq!(
        successor
            .replace_if_version(vec![item("successor")], Version::from_u64(1))
            .unwrap(),
        Version::from_u64(2)
    );
}

#[test]
fn no_argument_admission_holds_control_and_linearizes_before_release() {
    let session = Session::new("admit-first".into(), None);
    let lease = Arc::new(session.try_acquire().unwrap());
    let admit_pause = install_admit_with_control(&session);
    let release_probe = install_release_probe(&session);

    let admitting = Arc::clone(&lease);
    let admit = thread::spawn(move || admitting.admit());
    admit_pause.wait_until_reached();
    admit_pause.assert_control_is_locked();

    let releasing = Arc::clone(&lease);
    let release = thread::spawn(move || releasing.release());
    release_probe.wait_until_reached();
    admit_pause.proceed();
    assert!(admit.join().unwrap().is_ok());
    release_probe.proceed();
    release.join().unwrap();

    let successor = session.try_acquire().unwrap();
    assert!(!successor.is_admitted());
    successor.admit().unwrap();
    assert!(successor.is_admitted());
}

#[test]
fn release_before_admission_makes_old_admit_released_and_successor_admits() {
    let session = Session::new("release-first".into(), None);
    let old = Arc::new(session.try_acquire().unwrap());
    let admit_pause = install_admit_before_control(&session);

    let admitting = Arc::clone(&old);
    let admit = thread::spawn(move || admitting.admit());
    admit_pause.wait_until_reached();
    old.release();

    let successor = session.try_acquire().unwrap();
    successor.admit().unwrap();
    admit_pause.proceed();
    assert!(matches!(admit.join().unwrap(), Err(LeaseError::Released)));
    assert!(successor.is_admitted());
    successor.release();

    let continued = session.try_acquire().unwrap();
    continued.admit().unwrap();
}

#[test]
fn admission_commit_and_release_race_is_linearized() {
    for _ in 0..128 {
        let session = Session::new("admission-race".into(), None);
        let lease = Arc::new(session.try_acquire().unwrap());
        let start = Arc::new(Barrier::new(3));
        let admitting = Arc::clone(&lease);
        let admit_start = Arc::clone(&start);
        let admit = thread::spawn(move || {
            admit_start.wait();
            admitting.admit()
        });
        let releasing = Arc::clone(&lease);
        let release_start = Arc::clone(&start);
        let release = thread::spawn(move || {
            release_start.wait();
            releasing.release();
        });
        start.wait();
        let result = admit.join().unwrap();
        release.join().unwrap();

        let successor = session.try_acquire().unwrap();
        match result {
            Ok(()) | Err(LeaseError::Released) => successor.admit().unwrap(),
            Err(error) => panic!("unexpected admission race result: {error}"),
        }
    }
}

#[test]
fn concurrent_acquire_has_one_winner_and_mailbox_delivers_exactly_once() {
    let session = Session::new("concurrent".into(), None);
    let start = Arc::new(Barrier::new(17));
    let (leases_tx, leases_rx) = mpsc::channel();
    let mut workers = Vec::new();
    for _ in 0..16 {
        let session = session.clone();
        let start = Arc::clone(&start);
        let leases_tx = leases_tx.clone();
        workers.push(thread::spawn(move || {
            start.wait();
            if let Some(lease) = session.try_acquire() {
                leases_tx.send(lease).unwrap();
            }
        }));
    }
    start.wait();
    for worker in workers {
        worker.join().unwrap();
    }
    drop(leases_tx);
    let winners: Vec<_> = leases_rx.into_iter().collect();
    assert_eq!(winners.len(), 1);
    drop(winners);
    assert!(session.try_acquire().is_some());

    let mailbox = InputMailbox::new();
    let mut producers = Vec::new();
    for number in 0..64 {
        let mailbox = mailbox.clone();
        producers.push(thread::spawn(move || {
            mailbox.push(batch(InputTarget::NextStep, &number.to_string()));
        }));
    }
    for producer in producers {
        producer.join().unwrap();
    }
    let mut values: Vec<_> = mailbox
        .drain()
        .iter()
        .map(|entry| text(&entry.items()[0]).parse::<usize>().unwrap())
        .collect();
    values.sort_unstable();
    assert_eq!(values, (0..64).collect::<Vec<_>>());
}

#[test]
fn session_owned_mailbox_preserves_unclaimed_input_for_a_successor_lease() {
    let session = Session::new("miri".into(), None);
    let mailbox = session.input_mailbox();
    mailbox.push(batch(InputTarget::NextStep, "step"));
    mailbox.push(batch(InputTarget::NextTurn, "turn"));

    let first_run = session.try_acquire().unwrap();
    first_run.admit().unwrap();
    drop(first_run);

    let successor_run = session
        .try_acquire()
        .expect("the successor owns the Session");
    assert_eq!(
        text(&mailbox.claim(InputTarget::NextTurn).unwrap().items()[0]),
        "turn"
    );
    assert_eq!(
        text(&mailbox.claim(InputTarget::NextStep).unwrap().items()[0]),
        "step"
    );
    assert!(mailbox.is_empty());
    successor_run.release();
}

#[test]
fn successor_acquisition_cannot_cross_an_in_flight_transaction() {
    // Acquisition shares the transcript-transaction authority, so a successor can
    // never observe a version whose transaction has not resolved. The commit
    // pause holds the transaction open and the arrival probe proves the acquiring
    // thread is parked on it rather than merely losing a race.
    let session = Session::new("acquire-gate".into(), None);
    let lease = session.try_acquire().unwrap();
    lease.admit().unwrap();
    let overlap = install_commit_overlap(&session);
    let arrival = install_transaction_arrival(&session);

    thread::scope(|scope| {
        let committing =
            scope.spawn(|| lease.append_batch_if_version(vec![item("first")], Version::ZERO));
        overlap.wait_until_reached();
        // The predecessor still owns the lease, so this acquisition would fail on
        // the control lock alone; the point is that it never even gets there.
        arrival.arm();
        let (seen_tx, seen_rx) = mpsc::channel();
        let acquiring = scope.spawn(move || {
            let outcome = session.try_acquire();
            seen_tx.send(outcome.is_none()).unwrap();
        });
        arrival.wait_until_blocked();
        assert_eq!(seen_rx.try_recv(), Err(TryRecvError::Empty));

        overlap.proceed();
        assert_eq!(committing.join().unwrap().unwrap(), Version::from_u64(1));
        acquiring.join().unwrap();
        assert!(
            seen_rx.recv().unwrap(),
            "the predecessor still holds the lease, so acquisition fails after waiting"
        );
    });
}

/// The seed/live boundary is a fact the composition layer authored, not one core
/// has to store (ADR-022 item 3).
///
/// `Session::new` receives the replayed prefix, so its caller already knows both
/// coordinates the boundary can be expressed in — the prefix length and the
/// version the epoch resumed at — and both stay valid as live work appends. A
/// `first_live` field in the transcript would be a number core neither produces
/// nor consumes: no core path treats a replayed record differently from a live
/// one.
#[test]
fn a_resumed_session_lets_its_creator_name_the_boundary_between_replay_and_live() {
    let replayed = vec![item("turn-1 ask"), item("turn-1 answer")];
    // Everything a composition layer has to keep, taken where it forks or
    // resumes. Both are `Copy`-cheap and neither needs core's help.
    let first_live_index = replayed.len();
    let first_live_version = Version::from_u64(7);

    let session = Session::new(
        "resumed".into(),
        Some(Snapshot::new(first_live_version, replayed)),
    );
    let lease = session.try_acquire().unwrap();
    lease.admit().unwrap();
    lease
        .append_batch_if_version(vec![item("turn-2 ask")], first_live_version)
        .unwrap();
    lease
        .append_batch_if_version(
            vec![item("turn-2 answer")],
            Version::from_u64(first_live_version.as_u64() + 1),
        )
        .unwrap();

    let snapshot = session.transcript().snapshot().unwrap();
    assert_eq!(snapshot.version(), Version::from_u64(9));
    let (seed, live) = snapshot.items().split_at(first_live_index);
    assert_eq!(
        seed.iter().map(text).collect::<Vec<_>>(),
        ["turn-1 ask", "turn-1 answer"],
        "the replayed prefix is exactly what its creator handed in"
    );
    assert_eq!(
        live.iter().map(text).collect::<Vec<_>>(),
        ["turn-2 ask", "turn-2 answer"],
        "everything after it is this Run's own work"
    );
    // The version coordinate answers the same question without materialising
    // the history, which is what a persistence layer keying on versions wants.
    assert_eq!(
        snapshot.version().as_u64() - first_live_version.as_u64(),
        live.len() as u64
    );
}

#[test]
fn session_and_lease_debug_name_the_session_they_are_bound_to() {
    let session = Session::new("session-1".into(), None);
    assert_eq!(format!("{session:?}"), r#"Session { id: "session-1" }"#);
    let lease = session
        .try_acquire()
        .expect("a fresh session grants a lease");
    assert_eq!(format!("{lease:?}"), r#"Lease { session: "session-1" }"#);
}

#[test]
fn input_batch_debug_keeps_the_target_and_redacts_the_items() {
    let batch = InputBatch::new(InputTarget::NextTurn, vec![item(SECRET)])
        .expect("a non-empty batch freezes");
    assert_redacted(&batch);
    assert_states(
        &batch,
        &["target: NextTurn", "text: <21 bytes>", r#"subtype: "test""#],
    );
}

#[test]
fn mailbox_debug_reports_queue_depth_and_never_waits_for_the_lock() {
    let mailbox = InputMailbox::new();
    assert_eq!(format!("{mailbox:?}"), "InputMailbox { batches: 0 }");
    mailbox.push(InputBatch::new(InputTarget::NextTurn, vec![item(SECRET)]).expect("non-empty"));
    assert_redacted(&mailbox);
    assert_eq!(format!("{mailbox:?}"), "InputMailbox { batches: 1 }");

    // The mailbox is the session's only concurrent write entry point, so a
    // formatter that waited here could stall a live producer.
    let held = Barrier::new(2);
    let release = Barrier::new(2);
    thread::scope(|scope| {
        scope.spawn(|| hold_mailbox_lock(&mailbox, &held, &release));
        held.wait();
        assert_eq!(format!("{mailbox:?}"), "InputMailbox { batches: <locked> }");
        release.wait();
    });
    assert_eq!(format!("{mailbox:?}"), "InputMailbox { batches: 1 }");
}