sierradb-server 0.3.1

SierraDB server - distributed event store server with Redis RESP3 protocol
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
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::str::FromStr;
use std::time::Duration;

use clap::Parser;
use config::{Config, ConfigError, Environment, File, Value, ValueKind};
use directories::ProjectDirs;
use libp2p::Multiaddr;
use serde::Deserialize;
use sierradb::bucket::{BucketId, PartitionId};
use sierradb::cache::BLOCK_SIZE;
use thiserror::Error;

/// A distributed, partitioned event store with configurable replication
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
pub struct Args {
    /// Path to database data directory
    #[arg(long, short = 'd')]
    pub dir: Option<String>,

    /// Network address for client connections (e.g., "0.0.0.0:9090")
    #[arg(long)]
    pub client_address: Option<String>,

    /// Network address for inter-node cluster communication (QUIC/libp2p)
    #[arg(long)]
    pub cluster_address: Option<String>,

    /// Path to configuration file (TOML, YAML, or JSON)
    #[arg(short = 'c', long)]
    pub config: Option<PathBuf>,

    /// A log filter string
    #[arg(short = 'l', long)]
    pub log: Option<String>,

    /// Total number of nodes in the cluster
    #[arg(short = 'n', long)]
    pub node_count: Option<u32>,

    /// Index of this node in the cluster (0-based)
    #[arg(short = 'i', long)]
    pub node_index: Option<u32>,

    /// If mdns auto discovery is enabled
    #[arg(long)]
    pub mdns: Option<bool>,
}

#[derive(Debug, Deserialize)]
pub struct AppConfig {
    pub append: AppendConfig,
    pub bucket: BucketConfig,
    pub cache: CacheConfig,
    pub dir: PathBuf,
    pub heartbeat: HeartbeatConfig,
    pub network: NetworkConfig,
    pub node: NodeConfig,
    pub partition: PartitionConfig,
    pub replication: ReplicationConfig,
    pub segment: SegmentConfig,
    pub sync: SyncConfig,
    #[serde(default)]
    pub threads: Threads,

    pub nodes: Option<Vec<Value>>,
}

#[derive(Debug, Deserialize)]
pub struct AppendConfig {
    pub strict_versioning: bool,
}

#[derive(Debug, Deserialize)]
pub struct BucketConfig {
    pub count: u16,
    pub ids: Option<Vec<BucketId>>,
}

#[derive(Debug, Deserialize)]
pub struct CacheConfig {
    pub capacity_bytes: usize,
}

#[derive(Debug, Deserialize)]
pub struct HeartbeatConfig {
    pub interval_ms: u64,
    pub timeout_ms: u64,
}

#[derive(Debug, Deserialize)]
pub struct NetworkConfig {
    pub cluster_enabled: bool,
    pub cluster_address: Multiaddr, // For libp2p inter-node traffic
    pub client_address: String,     // For client connections
    pub mdns: bool,
}

#[derive(Debug, Deserialize)]
pub struct NodeConfig {
    pub count: Option<u32>,
    pub index: u32,
}

#[derive(Debug, Deserialize)]
pub struct PartitionConfig {
    pub count: u16,
    pub ids: Option<Vec<PartitionId>>,
}

#[derive(Debug, Deserialize)]
pub struct ReplicationConfig {
    pub buffer_size: usize,
    pub buffer_timeout_ms: u64,
    pub catchup_timeout_ms: u64,
    pub factor: u8,
}

#[derive(Debug, Deserialize)]
pub struct SegmentConfig {
    pub size_bytes: usize,
    pub compression: bool,
}

#[derive(Debug, Deserialize)]
pub struct SyncConfig {
    /// Maximum time to wait before syncing to disk (milliseconds)
    pub interval_ms: u64,
    /// Maximum time to wait before syncing to disk when idle (milliseconds)
    pub idle_interval_ms: Option<u64>,
    /// Maximum number of events to batch before syncing
    pub max_batch_size: usize,
    /// Minimum bytes to accumulate before syncing
    pub min_bytes: usize,
}

#[derive(Debug, Default, Deserialize)]
pub struct Threads {
    pub read: Option<u16>,
    pub write: Option<u16>,
}

impl AppConfig {
    // Load configuration with priority: CLI args > Environment vars > Config file >
    // Default values
    pub fn load(args: Args) -> Result<Self, ConfigError> {
        let project_dirs = ProjectDirs::from("io", "sierradb", "sierradb");

        let mut builder = Config::builder();

        if let Some(dirs) = &project_dirs {
            // Linux:   /home/alice/.config/sierradb/db
            //
            // Windows: C:\Users\Alice\AppData\Roaming\sierradb\sierradb\db
            //
            // macOS:   /Users/Alice/Library/Application
            // Support/io.sierradb.sierradb/db
            builder = builder.set_default(
                "dir",
                dirs.data_dir().join("db").to_string_lossy().into_owned(),
            )?
        }

        // Add config file if specified
        if let Some(config_path) = args.config {
            builder = builder.add_source(File::from(config_path));
        } else {
            // Try standard config locations if no explicit file provided
            builder = builder.add_source(File::with_name("sierra").required(false));
            if let Some(dirs) = &project_dirs {
                // Linux:   /home/alice/.config/sierradb/sierra.toml
                //
                // Windows: C:\Users\Alice\AppData\Roaming\sierradb\sierradb\
                // sierra.toml
                //
                // macOS:   /Users/Alice/Library/
                // Application Support/io.sierradb.sierradb/
                // sierra.toml
                builder = builder
                    .add_source(File::from(dirs.config_dir().join("sierra")).required(false));
            }
        }

        let overrides = builder.build_cloned()?;

        builder = builder
            .set_default("append.strict_versioning", true)?
            .set_default("bucket.count", 4)?
            .set_default("cache.capacity_bytes", 256 * 1024 * 1024)?
            .set_default("heartbeat.interval_ms", 1000)?
            .set_default("heartbeat.timeout_ms", 6000)?
            .set_default("network.cluster_enabled", true)?
            .set_default("network.cluster_address", "/ip4/0.0.0.0/tcp/0")?
            .set_default("network.client_address", "0.0.0.0:9090")?
            .set_default("network.mdns", false)?
            .set_default("partition.count", 32)?
            .set_default("replication.buffer_size", 1000)?
            .set_default("replication.buffer_timeout_ms", 8000)?
            .set_default("replication.catchup_timeout_ms", 2000)?
            .set_default("segment.size_bytes", 256 * 1024 * 1024)?
            .set_default("segment.compression", true)?
            .set_default("sync.interval_ms", 5)?
            .set_default("sync.max_batch_size", 50)?
            .set_default("sync.min_bytes", 4096)?;

        // Apply any overrides from the node config
        {
            let mut nodes = overrides.get_array("nodes").ok().unwrap_or_default();
            let nodes_count = if nodes.is_empty() {
                1
            } else {
                nodes.len() as u32
            };
            builder = builder.set_default("node.count", nodes_count)?;

            let node_index = args
                .node_index
                .or_else(|| overrides.get_int("node.index").map(|n| n as u32).ok());
            if let Some(node_index) = node_index
                && (node_index as usize) < nodes.len()
            {
                let overrides = nodes.remove(node_index as usize);
                for (key, value) in flatten_value(overrides) {
                    builder = builder.set_override(key, value)?;
                }
            }
        }

        // Add environment variables prefixed with "SIERRA_"
        builder = builder.add_source(Environment::with_prefix("SIERRA"));

        // Override with CLI arguments if provided
        builder = builder
            .set_override_option("dir", args.dir)?
            .set_override_option("network.cluster_address", args.cluster_address)?
            .set_override_option("network.client_address", args.client_address)?
            .set_override_option("network.mdns", args.mdns)?
            .set_override_option("node.index", args.node_index)?
            .set_override_option("node.count", args.node_count)?;

        {
            // First build to check node count and handle node.index conditionally
            let temp_config = builder.build_cloned()?;
            let node_count = temp_config.get::<u32>("node.count").unwrap_or(1);
            builder = builder.set_default("replication.factor", node_count.clamp(1, 3))?;

            // Handle node.index based on whether it's single or multi-node
            let node_index_set =
                args.node_index.is_some() || temp_config.get::<u32>("node.index").is_ok();

            if node_count == 1 && !node_index_set {
                // Single node: default to 0
                builder = builder.set_override("node.index", 0)?;
            } else if node_count > 1 && !node_index_set {
                // Multi-node: require explicit setting
                return Err(ConfigError::Message(
                    "node.index is required when node.count > 1 (use --node-index or set in config file)".to_string(),
                ));
            }
        }

        let config: AppConfig = builder.build()?.try_deserialize()?;

        Ok(config)
    }

    pub fn validate(&self) -> Result<Vec<ValidationError>, ConfigError> {
        let mut errs = Vec::new();

        // Bucket validation
        if self.bucket.count == 0 {
            errs.push(ValidationError::BucketCountZero);
        }
        if let Some(ids) = &self.bucket.ids {
            if ids.len() != self.bucket.count as usize {
                errs.push(ValidationError::BucketIdCountMismatch {
                    expected: self.bucket.count,
                    actual: ids.len(),
                });
            }
            let unique_ids: HashSet<_> = ids.iter().collect();
            if unique_ids.len() != ids.len() {
                errs.push(ValidationError::DuplicateBucketIds);
            }
        }

        // Heartbeat validation
        if self.heartbeat.interval_ms == 0 {
            errs.push(ValidationError::HeartbeatIntervalZero);
        }
        if self.heartbeat.timeout_ms == 0 {
            errs.push(ValidationError::HeartbeatTimeoutZero);
        }
        if self.heartbeat.timeout_ms <= self.heartbeat.interval_ms {
            errs.push(ValidationError::HeartbeatTimeoutTooShort {
                interval: self.heartbeat.interval_ms,
                timeout: self.heartbeat.timeout_ms,
            });
        }

        // Network validation
        if SocketAddr::from_str(&self.network.client_address).is_err() {
            errs.push(ValidationError::InvalidClientAddress {
                address: self.network.client_address.clone(),
            });
        }

        // Node validation
        if let Some(count) = self.node.count {
            if count == 0 {
                errs.push(ValidationError::NodeCountZero);
            }
            if self.node.index >= count {
                errs.push(ValidationError::NodeIndexOutOfBounds {
                    index: self.node.index,
                    count,
                });
            }
        }

        // Cluster mode validation
        if !self.network.cluster_enabled {
            // Non-cluster mode
            if let Some(count) = self.node.count
                && count > 1
            {
                errs.push(ValidationError::MultipleNodesWithoutCluster { count });
            }
        }

        // Partition validation
        if self.partition.count == 0 {
            errs.push(ValidationError::PartitionCountZero);
        }
        if let Some(ids) = &self.partition.ids {
            if ids.len() != self.partition.count as usize {
                errs.push(ValidationError::PartitionIdCountMismatch {
                    expected: self.partition.count,
                    actual: ids.len(),
                });
            }
            let unique_ids: HashSet<_> = ids.iter().collect();
            if unique_ids.len() != ids.len() {
                errs.push(ValidationError::DuplicatePartitionIds);
            }
        }

        // Replication validation
        if self.replication.factor == 0 {
            errs.push(ValidationError::ReplicationFactorZero);
        }
        if self.replication.buffer_size == 0 {
            errs.push(ValidationError::ReplicationBufferSizeZero);
        }
        if self.replication.buffer_timeout_ms == 0 {
            errs.push(ValidationError::ReplicationBufferTimeoutZero);
        }
        if self.replication.catchup_timeout_ms == 0 {
            errs.push(ValidationError::ReplicationCatchupTimeoutZero);
        }

        // Replication factor vs node count
        let node_count = self.node_count()?;
        if self.replication.factor as usize > node_count {
            errs.push(ValidationError::ReplicationFactorExceedsNodeCount {
                factor: self.replication.factor,
                node_count,
            });
        }

        // Segment validation
        if self.segment.size_bytes == 0 {
            errs.push(ValidationError::SegmentSizeZero);
        }
        const MIN_SEGMENT_SIZE: usize = BLOCK_SIZE * 2; // 128KB
        const MAX_SEGMENT_SIZE: usize = 1024 * 1024 * 1024 * 10; // 10GB
        if self.segment.size_bytes < MIN_SEGMENT_SIZE {
            errs.push(ValidationError::SegmentSizeTooSmall {
                size: self.segment.size_bytes,
                min: MIN_SEGMENT_SIZE,
            });
        }
        if self.segment.size_bytes > MAX_SEGMENT_SIZE {
            errs.push(ValidationError::SegmentSizeTooLarge {
                size: self.segment.size_bytes,
                max: MAX_SEGMENT_SIZE,
            });
        }

        // Sync validation
        if let Some(idle_interval_ms) = self.sync.idle_interval_ms
            && self.sync.interval_ms <= idle_interval_ms
        {
            errs.push(ValidationError::SyncIdleIntervalTooSmall {
                interval_ms: self.sync.interval_ms,
                idle_interval_ms,
            });
        }

        // Thread validation
        if let Some(read_threads) = self.threads.read {
            if read_threads == 0 {
                errs.push(ValidationError::ReadThreadsZero);
            }
            const MAX_THREADS: u16 = 1024;
            if read_threads > MAX_THREADS {
                errs.push(ValidationError::TooManyReadThreads {
                    count: read_threads,
                    max: MAX_THREADS,
                });
            }
        }
        if let Some(write_threads) = self.threads.write {
            if write_threads == 0 {
                errs.push(ValidationError::WriteThreadsZero);
            }
            const MAX_THREADS: u16 = 1024;
            if write_threads > MAX_THREADS {
                errs.push(ValidationError::TooManyWriteThreads {
                    count: write_threads,
                    max: MAX_THREADS,
                });
            }
        }

        // Cross-field validations for distribution
        if (self.partition.count as usize) < node_count {
            errs.push(ValidationError::TooFewPartitionsForNodes {
                partitions: self.partition.count,
                nodes: node_count,
            });
        }
        if self.partition.count < self.bucket.count {
            errs.push(ValidationError::TooFewPartitionsForBuckets {
                buckets: self.bucket.count,
                partitions: self.partition.count,
            });
        }

        Ok(errs)
    }

    pub fn assigned_buckets(&self) -> Result<HashSet<BucketId>, ConfigError> {
        match &self.bucket.ids {
            Some(ids) => Ok(ids.iter().copied().collect()),
            None => {
                let node_count = self.node_count()?;
                let effective_replication_factor =
                    (self.replication.factor as usize).min(node_count);
                let mut assigned = HashSet::new();

                let buckets_per_node = self.bucket.count as usize / node_count;
                let extra_buckets = self.bucket.count as usize % node_count;

                // For each replica position this node participates in
                for replica_offset in 0..effective_replication_factor {
                    // Which node position are we a replica for?
                    let primary_node =
                        (self.node.index as usize + node_count - replica_offset) % node_count;

                    // Calculate that node's bucket range
                    let start = primary_node * buckets_per_node + primary_node.min(extra_buckets);
                    let extra = if primary_node < extra_buckets { 1 } else { 0 };
                    let count = buckets_per_node + extra;

                    // Add all buckets in that range
                    for bucket_id in start..(start + count) {
                        assigned.insert(bucket_id.try_into().unwrap());
                    }
                }

                Ok(assigned)
            }
        }
    }

    pub fn assigned_partitions(&self, bucket_ids: &HashSet<BucketId>) -> HashSet<PartitionId> {
        match &self.partition.ids {
            Some(ids) => ids.iter().copied().collect(),
            None => (0..self.partition.count)
                .filter(|p| bucket_ids.contains(&(p % self.bucket.count)))
                .collect(),
        }
    }

    pub fn node_count(&self) -> Result<usize, ConfigError> {
        self.node
            .count
            .map(|node_count| node_count as usize)
            .or(self.nodes.as_ref().map(|nodes| nodes.len()))
            .ok_or_else(|| ConfigError::Message("node.count not specified".to_string()))
    }

    pub fn effective_idle_interval(&self) -> Duration {
        let active_interval = Duration::from_millis(self.sync.interval_ms);
        self.sync
            .idle_interval_ms
            .map(Duration::from_millis)
            .unwrap_or_else(|| {
                // Default: 10x active interval, capped at 1 second
                (active_interval * 10).min(Duration::from_secs(1))
            })
    }
}

impl fmt::Display for AppConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "append.strict_versioning = {}",
            self.append.strict_versioning
        )?;

        writeln!(f, "bucket.count = {}", self.bucket.count)?;
        match &self.bucket.ids {
            Some(ids) => writeln!(
                f,
                "bucket.ids = [{}]",
                ids.iter()
                    .map(|id| id.to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            )?,
            None => writeln!(f, "bucket.ids = <none>")?,
        }

        writeln!(f, "cache.capacity_bytes = {}", self.cache.capacity_bytes)?;

        writeln!(f, "dir = {}", self.dir.to_string_lossy())?;

        writeln!(f, "heartbeat.interval_ms = {}", self.heartbeat.interval_ms)?;
        writeln!(f, "heartbeat.timeout_ms = {}", self.heartbeat.timeout_ms)?;

        writeln!(
            f,
            "network.cluster_enabled = {}",
            self.network.cluster_enabled
        )?;
        writeln!(
            f,
            "network.cluster_address = {}",
            self.network.cluster_address
        )?;
        writeln!(
            f,
            "network.client_address = {}",
            self.network.client_address
        )?;
        writeln!(f, "network.mdns = {}", self.network.mdns)?;

        match self.node_count() {
            Ok(count) => writeln!(f, "node.count = {count}")?,
            Err(_) => writeln!(f, "node.count = <none>")?,
        }
        writeln!(f, "node.index = {}", self.node.index)?;

        writeln!(f, "partition.count = {}", self.partition.count)?;
        match &self.partition.ids {
            Some(ids) => writeln!(
                f,
                "partition.ids = [{}]",
                ids.iter()
                    .map(|id| id.to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            )?,
            None => writeln!(f, "partition.ids = <none>")?,
        }

        writeln!(
            f,
            "replication.buffer_size = {}",
            self.replication.buffer_size
        )?;
        writeln!(
            f,
            "replication.buffer_timeout_ms = {}",
            self.replication.buffer_timeout_ms
        )?;
        writeln!(f, "replication.factor = {}", self.replication.factor)?;

        writeln!(f, "segment.size_bytes = {}", self.segment.size_bytes)?;
        writeln!(f, "segment.compression = {}", self.segment.compression)?;

        writeln!(f, "sync.interval_ms = {}", self.sync.interval_ms)?;
        writeln!(
            f,
            "sync.idle_interval_ms = {}",
            self.effective_idle_interval().as_millis()
        )?;
        writeln!(f, "sync.max_batch_size = {}", self.sync.max_batch_size)?;
        writeln!(f, "sync.min_bytes = {}", self.sync.min_bytes)?;

        match self.threads.read {
            Some(count) => writeln!(f, "threads.read = {count}")?,
            None => writeln!(f, "threads.read = <none>")?,
        }
        match self.threads.write {
            Some(count) => write!(f, "threads.write = {count}")?,
            None => write!(f, "threads.write = <none>")?,
        }

        Ok(())
    }
}

fn flatten_value(value: Value) -> HashMap<String, Value> {
    let mut result = HashMap::new();
    flatten_value_recursive(value, "", &mut result);
    result
}

fn flatten_value_recursive(value: Value, prefix: &str, result: &mut HashMap<String, Value>) {
    match value.kind {
        ValueKind::Table(table) => {
            for (key, val) in table {
                let new_prefix = if prefix.is_empty() {
                    key
                } else {
                    format!("{prefix}.{key}")
                };

                match val.kind {
                    ValueKind::Table(_) => {
                        flatten_value_recursive(val, &new_prefix, result);
                    }
                    _ => {
                        result.insert(new_prefix, val);
                    }
                }
            }
        }
        _ => {
            if !prefix.is_empty() {
                result.insert(prefix.to_string(), value);
            }
        }
    }
}

#[derive(Clone, Debug, Error)]
pub enum ValidationError {
    // Bucket errors
    #[error("bucket count cannot be zero")]
    BucketCountZero,
    #[error("bucket ID count mismatch: expected {expected}, got {actual}")]
    BucketIdCountMismatch { expected: u16, actual: usize },
    #[error("duplicate bucket IDs found")]
    DuplicateBucketIds,

    // Heartbeat errors
    #[error("heartbeat interval cannot be zero")]
    HeartbeatIntervalZero,
    #[error("heartbeat timeout cannot be zero")]
    HeartbeatTimeoutZero,
    #[error("heartbeat timeout ({timeout}ms) must be greater than interval ({interval}ms)")]
    HeartbeatTimeoutTooShort { interval: u64, timeout: u64 },

    // Network errors
    #[error("invalid client address: {address}")]
    InvalidClientAddress { address: String },

    // Node errors
    #[error("node count cannot be zero")]
    NodeCountZero,
    #[error("node index {index} is out of bounds for count {count}")]
    NodeIndexOutOfBounds { index: u32, count: u32 },
    #[error("multiple nodes ({count}) configured but cluster is disabled")]
    MultipleNodesWithoutCluster { count: u32 },

    // Partition errors
    #[error("partition count cannot be zero")]
    PartitionCountZero,
    #[error("partition ID count mismatch: expected {expected}, got {actual}")]
    PartitionIdCountMismatch { expected: u16, actual: usize },
    #[error("duplicate partition IDs found")]
    DuplicatePartitionIds,

    // Replication errors
    #[error("replication factor cannot be zero")]
    ReplicationFactorZero,
    #[error("replication factor {factor} exceeds node count {node_count}")]
    ReplicationFactorExceedsNodeCount { factor: u8, node_count: usize },
    #[error("replication buffer size cannot be zero")]
    ReplicationBufferSizeZero,
    #[error("replication buffer timeout cannot be zero")]
    ReplicationBufferTimeoutZero,
    #[error("replication catchup timeout cannot be zero")]
    ReplicationCatchupTimeoutZero,

    // Segment errors
    #[error("segment size cannot be zero")]
    SegmentSizeZero,
    #[error("segment size {size} is too small (minimum: {min} bytes)")]
    SegmentSizeTooSmall { size: usize, min: usize },
    #[error("segment size {size} is too large (maximum: {max} bytes)")]
    SegmentSizeTooLarge { size: usize, max: usize },

    // Sync
    #[error(
        "idle sync interval {idle_interval_ms} cannot be less than sync interval {interval_ms}"
    )]
    SyncIdleIntervalTooSmall {
        interval_ms: u64,
        idle_interval_ms: u64,
    },

    // Thread errors
    #[error("read thread count cannot be zero")]
    ReadThreadsZero,
    #[error("write thread count cannot be zero")]
    WriteThreadsZero,
    #[error("too many read threads: {count} (maximum: {max})")]
    TooManyReadThreads { count: u16, max: u16 },
    #[error("too many write threads: {count} (maximum: {max})")]
    TooManyWriteThreads { count: u16, max: u16 },

    // Cross-field errors
    #[error("too few partitions ({partitions}) for {nodes} nodes")]
    TooFewPartitionsForNodes { partitions: u16, nodes: usize },
    #[error("too few partitions ({partitions}) for {buckets} buckets")]
    TooFewPartitionsForBuckets { buckets: u16, partitions: u16 },
}