batpak 0.10.0

Embedded, sync-first event store: append-only hash-chained journal, typed events, verifiable receipts, deterministic replay, projections. No async runtime.
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
use crate::event::EventPayloadValidation;
#[cfg(feature = "payload-encryption")]
use crate::store::keyscope::backend::{FileKeysetBackend, KeysetBackend};
#[cfg(feature = "payload-encryption")]
use crate::store::keyscope::KeyScopeGranularity;
pub(crate) use crate::store::platform::clock::{
    clock_from_fn, wall_ms_from_timestamp_us, Clock, MonotonicClock, SystemClock,
};
pub(crate) use crate::store::platform::fs::{RealFs, StoreFs};
pub(crate) use crate::store::platform::spawn::{Spawn, ThreadSpawn};
use crate::store::signing::SigningKey;
use crate::store::RestartPolicy;
use std::path::{Path, PathBuf};
use std::sync::Arc;

#[cfg(feature = "dangerous-test-hooks")]
use crate::store::fault::FaultInjector;

mod types;
mod validation;

pub use crate::store::index::idemp::{IdempotencyRetention, OverflowPolicy};
pub(crate) use types::WriterMode;
pub use types::{
    BatchConfig, ChainVerification, IndexConfig, IndexTopology, OpenReportObserver, SigningPolicy,
    SyncConfig, SyncMode, WriterConfig,
};
pub(crate) use validation::ValidatedStoreConfig;

/// StoreConfig: all settings for a Store instance.
/// No Default — callers must provide data_dir via `StoreConfig::new(path)`.
/// Manual Clone and Debug impls because `clock` field is `Arc<dyn Clock>`.
pub struct StoreConfig {
    /// Directory where segment files (.fbat) are stored.
    pub(crate) data_dir: PathBuf,
    /// Maximum bytes per segment file before rotation.
    pub(crate) segment_max_bytes: u64,
    /// Maximum number of open segment file descriptors.
    pub(crate) fd_budget: usize,
    /// Capacity of each subscriber's broadcast channel.
    pub(crate) broadcast_capacity: usize,
    /// Maximum serialized payload plus encoded receipt-extension size for a
    /// single append operation.
    pub(crate) single_append_max_bytes: u32,
    /// Batch append limits and group-commit behavior.
    pub(crate) batch: BatchConfig,
    /// Writer thread channel, stack, restart, and shutdown-drain configuration.
    pub(crate) writer: WriterConfig,
    /// How the writer pipeline is driven (threaded vs. cooperative inline).
    pub(crate) writer_mode: WriterMode,
    /// fsync strategy and cadence.
    pub(crate) sync: SyncConfig,
    /// Secondary query index topology, projection, and checkpoint configuration.
    pub(crate) index: IndexConfig,
    /// Injectable clock for deterministic testing. None = SystemClock.
    pub(crate) clock: Option<Arc<dyn Clock>>,
    /// Spawner for store background threads. Defaults to [`ThreadSpawn`]
    /// (one OS thread per spawn, identical to direct `std::thread` usage).
    /// A deterministic simulation backend can be installed via
    /// [`StoreConfig::with_spawner`].
    pub(crate) spawner: Arc<dyn Spawn>,
    /// Filesystem backend for store data-path operations. Defaults to
    /// [`RealFs`] (every op delegates to `std::fs` via the platform free fns,
    /// identical to direct usage). A deterministic simulation backend can be
    /// installed via [`StoreConfig::with_fs`].
    pub(crate) fs: Arc<dyn StoreFs>,
    /// Optional callback fired once after a successful open completes.
    pub(crate) open_report_observer: Option<OpenReportObserver>,
    /// Optional platform profile record that must match current platform evidence at open.
    pub(crate) platform_profile_path: Option<PathBuf>,
    /// Signing keys known to this store. The last configured key signs new
    /// receipts; earlier keys remain available for verification.
    pub(crate) signing_keys: Vec<SigningKey>,
    /// Whether a keyless store is permitted (`Optional`, default) or open is
    /// refused without a signing key (`Required`). See [`SigningPolicy`].
    pub(crate) signing_policy: SigningPolicy,
    /// When a signer is configured but its signature cover cannot be built,
    /// permit a best-effort downgrade to an unsigned receipt instead of failing
    /// the append. Default `false` (fail closed).
    pub(crate) signing_downgrade_allowed: bool,
    /// Whether the full hash chain is recomputed at open (`Recompute`) or the
    /// per-frame CRC alone is trusted (`Crc`, default). See [`ChainVerification`].
    pub(crate) chain_verification: ChainVerification,
    /// Payload-registry collision policy applied during `Store::open`.
    pub(crate) event_payload_validation: EventPayloadValidation,
    /// Opt-in crypto-shred payload encryption. `None` (default) disables it and
    /// preserves today's plaintext-payload behavior; `Some(granularity)` selects
    /// the [`KeyScopeGranularity`] keys are partitioned by. Holds only the
    /// granularity — never any key material. When set, every appended payload is
    /// sealed under its scope key on the write path before it is hashed and framed
    /// (`event_hash` covers the ciphertext); reads decrypt it transparently.
    #[cfg(feature = "payload-encryption")]
    #[cfg_attr(
        all(docsrs, not(batpak_stable_docs)),
        doc(cfg(feature = "payload-encryption"))
    )]
    pub(crate) payload_encryption: Option<KeyScopeGranularity>,
    /// Optional pluggable keyset storage (issue #162). `None` (default) keeps
    /// the keyset as the in-directory `keyset.fbatk` file; `Some(backend)`
    /// routes every keyset load/persist through the caller's
    /// [`KeysetBackend`] instead.
    #[cfg(feature = "payload-encryption")]
    #[cfg_attr(
        all(docsrs, not(batpak_stable_docs)),
        doc(cfg(feature = "payload-encryption"))
    )]
    pub(crate) keyset_backend: Option<Arc<dyn KeysetBackend>>,
    /// Fault injector for testing failure scenarios.
    /// Only available with the `dangerous-test-hooks` feature.
    #[cfg(feature = "dangerous-test-hooks")]
    #[cfg_attr(
        all(docsrs, not(batpak_stable_docs)),
        doc(cfg(feature = "dangerous-test-hooks"))
    )]
    pub(crate) fault_injector: Option<Arc<dyn FaultInjector>>,
}

impl StoreConfig {
    /// Create a StoreConfig with required data_dir and sensible defaults.
    /// All numeric defaults are documented. Override fields after construction
    /// to tune for your deployment (embedded, server, CLI).
    pub fn new(data_dir: impl Into<PathBuf>) -> Self {
        Self {
            data_dir: data_dir.into(),
            segment_max_bytes: 256 * 1024 * 1024,
            fd_budget: 64,
            broadcast_capacity: 8192,
            single_append_max_bytes: 16 * 1024 * 1024,
            batch: BatchConfig::default(),
            writer: WriterConfig::default(),
            writer_mode: WriterMode::default(),
            sync: SyncConfig::default(),
            index: IndexConfig::default(),
            clock: None,
            spawner: Arc::new(ThreadSpawn),
            fs: Arc::new(RealFs),
            open_report_observer: None,
            platform_profile_path: None,
            signing_keys: Vec::new(),
            // Optional: a keyless store is a valid "regular store"; its receipts
            // verify structurally but are never `is_signed()`. Regulated callers
            // opt into `SigningPolicy::Required`, which refuses to open without a
            // signing key. Signing is a deliberate per-deployment choice.
            signing_policy: SigningPolicy::Optional,
            signing_downgrade_allowed: false,
            // Crc: a regular store pays nothing extra at open; the per-frame CRC
            // already guarded every frame at read time. Regulated callers opt
            // into ChainVerification::Recompute for tamper-evidence at open.
            chain_verification: ChainVerification::Crc,
            // FailFast (the default): refuse to open when two linked payload
            // types claim the same (category, type_id) and would otherwise get
            // ambiguous wire identity. Callers who knowingly tolerate a
            // collision opt out via EventPayloadValidation::Warn / Silent.
            event_payload_validation: EventPayloadValidation::default(),
            // Opt-in: a default store keeps writing plaintext payloads. Callers
            // enable crypto-shred explicitly via `with_payload_encryption`.
            #[cfg(feature = "payload-encryption")]
            payload_encryption: None,
            // Default keyset storage is the in-directory file backend; a
            // custom backend is installed via `with_keyset_backend`.
            #[cfg(feature = "payload-encryption")]
            keyset_backend: None,
            #[cfg(feature = "dangerous-test-hooks")]
            fault_injector: None,
        }
        // Funnel the default spawner through the builder so the install seam is
        // exercised on every construction; a deterministic-sim backend swaps it
        // in via the same builder without touching any spawn site.
        .with_spawner(Arc::new(ThreadSpawn))
        // Funnel the default filesystem backend through the builder too, so the
        // install seam is exercised on every construction; a deterministic-sim
        // backend swaps it in via the same builder without touching call sites.
        .with_fs(Arc::new(RealFs))
    }

    /// Set the maximum segment file size in bytes before rotation.
    pub fn with_segment_max_bytes(mut self, segment_max_bytes: u64) -> Self {
        self.segment_max_bytes = segment_max_bytes;
        self
    }

    /// Set how many events are written between periodic fsyncs.
    pub fn with_sync_every_n_events(mut self, sync_every_n_events: u32) -> Self {
        self.sync.every_n_events = sync_every_n_events;
        self
    }

    /// Set the maximum number of concurrently open segment file descriptors.
    pub fn with_fd_budget(mut self, fd_budget: usize) -> Self {
        self.fd_budget = fd_budget;
        self
    }

    /// Set the capacity of the writer command channel.
    pub fn with_writer_channel_capacity(mut self, writer_channel_capacity: usize) -> Self {
        self.writer.channel_capacity = writer_channel_capacity;
        self
    }

    /// Set the soft-pressure threshold used by `try_submit*`.
    pub fn with_writer_pressure_retry_threshold_pct(
        mut self,
        pressure_retry_threshold_pct: u8,
    ) -> Self {
        self.writer.pressure_retry_threshold_pct = pressure_retry_threshold_pct;
        self
    }

    /// Set the per-subscriber broadcast channel capacity.
    pub fn with_broadcast_capacity(mut self, broadcast_capacity: usize) -> Self {
        self.broadcast_capacity = broadcast_capacity;
        self
    }

    /// Set the maximum serialized payload plus encoded receipt-extension size
    /// for a single append.
    pub fn with_single_append_max_bytes(mut self, single_append_max_bytes: u32) -> Self {
        self.single_append_max_bytes = single_append_max_bytes;
        self
    }

    /// Set the writer thread restart policy on panic.
    pub fn with_restart_policy(mut self, restart_policy: RestartPolicy) -> Self {
        self.writer.restart_policy = restart_policy;
        self
    }

    /// Set how many pending appends the writer drains before shutting down.
    pub fn with_shutdown_drain_limit(mut self, shutdown_drain_limit: usize) -> Self {
        self.writer.shutdown_drain_limit = shutdown_drain_limit;
        self
    }

    /// Set an explicit stack size for the writer thread; `None` uses the OS default.
    pub fn with_writer_stack_size(mut self, writer_stack_size: Option<usize>) -> Self {
        self.writer.stack_size = writer_stack_size;
        self
    }

    /// Install a custom clock for deterministic testing.
    ///
    /// The runtime installs the monotonic wrapper during validation/open so
    /// direct field assignment (`config.clock = ...`) and builder use follow
    /// the same path.
    ///
    /// **Observable scope.** The injected clock controls both the wall-clock
    /// reads used by internal timestamping AND the `Freshness::MaybeStale`
    /// age comparison in the projection pipeline. Tests may fast-forward the
    /// injected clock to observe age-based cache invalidation: a cached
    /// projection returned from an earlier `project()` becomes stale once
    /// the clock advances past `max_stale_ms`, forcing a re-project on the
    /// next call. See G6.
    ///
    /// Negative timestamps are rejected at append/batch execution time with
    /// `StoreError::InvalidClock` rather than being truncated or panicking.
    ///
    /// **Wait deadlines.** The injected [`Clock::now_mono_ns`] is the time
    /// authority for wait timeouts (`wait_for_durable*`, cursor pulls, gate
    /// waits): store activity observed while the clock's monotonic reading
    /// stands still consumes none of the caller's timeout, so a clock that
    /// never advances defers busy-store timeouts until it moves. Idle waits
    /// stay bounded regardless — a fully timed-out park is accumulated as a
    /// real-time deadline floor. See the [`Clock`] trait docs for the full
    /// contract.
    pub fn with_clock(mut self, clock: Option<Arc<dyn Clock>>) -> Self {
        self.clock = clock;
        self
    }

    /// Install a microsecond wall-clock closure for deterministic tests.
    ///
    /// This is an adapter for older closure-based tests. New callers that need
    /// control over monotonic or boot-epoch observations should implement
    /// [`Clock`] and pass it through [`StoreConfig::with_clock`].
    pub fn with_clock_fn<F>(mut self, clock: F) -> Self
    where
        F: Fn() -> i64 + Send + Sync + 'static,
    {
        self.clock = Some(clock_from_fn(Arc::new(clock)));
        self
    }

    /// Install a callback that observes the structured open report.
    pub fn with_open_report_observer(mut self, observer: Option<OpenReportObserver>) -> Self {
        self.open_report_observer = observer;
        self
    }

    /// Set a platform profile that must verify during store open.
    pub fn with_platform_profile_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.platform_profile_path = Some(path.into());
        self
    }

    /// Clear any configured platform profile.
    pub fn without_platform_profile_path(mut self) -> Self {
        self.platform_profile_path = None;
        self
    }

    /// Add a signing key to the receipt-signature registry.
    pub fn with_signing_key(mut self, signing_key: SigningKey) -> Self {
        self.signing_keys.push(signing_key);
        self
    }

    /// Set the receipt signing policy.
    ///
    /// `Optional` (default) permits a keyless store; `Required` refuses to open
    /// without a signing key, so unsigned receipts can never be accepted.
    pub fn with_signing_policy(mut self, signing_policy: SigningPolicy) -> Self {
        self.signing_policy = signing_policy;
        self
    }

    /// Permit best-effort downgrade to an unsigned receipt when a configured
    /// signer cannot build its signature cover. Default `false` (the append
    /// fails closed rather than silently emitting an unsigned receipt).
    pub fn with_signing_downgrade_allowed(mut self, allow: bool) -> Self {
        self.signing_downgrade_allowed = allow;
        self
    }

    /// Set whether the full hash chain is recomputed at open.
    ///
    /// `Crc` (default) trusts the per-frame CRC and rehashes nothing at open;
    /// `Recompute` runs [`Store::verify_chain`](crate::store::Store::verify_chain)
    /// at open and refuses to open on any content-hash mismatch or dangling
    /// chain link. See [`ChainVerification`].
    pub fn with_chain_verification(mut self, chain_verification: ChainVerification) -> Self {
        self.chain_verification = chain_verification;
        self
    }

    /// Set the open-time payload-registry collision policy.
    pub fn with_event_payload_validation(mut self, validation: EventPayloadValidation) -> Self {
        self.event_payload_validation = validation;
        self
    }

    /// Enable opt-in crypto-shred payload encryption at the given
    /// [`KeyScopeGranularity`].
    ///
    /// Stores only the granularity; no key material is held on the config. This
    /// is opt-in — a store left at the default `None` keeps writing plaintext
    /// payloads. When set, every appended payload is encrypted under its scope
    /// key before it is hashed and framed, so the on-disk payload is ciphertext
    /// and the plaintext is never written.
    #[cfg(feature = "payload-encryption")]
    #[cfg_attr(
        all(docsrs, not(batpak_stable_docs)),
        doc(cfg(feature = "payload-encryption"))
    )]
    pub fn with_payload_encryption(mut self, granularity: KeyScopeGranularity) -> Self {
        self.payload_encryption = Some(granularity);
        self
    }

    /// The configured payload-encryption granularity, or `None` when disabled.
    #[cfg(feature = "payload-encryption")]
    #[cfg_attr(
        all(docsrs, not(batpak_stable_docs)),
        doc(cfg(feature = "payload-encryption"))
    )]
    pub fn payload_encryption(&self) -> Option<KeyScopeGranularity> {
        self.payload_encryption
    }

    /// Install a custom [`KeysetBackend`] for crypto-shred keyset storage
    /// (issue #162).
    ///
    /// By default the keyset lives as a single crash-safe file inside the
    /// store directory ([`FileKeysetBackend`](crate::store::FileKeysetBackend)).
    /// A custom backend holds the encoded keyset image anywhere else — a
    /// separate volume, an OS keychain, a database row wrapped by a KMS — and
    /// must uphold the durability obligations documented on
    /// [`KeysetBackend`](crate::store::KeysetBackend): the store's
    /// flush-before-ack fence and shred acknowledgement rely on them. Only
    /// meaningful together with
    /// [`with_payload_encryption`](Self::with_payload_encryption).
    #[cfg(feature = "payload-encryption")]
    #[cfg_attr(
        all(docsrs, not(batpak_stable_docs)),
        doc(cfg(feature = "payload-encryption"))
    )]
    pub fn with_keyset_backend(mut self, backend: Arc<dyn KeysetBackend>) -> Self {
        self.keyset_backend = Some(backend);
        self
    }

    /// The keyset backend every keyset load/persist routes through: the
    /// configured one, or the default in-directory file backend over this
    /// config's data dir and filesystem.
    #[cfg(feature = "payload-encryption")]
    pub(crate) fn keyset_backend(&self) -> Arc<dyn KeysetBackend> {
        match &self.keyset_backend {
            Some(backend) => Arc::clone(backend),
            None => Arc::new(FileKeysetBackend::with_store_fs(
                self.data_dir.clone(),
                Arc::clone(&self.fs),
            )),
        }
    }

    /// Set the fsync strategy used after writes.
    pub fn with_sync_mode(mut self, sync_mode: SyncMode) -> Self {
        self.sync.mode = sync_mode;
        self
    }

    /// Set maximum appends batched before a single fsync.
    /// Default: 1 (per-event sync). When > 1, all appends
    /// must include an idempotency key for crash safety.
    pub fn with_group_commit_max_batch(mut self, group_commit_max_batch: u32) -> Self {
        self.batch.group_commit_max_batch = group_commit_max_batch;
        self
    }

    /// Set the explicit in-memory scan topology.
    pub fn with_index_topology(mut self, index_topology: IndexTopology) -> Self {
        self.index.topology = index_topology;
        self
    }

    /// Enable or disable incremental projection for types that support it.
    pub fn with_incremental_projection(mut self, incremental_projection: bool) -> Self {
        self.index.incremental_projection = incremental_projection;
        self
    }

    /// Enable or disable index checkpoint on close.
    pub fn with_enable_checkpoint(mut self, enable_checkpoint: bool) -> Self {
        self.index.enable_checkpoint = enable_checkpoint;
        self
    }

    /// Enable or disable the mmap-first index artifact on close/open.
    pub fn with_enable_mmap_index(mut self, enable_mmap_index: bool) -> Self {
        self.index.enable_mmap_index = enable_mmap_index;
        self
    }

    /// Set the growth-bound policy for the durable idempotency store.
    ///
    /// Default is the window-priority [`IdempotencyRetention::Hybrid`]: a keyed
    /// retry whose original commit is within the window is ALWAYS a no-op,
    /// regardless of compaction or load. See [`IdempotencyRetention`].
    pub fn with_idempotency_retention(mut self, retention: IdempotencyRetention) -> Self {
        self.index.idempotency_retention = retention;
        self
    }

    /// Set the escalation policy when within-window keys alone exceed the soft
    /// cap (residual pigeonhole). Default [`OverflowPolicy::Warn`].
    pub fn with_idempotency_overflow(mut self, overflow: OverflowPolicy) -> Self {
        self.index.idempotency_overflow = overflow;
        self
    }

    /// Set maximum items per batch append. Default: 256.
    pub fn with_batch_max_size(mut self, batch_max_size: u32) -> Self {
        self.batch.max_size = batch_max_size;
        self
    }

    /// Set maximum total payload plus encoded receipt-extension bytes per batch append.
    /// Default: 1MB.
    pub fn with_batch_max_bytes(mut self, batch_max_bytes: u32) -> Self {
        self.batch.max_bytes = batch_max_bytes;
        self
    }

    /// Directory where segment files (`.fbat`) are stored.
    pub fn data_dir(&self) -> &Path {
        &self.data_dir
    }

    /// Maximum bytes per segment file before rotation.
    pub fn segment_max_bytes(&self) -> u64 {
        self.segment_max_bytes
    }

    /// Maximum number of concurrently open segment file descriptors.
    pub fn fd_budget(&self) -> usize {
        self.fd_budget
    }

    /// Capacity of each subscriber broadcast channel.
    pub fn broadcast_capacity(&self) -> usize {
        self.broadcast_capacity
    }

    /// Maximum serialized payload plus encoded receipt-extension size for a single append.
    pub fn single_append_max_bytes(&self) -> u32 {
        self.single_append_max_bytes
    }

    /// Batch append limits and group-commit behavior.
    pub fn batch(&self) -> &BatchConfig {
        &self.batch
    }

    /// Writer thread channel, stack, restart, and shutdown-drain configuration.
    pub fn writer(&self) -> &WriterConfig {
        &self.writer
    }

    /// fsync strategy and cadence.
    pub fn sync(&self) -> &SyncConfig {
        &self.sync
    }

    /// Secondary query index topology, projection, and checkpoint configuration.
    pub fn index(&self) -> &IndexConfig {
        &self.index
    }

    /// Whether a custom clock has been configured.
    pub fn has_custom_clock(&self) -> bool {
        self.clock.is_some()
    }

    /// Install a custom spawner for store background threads.
    ///
    /// Production uses the default [`ThreadSpawn`] (one OS thread per spawn).
    /// A deterministic simulation backend installs an alternate [`Spawn`] here
    /// without touching any spawn site.
    pub(crate) fn with_spawner(mut self, spawner: Arc<dyn Spawn>) -> Self {
        self.spawner = spawner;
        self
    }

    /// The configured spawner for store background threads.
    pub(crate) fn spawner(&self) -> &Arc<dyn Spawn> {
        &self.spawner
    }

    /// Select how the writer pipeline is driven.
    ///
    /// Production uses the default [`WriterMode::Threaded`] (a dedicated writer
    /// thread). The cooperative mode runs the writer inline on the calling
    /// thread with NO writer thread, for deterministic simulation, and is only
    /// available under `dangerous-test-hooks`.
    #[cfg(feature = "dangerous-test-hooks")]
    pub(crate) fn with_writer_mode(mut self, writer_mode: WriterMode) -> Self {
        self.writer_mode = writer_mode;
        self
    }

    /// How the writer pipeline is driven.
    pub(crate) fn writer_mode(&self) -> WriterMode {
        self.writer_mode
    }

    /// Whether the full hash chain is recomputed at open.
    pub(crate) fn chain_verification(&self) -> ChainVerification {
        self.chain_verification
    }

    /// Install a custom filesystem backend for store data-path operations.
    ///
    /// Production uses the default [`RealFs`] (every op delegates to `std::fs`);
    /// deterministic simulation and embeddings install an alternate [`StoreFs`]
    /// here without touching routed call sites. Public since 0.10.0 alongside
    /// the [`StoreFs`] promotion (issue #164); implementations must uphold the
    /// durability contract documented on the trait.
    ///
    /// ```no_run
    /// use std::sync::Arc;
    /// use batpak::store::{RealFs, Store, StoreConfig};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let dir = tempfile::tempdir()?;
    /// let config = StoreConfig::new(dir.path()).with_fs(Arc::new(RealFs));
    /// let store = Store::open(config)?;
    /// store.close()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_fs(mut self, fs: Arc<dyn StoreFs>) -> Self {
        self.fs = fs;
        self
    }

    /// The configured filesystem backend for store data-path operations.
    pub(crate) fn fs(&self) -> &Arc<dyn StoreFs> {
        &self.fs
    }

    /// Optional platform profile path.
    pub fn platform_profile_path(&self) -> Option<&Path> {
        self.platform_profile_path.as_deref()
    }

    /// Payload-registry collision policy applied during `Store::open`.
    pub fn event_payload_validation(&self) -> EventPayloadValidation {
        self.event_payload_validation
    }

    /// Configure a fault injector for dangerous test hooks.
    #[cfg(feature = "dangerous-test-hooks")]
    #[cfg_attr(
        all(docsrs, not(batpak_stable_docs)),
        doc(cfg(feature = "dangerous-test-hooks"))
    )]
    pub fn with_fault_injector(mut self, injector: Option<Arc<dyn FaultInjector>>) -> Self {
        self.fault_injector = injector;
        self
    }
}

impl Clone for StoreConfig {
    fn clone(&self) -> Self {
        Self {
            data_dir: self.data_dir.clone(),
            segment_max_bytes: self.segment_max_bytes,
            fd_budget: self.fd_budget,
            broadcast_capacity: self.broadcast_capacity,
            single_append_max_bytes: self.single_append_max_bytes,
            batch: self.batch.clone(),
            writer: self.writer.clone(),
            writer_mode: self.writer_mode,
            sync: self.sync.clone(),
            index: self.index.clone(),
            clock: self.clock.clone(),
            spawner: Arc::clone(&self.spawner),
            fs: Arc::clone(&self.fs),
            open_report_observer: self.open_report_observer.clone(),
            platform_profile_path: self.platform_profile_path.clone(),
            signing_keys: self.signing_keys.clone(),
            signing_policy: self.signing_policy,
            signing_downgrade_allowed: self.signing_downgrade_allowed,
            chain_verification: self.chain_verification,
            event_payload_validation: self.event_payload_validation,
            #[cfg(feature = "payload-encryption")]
            payload_encryption: self.payload_encryption,
            #[cfg(feature = "payload-encryption")]
            keyset_backend: self.keyset_backend.clone(),
            #[cfg(feature = "dangerous-test-hooks")]
            fault_injector: self.fault_injector.clone(),
        }
    }
}

impl std::fmt::Debug for StoreConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut debug = f.debug_struct("StoreConfig");
        debug
            .field("data_dir", &self.data_dir)
            .field("segment_max_bytes", &self.segment_max_bytes)
            .field("fd_budget", &self.fd_budget)
            .field("broadcast_capacity", &self.broadcast_capacity)
            .field("single_append_max_bytes", &self.single_append_max_bytes)
            .field("batch", &self.batch)
            .field("writer", &self.writer)
            .field("writer_mode", &self.writer_mode)
            .field("sync", &self.sync)
            .field("index", &self.index)
            .field("clock", &self.clock.as_ref().map(|_| "<clock>"))
            .field("spawner", &"<spawner>")
            .field("fs", &"<fs>")
            .field(
                "open_report_observer",
                &self.open_report_observer.as_ref().map(|_| "<observer>"),
            )
            .field("platform_profile_path", &self.platform_profile_path)
            .field("signing_keys", &self.signing_keys.len())
            .field("signing_policy", &self.signing_policy)
            .field("signing_downgrade_allowed", &self.signing_downgrade_allowed)
            .field("chain_verification", &self.chain_verification)
            .field("event_payload_validation", &self.event_payload_validation);
        // Only the granularity is ever shown — the config holds no key material.
        #[cfg(feature = "payload-encryption")]
        debug.field("payload_encryption", &self.payload_encryption);
        #[cfg(feature = "payload-encryption")]
        debug.field(
            "keyset_backend",
            &self.keyset_backend.as_ref().map(|_| "<backend>"),
        );
        debug.finish()
    }
}

/// Convert an [`Instant::elapsed`] duration to microseconds as `u64`.
///
/// `Duration::as_micros()` returns `u128`; the cast to `u64` would overflow
/// after ~584,942 years of elapsed time. Caps at `u64::MAX` rather than
/// panicking — a saturating ceiling is more useful than a crash for telemetry.
#[inline]
pub(crate) fn duration_micros(d: std::time::Duration) -> u64 {
    u64::try_from(d.as_micros()).unwrap_or(u64::MAX)
}

#[cfg(test)]
mod tests;