oxide-batch 0.5.0

Embedded Core Production Preview of restartable batch processing for Rust, inspired by Spring Batch
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
//! Facade-owned lifecycle events and value-redacted diagnostic projections.

use std::fmt;
use std::num::NonZeroU64;
use std::time::Duration;

use crate::{
    BatchStatus, ChunkCount, FailureSummary, FaultPhase, JobExecutionId, JobInstanceId, JobName,
    RetryOrdinal, StepExecutionId, StepName,
};

/// A nonzero, instance-scoped execution-attempt ordinal.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ExecutionAttempt(NonZeroU64);

impl ExecutionAttempt {
    /// Constructs an attempt ordinal from a nonzero value.
    #[must_use]
    pub const fn new(value: NonZeroU64) -> Self {
        Self(value)
    }

    /// Returns the numeric attempt ordinal.
    #[must_use]
    pub const fn get(self) -> u64 {
        self.0.get()
    }
}

impl fmt::Display for ExecutionAttempt {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.get().fmt(formatter)
    }
}

/// Stable, bounded identifiers shared by job and step diagnostics.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExecutionCorrelation {
    job_name: JobName,
    job_instance_id: JobInstanceId,
    job_execution_id: JobExecutionId,
    job_attempt: ExecutionAttempt,
    step_name: StepName,
    step_execution_id: StepExecutionId,
    step_attempt: ExecutionAttempt,
}

impl ExecutionCorrelation {
    /// Constructs complete correlation for a single-step execution graph.
    #[must_use]
    #[allow(clippy::too_many_arguments)]
    pub const fn new(
        job_name: JobName,
        job_instance_id: JobInstanceId,
        job_execution_id: JobExecutionId,
        job_attempt: ExecutionAttempt,
        step_name: StepName,
        step_execution_id: StepExecutionId,
        step_attempt: ExecutionAttempt,
    ) -> Self {
        Self {
            job_name,
            job_instance_id,
            job_execution_id,
            job_attempt,
            step_name,
            step_execution_id,
            step_attempt,
        }
    }

    /// Borrows the job definition name.
    #[must_use]
    pub const fn job_name(&self) -> &JobName {
        &self.job_name
    }

    /// Returns the logical job-instance identifier.
    #[must_use]
    pub const fn job_instance_id(&self) -> JobInstanceId {
        self.job_instance_id
    }

    /// Returns the job-attempt identifier.
    #[must_use]
    pub const fn job_execution_id(&self) -> JobExecutionId {
        self.job_execution_id
    }

    /// Returns the instance-scoped job attempt.
    #[must_use]
    pub const fn job_attempt(&self) -> ExecutionAttempt {
        self.job_attempt
    }

    /// Borrows the step definition name.
    #[must_use]
    pub const fn step_name(&self) -> &StepName {
        &self.step_name
    }

    /// Returns the step-attempt identifier.
    #[must_use]
    pub const fn step_execution_id(&self) -> StepExecutionId {
        self.step_execution_id
    }

    /// Returns the instance-scoped step attempt.
    #[must_use]
    pub const fn step_attempt(&self) -> ExecutionAttempt {
        self.step_attempt
    }
}

/// Stable severity for a lifecycle event.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum EventSeverity {
    /// High-volume detail disabled by default.
    Debug,
    /// Normal lifecycle progress.
    Info,
    /// A cooperative stop or recoverable condition.
    Warn,
    /// A failed lifecycle or user-component boundary.
    Error,
}

impl EventSeverity {
    /// Returns the stable lowercase representation.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Debug => "debug",
            Self::Info => "info",
            Self::Warn => "warn",
            Self::Error => "error",
        }
    }
}

impl fmt::Display for EventSeverity {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// The framework component associated with an event.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum EventComponent {
    /// The launch facade.
    Launcher,
    /// A job execution.
    Job,
    /// A step execution.
    Step,
    /// A bounded chunk transaction.
    Chunk,
    /// A job or step listener boundary.
    Listener,
    /// A bounded retry scope.
    Retry,
    /// One item classified by a fault policy.
    Item,
    /// A rollback or no-rollback classification.
    Fault,
    /// Durable flow traversal.
    Flow,
    /// Repository command/query behavior.
    Repository,
    /// Checkpoint lifecycle.
    Checkpoint,
    /// Guarded operator services.
    Operator,
    /// Bounded explorer services.
    Explorer,
    /// Graceful process shutdown.
    Shutdown,
    /// Stale detection and recovery.
    Recovery,
    /// Guarded retention.
    Retention,
    /// Local split execution.
    Split,
    /// Local partition execution.
    Partition,
    /// Export infrastructure.
    Telemetry,
    /// Metadata migration.
    Migration,
}

impl EventComponent {
    /// Returns the stable lowercase representation.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Launcher => "launcher",
            Self::Job => "job",
            Self::Step => "step",
            Self::Chunk => "chunk",
            Self::Listener => "listener",
            Self::Retry => "retry",
            Self::Item => "item",
            Self::Fault => "fault",
            Self::Flow => "flow",
            Self::Repository => "repository",
            Self::Checkpoint => "checkpoint",
            Self::Operator => "operator",
            Self::Explorer => "explorer",
            Self::Shutdown => "shutdown",
            Self::Recovery => "recovery",
            Self::Retention => "retention",
            Self::Split => "split",
            Self::Partition => "partition",
            Self::Telemetry => "telemetry",
            Self::Migration => "migration",
        }
    }
}

impl fmt::Display for EventComponent {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Stable M1 lifecycle event names.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum LifecycleEventKind {
    /// The repository accepted a launch and created its execution graph.
    LaunchAccepted,
    /// Job metadata is durably `STARTING`.
    JobStarting,
    /// Step metadata is durably `STARTING`.
    StepStarting,
    /// Job metadata is durably `STARTED`.
    JobStarted,
    /// Step metadata is durably `STARTED`.
    StepStarted,
    /// Job metadata is durably `STOPPING`.
    JobStopping,
    /// Step metadata is durably `STOPPING`.
    StepStopping,
    /// Job metadata is durably `STOPPED`.
    JobStopped,
    /// Step metadata is durably `STOPPED`.
    StepStopped,
    /// Job metadata is durably `COMPLETED`.
    JobCompleted,
    /// Step metadata is durably `COMPLETED`.
    StepCompleted,
    /// Job metadata is durably `FAILED`.
    JobFailed,
    /// Step metadata is durably `FAILED`.
    StepFailed,
    /// Job metadata is durably `UNKNOWN`.
    JobUnknown,
    /// Step metadata is durably `UNKNOWN`.
    StepUnknown,
    /// A bounded chunk transaction is starting.
    ChunkStarted,
    /// A bounded chunk transaction committed.
    ChunkCommitted,
    /// A bounded chunk transaction rolled back.
    ChunkRolledBack,
    /// A chunk commit result is unknown.
    ChunkUnknown,
    /// A job before-listener returned an error or panicked.
    JobBeforeListenerFailed,
    /// A job after-listener returned an error or panicked.
    JobAfterListenerFailed,
    /// A step before-listener returned an error or panicked.
    StepBeforeListenerFailed,
    /// A step after-listener returned an error or panicked.
    StepAfterListenerFailed,
    /// A retry ordinal became durably reserved.
    RetryReserved,
    /// A cancellable backoff wait started.
    RetryBackoffStarted,
    /// Cooperative stop cancelled a backoff wait.
    RetryBackoffCancelled,
    /// A retry budget is durably spent for one key.
    RetryExhausted,
    /// A skip became authoritative in the accepting chunk commit.
    ItemSkipped,
    /// A known rollback was classified by the fault policy.
    FaultRollbackCommitted,
    /// A commit-safe skip committed without rolling back.
    FaultNoRollbackCommitted,
}

impl LifecycleEventKind {
    /// Maps this legacy facade event into telemetry schema version 1.
    #[must_use]
    pub const fn telemetry_kind(self) -> crate::TelemetryEventKind {
        match self {
            Self::LaunchAccepted => crate::TelemetryEventKind::LaunchAccepted,
            Self::JobStarting => crate::TelemetryEventKind::JobStarting,
            Self::StepStarting => crate::TelemetryEventKind::StepStarting,
            Self::JobStarted => crate::TelemetryEventKind::JobStarted,
            Self::StepStarted => crate::TelemetryEventKind::StepStarted,
            Self::JobStopping => crate::TelemetryEventKind::JobStopping,
            Self::StepStopping => crate::TelemetryEventKind::StepStopping,
            Self::JobStopped => crate::TelemetryEventKind::JobStopped,
            Self::StepStopped => crate::TelemetryEventKind::StepStopped,
            Self::JobCompleted => crate::TelemetryEventKind::JobCompleted,
            Self::StepCompleted => crate::TelemetryEventKind::StepCompleted,
            Self::JobFailed => crate::TelemetryEventKind::JobFailed,
            Self::StepFailed => crate::TelemetryEventKind::StepFailed,
            Self::JobUnknown => crate::TelemetryEventKind::JobUnknown,
            Self::StepUnknown => crate::TelemetryEventKind::StepUnknown,
            Self::ChunkStarted => crate::TelemetryEventKind::ChunkStarted,
            Self::ChunkCommitted => crate::TelemetryEventKind::ChunkCommitted,
            Self::ChunkRolledBack => crate::TelemetryEventKind::ChunkRolledBack,
            Self::ChunkUnknown => crate::TelemetryEventKind::ChunkUnknown,
            Self::JobBeforeListenerFailed => crate::TelemetryEventKind::JobBeforeListenerFailed,
            Self::JobAfterListenerFailed => crate::TelemetryEventKind::JobAfterListenerFailed,
            Self::StepBeforeListenerFailed => crate::TelemetryEventKind::StepBeforeListenerFailed,
            Self::StepAfterListenerFailed => crate::TelemetryEventKind::StepAfterListenerFailed,
            Self::RetryReserved => crate::TelemetryEventKind::RetryReserved,
            Self::RetryBackoffStarted => crate::TelemetryEventKind::RetryBackoffStarted,
            Self::RetryBackoffCancelled => crate::TelemetryEventKind::RetryBackoffCancelled,
            Self::RetryExhausted => crate::TelemetryEventKind::RetryExhausted,
            Self::ItemSkipped => crate::TelemetryEventKind::ItemSkipped,
            Self::FaultRollbackCommitted => crate::TelemetryEventKind::FaultRollbackCommitted,
            Self::FaultNoRollbackCommitted => crate::TelemetryEventKind::FaultNoRollbackCommitted,
        }
    }

    /// Returns the stable dotted event name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::LaunchAccepted => "launch.accepted",
            Self::JobStarting => "job.starting",
            Self::StepStarting => "step.starting",
            Self::JobStarted => "job.started",
            Self::StepStarted => "step.started",
            Self::JobStopping => "job.stopping",
            Self::StepStopping => "step.stopping",
            Self::JobStopped => "job.stopped",
            Self::StepStopped => "step.stopped",
            Self::JobCompleted => "job.completed",
            Self::StepCompleted => "step.completed",
            Self::JobFailed => "job.failed",
            Self::StepFailed => "step.failed",
            Self::JobUnknown => "job.unknown",
            Self::StepUnknown => "step.unknown",
            Self::ChunkStarted => "chunk.started",
            Self::ChunkCommitted => "chunk.committed",
            Self::ChunkRolledBack => "chunk.rolled_back",
            Self::ChunkUnknown => "chunk.unknown",
            Self::JobBeforeListenerFailed => "job.before_listener.failed",
            Self::JobAfterListenerFailed => "job.after_listener.failed",
            Self::StepBeforeListenerFailed => "step.before_listener.failed",
            Self::StepAfterListenerFailed => "step.after_listener.failed",
            Self::RetryReserved => "retry.reserved",
            Self::RetryBackoffStarted => "retry.backoff_started",
            Self::RetryBackoffCancelled => "retry.backoff_cancelled",
            Self::RetryExhausted => "retry.exhausted",
            Self::ItemSkipped => "item.skipped",
            Self::FaultRollbackCommitted => "fault.rollback_committed",
            Self::FaultNoRollbackCommitted => "fault.no_rollback_committed",
        }
    }

    /// Returns the component associated with the event.
    #[must_use]
    pub const fn component(self) -> EventComponent {
        match self {
            Self::LaunchAccepted => EventComponent::Launcher,
            Self::JobStarting
            | Self::JobStarted
            | Self::JobStopping
            | Self::JobStopped
            | Self::JobCompleted
            | Self::JobFailed
            | Self::JobUnknown => EventComponent::Job,
            Self::StepStarting
            | Self::StepStarted
            | Self::StepStopping
            | Self::StepStopped
            | Self::StepCompleted
            | Self::StepFailed
            | Self::StepUnknown => EventComponent::Step,
            Self::ChunkStarted
            | Self::ChunkCommitted
            | Self::ChunkRolledBack
            | Self::ChunkUnknown => EventComponent::Chunk,
            Self::JobBeforeListenerFailed
            | Self::JobAfterListenerFailed
            | Self::StepBeforeListenerFailed
            | Self::StepAfterListenerFailed => EventComponent::Listener,
            Self::RetryReserved
            | Self::RetryBackoffStarted
            | Self::RetryBackoffCancelled
            | Self::RetryExhausted => EventComponent::Retry,
            Self::ItemSkipped => EventComponent::Item,
            Self::FaultRollbackCommitted | Self::FaultNoRollbackCommitted => EventComponent::Fault,
        }
    }

    /// Returns the lifecycle status represented by the event, when any.
    #[must_use]
    pub const fn status(self) -> Option<BatchStatus> {
        match self {
            Self::JobStarting | Self::StepStarting => Some(BatchStatus::Starting),
            Self::JobStarted | Self::StepStarted => Some(BatchStatus::Started),
            Self::JobStopping | Self::StepStopping => Some(BatchStatus::Stopping),
            Self::JobStopped | Self::StepStopped => Some(BatchStatus::Stopped),
            Self::JobCompleted | Self::StepCompleted => Some(BatchStatus::Completed),
            Self::JobFailed | Self::StepFailed => Some(BatchStatus::Failed),
            Self::JobUnknown | Self::StepUnknown => Some(BatchStatus::Unknown),
            Self::LaunchAccepted
            | Self::ChunkStarted
            | Self::ChunkCommitted
            | Self::ChunkRolledBack
            | Self::ChunkUnknown
            | Self::JobBeforeListenerFailed
            | Self::JobAfterListenerFailed
            | Self::StepBeforeListenerFailed
            | Self::StepAfterListenerFailed
            | Self::RetryReserved
            | Self::RetryBackoffStarted
            | Self::RetryBackoffCancelled
            | Self::RetryExhausted
            | Self::ItemSkipped
            | Self::FaultRollbackCommitted
            | Self::FaultNoRollbackCommitted => None,
        }
    }

    /// Returns the stable event severity.
    #[must_use]
    pub const fn severity(self) -> EventSeverity {
        match self {
            Self::JobFailed
            | Self::StepFailed
            | Self::JobUnknown
            | Self::StepUnknown
            | Self::ChunkUnknown
            | Self::JobBeforeListenerFailed
            | Self::JobAfterListenerFailed
            | Self::StepBeforeListenerFailed
            | Self::StepAfterListenerFailed
            | Self::RetryExhausted => EventSeverity::Error,
            Self::JobStopping
            | Self::StepStopping
            | Self::JobStopped
            | Self::StepStopped
            | Self::ChunkRolledBack
            | Self::RetryReserved
            | Self::RetryBackoffCancelled
            | Self::ItemSkipped
            | Self::FaultRollbackCommitted
            | Self::FaultNoRollbackCommitted => EventSeverity::Warn,
            Self::LaunchAccepted
            | Self::RetryBackoffStarted
            | Self::JobStarting
            | Self::StepStarting
            | Self::JobStarted
            | Self::StepStarted
            | Self::JobCompleted
            | Self::StepCompleted
            | Self::ChunkStarted
            | Self::ChunkCommitted => EventSeverity::Info,
        }
    }
}

impl fmt::Display for LifecycleEventKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// A structured lifecycle event containing only reviewed, bounded fields.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LifecycleEvent {
    kind: LifecycleEventKind,
    correlation: ExecutionCorrelation,
    failure: Option<FailureSummary>,
    chunk_sequence: Option<ChunkCount>,
    fault_phase: Option<FaultPhase>,
    retry_ordinal: Option<RetryOrdinal>,
    backoff: Option<Duration>,
}

impl LifecycleEvent {
    /// Returns the telemetry schema version carried by this event mapping.
    #[must_use]
    pub const fn schema_version(&self) -> u16 {
        crate::TELEMETRY_SCHEMA_VERSION
    }
    pub(crate) const fn new(kind: LifecycleEventKind, correlation: ExecutionCorrelation) -> Self {
        Self {
            kind,
            correlation,
            failure: None,
            chunk_sequence: None,
            fault_phase: None,
            retry_ordinal: None,
            backoff: None,
        }
    }

    pub(crate) const fn failed(
        kind: LifecycleEventKind,
        correlation: ExecutionCorrelation,
        failure: FailureSummary,
    ) -> Self {
        Self {
            kind,
            correlation,
            failure: Some(failure),
            chunk_sequence: None,
            fault_phase: None,
            retry_ordinal: None,
            backoff: None,
        }
    }

    pub(crate) const fn chunk(
        kind: LifecycleEventKind,
        correlation: ExecutionCorrelation,
        sequence: ChunkCount,
    ) -> Self {
        Self {
            kind,
            correlation,
            failure: None,
            chunk_sequence: Some(sequence),
            fault_phase: None,
            retry_ordinal: None,
            backoff: None,
        }
    }

    pub(crate) const fn fault(
        kind: LifecycleEventKind,
        correlation: ExecutionCorrelation,
        sequence: ChunkCount,
        phase: FaultPhase,
    ) -> Self {
        Self {
            kind,
            correlation,
            failure: None,
            chunk_sequence: Some(sequence),
            fault_phase: Some(phase),
            retry_ordinal: None,
            backoff: None,
        }
    }

    pub(crate) const fn with_failure(mut self, failure: FailureSummary) -> Self {
        self.failure = Some(failure);
        self
    }

    pub(crate) const fn with_retry_ordinal(mut self, ordinal: RetryOrdinal) -> Self {
        self.retry_ordinal = Some(ordinal);
        self
    }

    pub(crate) const fn with_backoff(mut self, backoff: Duration) -> Self {
        self.backoff = Some(backoff);
        self
    }

    /// Returns the fault phase for a retry, skip, or rollback event.
    #[must_use]
    pub const fn fault_phase(&self) -> Option<FaultPhase> {
        self.fault_phase
    }

    /// Returns the reserved retry ordinal for a retry event.
    #[must_use]
    pub const fn retry_ordinal(&self) -> Option<RetryOrdinal> {
        self.retry_ordinal
    }

    /// Returns the deterministic backoff duration for a backoff event.
    #[must_use]
    pub const fn backoff(&self) -> Option<Duration> {
        self.backoff
    }

    /// Returns the stable event kind.
    #[must_use]
    pub const fn kind(&self) -> LifecycleEventKind {
        self.kind
    }

    /// Borrows the complete execution correlation.
    #[must_use]
    pub const fn correlation(&self) -> &ExecutionCorrelation {
        &self.correlation
    }

    /// Returns the redacted failure summary, when present.
    #[must_use]
    pub const fn failure(&self) -> Option<FailureSummary> {
        self.failure
    }

    /// Returns the chunk-attempt sequence for chunk events.
    #[must_use]
    pub const fn chunk_sequence(&self) -> Option<ChunkCount> {
        self.chunk_sequence
    }

    /// Produces the reviewed fields suitable for a tracing span or event.
    #[must_use]
    pub fn span_fields(&self) -> Vec<DiagnosticField> {
        let mut fields = vec![
            DiagnosticField::new("event.name", self.kind.as_str()),
            DiagnosticField::new("event.severity", self.kind.severity().as_str()),
            DiagnosticField::new("component", self.kind.component().as_str()),
            DiagnosticField::new("job.name", self.correlation.job_name().as_str()),
            DiagnosticField::new(
                "job.instance.id",
                self.correlation.job_instance_id().to_string(),
            ),
            DiagnosticField::new(
                "job.execution.id",
                self.correlation.job_execution_id().to_string(),
            ),
            DiagnosticField::new("job.attempt", self.correlation.job_attempt().to_string()),
            DiagnosticField::new("step.name", self.correlation.step_name().as_str()),
            DiagnosticField::new(
                "step.execution.id",
                self.correlation.step_execution_id().to_string(),
            ),
            DiagnosticField::new("step.attempt", self.correlation.step_attempt().to_string()),
        ];
        if let Some(status) = self.kind.status() {
            fields.push(DiagnosticField::new("batch.status", status.to_string()));
        }
        if let Some(sequence) = self.chunk_sequence {
            fields.push(DiagnosticField::new(
                "chunk.sequence",
                sequence.get().to_string(),
            ));
        }
        if let Some(phase) = self.fault_phase {
            fields.push(DiagnosticField::new("fault.phase", phase.as_str()));
        }
        if let Some(ordinal) = self.retry_ordinal {
            fields.push(DiagnosticField::new(
                "retry.ordinal",
                ordinal.get().to_string(),
            ));
        }
        if let Some(backoff) = self.backoff {
            fields.push(DiagnosticField::new(
                "retry.backoff_ms",
                u64::try_from(backoff.as_millis())
                    .unwrap_or(u64::MAX)
                    .to_string(),
            ));
        }
        if let Some(failure) = self.failure {
            fields.push(DiagnosticField::new(
                "failure.category",
                format!("{:?}", failure.category()),
            ));
            fields.push(DiagnosticField::new(
                "failure.id",
                failure.failure_id().to_string(),
            ));
        }
        fields
    }

    /// Produces a bounded metric label set.
    ///
    /// Identifiers, names, parameters, contexts, records, and error text are
    /// intentionally absent.
    #[must_use]
    pub fn metric_labels(&self) -> Vec<MetricLabel> {
        let mut labels = vec![
            MetricLabel::new("event", self.kind.as_str()),
            MetricLabel::new("component", self.kind.component().as_str()),
        ];
        if let Some(status) = self.kind.status() {
            labels.push(MetricLabel::new("status", status.to_string()));
        }
        if let Some(phase) = self.fault_phase {
            labels.push(MetricLabel::new("fault_phase", phase.as_str()));
        }
        labels
    }
}

impl fmt::Display for LifecycleEvent {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "event={} severity={} job={} job_instance_id={} job_execution_id={} \
             job_attempt={} step={} step_execution_id={} step_attempt={}",
            self.kind,
            self.kind.severity(),
            self.correlation.job_name(),
            self.correlation.job_instance_id(),
            self.correlation.job_execution_id(),
            self.correlation.job_attempt(),
            self.correlation.step_name(),
            self.correlation.step_execution_id(),
            self.correlation.step_attempt(),
        )?;
        if let Some(status) = self.kind.status() {
            write!(formatter, " status={status}")?;
        }
        if let Some(sequence) = self.chunk_sequence {
            write!(formatter, " chunk_sequence={}", sequence.get())?;
        }
        if let Some(phase) = self.fault_phase {
            write!(formatter, " fault_phase={phase}")?;
        }
        if let Some(ordinal) = self.retry_ordinal {
            write!(formatter, " retry_ordinal={}", ordinal.get())?;
        }
        if let Some(backoff) = self.backoff {
            write!(formatter, " backoff_ms={}", backoff.as_millis())?;
        }
        if let Some(failure) = self.failure {
            write!(
                formatter,
                " failure_category={:?} failure_id={}",
                failure.category(),
                failure.failure_id()
            )?;
        }
        Ok(())
    }
}

/// A reviewed key/value field suitable for structured logs or spans.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DiagnosticField {
    key: &'static str,
    value: String,
}

impl DiagnosticField {
    pub(crate) fn new(key: &'static str, value: impl Into<String>) -> Self {
        Self {
            key,
            value: value.into(),
        }
    }

    /// Returns the stable field key.
    #[must_use]
    pub const fn key(&self) -> &'static str {
        self.key
    }

    /// Returns the reviewed field value.
    #[must_use]
    pub fn value(&self) -> &str {
        &self.value
    }
}

impl fmt::Display for DiagnosticField {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}={}", self.key, self.value)
    }
}

/// A bounded, framework-owned metric label.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MetricLabel {
    key: &'static str,
    value: String,
}

impl MetricLabel {
    pub(crate) fn new(key: &'static str, value: impl Into<String>) -> Self {
        Self {
            key,
            value: value.into(),
        }
    }

    /// Returns the stable label key.
    #[must_use]
    pub const fn key(&self) -> &'static str {
        self.key
    }

    /// Returns the bounded framework-owned value.
    #[must_use]
    pub fn value(&self) -> &str {
        &self.value
    }

    pub(crate) fn replace_value(&mut self, value: &'static str) {
        value.clone_into(&mut self.value);
    }
}

impl fmt::Display for MetricLabel {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}={}", self.key, self.value)
    }
}

/// Receives committed lifecycle observations.
///
/// Sink failures and panics are isolated by [`crate::JobLauncher`] and cannot
/// change execution correctness.
pub trait LifecycleEventSink: Send + Sync {
    /// Emits one event after the corresponding metadata commit.
    fn emit(&self, event: &LifecycleEvent);
}