feldera-types 0.367.0

Public API types for Feldera
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
use crate::size::{ConfigSize, LegacySizeUnit};
use std::collections::BTreeMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;

/// The largest value either merge threshold accepts.
///
/// A spine blocks its producer at 128 loose batches, and a level below its
/// threshold never merges.  With threshold `n`, `14 + 7 * (n - 1)` batches
/// can wait with no merge due, which reaches 128 at `n = 18`.  15 is a
/// conservative choice; `merge_threshold_test` pins it.
pub const MAX_MERGE_THRESHOLD_BATCHES: u16 = 15;

/// Smallest key block a layer file writer accepts, in bytes; see
/// [`DevTweaks::lazy_input_map_key_block_bytes`].
///
/// A copy of the floor the writer asserts on `Parameters::min_key_data_block`,
/// kept here because this crate sits below the one that owns it.  It buys the
/// user a named error where they set the size, instead of a panic once a
/// builder reaches for it.
pub const MIN_KEY_BLOCK_BYTES: u64 = 4096;

crate::size_setting!(
    size_fbuf_slab_size_per_class,
    "fbuf_slab_size_per_class",
    LegacySizeUnit::Bytes
);
crate::size_setting!(size_storage_max, "storage_max", LegacySizeUnit::Mebibytes);
crate::size_setting!(
    size_lazy_input_map_key_block_size,
    "lazy_input_map_key_block_size",
    LegacySizeUnit::Bytes
);
crate::size_setting!(
    size_exchange_channel_capacity,
    "exchange_channel_capacity",
    LegacySizeUnit::Bytes
);

/// Optional settings for tweaking Feldera internals.
///
/// These settings reflect experiments that may come and go and change from
/// version to version.  Users should not consider them to be stable.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(default)]
pub struct DevTweaks {
    /// Buffer-cache implementation to use for storage reads.
    ///
    /// The default is `s3_fifo`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub buffer_cache_strategy: Option<BufferCacheStrategy>,

    /// Override the number of buckets/shards used by sharded buffer caches.
    ///
    /// This only applies when `buffer_cache_strategy = "s3_fifo"`. Values are
    /// rounded up to the next power of two because the current implementation
    /// shards by `hash(key) & (n - 1)`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub buffer_max_buckets: Option<usize>,

    /// How S3-FIFO caches are assigned to foreground/background workers.
    ///
    /// This only applies when `buffer_cache_strategy = "s3_fifo"`. The
    /// default is `shared_per_worker_pair`; LRU always uses `per_thread`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub buffer_cache_allocation_strategy: Option<BufferCacheAllocationStrategy>,

    /// Target size of the cache retained in each `FBuf` slab size class.
    ///
    /// The default is `"16Mi"`. Before release 0.367.0 this setting was
    /// `fbuf_slab_bytes_per_class`, a number of bytes.
    #[serde(
        alias = "fbuf_slab_bytes_per_class",
        deserialize_with = "size_fbuf_slab_size_per_class",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub fbuf_slab_size_per_class: Option<ConfigSize>,

    /// Whether to asynchronously fetch keys needed for the join operator from
    /// storage.  Asynchronous fetching should be faster for high-latency
    /// storage, such as object storage, but it could use excessive amounts of
    /// memory if the number of keys fetched is very large.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fetch_join: Option<bool>,

    /// Whether to asynchronously fetch keys needed for the distinct operator
    /// from storage.  Asynchronous fetching should be faster for high-latency
    /// storage, such as object storage, but it could use excessive amounts of
    /// memory if the number of keys fetched is very large.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fetch_distinct: Option<bool>,

    /// Which merger to use.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merger: Option<MergerType>,

    /// If set, the maximum amount of storage for the POSIX backend to allow to
    /// be in use before failing all writes with `StorageFull`.  This is useful
    /// for testing on top of storage that does not implement its own quota
    /// mechanism.
    ///
    /// Before release 0.367.0 this setting was `storage_mb_max`, a number of
    /// mebibytes.
    #[serde(
        alias = "storage_mb_max",
        deserialize_with = "size_storage_max",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub storage_max: Option<ConfigSize>,

    /// Attempt to print a stack trace on stack overflow.
    ///
    /// To be used for debugging only; do not enable in production.
    // NOTE: this flag is handled manually in `adapters/src/server.rs` before
    // parsing DevTweaks. If the name or type of this field changes, make sure to
    // adjust `server.rs` accordingly.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stack_overflow_backtrace: Option<bool>,

    /// Controls the maximal number of records output by splitter operators
    /// (joins, distinct, aggregation, rolling window and group operators) at
    /// each step.
    ///
    /// The default value is 10,000 records.
    // TODO: It would be better if the value were denominated in bytes rather
    // than records, and if it were configurable per-operator.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub splitter_chunk_size_records: Option<u64>,

    /// How many keys a lazy input map resolves against its integral in one step.
    ///
    /// The lazy upsert operator may scan a large number of keys without
    /// producing any output. Therefore bounding its step by the number of
    /// outputs is not sufficient. This setting additionally bounds it by its
    /// input.
    ///
    /// The default is 100,000.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lazy_input_map_keys_per_step: Option<u64>,

    /// Minimum size of the key blocks in the batches a lazy input map's
    /// accumulator writes for itself.  A power of two, at least 4096 bytes.
    ///
    /// The map resolves a transaction by walking the accumulated updates in
    /// key order without reading values, one storage request per key block,
    /// so larger blocks mean fewer requests.  Only the accumulator's own
    /// batches (merge outputs and spills) take this size; the batches that
    /// reach the integral keep it until its merger rewrites them at the
    /// default size.  The default is `"32Ki"`; `"8Ki"` is the file writer's
    /// default. Before release 0.367.0 this setting was
    /// `lazy_input_map_key_block_bytes`, a number of bytes.
    #[serde(
        alias = "lazy_input_map_key_block_bytes",
        deserialize_with = "size_lazy_input_map_key_block_size",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub lazy_input_map_key_block_size: Option<ConfigSize>,

    /// How many data blocks a layer-file cursor that declared a sequential
    /// walk reads ahead of its position.
    ///
    /// Each block a cursor steps into that the buffer cache does not hold is a
    /// device round trip the worker waits out, and a key column is a strided
    /// subset of its file that the kernel's readahead never serves.  Reading
    /// ahead this many blocks keeps that many round trips in flight.  Zero
    /// disables it.  The default is 8.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub layer_file_read_ahead_blocks: Option<u64>,

    /// Enable adaptive joins.
    ///
    /// Adaptive joins dynamically change their partitioning policy to avoid skew.
    ///
    /// Adaptive joins are disabled by default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adaptive_joins: Option<bool>,

    /// Evict eagerly from buffer caches as files get deleted.
    ///
    /// This is an optimization that drops files from
    /// the cache as soon as they are deleted.
    ///
    /// It has unknown (no?) performance benefits from what I can tell.
    ///
    /// Historically it made sense to do this for two reasons:
    /// a) we know with 100% guarantee that the file won't ever be
    ///    read again.
    /// b) we could do this in O(logn) time with the LRU cache.
    ///    This is no longer true for s3-fifo where it is O(n).
    ///
    /// If the eviction is expensive, (many small objects in the cache)
    /// this can cause a regression.
    ///
    /// New default disables this behavior by making it false.
    ///
    /// If this doesn't cause regression we will remove this option
    /// in the future.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub eager_evict: Option<bool>,

    /// The minimum relative improvement threshold for the join balancer.
    ///
    /// The join balancer is a component that dynamically chooses an optimal
    /// partitioning policy for adaptive join operators.  This parameter
    /// prevents the join balancer from making changes to the partitioning
    /// policy if the improvement is not significant, since the overhead of such
    /// rebalancing, especially when performed frequently, can exceed the
    /// benefits.
    ///
    /// A rebalancing is considered significant if the relative estimated
    /// improvement across the collections whose partitioning policy the
    /// rebalancing changes is at least this threshold. Collections that keep
    /// their policy are excluded, since they cost the same either way.
    ///
    /// A rebalancing is applied if both this threshold and
    /// `balancer_min_absolute_improvement_threshold` are met.
    ///
    /// The default value is 1.2.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
    pub balancer_min_relative_improvement_threshold: Option<f64>,

    /// The minimum absolute improvement threshold for the balancer.
    ///
    /// The join balancer is a component that dynamically chooses an optimal
    /// partitioning policy for adaptive join operators.  This parameter
    /// prevents the join balancer from making changes to the partitioning
    /// policy if the improvement is not significant, since the overhead of such
    /// rebalancing, especially when performed frequently, can exceed the
    /// benefits.
    ///
    /// A rebalancing is considered significant if the absolute estimated
    /// improvement across the collections whose partitioning policy the
    /// rebalancing changes is at least this threshold. The cost model used by the
    /// balancer is based on the number of records in the largest partition of a
    /// collection.
    ///
    /// A rebalancing is applied if both this threshold and
    /// `balancer_min_relative_improvement_threshold` are met.
    ///
    /// The default value is 10,000.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub balancer_min_absolute_improvement_threshold: Option<u64>,

    /// Factor that discourages the use of the Balance policy in a perfectly balanced collection.
    ///
    /// Assuming a perfectly balanced key distribution, the Balance policy is slightly less efficient than Shard,
    /// since it requires computing the hash of the entire key/value pair. This factor discourages the use of this policy
    /// if the skew is `<balancer_balance_tax`.
    ///
    /// The default value is 1.1.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
    pub balancer_balance_tax: Option<f64>,

    /// The balancer threshold for checking for an improved partitioning policy for a stream.
    ///
    /// Finding a good partitioning policy for a circuit involves solving an optimization problem,
    /// which can be relatively expensive. Instead of doing this on every step, the balancer only
    /// checks for an improved partitioning policy if the key distribution of a stream has changed
    /// significantly since the current solution was computed.  Specifically, it only kicks in when
    /// the size of at least one shard of at least one stream in the cluster has changed by more than
    /// this threshold.
    ///
    /// The default value is 0.1.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
    pub balancer_key_distribution_refresh_threshold: Option<f64>,

    /// False-positive rate for Bloom filters on batches on storage.
    ///
    /// Deprecated: use `storage.bloom_false_positive_rate` instead.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
    pub bloom_false_positive_rate: Option<f64>,

    /// Whether file-backed batches may use roaring membership filters when the
    /// key type supports them.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_roaring: Option<bool>,

    /// Maximum batch size in records for level 0 merges.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_level0_batch_size_records: Option<u16>,

    /// Merge threshold of an accumulator's spine: how many batches each
    /// level above level 1 waits for before it merges them.
    ///
    /// Zero restores the built-in minimum.  A spine that garbage-collects old
    /// records always uses the built-in minimum.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub accumulator_merge_threshold_batches: Option<u16>,

    /// Merge threshold of an integral's spine: how many batches each level
    /// above level 1 waits for before it merges them.
    ///
    /// The default is ten.  Zero restores the built-in minimum.  A spine
    /// that garbage-collects old records always uses the built-in minimum.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub integral_merge_threshold_batches: Option<u16>,

    /// The number of merger threads.
    ///
    /// The default value is equal to the number of worker threads.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merger_threads: Option<u16>,

    /// Additional bias the merger assigns to records with negative weights
    /// (retractions) to promote them to higher levels of the LSM tree sooner.
    ///
    /// Reasonable values for this parameter are in the range [0, 10].
    ///
    /// The default value is 0, which means that retractions are not given
    /// any additional bias.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub negative_weight_multiplier: Option<u16>,

    /// The share of the records at a spine's highest level with negative
    /// weights above which the level merges its batches.
    ///
    /// A spine keeps most of its records at its highest level.  When many of
    /// them are retractions, merging the level's batches cancels them against
    /// the records they retract, which shrinks the spine's storage.
    ///
    /// A fraction from 0 through 1; the default is 0.2.  At 1 the level never
    /// merges for this reason.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
    pub top_level_negative_weight_fraction: Option<f64>,

    /// Don't automatically start a transaction for every step.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disable_auto_transaction: Option<bool>,

    /// Override the timestamp returned by SQL `NOW()` at pipeline start.
    ///
    /// When set, the clock connector anchors `NOW()` to this RFC 3339
    /// timestamp the first time the pipeline starts and advances at
    /// wall-clock cadence from there:
    /// `NOW() = now_offset + (wall_clock - wall_clock_at_start)`.
    ///
    /// Any RFC 3339 timestamp parseable by `chrono::DateTime<Utc>` is
    /// accepted (years `0001` through `9999`), in the past or future
    /// relative to wall clock.
    ///
    /// This is a testing knob for queries that depend on `NOW()`.
    ///
    /// On resume the clock continues from the last journaled `NOW()`;
    /// `now_offset`'s value is honored only on a fresh start:
    ///
    /// | Initial run | Resume from checkpoint | Post-replay `NOW()` |
    /// |---|---|---|
    /// | no offset | no offset | wall clock (unchanged) |
    /// | offset    | offset    | wall-clock pace from the last journaled value; the new offset value is ignored |
    /// | offset    | no offset | jumps to wall clock (explicit opt-out of the anchor) |
    /// | no offset | offset    | wall-clock pace from the last journaled value; the new offset value is ignored |
    #[serde(skip_serializing_if = "Option::is_none")]
    pub now_offset: Option<DateTime<Utc>>,

    /// Drive `NOW()` from an external HTTP endpoint instead of wall clock.
    ///
    /// When `true`, the clock connector emits one initial tick (using
    /// `now_offset` if set, otherwise wall clock) and then holds that
    /// value.  Subsequent calls to `POST /clock/advance` move `NOW()`
    /// forward by the requested delta.  Negative deltas are rejected;
    /// the clock is forward-only.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub now_http_driven: Option<bool>,

    /// Enable streaming exchange.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub streaming_exchange: Option<bool>,

    /// Maximum size of the queued but unacknowledged exchange messages per
    /// pair of remote host and message type.
    ///
    /// A sender that pushes past this budget waits for the receiver to
    /// acknowledge earlier messages before it queues more.  There are three
    /// message types, so a host buffers up to three times this many bytes for
    /// each of the other hosts, plus any single message that exceeds the
    /// budget on its own.
    ///
    /// The default is `"10M"`. Before release 0.367.0 this setting was
    /// `exchange_channel_capacity_bytes`, a number of bytes.
    #[serde(
        alias = "exchange_channel_capacity_bytes",
        deserialize_with = "size_exchange_channel_capacity",
        skip_serializing_if = "Option::is_none"
    )]
    #[schema(value_type = Option<String>)]
    pub exchange_channel_capacity: Option<ConfigSize>,

    /// Optimize input operators during transaction commit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub optimize_input_during_commit: Option<bool>,

    /// Options not understood by this particular version.
    ///
    /// This allows the pipeline manager to take options that a custom or old
    /// runtime version accepts.
    #[serde(flatten)]
    pub other_options: BTreeMap<String, serde_json::Value>,
}

impl DevTweaks {
    pub fn buffer_cache_strategy(&self) -> BufferCacheStrategy {
        self.buffer_cache_strategy.unwrap_or_default()
    }
    pub fn buffer_cache_allocation_strategy(&self) -> BufferCacheAllocationStrategy {
        self.buffer_cache_allocation_strategy.unwrap_or_default()
    }
    pub fn effective_buffer_cache_allocation_strategy(&self) -> BufferCacheAllocationStrategy {
        match self.buffer_cache_strategy() {
            BufferCacheStrategy::S3Fifo => self.buffer_cache_allocation_strategy(),
            BufferCacheStrategy::Lru => BufferCacheAllocationStrategy::PerThread,
        }
    }
    pub fn fetch_join(&self) -> bool {
        self.fetch_join.unwrap_or(false)
    }
    pub fn fetch_distinct(&self) -> bool {
        self.fetch_distinct.unwrap_or(false)
    }
    pub fn merger(&self) -> MergerType {
        self.merger.unwrap_or_default()
    }
    pub fn stack_overflow_backtrace(&self) -> bool {
        self.stack_overflow_backtrace.unwrap_or(false)
    }
    pub fn splitter_chunk_size_records(&self) -> u64 {
        self.splitter_chunk_size_records.unwrap_or(10_000)
    }
    pub fn lazy_input_map_keys_per_step(&self) -> u64 {
        self.lazy_input_map_keys_per_step.unwrap_or(100_000)
    }
    pub fn lazy_input_map_key_block_bytes(&self) -> u64 {
        self.lazy_input_map_key_block_size
            .unwrap_or(ConfigSize::from_kib(32))
            .as_bytes()
    }
    pub fn fbuf_slab_bytes_per_class(&self) -> usize {
        self.fbuf_slab_size_per_class
            .map(ConfigSize::as_usize)
            .unwrap_or(16 << 20)
    }
    pub fn layer_file_read_ahead_blocks(&self) -> u64 {
        self.layer_file_read_ahead_blocks.unwrap_or(8)
    }
    pub fn adaptive_joins(&self) -> bool {
        self.adaptive_joins.unwrap_or(false)
    }
    pub fn balancer_min_relative_improvement_threshold(&self) -> f64 {
        self.balancer_min_relative_improvement_threshold
            .unwrap_or(1.2)
    }
    pub fn balancer_min_absolute_improvement_threshold(&self) -> u64 {
        self.balancer_min_absolute_improvement_threshold
            .unwrap_or(10_000)
    }
    pub fn balancer_balance_tax(&self) -> f64 {
        self.balancer_balance_tax.unwrap_or(1.1)
    }
    pub fn balancer_key_distribution_refresh_threshold(&self) -> f64 {
        self.balancer_key_distribution_refresh_threshold
            .unwrap_or(0.1)
    }
    pub fn bloom_false_positive_rate(&self) -> f64 {
        self.bloom_false_positive_rate.unwrap_or(0.0001)
    }
    pub fn enable_roaring(&self) -> bool {
        // Roaring is enabled by default, but `enable_roaring = false` remains
        // available as a kill switch while the feature is still being tuned.
        self.enable_roaring.unwrap_or(true)
    }

    /// Rejects settings outside their valid range, naming the field, the
    /// value and the range.
    ///
    /// # Returns
    ///
    /// `Ok` if every setting is in range, otherwise the first one that is not,
    /// described for the user who wrote it.
    pub fn validate(&self) -> Result<(), String> {
        for (name, value) in [
            (
                "accumulator_merge_threshold_batches",
                self.accumulator_merge_threshold_batches,
            ),
            (
                "integral_merge_threshold_batches",
                self.integral_merge_threshold_batches,
            ),
        ] {
            if let Some(value) = value
                && value > MAX_MERGE_THRESHOLD_BATCHES
            {
                return Err(format!(
                    "dev_tweaks.{name} is {value}, but the valid range is 0 through \
                     {MAX_MERGE_THRESHOLD_BATCHES}; 0 keeps the built-in minimum"
                ));
            }
        }
        if let Some(fraction) = self.top_level_negative_weight_fraction
            && !(0.0..=1.0).contains(&fraction)
        {
            return Err(format!(
                "dev_tweaks.top_level_negative_weight_fraction is {fraction}, but the valid \
                 range is 0 through 1"
            ));
        }
        if let Some(size) = self.lazy_input_map_key_block_size
            && let bytes = size.as_bytes()
            && !(bytes.is_power_of_two() && bytes >= MIN_KEY_BLOCK_BYTES)
        {
            return Err(format!(
                "dev_tweaks.lazy_input_map_key_block_size is {bytes} bytes, but it must be a \
                 power of two and at least {MIN_KEY_BLOCK_BYTES}"
            ));
        }
        Ok(())
    }

    /// Batches an accumulator's spine waits for above level 1; zero means the
    /// built-in minimum.
    pub fn accumulator_merge_threshold_batches(&self) -> u16 {
        self.accumulator_merge_threshold_batches.unwrap_or(10)
    }

    /// Batches an integral's spine waits for above level 1; zero means the
    /// built-in minimum.
    pub fn integral_merge_threshold_batches(&self) -> u16 {
        self.integral_merge_threshold_batches.unwrap_or(10)
    }

    pub fn negative_weight_multiplier(&self) -> u16 {
        self.negative_weight_multiplier.unwrap_or(0)
    }

    /// The share of the records at a spine's highest level with negative
    /// weights above which the level merges its batches.
    pub fn top_level_negative_weight_fraction(&self) -> f64 {
        self.top_level_negative_weight_fraction.unwrap_or(0.2)
    }

    pub fn disable_auto_transaction(&self) -> bool {
        self.disable_auto_transaction.unwrap_or(false)
    }

    /// Configured `now_offset` as milliseconds since the Unix epoch,
    /// or `None` if no override is set.
    pub fn now_offset_ms(&self) -> Option<i64> {
        self.now_offset.map(|target| target.timestamp_millis())
    }

    pub fn now_http_driven(&self) -> bool {
        self.now_http_driven.unwrap_or(false)
    }

    pub fn streaming_exchange(&self) -> bool {
        self.streaming_exchange.unwrap_or(true)
    }

    pub fn exchange_channel_capacity_bytes(&self) -> usize {
        self.exchange_channel_capacity
            .map(ConfigSize::as_usize)
            .unwrap_or(10_000_000)
    }

    pub fn optimize_input_during_commit(&self) -> bool {
        self.optimize_input_during_commit.unwrap_or(true)
    }
}

/// Selects which eviction strategy backs a cache instance.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum BufferCacheStrategy {
    /// Use the sharded S3-FIFO cache backed by `quick_cache`.
    #[default]
    S3Fifo,

    /// Use the mutex-protected weighted LRU cache.
    Lru,
}

/// Controls how caches are shared across a foreground/background worker pair.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum BufferCacheAllocationStrategy {
    /// Share one cache across a foreground/background worker pair.
    #[default]
    SharedPerWorkerPair,

    /// Create a separate cache for each foreground/background thread.
    PerThread,

    /// Share one cache across all foreground/background threads.
    Global,
}

/// Which merger to use.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum MergerType {
    /// Newer merger, which should be faster for high-latency storage, such as
    /// object storage, but it likely needs tuning.
    PushMerger,

    /// The old standby, with known performance.
    #[default]
    ListMerger,
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use crate::config::{PipelineConfig, RuntimeConfig};

    use super::*;

    /// Either merge threshold is accepted up to the bound and rejected past
    /// it, by name, with the value and the range in the message.
    #[test]
    fn merge_thresholds_are_bounded() {
        assert_eq!(DevTweaks::default().validate(), Ok(()));
        for field in [
            "accumulator_merge_threshold_batches",
            "integral_merge_threshold_batches",
        ] {
            let with = |value: u16| {
                let mut tweaks = DevTweaks::default();
                if field == "accumulator_merge_threshold_batches" {
                    tweaks.accumulator_merge_threshold_batches = Some(value);
                } else {
                    tweaks.integral_merge_threshold_batches = Some(value);
                }
                tweaks
            };
            assert_eq!(with(0).validate(), Ok(()), "{field} = 0");
            assert_eq!(
                with(MAX_MERGE_THRESHOLD_BATCHES).validate(),
                Ok(()),
                "{field} at the bound"
            );
            let error = with(MAX_MERGE_THRESHOLD_BATCHES + 1)
                .validate()
                .expect_err("a value past the bound must be rejected");
            assert!(error.contains(field), "{error}");
            assert!(error.contains("16"), "{error}");
            assert!(error.contains("0 through 15"), "{error}");
        }
    }

    /// The share of negative weights that merges a spine's highest level
    /// defaults to a fifth, and is accepted from 0 through 1 and rejected
    /// outside that range or when it is not a number at all.
    #[test]
    fn top_level_negative_weight_fraction_is_a_share() {
        assert_eq!(
            DevTweaks::default().top_level_negative_weight_fraction(),
            0.2
        );
        let with = |fraction| DevTweaks {
            top_level_negative_weight_fraction: Some(fraction),
            ..DevTweaks::default()
        };
        for fraction in [0.0, 0.2, 1.0] {
            assert_eq!(with(fraction).validate(), Ok(()), "{fraction}");
        }
        for fraction in [-0.1, 1.5, f64::INFINITY, f64::NAN] {
            let error = with(fraction)
                .validate()
                .expect_err("a share outside 0 through 1 must be rejected");
            assert!(
                error.contains("top_level_negative_weight_fraction"),
                "{error}"
            );
            assert!(error.contains("0 through 1"), "{error}");
        }
    }

    /// The lazy map's key block size is accepted at the bound and above it on a
    /// power of two, and rejected otherwise, by name and with the value.
    ///
    /// The writer asserts the same thing, but only a caller that reached it: a
    /// value this rejects never gets that far, and the user is told which
    /// setting of theirs is wrong instead of losing a pipeline to a panic.
    #[test]
    fn the_key_block_size_must_be_a_power_of_two() {
        let with = |bytes: u64| DevTweaks {
            lazy_input_map_key_block_size: Some(ConfigSize::from_bytes(bytes)),
            ..DevTweaks::default()
        };
        for good in [MIN_KEY_BLOCK_BYTES, 8192, 32768, 1 << 30] {
            assert_eq!(with(good).validate(), Ok(()), "{good} bytes");
        }
        for bad in [0, 1, 512, MIN_KEY_BLOCK_BYTES - 1, 5000, 6144, u64::MAX] {
            let error = with(bad)
                .validate()
                .expect_err("a size off a power of two, or under the bound, must be rejected");
            assert!(error.contains("lazy_input_map_key_block_size"), "{error}");
            assert!(error.contains(&bad.to_string()), "{error}");
            assert!(error.contains("power of two"), "{error}");
            assert!(error.contains("4096"), "{error}");
        }
    }

    /// Regression test: `Option<f64>` fields inside `DevTweaks` must
    /// survive a JSON-string round-trip through `PipelineConfig`, which
    /// uses `#[serde(flatten)]` on `RuntimeConfig`. With `serde_json`'s
    /// `arbitrary_precision` feature enabled, the serde `Content` buffer
    /// represents numbers as maps, which breaks plain `f64`
    /// deserialization (serde-rs/json#1157). The `serde_via_value`
    /// workaround on each `Option<f64>` field fixes this.
    #[test]
    fn dev_tweaks_f64_roundtrip_through_pipeline_config() {
        let rc = RuntimeConfig {
            dev_tweaks: DevTweaks {
                bloom_false_positive_rate: Some(0.0),
                balancer_balance_tax: Some(1.1),
                balancer_min_relative_improvement_threshold: Some(1.2),
                balancer_key_distribution_refresh_threshold: Some(0.1),
                top_level_negative_weight_fraction: Some(0.25),
                ..Default::default()
            },
            ..Default::default()
        };
        let pc = PipelineConfig {
            global: rc,
            multihost: None,
            name: Some("test-pipeline".into()),
            given_name: None,
            storage_config: None,
            secrets_dir: None,
            inputs: Default::default(),
            outputs: Default::default(),
            program_ir: None,
        };

        // JSON string round-trip (the path the pipeline process takes).
        let json = serde_json::to_string_pretty(&pc).unwrap();
        let pc2: PipelineConfig = serde_json::from_str(&json)
            .expect("JSON string round-trip of PipelineConfig with f64 dev_tweaks must succeed");
        assert_eq!(pc2.global.dev_tweaks.bloom_false_positive_rate, Some(0.0));
        assert_eq!(pc2.global.dev_tweaks.balancer_balance_tax, Some(1.1));
        assert_eq!(
            pc2.global
                .dev_tweaks
                .balancer_min_relative_improvement_threshold,
            Some(1.2)
        );
        assert_eq!(
            pc2.global
                .dev_tweaks
                .balancer_key_distribution_refresh_threshold,
            Some(0.1)
        );
        assert_eq!(
            pc2.global.dev_tweaks.top_level_negative_weight_fraction,
            Some(0.25)
        );

        // serde_json::Value round-trip (the path the pipeline manager takes).
        let value = serde_json::to_value(&pc).unwrap();
        let pc3: PipelineConfig = serde_json::from_value(value)
            .expect("Value round-trip of PipelineConfig with f64 dev_tweaks must succeed");
        assert_eq!(pc3.global.dev_tweaks.bloom_false_positive_rate, Some(0.0));
    }

    #[test]
    fn other_options() {
        let dt =
            serde_json::from_value::<DevTweaks>(json!({"xyzzy": 1.0, "foobar": {"key": "value"}}))
                .unwrap();
        assert_eq!(
            &dt.other_options,
            &BTreeMap::from_iter([
                (String::from("xyzzy"), json!(1.0)),
                (String::from("foobar"), json!({"key": "value"}))
            ]),
        );
    }
}