reliar-store-postgres 0.9.0

PostgreSQL provider for the Reliar transactional outbox and inbox: migrations, migrate(), enqueue and the SKIP LOCKED claim.
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
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
//! I-P30 (ADR 0042 Amendment C.5): every provider-emitted `reliar.inbox.*` span carries the
//! documented entry/exit fields, and none of them ever leaks a payload, header value or
//! `last_error` text — mirrors `outbox_enqueue_spans.rs`'s `Recorder` layer, extended to the
//! inbox's own set: `claim` (all four outcomes), `fail` (all three outcomes), `complete`,
//! `purge`, and all three dead-letter operations (`list_dead`, `retry_dead`, `purge_dead`). The
//! `claimed` case also pins `inbox.attempt` as **singular** and `inbox.attempts` as **plural**
//! (C.5's rule) so a swap between the two is caught.
//!
//! I-N30 (ADR 0043 §3 — folded here from `reliar-inbox`'s removed fake-backed `spans.rs`):
//! `InboxStore::process`'s own `reliar.inbox.process` span, distinct from the provider spans
//! above — it wraps `claim` (and, on `Claimed`, the handler and `complete`), so it gets its own
//! outcome coverage at the bottom of this file.

use crate::common;
use crate::common::inbox::{NoopHandler, message};

use std::fmt::Write as _;
use std::sync::{Arc, Mutex};

use reliar_core::MessageId;
use reliar_inbox::{InboxDeadLetters, InboxScope, InboxStore};
use reliar_store_postgres::{PostgresInboxSettings, PostgresInboxStore};
use tracing::field::{Field, Visit};
use tracing_subscriber::layer::{Context, SubscriberExt};

const SECRET_ERROR_MARKER: &str = "RELIAR_LAST_ERROR_MUST_NEVER_APPEAR_IN_A_SPAN";

#[derive(Debug)]
struct SecretError;

impl std::fmt::Display for SecretError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{SECRET_ERROR_MARKER}")
    }
}

impl std::error::Error for SecretError {}

/// Renders every recorded field as `name=value ` — shared by span-open and event recording,
/// mirroring `outbox_enqueue_spans.rs`'s own `TranscriptVisitor`.
struct TranscriptVisitor<'a>(&'a mut String);

impl Visit for TranscriptVisitor<'_> {
    fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
        let _ = write!(self.0, "{}={value:?} ", field.name());
    }
}

#[derive(Default, Clone)]
struct Transcript(Arc<Mutex<String>>);

impl Transcript {
    fn text(&self) -> String {
        self.0.lock().unwrap().clone()
    }
}

struct Recorder(Transcript);

impl<S> tracing_subscriber::Layer<S> for Recorder
where
    S: tracing::Subscriber + for<'lookup> tracing_subscriber::registry::LookupSpan<'lookup>,
{
    fn on_new_span(
        &self,
        attrs: &tracing::span::Attributes<'_>,
        _id: &tracing::span::Id,
        _ctx: Context<'_, S>,
    ) {
        let mut line = format!("SPAN_OPEN {}{{ ", attrs.metadata().name());

        attrs.record(&mut TranscriptVisitor(&mut line));
        line.push_str("}\n");

        self.0.0.lock().unwrap().push_str(&line);
    }

    fn on_record(
        &self,
        _id: &tracing::span::Id,
        values: &tracing::span::Record<'_>,
        _ctx: Context<'_, S>,
    ) {
        let mut line = "SPAN_RECORD ".to_string();

        values.record(&mut TranscriptVisitor(&mut line));
        line.push('\n');

        self.0.0.lock().unwrap().push_str(&line);
    }
}

fn install_recorder() -> (Transcript, tracing::subscriber::DefaultGuard) {
    let transcript = Transcript::default();
    let subscriber = tracing_subscriber::registry().with(Recorder(transcript.clone()));
    let guard = common::install_recording_subscriber(subscriber);

    (transcript, guard)
}

async fn claim_span_carries_entry_and_dead_outcome_fields() {
    let pool = common::fresh_db().await;
    let settings = PostgresInboxSettings::default().max_attempts(1);
    let store = PostgresInboxStore::with_settings(pool.clone(), settings).unwrap();
    let scope = InboxScope::new("orders-projection").unwrap();
    let id = MessageId::new();

    // Kill the row first (on the pool, no span assertions here) so the claim below hits the
    // `Dead` outcome, exercising `inbox.record_id` on the way out.
    let failure = store.fail(&scope, message(id), &SecretError).await.unwrap();
    let dead_record_id = match failure {
        reliar_inbox::InboxFailure::Dead { id, .. } => id,
        other => panic!("expected Dead, got {other:?}"),
    };

    let (transcript, _guard) = install_recorder();

    let mut tx = pool.begin().await.unwrap();
    let claim = store.claim(&mut tx, &scope, message(id)).await.unwrap();

    tx.rollback().await.unwrap();

    assert!(matches!(claim, reliar_inbox::InboxClaim::Dead { .. }));

    let text = transcript.text();
    assert_eq!(
        text.matches("SPAN_OPEN reliar.inbox.claim{").count(),
        1,
        "expected exactly one claim span:\n{text}"
    );
    assert!(text.contains(&format!("message.id={id}")), "{text}");
    assert!(text.contains("message.type=orders.created"), "{text}");
    assert!(text.contains("inbox.scope=orders-projection"), "{text}");
    assert!(text.contains("inbox.outcome=\"dead\""), "{text}");
    assert!(
        text.contains(&format!("inbox.record_id={dead_record_id}")),
        "expected the dead row's id on the claim span:\n{text}"
    );
    assert!(
        !text.contains(SECRET_ERROR_MARKER),
        "last_error must never reach a span:\n{text}"
    );
}

/// The `claimed` outcome, the one C.5 pins to a **singular** `inbox.attempt` — as opposed to the
/// `dead` outcome's **plural** `inbox.attempts` above. Asserting both names, not just one value,
/// is what catches a swap between the two: a regression that recorded the attempt ordinal under
/// `inbox.attempts` instead would still make `text.contains("inbox.attempt=1")` pass as a
/// substring of `"inbox.attempts=1"` were it not for the missing `=` — the plural assertion here
/// closes that gap by asserting the singular field's absence is impossible, i.e. it is present.
async fn claim_span_records_claimed_outcome_with_singular_attempt() {
    let pool = common::fresh_db().await;
    let store =
        PostgresInboxStore::with_settings(pool.clone(), PostgresInboxSettings::default()).unwrap();
    let scope = InboxScope::new("orders-projection").unwrap();
    let id = MessageId::new();

    let (transcript, _guard) = install_recorder();

    let mut tx = pool.begin().await.unwrap();
    let claim = store.claim(&mut tx, &scope, message(id)).await.unwrap();

    tx.rollback().await.unwrap();

    assert_eq!(claim, reliar_inbox::InboxClaim::Claimed { attempt: 1 });

    let text = transcript.text();
    assert!(text.contains("inbox.outcome=\"claimed\""), "{text}");
    assert!(
        text.contains("inbox.attempt=1"),
        "expected the singular inbox.attempt field:\n{text}"
    );
    assert!(
        !text.contains("inbox.attempts=1") && !text.contains("inbox.attempts=\"1\""),
        "inbox.attempts (plural) must not be recorded on a claimed outcome:\n{text}"
    );
}

/// The `already_completed` outcome: `claim` on a message a prior transaction already committed
/// and completed.
async fn claim_span_records_already_completed_outcome() {
    let pool = common::fresh_db().await;
    let store =
        PostgresInboxStore::with_settings(pool.clone(), PostgresInboxSettings::default()).unwrap();
    let scope = InboxScope::new("orders-projection").unwrap();
    let id = MessageId::new();

    let mut tx = pool.begin().await.unwrap();

    store.claim(&mut tx, &scope, message(id)).await.unwrap();
    store.complete(&mut tx, &scope, id).await.unwrap();
    tx.commit().await.unwrap();

    let (transcript, _guard) = install_recorder();

    let mut tx = pool.begin().await.unwrap();
    let claim = store.claim(&mut tx, &scope, message(id)).await.unwrap();

    tx.rollback().await.unwrap();

    assert!(matches!(
        claim,
        reliar_inbox::InboxClaim::AlreadyCompleted { .. }
    ));

    let text = transcript.text();
    assert!(
        text.contains("inbox.outcome=\"already_completed\""),
        "{text}"
    );
}

/// The `in_progress` outcome: a second, concurrent transaction on the same key — mirrors
/// `inbox_concurrency.rs`'s `concurrent_duplicate_claim_reports_in_progress_immediately`, bounded
/// the same way so a regression that blocks instead of skipping fails this test rather than the
/// suite hanging.
async fn claim_span_records_in_progress_outcome() {
    let pool = common::fresh_db().await;
    let store =
        PostgresInboxStore::with_settings(pool.clone(), PostgresInboxSettings::default()).unwrap();
    let scope = InboxScope::new("orders-projection").unwrap();
    let id = MessageId::new();

    let mut tx_a = pool.begin().await.unwrap();

    store.claim(&mut tx_a, &scope, message(id)).await.unwrap();

    let (transcript, _guard) = install_recorder();

    let mut tx_b = pool.begin().await.unwrap();
    let claim_b = tokio::time::timeout(
        std::time::Duration::from_millis(500),
        store.claim(&mut tx_b, &scope, message(id)),
    )
    .await
    .expect("claim must return within 500ms instead of blocking on the advisory lock")
    .unwrap();

    tx_b.rollback().await.unwrap();
    tx_a.rollback().await.unwrap();

    assert_eq!(claim_b, reliar_inbox::InboxClaim::InProgress);

    let text = transcript.text();
    assert!(text.contains("inbox.outcome=\"in_progress\""), "{text}");
}

async fn fail_span_carries_entry_and_dead_outcome_fields() {
    let pool = common::fresh_db().await;
    let settings = PostgresInboxSettings::default().max_attempts(1);
    let store = PostgresInboxStore::with_settings(pool.clone(), settings).unwrap();
    let scope = InboxScope::new("orders-projection").unwrap();
    let id = MessageId::new();

    let (transcript, _guard) = install_recorder();

    let failure = store.fail(&scope, message(id), &SecretError).await.unwrap();
    let dead_record_id = match failure {
        reliar_inbox::InboxFailure::Dead { id, .. } => id,
        other => panic!("expected Dead at max_attempts(1), got {other:?}"),
    };

    let text = transcript.text();

    assert_eq!(
        text.matches("SPAN_OPEN reliar.inbox.fail{").count(),
        1,
        "expected exactly one fail span:\n{text}"
    );
    assert!(text.contains(&format!("message.id={id}")), "{text}");
    assert!(text.contains("message.type=orders.created"), "{text}");
    assert!(text.contains("inbox.outcome=\"dead\""), "{text}");
    assert!(text.contains("inbox.attempts=1"), "{text}");
    assert!(
        text.contains(&format!("inbox.record_id={dead_record_id}")),
        "expected the dead row's id on the fail span:\n{text}"
    );
    assert!(
        !text.contains(SECRET_ERROR_MARKER),
        "last_error must never reach a span, even though it caused the transition:\n{text}"
    );
}

/// The `recorded` outcome: a failure short of `max_attempts`, so nothing goes dead.
/// `inbox.record_id` is **never** recorded here (ADR 0042's dated correction to C.5, 2026-09-07):
/// `InboxFailure::Recorded` carries no row id, and a non-dead row has no operator action —
/// `inbox.record_id` present ⇔ the row is dead, on every outcome-bearing span.
async fn fail_span_records_recorded_outcome() {
    let pool = common::fresh_db().await;
    let settings = PostgresInboxSettings::default().max_attempts(2);
    let store = PostgresInboxStore::with_settings(pool.clone(), settings).unwrap();
    let scope = InboxScope::new("orders-projection").unwrap();
    let id = MessageId::new();

    let (transcript, _guard) = install_recorder();

    let failure = store.fail(&scope, message(id), &SecretError).await.unwrap();

    assert_eq!(
        failure,
        reliar_inbox::InboxFailure::Recorded { attempts: 1 }
    );

    let text = transcript.text();
    assert!(text.contains("inbox.outcome=\"recorded\""), "{text}");
    assert!(text.contains("inbox.attempts=1"), "{text}");
    assert!(
        !text.contains("inbox.record_id="),
        "inbox.record_id must not be recorded on a non-dead outcome:\n{text}"
    );
}

/// The `already_completed` outcome: `fail` on a message a prior transaction already completed —
/// the completed-row guard leaves it untouched and nothing is recorded, so neither
/// `inbox.attempts` nor `inbox.record_id` is set (the dated correction to C.5).
async fn fail_span_records_already_completed_outcome() {
    let pool = common::fresh_db().await;
    let store =
        PostgresInboxStore::with_settings(pool.clone(), PostgresInboxSettings::default()).unwrap();
    let scope = InboxScope::new("orders-projection").unwrap();
    let id = MessageId::new();

    let mut tx = pool.begin().await.unwrap();

    store.claim(&mut tx, &scope, message(id)).await.unwrap();
    store.complete(&mut tx, &scope, id).await.unwrap();
    tx.commit().await.unwrap();

    let (transcript, _guard) = install_recorder();

    let failure = store.fail(&scope, message(id), &SecretError).await.unwrap();

    assert_eq!(failure, reliar_inbox::InboxFailure::AlreadyCompleted);

    let text = transcript.text();
    assert!(
        text.contains("inbox.outcome=\"already_completed\""),
        "{text}"
    );
    assert!(
        !text.contains("inbox.attempts=") && !text.contains("inbox.record_id="),
        "neither attempts nor record_id is recorded on already_completed:\n{text}"
    );
}

async fn complete_span_carries_entry_fields_only() {
    let pool = common::fresh_db().await;
    let store =
        PostgresInboxStore::with_settings(pool.clone(), PostgresInboxSettings::default()).unwrap();
    let scope = InboxScope::new("orders-projection").unwrap();
    let id = MessageId::new();

    let mut tx = pool.begin().await.unwrap();

    store.claim(&mut tx, &scope, message(id)).await.unwrap();

    let (transcript, _guard) = install_recorder();

    store.complete(&mut tx, &scope, id).await.unwrap();
    tx.commit().await.unwrap();

    let text = transcript.text();

    assert_eq!(
        text.matches("SPAN_OPEN reliar.inbox.complete{").count(),
        1,
        "expected exactly one complete span:\n{text}"
    );
    assert!(text.contains(&format!("message.id={id}")), "{text}");
    assert!(text.contains("inbox.scope=orders-projection"), "{text}");
}

async fn purge_span_carries_exit_counts() {
    let pool = common::fresh_db().await;
    let store =
        PostgresInboxStore::with_settings(pool.clone(), PostgresInboxSettings::default()).unwrap();
    let scope = InboxScope::new("orders-projection").unwrap();
    let id = MessageId::new();

    let mut tx = pool.begin().await.unwrap();

    store.claim(&mut tx, &scope, message(id)).await.unwrap();
    store.complete(&mut tx, &scope, id).await.unwrap();
    tx.commit().await.unwrap();

    let (transcript, _guard) = install_recorder();

    let report = store
        .purge(
            reliar_inbox::InboxPurgeRequest::default()
                .completed_retention(Some(std::time::Duration::ZERO)),
        )
        .await
        .unwrap();
    assert_eq!(report.completed_deleted, 1);

    let text = transcript.text();
    assert_eq!(
        text.matches("SPAN_OPEN reliar.inbox.purge{").count(),
        1,
        "expected exactly one purge span:\n{text}"
    );
    assert!(text.contains("inbox.completed_deleted=1"), "{text}");
    assert!(text.contains("inbox.incomplete_deleted=0"), "{text}");
    assert!(text.contains("inbox.dead_deleted=0"), "{text}");
}

/// I-P30 — two of the three dead-letter operator spans, `list_dead` and `retry_dead`
/// (`purge_dead` gets its own test below).
async fn dead_letter_spans_carry_entry_and_exit_fields() {
    let pool = common::fresh_db().await;
    let settings = PostgresInboxSettings::default().max_attempts(1);
    let store = PostgresInboxStore::with_settings(pool.clone(), settings).unwrap();
    let scope = InboxScope::new("orders-projection").unwrap();
    let id = MessageId::new();

    store.fail(&scope, message(id), &SecretError).await.unwrap();
    let record = store.find(&scope, id).await.unwrap().unwrap();

    let (transcript, _guard) = install_recorder();

    let page = store
        .list_dead(
            reliar_inbox::InboxDeadQuery::default()
                .scope(scope.clone())
                .limit(u32::MAX),
        )
        .await
        .unwrap();
    assert_eq!(page.len(), 1);

    let affected = store.retry_dead(&[record.id]).await.unwrap();
    assert_eq!(affected, 1);

    let text = transcript.text();
    assert_eq!(
        text.matches("SPAN_OPEN reliar.inbox.list_dead{").count(),
        1,
        "expected exactly one list_dead span:\n{text}"
    );
    // `list_dead`'s `inbox.scope` is an `Option<&str>` field (Some/None on whether the query
    // filters), not the `%scope` Display sigil `claim`/`complete`/`fail` use — its `Value`
    // dispatch renders through `record_str`'s Debug fallback, quoted, unlike the sigil form.
    assert!(text.contains("inbox.scope=\"orders-projection\""), "{text}");
    // `limit(u32::MAX)` proves the provider caps the recorded field at
    // `MAX_LIST_DEAD_LIMIT` (1000) rather than the raw requested value.
    assert!(text.contains("inbox.limit=1000"), "{text}");
    assert!(text.contains("inbox.returned=1"), "{text}");

    assert_eq!(
        text.matches("SPAN_OPEN reliar.inbox.retry_dead{").count(),
        1,
        "expected exactly one retry_dead span:\n{text}"
    );
    assert!(text.contains("inbox.requested=1"), "{text}");
    assert!(text.contains("inbox.affected=1"), "{text}");
    assert!(
        !text.contains(SECRET_ERROR_MARKER),
        "last_error must never reach a span:\n{text}"
    );
}

/// `reliar.inbox.purge_dead`: entry `inbox.requested`, exit `inbox.affected` — the third
/// dead-letter operator span, alongside `list_dead` and `retry_dead` above.
async fn purge_dead_span_carries_entry_and_exit_fields() {
    let pool = common::fresh_db().await;
    let settings = PostgresInboxSettings::default().max_attempts(1);
    let store = PostgresInboxStore::with_settings(pool.clone(), settings).unwrap();
    let scope = InboxScope::new("orders-projection").unwrap();
    let id = MessageId::new();

    store.fail(&scope, message(id), &SecretError).await.unwrap();
    let record = store.find(&scope, id).await.unwrap().unwrap();

    let (transcript, _guard) = install_recorder();

    let affected = store.purge_dead(&[record.id]).await.unwrap();
    assert_eq!(affected, 1);

    let text = transcript.text();
    assert_eq!(
        text.matches("SPAN_OPEN reliar.inbox.purge_dead{").count(),
        1,
        "expected exactly one purge_dead span:\n{text}"
    );
    assert!(text.contains("inbox.requested=1"), "{text}");
    assert!(text.contains("inbox.affected=1"), "{text}");
    assert!(
        !text.contains(SECRET_ERROR_MARKER),
        "last_error must never reach a span:\n{text}"
    );
}

/// I-N30 (ADR 0043 §3, folded from `reliar-inbox`'s removed fake-backed `spans.rs`) —
/// `InboxStore::process`'s own `reliar.inbox.process` span, distinct from the provider spans
/// above: one span per call, the three entry fields recorded before `claim` runs, and
/// `inbox.outcome` for the `processed` outcome.
async fn process_span_emits_one_span_with_processed_outcome() {
    let pool = common::fresh_db().await;
    let store =
        PostgresInboxStore::with_settings(pool.clone(), PostgresInboxSettings::default()).unwrap();
    let scope = InboxScope::new("orders-projection").unwrap();
    let id = MessageId::new();

    let (transcript, _guard) = install_recorder();

    let mut tx = pool.begin().await.unwrap();
    let outcome = store
        .process(&mut tx, &scope, message(id), &NoopHandler)
        .await
        .unwrap();

    tx.commit().await.unwrap();

    assert_eq!(outcome, reliar_inbox::InboxOutcome::Processed(()));

    let text = transcript.text();
    assert_eq!(
        text.matches("SPAN_OPEN reliar.inbox.process{").count(),
        1,
        "expected exactly one process span:\n{text}"
    );
    assert!(text.contains(&format!("message.id={id}")), "{text}");
    assert!(text.contains("message.type=orders.created"), "{text}");
    assert!(text.contains("inbox.scope=orders-projection"), "{text}");
    assert!(text.contains("inbox.outcome=\"processed\""), "{text}");
}

/// The `already_completed` outcome on `process`'s own span.
async fn process_span_records_already_completed_outcome() {
    let pool = common::fresh_db().await;
    let store =
        PostgresInboxStore::with_settings(pool.clone(), PostgresInboxSettings::default()).unwrap();
    let scope = InboxScope::new("orders-projection").unwrap();
    let id = MessageId::new();

    let mut tx = pool.begin().await.unwrap();

    store
        .process(&mut tx, &scope, message(id), &NoopHandler)
        .await
        .unwrap();
    tx.commit().await.unwrap();

    let (transcript, _guard) = install_recorder();

    let mut tx2 = pool.begin().await.unwrap();
    let outcome = store
        .process(&mut tx2, &scope, message(id), &NoopHandler)
        .await
        .unwrap();
    tx2.rollback().await.unwrap();

    assert!(matches!(
        outcome,
        reliar_inbox::InboxOutcome::AlreadyCompleted { .. }
    ));

    let text = transcript.text();
    assert!(
        text.contains("inbox.outcome=\"already_completed\""),
        "{text}"
    );
}

/// The `in_progress` outcome on `process`'s own span — a second, real, concurrent transaction on
/// the same key, bounded so a regression that blocks fails the test rather than the suite hanging.
async fn process_span_records_in_progress_outcome() {
    let pool = common::fresh_db().await;
    let store =
        PostgresInboxStore::with_settings(pool.clone(), PostgresInboxSettings::default()).unwrap();
    let scope = InboxScope::new("orders-projection").unwrap();
    let id = MessageId::new();

    let mut tx_a = pool.begin().await.unwrap();

    store.claim(&mut tx_a, &scope, message(id)).await.unwrap();

    let (transcript, _guard) = install_recorder();

    let mut tx_b = pool.begin().await.unwrap();
    let outcome = tokio::time::timeout(
        std::time::Duration::from_millis(500),
        store.process(&mut tx_b, &scope, message(id), &NoopHandler),
    )
    .await
    .expect("process must return within 500ms instead of blocking on the advisory lock")
    .unwrap();

    tx_b.rollback().await.unwrap();
    tx_a.rollback().await.unwrap();

    assert_eq!(outcome, reliar_inbox::InboxOutcome::InProgress);

    let text = transcript.text();
    assert!(text.contains("inbox.outcome=\"in_progress\""), "{text}");
}

/// The `dead` outcome on `process`'s own span, plus `inbox.record_id` — mirrors
/// `claim_span_carries_entry_and_dead_outcome_fields` above, through `process` instead of `claim`.
async fn process_span_records_dead_outcome_and_record_id() {
    let pool = common::fresh_db().await;
    let settings = PostgresInboxSettings::default().max_attempts(1);
    let store = PostgresInboxStore::with_settings(pool.clone(), settings).unwrap();
    let scope = InboxScope::new("orders-projection").unwrap();
    let id = MessageId::new();

    let failure = store.fail(&scope, message(id), &SecretError).await.unwrap();
    let dead_record_id = match failure {
        reliar_inbox::InboxFailure::Dead { id, .. } => id,
        other => panic!("expected Dead, got {other:?}"),
    };

    let (transcript, _guard) = install_recorder();

    let mut tx = pool.begin().await.unwrap();
    let outcome = store
        .process(&mut tx, &scope, message(id), &NoopHandler)
        .await
        .unwrap();

    tx.rollback().await.unwrap();

    assert!(matches!(outcome, reliar_inbox::InboxOutcome::Dead { .. }));

    let text = transcript.text();
    assert!(text.contains("inbox.outcome=\"dead\""), "{text}");
    assert!(
        text.contains(&format!("inbox.record_id={dead_record_id}")),
        "expected the dead row's id on the process span:\n{text}"
    );
    assert!(
        !text.contains(SECRET_ERROR_MARKER),
        "last_error must never reach a span:\n{text}"
    );
}

/// Every trial in this file installs a thread-local recording subscriber — must run in `main.rs`'s
/// serialised recorder phase, never in the parallel batch (mirrors `outbox_enqueue_spans.rs`).
#[allow(
    clippy::too_many_lines,
    reason = "one Trial per scenario function above; splitting the list would scatter it with no reuse"
)]
pub(crate) fn recorder_trials(rt: &'static tokio::runtime::Runtime) -> Vec<libtest_mimic::Trial> {
    vec![
        libtest_mimic::Trial::test(
            "inbox_spans::claim_span_carries_entry_and_dead_outcome_fields",
            move || {
                rt.block_on(claim_span_carries_entry_and_dead_outcome_fields());
                Ok(())
            },
        ),
        libtest_mimic::Trial::test(
            "inbox_spans::claim_span_records_claimed_outcome_with_singular_attempt",
            move || {
                rt.block_on(claim_span_records_claimed_outcome_with_singular_attempt());
                Ok(())
            },
        ),
        libtest_mimic::Trial::test(
            "inbox_spans::claim_span_records_already_completed_outcome",
            move || {
                rt.block_on(claim_span_records_already_completed_outcome());
                Ok(())
            },
        ),
        libtest_mimic::Trial::test(
            "inbox_spans::claim_span_records_in_progress_outcome",
            move || {
                rt.block_on(claim_span_records_in_progress_outcome());
                Ok(())
            },
        ),
        libtest_mimic::Trial::test(
            "inbox_spans::fail_span_carries_entry_and_dead_outcome_fields",
            move || {
                rt.block_on(fail_span_carries_entry_and_dead_outcome_fields());
                Ok(())
            },
        ),
        libtest_mimic::Trial::test(
            "inbox_spans::fail_span_records_recorded_outcome",
            move || {
                rt.block_on(fail_span_records_recorded_outcome());
                Ok(())
            },
        ),
        libtest_mimic::Trial::test(
            "inbox_spans::fail_span_records_already_completed_outcome",
            move || {
                rt.block_on(fail_span_records_already_completed_outcome());
                Ok(())
            },
        ),
        libtest_mimic::Trial::test(
            "inbox_spans::complete_span_carries_entry_fields_only",
            move || {
                rt.block_on(complete_span_carries_entry_fields_only());
                Ok(())
            },
        ),
        libtest_mimic::Trial::test("inbox_spans::purge_span_carries_exit_counts", move || {
            rt.block_on(purge_span_carries_exit_counts());
            Ok(())
        }),
        libtest_mimic::Trial::test(
            "inbox_spans::dead_letter_spans_carry_entry_and_exit_fields",
            move || {
                rt.block_on(dead_letter_spans_carry_entry_and_exit_fields());
                Ok(())
            },
        ),
        libtest_mimic::Trial::test(
            "inbox_spans::purge_dead_span_carries_entry_and_exit_fields",
            move || {
                rt.block_on(purge_dead_span_carries_entry_and_exit_fields());
                Ok(())
            },
        ),
        libtest_mimic::Trial::test(
            "inbox_spans::process_span_emits_one_span_with_processed_outcome",
            move || {
                rt.block_on(process_span_emits_one_span_with_processed_outcome());
                Ok(())
            },
        ),
        libtest_mimic::Trial::test(
            "inbox_spans::process_span_records_already_completed_outcome",
            move || {
                rt.block_on(process_span_records_already_completed_outcome());
                Ok(())
            },
        ),
        libtest_mimic::Trial::test(
            "inbox_spans::process_span_records_in_progress_outcome",
            move || {
                rt.block_on(process_span_records_in_progress_outcome());
                Ok(())
            },
        ),
        libtest_mimic::Trial::test(
            "inbox_spans::process_span_records_dead_outcome_and_record_id",
            move || {
                rt.block_on(process_span_records_dead_outcome_and_record_id());
                Ok(())
            },
        ),
    ]
}