1#[cfg(any(test, feature = "fault-injection"))]
21use std::sync::atomic::Ordering;
22use std::sync::Arc;
23use std::time::Duration;
24
25use parking_lot::Mutex;
26use tokio::sync::oneshot;
27use tokio::task::JoinHandle;
28
29use khive_storage::event::EventAppendDisposition;
30use khive_storage::{Event, EventStore, StorageError, WriterTaskRequestState};
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub(crate) enum AuditProductionClass {
36 DispatchObligation,
39 PureObservability,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum AuditProducer {
49 GateDenied,
51 GateUnavailable,
55 DispatchSucceeded,
57 DispatchFailed,
59 UnknownVerb,
61 GitDigestReceipt,
63 ConfigLocked,
65 #[allow(dead_code)]
76 RecallExecuted,
77}
78
79pub(crate) const fn classify(producer: AuditProducer) -> AuditProductionClass {
82 match producer {
83 AuditProducer::GateDenied
84 | AuditProducer::DispatchSucceeded
85 | AuditProducer::DispatchFailed
86 | AuditProducer::UnknownVerb
87 | AuditProducer::GitDigestReceipt => AuditProductionClass::DispatchObligation,
88 AuditProducer::ConfigLocked
89 | AuditProducer::RecallExecuted
90 | AuditProducer::GateUnavailable => AuditProductionClass::PureObservability,
91 }
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum AuditTerminalReason {
100 PreflightRejected,
103 AdmissionClosed,
105 QueueAdmissionExhausted,
110 AdmissionDeadlineExpired,
128 IdentityConflict,
131 StoreFailure,
134 IdempotencyUnsupported,
137 DriverPanicked,
140 DriverCancelled,
143 DriverJoinLost,
146 DriverExitedInconsistent,
150}
151
152pub struct PreparedAuditRow {
156 pub event: Event,
157 pub producer: AuditProducer,
158}
159
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub enum AuditCommitOutcome {
163 Committed,
165 AlreadyPresentIdentical,
168}
169
170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177pub struct AuditBatchHealthMetrics {
178 pub flush_failures: u64,
179 pub degraded_rows: u64,
180 pub degraded: bool,
181}
182
183#[derive(Debug, Clone)]
186pub struct AuditBatchConfig {
187 pub max_pending_rows: std::num::NonZeroUsize,
188 pub max_rows_per_generation: std::num::NonZeroUsize,
189 pub max_commit_attempts: std::num::NonZeroU8,
190 pub retry_backoff: Duration,
191 pub admission_deadline: Duration,
192}
193
194impl Default for AuditBatchConfig {
195 fn default() -> Self {
196 Self {
197 max_pending_rows: std::num::NonZeroUsize::new(4096).unwrap(),
198 max_rows_per_generation: std::num::NonZeroUsize::new(256).unwrap(),
199 max_commit_attempts: std::num::NonZeroU8::new(3).unwrap(),
200 retry_backoff: Duration::from_millis(20),
201 admission_deadline: Duration::from_secs(5),
202 }
203 }
204}
205
206#[async_trait::async_trait]
207pub trait AuditBatchControl: Send + Sync {
208 async fn submit(
209 &self,
210 row: PreparedAuditRow,
211 ) -> Result<AuditCommitOutcome, AuditTerminalReason>;
212 async fn quiesce(&self) -> Result<(), AuditTerminalReason>;
213 async fn close_and_drain(&self) -> Result<(), AuditTerminalReason>;
214}
215
216#[derive(Debug, Clone, PartialEq, Eq)]
217enum Lifecycle {
218 Open,
219 Closing,
220 Closed,
221 Failed(AuditTerminalReason),
222}
223
224struct Waiting {
225 event: Event,
226 producer: AuditProducer,
227 responder: oneshot::Sender<Result<AuditCommitOutcome, AuditTerminalReason>>,
228}
229
230#[derive(Debug, Clone, PartialEq, Eq)]
234pub struct AuditGenerationSnapshot {
235 pub generation_id: u64,
236 pub submitted_rows: u64,
237 pub committed_rows: u64,
238 pub store_batch_calls: u64,
239 pub terminal_reason: Option<AuditTerminalReason>,
240}
241
242struct State {
243 lifecycle: Lifecycle,
244 pending: Vec<Waiting>,
245 in_flight_generation: Option<u64>,
246 driver_active: bool,
247 next_generation_id: u64,
248 submitted_rows: u64,
249 committed_rows: u64,
250 store_batch_calls: u64,
251 generations: Vec<AuditGenerationSnapshot>,
252 flush_failures: u64,
253 degraded_rows: u64,
254 degraded: bool,
255}
256
257impl State {
258 fn new() -> Self {
259 Self {
260 lifecycle: Lifecycle::Open,
261 pending: Vec::new(),
262 in_flight_generation: None,
263 driver_active: false,
264 next_generation_id: 0,
265 submitted_rows: 0,
266 committed_rows: 0,
267 store_batch_calls: 0,
268 generations: Vec::new(),
269 flush_failures: 0,
270 degraded_rows: 0,
271 degraded: false,
272 }
273 }
274
275 fn is_idle(&self) -> bool {
276 self.pending.is_empty() && self.in_flight_generation.is_none() && !self.driver_active
277 }
278}
279
280struct Inner {
281 state: Mutex<State>,
282}
283
284impl Inner {
285 fn fail_driver(&self, reason: AuditTerminalReason, in_flight_waiters: Vec<Waiting>) {
291 let mut state = self.state.lock();
292 let already_failed = matches!(state.lifecycle, Lifecycle::Failed(_));
293 if !already_failed {
294 state.lifecycle = Lifecycle::Failed(reason);
295 }
296 state.driver_active = false;
297 state.in_flight_generation = None;
298 let drained: Vec<Waiting> = std::mem::take(&mut state.pending);
299 if !already_failed {
300 state.flush_failures += 1;
301 let generation_id = state.next_generation_id;
302 state.generations.push(AuditGenerationSnapshot {
303 generation_id,
304 submitted_rows: (in_flight_waiters.len() + drained.len()) as u64,
305 committed_rows: 0,
306 store_batch_calls: 0,
307 terminal_reason: Some(reason),
308 });
309 state.next_generation_id += 1;
310 }
311 drop(state);
312 for waiting in in_flight_waiters.into_iter().chain(drained) {
313 record_degradation_if_pure(self, waiting.producer);
314 let _ = waiting.responder.send(Err(reason));
315 }
316 }
317
318 fn record_degradation(&self) {
319 let mut state = self.state.lock();
320 state.degraded_rows += 1;
321 state.degraded = true;
322 }
323}
324
325fn record_degradation_if_pure(inner: &Inner, producer: AuditProducer) {
326 if classify(producer) == AuditProductionClass::PureObservability {
327 inner.record_degradation();
328 }
329}
330
331struct SupervisorGuard<'a> {
338 inner: &'a Arc<Inner>,
339 waiting: Option<Vec<Waiting>>,
340}
341
342impl<'a> SupervisorGuard<'a> {
343 fn armed(inner: &'a Arc<Inner>, waiting: Vec<Waiting>) -> Self {
344 Self {
345 inner,
346 waiting: Some(waiting),
347 }
348 }
349
350 fn disarm(mut self) -> Vec<Waiting> {
353 self.waiting.take().unwrap_or_default()
354 }
355
356 fn fail(mut self, reason: AuditTerminalReason) {
360 if let Some(waiting) = self.waiting.take() {
361 self.inner.fail_driver(reason, waiting);
362 }
363 }
364}
365
366impl Drop for SupervisorGuard<'_> {
367 fn drop(&mut self) {
368 let Some(waiting) = self.waiting.take() else {
369 return;
370 };
371 let reason = if std::thread::panicking() {
372 AuditTerminalReason::DriverPanicked
373 } else {
374 AuditTerminalReason::DriverCancelled
375 };
376 self.inner.fail_driver(reason, waiting);
377 }
378}
379
380enum RetryDecision {
381 Retry,
382 Terminal(AuditTerminalReason),
383}
384
385fn classify_store_error(err: &StorageError) -> RetryDecision {
386 match err {
387 StorageError::WriteQueueFull { .. } | StorageError::WriterTaskBusy { .. } => {
388 RetryDecision::Retry
389 }
390 StorageError::Pool { .. } | StorageError::Timeout { .. } => RetryDecision::Retry,
397 StorageError::WriterTaskTerminated { request_state } => match request_state {
398 WriterTaskRequestState::NotStarted | WriterTaskRequestState::TransactionRolledBack => {
399 RetryDecision::Retry
400 }
401 WriterTaskRequestState::SideEffectsUnknown => RetryDecision::Retry,
402 },
403 StorageError::Unsupported { operation, .. }
404 if operation.as_ref() == "append_events_idempotent" =>
405 {
406 RetryDecision::Terminal(AuditTerminalReason::IdempotencyUnsupported)
407 }
408 _ => RetryDecision::Terminal(AuditTerminalReason::StoreFailure),
409 }
410}
411
412enum GenerationResult {
413 Committed(Vec<EventAppendDisposition>),
414 Failed(AuditTerminalReason),
415 #[cfg_attr(not(any(test, feature = "fault-injection")), allow(dead_code))]
418 FakedInconsistent,
419}
420
421async fn run_generation(
422 store: Arc<dyn EventStore>,
423 events: Vec<Event>,
424 config: Arc<AuditBatchConfig>,
425) -> GenerationResult {
426 #[cfg(any(test, feature = "fault-injection"))]
427 if fault::CHILD_PANIC.swap(false, Ordering::SeqCst) {
428 panic!("adr133 fault injection: audit_batch child_panic");
429 }
430 #[cfg(any(test, feature = "fault-injection"))]
431 if fault::INCONSISTENT_EXIT.swap(false, Ordering::SeqCst) {
432 return GenerationResult::FakedInconsistent;
433 }
434
435 let mut attempt: u8 = 0;
436 loop {
437 attempt += 1;
438 match store.append_events_idempotent(events.clone()).await {
439 Ok(result) => return GenerationResult::Committed(result.rows),
440 Err(err) => match classify_store_error(&err) {
441 RetryDecision::Retry if attempt < config.max_commit_attempts.get() => {
442 tokio::time::sleep(config.retry_backoff).await;
443 }
444 RetryDecision::Retry => {
445 return GenerationResult::Failed(AuditTerminalReason::StoreFailure)
446 }
447 RetryDecision::Terminal(reason) => return GenerationResult::Failed(reason),
448 },
449 }
450 }
451}
452
453pub struct AuditBatch {
457 inner: Arc<Inner>,
458 store: Arc<dyn EventStore>,
459 config: Arc<AuditBatchConfig>,
460 supervisor: Mutex<Option<JoinHandle<()>>>,
461}
462
463impl AuditBatch {
464 pub fn new(store: Arc<dyn EventStore>, config: AuditBatchConfig) -> Arc<Self> {
465 Arc::new(Self {
466 inner: Arc::new(Inner {
467 state: Mutex::new(State::new()),
468 }),
469 store,
470 config: Arc::new(config),
471 supervisor: Mutex::new(None),
472 })
473 }
474
475 pub fn health_metrics(&self) -> AuditBatchHealthMetrics {
482 let state = self.inner.state.lock();
483 AuditBatchHealthMetrics {
484 flush_failures: state.flush_failures,
485 degraded_rows: state.degraded_rows,
486 degraded: state.degraded,
487 }
488 }
489
490 fn spawn_supervisor_if_idle(&self) {
491 let inner = self.inner.clone();
492 let store = self.store.clone();
493 let config = self.config.clone();
494 let handle = tokio::spawn(async move {
495 supervisor_loop(inner, store, config).await;
496 });
497 *self.supervisor.lock() = Some(handle);
498 }
499}
500
501async fn supervisor_loop(
502 inner: Arc<Inner>,
503 store: Arc<dyn EventStore>,
504 config: Arc<AuditBatchConfig>,
505) {
506 loop {
507 let waiting = {
508 let mut state = inner.state.lock();
509 if matches!(state.lifecycle, Lifecycle::Failed(_)) {
510 state.driver_active = false;
511 break;
512 }
513 if state.pending.is_empty() {
514 state.driver_active = false;
515 break;
516 }
517 let take_n = state
518 .pending
519 .len()
520 .min(config.max_rows_per_generation.get());
521 let waiting: Vec<Waiting> = state.pending.drain(..take_n).collect();
522 let generation_id = state.next_generation_id;
523 state.next_generation_id += 1;
524 state.in_flight_generation = Some(generation_id);
525 waiting
526 };
527
528 #[cfg(any(test, feature = "fault-injection"))]
529 if fault::SUPERVISOR_PANIC.swap(false, Ordering::SeqCst) {
530 let _guard = SupervisorGuard::armed(&inner, waiting);
531 panic!("adr133 fault injection: audit_batch supervisor_panic");
532 }
533 #[cfg(any(test, feature = "fault-injection"))]
534 if fault::SUPERVISOR_SLEEP_BEFORE_SPAWN.swap(false, Ordering::SeqCst) {
535 let guard = SupervisorGuard::armed(&inner, waiting);
536 tokio::time::sleep(Duration::from_secs(3600)).await;
537 drop(guard);
538 continue;
539 }
540
541 let guard = SupervisorGuard::armed(&inner, waiting);
542 let events: Vec<Event> = guard
543 .waiting
544 .as_ref()
545 .expect("guard freshly armed")
546 .iter()
547 .map(|w| w.event.clone())
548 .collect();
549
550 let child: JoinHandle<GenerationResult> =
551 tokio::spawn(run_generation(store.clone(), events, config.clone()));
552
553 #[cfg(any(test, feature = "fault-injection"))]
554 if fault::CHILD_CANCEL.swap(false, Ordering::SeqCst) {
555 child.abort();
556 }
557 #[cfg(any(test, feature = "fault-injection"))]
558 if fault::JOIN_LOST.swap(false, Ordering::SeqCst) {
559 drop(child);
560 guard.fail(AuditTerminalReason::DriverJoinLost);
561 continue;
562 }
563
564 let join_result = child.await;
565 match join_result {
566 Err(join_err) => {
567 let reason = if join_err.is_panic() {
568 AuditTerminalReason::DriverPanicked
569 } else {
570 AuditTerminalReason::DriverCancelled
571 };
572 guard.fail(reason);
573 }
574 Ok(GenerationResult::FakedInconsistent) => {
575 guard.fail(AuditTerminalReason::DriverExitedInconsistent);
576 }
577 Ok(GenerationResult::Failed(reason)) => {
578 let waiting = guard.disarm();
579 let submitted = waiting.len() as u64;
580 {
581 let mut state = inner.state.lock();
582 state.in_flight_generation = None;
583 state.store_batch_calls += 1;
584 state.flush_failures += 1;
585 let generation_id = state.next_generation_id.saturating_sub(1);
586 state.generations.push(AuditGenerationSnapshot {
587 generation_id,
588 submitted_rows: submitted,
589 committed_rows: 0,
590 store_batch_calls: 1,
591 terminal_reason: Some(reason),
592 });
593 }
594 for w in waiting {
595 record_degradation_if_pure(&inner, w.producer);
596 let _ = w.responder.send(Err(reason));
597 }
598 }
599 Ok(GenerationResult::Committed(dispositions)) => {
600 let waiting = guard.disarm();
601 if dispositions.len() != waiting.len() {
602 {
607 let mut state = inner.state.lock();
608 state.in_flight_generation = None;
609 }
610 inner.fail_driver(AuditTerminalReason::DriverExitedInconsistent, waiting);
611 continue;
612 }
613 let mut committed_n = 0u64;
614 for d in &dispositions {
615 if !matches!(d, EventAppendDisposition::IdentityConflict) {
616 committed_n += 1;
617 }
618 }
619 let submitted = dispositions.len() as u64;
620 {
621 let mut state = inner.state.lock();
622 state.in_flight_generation = None;
623 state.store_batch_calls += 1;
624 state.committed_rows += committed_n;
625 let generation_id = state.next_generation_id.saturating_sub(1);
626 state.generations.push(AuditGenerationSnapshot {
627 generation_id,
628 submitted_rows: submitted,
629 committed_rows: committed_n,
630 store_batch_calls: 1,
631 terminal_reason: None,
632 });
633 }
634 for (w, disposition) in waiting.into_iter().zip(dispositions) {
635 let result = match disposition {
636 EventAppendDisposition::Inserted => Ok(AuditCommitOutcome::Committed),
637 EventAppendDisposition::AlreadyPresentIdentical => {
638 Ok(AuditCommitOutcome::AlreadyPresentIdentical)
639 }
640 EventAppendDisposition::IdentityConflict => {
641 record_degradation_if_pure(&inner, w.producer);
642 Err(AuditTerminalReason::IdentityConflict)
643 }
644 };
645 let _ = w.responder.send(result);
646 }
647 }
648 }
649 }
650}
651
652#[async_trait::async_trait]
653impl AuditBatchControl for AuditBatch {
654 async fn submit(
655 &self,
656 row: PreparedAuditRow,
657 ) -> Result<AuditCommitOutcome, AuditTerminalReason> {
658 if self.store.preflight_event(&row.event).is_err() {
661 return Err(AuditTerminalReason::PreflightRejected);
662 }
663
664 let (tx, rx) = oneshot::channel();
665 let need_spawn = {
666 let mut state = self.inner.state.lock();
667 match state.lifecycle {
668 Lifecycle::Closed | Lifecycle::Closing => {
669 return Err(AuditTerminalReason::AdmissionClosed)
670 }
671 Lifecycle::Failed(reason) => return Err(reason),
672 Lifecycle::Open => {}
673 }
674 if state.pending.len() >= self.config.max_pending_rows.get() {
675 return Err(AuditTerminalReason::QueueAdmissionExhausted);
676 }
677 state.pending.push(Waiting {
678 event: row.event,
679 producer: row.producer,
680 responder: tx,
681 });
682 state.submitted_rows += 1;
683 let need_spawn = !state.driver_active;
684 if need_spawn {
685 state.driver_active = true;
686 }
687 need_spawn
688 };
689 if need_spawn {
690 self.spawn_supervisor_if_idle();
691 }
692
693 match tokio::time::timeout(self.config.admission_deadline, rx).await {
694 Ok(Ok(result)) => result,
695 Ok(Err(_recv_error)) => Err(AuditTerminalReason::DriverJoinLost),
696 Err(_elapsed) => Err(AuditTerminalReason::AdmissionDeadlineExpired),
703 }
704 }
705
706 async fn quiesce(&self) -> Result<(), AuditTerminalReason> {
707 loop {
708 let (lifecycle, idle) = {
709 let state = self.inner.state.lock();
710 (state.lifecycle.clone(), state.is_idle())
711 };
712 match lifecycle {
713 Lifecycle::Failed(reason) => return Err(reason),
714 Lifecycle::Closed => return Ok(()),
715 _ if idle => return Ok(()),
716 _ => tokio::time::sleep(Duration::from_millis(2)).await,
717 }
718 }
719 }
720
721 async fn close_and_drain(&self) -> Result<(), AuditTerminalReason> {
722 {
723 let mut state = self.inner.state.lock();
724 if matches!(state.lifecycle, Lifecycle::Open) {
725 state.lifecycle = Lifecycle::Closing;
726 }
727 }
728 let result = AuditBatchControl::quiesce(self).await;
729 {
730 let mut state = self.inner.state.lock();
731 if result.is_ok() && matches!(state.lifecycle, Lifecycle::Closing) {
732 state.lifecycle = Lifecycle::Closed;
733 }
734 }
735 let handle = self.supervisor.lock().take();
736 if let Some(handle) = handle {
737 let _ = handle.await;
738 }
739 result
740 }
741}
742
743#[cfg(any(test, feature = "fault-injection"))]
744mod fault {
745 use std::sync::atomic::AtomicBool;
746
747 pub(super) static CHILD_PANIC: AtomicBool = AtomicBool::new(false);
748 pub(super) static CHILD_CANCEL: AtomicBool = AtomicBool::new(false);
749 pub(super) static SUPERVISOR_PANIC: AtomicBool = AtomicBool::new(false);
750 pub(super) static SUPERVISOR_SLEEP_BEFORE_SPAWN: AtomicBool = AtomicBool::new(false);
751 pub(super) static JOIN_LOST: AtomicBool = AtomicBool::new(false);
752 pub(super) static INCONSISTENT_EXIT: AtomicBool = AtomicBool::new(false);
753}
754
755#[cfg(any(test, feature = "fault-injection"))]
759pub mod fault_injection {
760 use std::sync::atomic::Ordering;
761
762 pub fn arm_child_panic() {
763 super::fault::CHILD_PANIC.store(true, Ordering::SeqCst);
764 }
765 pub fn arm_child_cancel() {
766 super::fault::CHILD_CANCEL.store(true, Ordering::SeqCst);
767 }
768 pub fn arm_supervisor_panic() {
769 super::fault::SUPERVISOR_PANIC.store(true, Ordering::SeqCst);
770 }
771 pub fn arm_supervisor_sleep_before_spawn() {
772 super::fault::SUPERVISOR_SLEEP_BEFORE_SPAWN.store(true, Ordering::SeqCst);
773 }
774 pub fn arm_join_lost() {
775 super::fault::JOIN_LOST.store(true, Ordering::SeqCst);
776 }
777 pub fn arm_inconsistent_exit() {
778 super::fault::INCONSISTENT_EXIT.store(true, Ordering::SeqCst);
779 }
780}
781
782#[cfg(any(test, feature = "test-internals"))]
788mod test_internals {
789 use super::*;
790
791 #[derive(Debug, Clone)]
795 pub struct AuditBatchSnapshot {
796 pub pending_rows: usize,
797 pub in_flight_generation: Option<u64>,
798 pub driver_active: bool,
799 pub next_generation_id: u64,
800 pub submitted_rows: u64,
801 pub committed_rows: u64,
802 pub store_batch_calls: u64,
803 pub per_generation: Vec<AuditGenerationSnapshot>,
804 }
805
806 impl AuditBatchSnapshot {
807 pub fn is_idle(&self) -> bool {
808 self.pending_rows == 0 && self.in_flight_generation.is_none() && !self.driver_active
809 }
810 }
811
812 #[derive(Debug, Clone, Copy)]
813 pub struct AuditBatchMetricsSnapshot {
814 pub flush_failures: u64,
815 pub degraded_rows: u64,
816 pub degraded: bool,
817 }
818
819 #[derive(Debug, Clone, PartialEq)]
820 pub struct AuditBatchDelta {
821 pub submitted_rows: u64,
822 pub committed_rows: u64,
823 pub store_batch_calls: u64,
824 pub per_generation: Vec<AuditGenerationSnapshot>,
825 }
826
827 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
828 pub enum AuditSnapshotError {
829 CounterRegressed,
830 GenerationHistoryRegressed,
831 }
832
833 impl AuditBatch {
834 pub fn test_snapshot(&self) -> AuditBatchSnapshot {
835 let state = self.inner.state.lock();
836 AuditBatchSnapshot {
837 pending_rows: state.pending.len(),
838 in_flight_generation: state.in_flight_generation,
839 driver_active: state.driver_active,
840 next_generation_id: state.next_generation_id,
841 submitted_rows: state.submitted_rows,
842 committed_rows: state.committed_rows,
843 store_batch_calls: state.store_batch_calls,
844 per_generation: state.generations.clone(),
845 }
846 }
847
848 pub fn metrics_snapshot(&self) -> AuditBatchMetricsSnapshot {
849 let state = self.inner.state.lock();
850 AuditBatchMetricsSnapshot {
851 flush_failures: state.flush_failures,
852 degraded_rows: state.degraded_rows,
853 degraded: state.degraded,
854 }
855 }
856
857 pub fn test_abort_supervisor(&self) -> bool {
863 let handle = self.supervisor.lock().take();
864 match handle {
865 Some(handle) => {
866 handle.abort();
867 true
868 }
869 None => false,
870 }
871 }
872 }
873
874 pub fn audit_delta(
877 before: &AuditBatchSnapshot,
878 after: &AuditBatchSnapshot,
879 ) -> Result<AuditBatchDelta, AuditSnapshotError> {
880 let submitted_rows = after
881 .submitted_rows
882 .checked_sub(before.submitted_rows)
883 .ok_or(AuditSnapshotError::CounterRegressed)?;
884 let committed_rows = after
885 .committed_rows
886 .checked_sub(before.committed_rows)
887 .ok_or(AuditSnapshotError::CounterRegressed)?;
888 let store_batch_calls = after
889 .store_batch_calls
890 .checked_sub(before.store_batch_calls)
891 .ok_or(AuditSnapshotError::CounterRegressed)?;
892 if after.per_generation.len() < before.per_generation.len() {
893 return Err(AuditSnapshotError::GenerationHistoryRegressed);
894 }
895 if after.per_generation[..before.per_generation.len()] != before.per_generation[..] {
896 return Err(AuditSnapshotError::GenerationHistoryRegressed);
897 }
898 let per_generation = after.per_generation[before.per_generation.len()..].to_vec();
899 Ok(AuditBatchDelta {
900 submitted_rows,
901 committed_rows,
902 store_batch_calls,
903 per_generation,
904 })
905 }
906
907 #[allow(dead_code)]
941 struct DoctestAnchor;
942}
943
944#[cfg(any(test, feature = "test-internals"))]
945pub use test_internals::*;