Skip to main content

feldera_types/config/
dev_tweaks.rs

1use std::collections::BTreeMap;
2
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5use utoipa::ToSchema;
6
7/// The largest value either merge threshold accepts.
8///
9/// A spine blocks its producer at 128 loose batches, and a level below its
10/// threshold never merges.  With threshold `n`, `14 + 7 * (n - 1)` batches
11/// can wait with no merge due, which reaches 128 at `n = 18`.  15 is a
12/// conservative choice; `merge_threshold_test` pins it.
13pub const MAX_MERGE_THRESHOLD_BATCHES: u16 = 15;
14
15/// Smallest key block a layer file writer accepts, in bytes; see
16/// [`DevTweaks::lazy_input_map_key_block_bytes`].
17///
18/// A copy of the floor the writer asserts on `Parameters::min_key_data_block`,
19/// kept here because this crate sits below the one that owns it.  It buys the
20/// user a named error where they set the size, instead of a panic once a
21/// builder reaches for it.
22pub const MIN_KEY_BLOCK_BYTES: u64 = 4096;
23
24/// Optional settings for tweaking Feldera internals.
25///
26/// These settings reflect experiments that may come and go and change from
27/// version to version.  Users should not consider them to be stable.
28#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
29#[serde(default)]
30pub struct DevTweaks {
31    /// Buffer-cache implementation to use for storage reads.
32    ///
33    /// The default is `s3_fifo`.
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub buffer_cache_strategy: Option<BufferCacheStrategy>,
36
37    /// Override the number of buckets/shards used by sharded buffer caches.
38    ///
39    /// This only applies when `buffer_cache_strategy = "s3_fifo"`. Values are
40    /// rounded up to the next power of two because the current implementation
41    /// shards by `hash(key) & (n - 1)`.
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub buffer_max_buckets: Option<usize>,
44
45    /// How S3-FIFO caches are assigned to foreground/background workers.
46    ///
47    /// This only applies when `buffer_cache_strategy = "s3_fifo"`. The
48    /// default is `shared_per_worker_pair`; LRU always uses `per_thread`.
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub buffer_cache_allocation_strategy: Option<BufferCacheAllocationStrategy>,
51
52    /// Target number of cached bytes retained in each `FBuf` slab size class.
53    ///
54    /// The default is 16 MiB.
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub fbuf_slab_bytes_per_class: Option<usize>,
57
58    /// Whether to asynchronously fetch keys needed for the join operator from
59    /// storage.  Asynchronous fetching should be faster for high-latency
60    /// storage, such as object storage, but it could use excessive amounts of
61    /// memory if the number of keys fetched is very large.
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub fetch_join: Option<bool>,
64
65    /// Whether to asynchronously fetch keys needed for the distinct operator
66    /// from storage.  Asynchronous fetching should be faster for high-latency
67    /// storage, such as object storage, but it could use excessive amounts of
68    /// memory if the number of keys fetched is very large.
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub fetch_distinct: Option<bool>,
71
72    /// Which merger to use.
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub merger: Option<MergerType>,
75
76    /// If set, the maximum amount of storage, in MiB, for the POSIX backend to
77    /// allow to be in use before failing all writes with `StorageFull`.  This
78    /// is useful for testing on top of storage that does not implement its own
79    /// quota mechanism.
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub storage_mb_max: Option<u64>,
82
83    /// Attempt to print a stack trace on stack overflow.
84    ///
85    /// To be used for debugging only; do not enable in production.
86    // NOTE: this flag is handled manually in `adapters/src/server.rs` before
87    // parsing DevTweaks. If the name or type of this field changes, make sure to
88    // adjust `server.rs` accordingly.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub stack_overflow_backtrace: Option<bool>,
91
92    /// Controls the maximal number of records output by splitter operators
93    /// (joins, distinct, aggregation, rolling window and group operators) at
94    /// each step.
95    ///
96    /// The default value is 10,000 records.
97    // TODO: It would be better if the value were denominated in bytes rather
98    // than records, and if it were configurable per-operator.
99    #[serde(skip_serializing_if = "Option::is_none")]
100    pub splitter_chunk_size_records: Option<u64>,
101
102    /// How many keys a lazy input map resolves against its integral in one step.
103    ///
104    /// The lazy upsert operator may scan a large number of keys without
105    /// producing any output. Therefore bounding its step by the number of
106    /// outputs is not sufficient. This setting additionally bounds it by its
107    /// input.
108    ///
109    /// The default is 100,000.
110    #[serde(skip_serializing_if = "Option::is_none")]
111    pub lazy_input_map_keys_per_step: Option<u64>,
112
113    /// Minimum size of the key blocks in the batches a lazy input map's
114    /// accumulator writes for itself, in bytes.  A power of two, at least
115    /// 4096.
116    ///
117    /// The map resolves a transaction by walking the accumulated updates in
118    /// key order without reading values, one storage request per key block,
119    /// so larger blocks mean fewer requests.  Only the accumulator's own
120    /// batches (merge outputs and spills) take this size; the batches that
121    /// reach the integral keep it until its merger rewrites them at the
122    /// default size.  The default is 32768; 8192 is the file writer's default.
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub lazy_input_map_key_block_bytes: Option<u64>,
125
126    /// How many data blocks a layer-file cursor that declared a sequential
127    /// walk reads ahead of its position.
128    ///
129    /// Each block a cursor steps into that the buffer cache does not hold is a
130    /// device round trip the worker waits out, and a key column is a strided
131    /// subset of its file that the kernel's readahead never serves.  Reading
132    /// ahead this many blocks keeps that many round trips in flight.  Zero
133    /// disables it.  The default is 8.
134    #[serde(skip_serializing_if = "Option::is_none")]
135    pub layer_file_read_ahead_blocks: Option<u64>,
136
137    /// Enable adaptive joins.
138    ///
139    /// Adaptive joins dynamically change their partitioning policy to avoid skew.
140    ///
141    /// Adaptive joins are disabled by default.
142    #[serde(skip_serializing_if = "Option::is_none")]
143    pub adaptive_joins: Option<bool>,
144
145    /// Evict eagerly from buffer caches as files get deleted.
146    ///
147    /// This is an optimization that drops files from
148    /// the cache as soon as they are deleted.
149    ///
150    /// It has unknown (no?) performance benefits from what I can tell.
151    ///
152    /// Historically it made sense to do this for two reasons:
153    /// a) we know with 100% guarantee that the file won't ever be
154    ///    read again.
155    /// b) we could do this in O(logn) time with the LRU cache.
156    ///    This is no longer true for s3-fifo where it is O(n).
157    ///
158    /// If the eviction is expensive, (many small objects in the cache)
159    /// this can cause a regression.
160    ///
161    /// New default disables this behavior by making it false.
162    ///
163    /// If this doesn't cause regression we will remove this option
164    /// in the future.
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub eager_evict: Option<bool>,
167
168    /// The minimum relative improvement threshold for the join balancer.
169    ///
170    /// The join balancer is a component that dynamically chooses an optimal
171    /// partitioning policy for adaptive join operators.  This parameter
172    /// prevents the join balancer from making changes to the partitioning
173    /// policy if the improvement is not significant, since the overhead of such
174    /// rebalancing, especially when performed frequently, can exceed the
175    /// benefits.
176    ///
177    /// A rebalancing is considered significant if the relative estimated
178    /// improvement across the collections whose partitioning policy the
179    /// rebalancing changes is at least this threshold. Collections that keep
180    /// their policy are excluded, since they cost the same either way.
181    ///
182    /// A rebalancing is applied if both this threshold and
183    /// `balancer_min_absolute_improvement_threshold` are met.
184    ///
185    /// The default value is 1.2.
186    #[serde(skip_serializing_if = "Option::is_none")]
187    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
188    pub balancer_min_relative_improvement_threshold: Option<f64>,
189
190    /// The minimum absolute improvement threshold for the balancer.
191    ///
192    /// The join balancer is a component that dynamically chooses an optimal
193    /// partitioning policy for adaptive join operators.  This parameter
194    /// prevents the join balancer from making changes to the partitioning
195    /// policy if the improvement is not significant, since the overhead of such
196    /// rebalancing, especially when performed frequently, can exceed the
197    /// benefits.
198    ///
199    /// A rebalancing is considered significant if the absolute estimated
200    /// improvement across the collections whose partitioning policy the
201    /// rebalancing changes is at least this threshold. The cost model used by the
202    /// balancer is based on the number of records in the largest partition of a
203    /// collection.
204    ///
205    /// A rebalancing is applied if both this threshold and
206    /// `balancer_min_relative_improvement_threshold` are met.
207    ///
208    /// The default value is 10,000.
209    #[serde(skip_serializing_if = "Option::is_none")]
210    pub balancer_min_absolute_improvement_threshold: Option<u64>,
211
212    /// Factor that discourages the use of the Balance policy in a perfectly balanced collection.
213    ///
214    /// Assuming a perfectly balanced key distribution, the Balance policy is slightly less efficient than Shard,
215    /// since it requires computing the hash of the entire key/value pair. This factor discourages the use of this policy
216    /// if the skew is `<balancer_balance_tax`.
217    ///
218    /// The default value is 1.1.
219    #[serde(skip_serializing_if = "Option::is_none")]
220    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
221    pub balancer_balance_tax: Option<f64>,
222
223    /// The balancer threshold for checking for an improved partitioning policy for a stream.
224    ///
225    /// Finding a good partitioning policy for a circuit involves solving an optimization problem,
226    /// which can be relatively expensive. Instead of doing this on every step, the balancer only
227    /// checks for an improved partitioning policy if the key distribution of a stream has changed
228    /// significantly since the current solution was computed.  Specifically, it only kicks in when
229    /// the size of at least one shard of at least one stream in the cluster has changed by more than
230    /// this threshold.
231    ///
232    /// The default value is 0.1.
233    #[serde(skip_serializing_if = "Option::is_none")]
234    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
235    pub balancer_key_distribution_refresh_threshold: Option<f64>,
236
237    /// False-positive rate for Bloom filters on batches on storage.
238    ///
239    /// Deprecated: use `storage.bloom_false_positive_rate` instead.
240    #[serde(skip_serializing_if = "Option::is_none")]
241    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
242    pub bloom_false_positive_rate: Option<f64>,
243
244    /// Whether file-backed batches may use roaring membership filters when the
245    /// key type supports them.
246    #[serde(skip_serializing_if = "Option::is_none")]
247    pub enable_roaring: Option<bool>,
248
249    /// Maximum batch size in records for level 0 merges.
250    #[serde(skip_serializing_if = "Option::is_none")]
251    pub max_level0_batch_size_records: Option<u16>,
252
253    /// Merge threshold of an accumulator's spine: how many batches each
254    /// level above level 1 waits for before it merges them.
255    ///
256    /// Zero restores the built-in minimum.  A spine that garbage-collects old
257    /// records always uses the built-in minimum.
258    #[serde(skip_serializing_if = "Option::is_none")]
259    pub accumulator_merge_threshold_batches: Option<u16>,
260
261    /// Merge threshold of an integral's spine: how many batches each level
262    /// above level 1 waits for before it merges them.
263    ///
264    /// The default is ten.  Zero restores the built-in minimum.  A spine
265    /// that garbage-collects old records always uses the built-in minimum.
266    #[serde(skip_serializing_if = "Option::is_none")]
267    pub integral_merge_threshold_batches: Option<u16>,
268
269    /// The number of merger threads.
270    ///
271    /// The default value is equal to the number of worker threads.
272    #[serde(skip_serializing_if = "Option::is_none")]
273    pub merger_threads: Option<u16>,
274
275    /// Additional bias the merger assigns to records with negative weights
276    /// (retractions) to promote them to higher levels of the LSM tree sooner.
277    ///
278    /// Reasonable values for this parameter are in the range [0, 10].
279    ///
280    /// The default value is 0, which means that retractions are not given
281    /// any additional bias.
282    #[serde(skip_serializing_if = "Option::is_none")]
283    pub negative_weight_multiplier: Option<u16>,
284
285    /// The share of the records at a spine's highest level with negative
286    /// weights above which the level merges its batches.
287    ///
288    /// A spine keeps most of its records at its highest level.  When many of
289    /// them are retractions, merging the level's batches cancels them against
290    /// the records they retract, which shrinks the spine's storage.
291    ///
292    /// A fraction from 0 through 1; the default is 0.2.  At 1 the level never
293    /// merges for this reason.
294    #[serde(skip_serializing_if = "Option::is_none")]
295    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
296    pub top_level_negative_weight_fraction: Option<f64>,
297
298    /// Don't automatically start a transaction for every step.
299    #[serde(skip_serializing_if = "Option::is_none")]
300    pub disable_auto_transaction: Option<bool>,
301
302    /// Override the timestamp returned by SQL `NOW()` at pipeline start.
303    ///
304    /// When set, the clock connector anchors `NOW()` to this RFC 3339
305    /// timestamp the first time the pipeline starts and advances at
306    /// wall-clock cadence from there:
307    /// `NOW() = now_offset + (wall_clock - wall_clock_at_start)`.
308    ///
309    /// Any RFC 3339 timestamp parseable by `chrono::DateTime<Utc>` is
310    /// accepted (years `0001` through `9999`), in the past or future
311    /// relative to wall clock.
312    ///
313    /// This is a testing knob for queries that depend on `NOW()`.
314    ///
315    /// On resume the clock continues from the last journaled `NOW()`;
316    /// `now_offset`'s value is honored only on a fresh start:
317    ///
318    /// | Initial run | Resume from checkpoint | Post-replay `NOW()` |
319    /// |---|---|---|
320    /// | no offset | no offset | wall clock (unchanged) |
321    /// | offset    | offset    | wall-clock pace from the last journaled value; the new offset value is ignored |
322    /// | offset    | no offset | jumps to wall clock (explicit opt-out of the anchor) |
323    /// | no offset | offset    | wall-clock pace from the last journaled value; the new offset value is ignored |
324    #[serde(skip_serializing_if = "Option::is_none")]
325    pub now_offset: Option<DateTime<Utc>>,
326
327    /// Drive `NOW()` from an external HTTP endpoint instead of wall clock.
328    ///
329    /// When `true`, the clock connector emits one initial tick (using
330    /// `now_offset` if set, otherwise wall clock) and then holds that
331    /// value.  Subsequent calls to `POST /clock/advance` move `NOW()`
332    /// forward by the requested delta.  Negative deltas are rejected;
333    /// the clock is forward-only.
334    #[serde(skip_serializing_if = "Option::is_none")]
335    pub now_http_driven: Option<bool>,
336
337    /// Enable streaming exchange.
338    #[serde(skip_serializing_if = "Option::is_none")]
339    pub streaming_exchange: Option<bool>,
340
341    /// Maximum number of bytes of queued but unacknowledged exchange messages
342    /// per pair of remote host and message type.
343    ///
344    /// A sender that pushes past this budget waits for the receiver to
345    /// acknowledge earlier messages before it queues more.  There are three
346    /// message types, so a host buffers up to three times this many bytes for
347    /// each of the other hosts, plus any single message that exceeds the
348    /// budget on its own.
349    ///
350    /// The default is 10,000,000 bytes.
351    #[serde(skip_serializing_if = "Option::is_none")]
352    pub exchange_channel_capacity_bytes: Option<usize>,
353
354    /// Optimize input operators during transaction commit.
355    #[serde(skip_serializing_if = "Option::is_none")]
356    pub optimize_input_during_commit: Option<bool>,
357
358    /// Options not understood by this particular version.
359    ///
360    /// This allows the pipeline manager to take options that a custom or old
361    /// runtime version accepts.
362    #[serde(flatten)]
363    pub other_options: BTreeMap<String, serde_json::Value>,
364}
365
366impl DevTweaks {
367    pub fn buffer_cache_strategy(&self) -> BufferCacheStrategy {
368        self.buffer_cache_strategy.unwrap_or_default()
369    }
370    pub fn buffer_cache_allocation_strategy(&self) -> BufferCacheAllocationStrategy {
371        self.buffer_cache_allocation_strategy.unwrap_or_default()
372    }
373    pub fn effective_buffer_cache_allocation_strategy(&self) -> BufferCacheAllocationStrategy {
374        match self.buffer_cache_strategy() {
375            BufferCacheStrategy::S3Fifo => self.buffer_cache_allocation_strategy(),
376            BufferCacheStrategy::Lru => BufferCacheAllocationStrategy::PerThread,
377        }
378    }
379    pub fn fetch_join(&self) -> bool {
380        self.fetch_join.unwrap_or(false)
381    }
382    pub fn fetch_distinct(&self) -> bool {
383        self.fetch_distinct.unwrap_or(false)
384    }
385    pub fn merger(&self) -> MergerType {
386        self.merger.unwrap_or_default()
387    }
388    pub fn stack_overflow_backtrace(&self) -> bool {
389        self.stack_overflow_backtrace.unwrap_or(false)
390    }
391    pub fn splitter_chunk_size_records(&self) -> u64 {
392        self.splitter_chunk_size_records.unwrap_or(10_000)
393    }
394    pub fn lazy_input_map_keys_per_step(&self) -> u64 {
395        self.lazy_input_map_keys_per_step.unwrap_or(100_000)
396    }
397    pub fn lazy_input_map_key_block_bytes(&self) -> u64 {
398        self.lazy_input_map_key_block_bytes.unwrap_or(32 * 1024)
399    }
400    pub fn layer_file_read_ahead_blocks(&self) -> u64 {
401        self.layer_file_read_ahead_blocks.unwrap_or(8)
402    }
403    pub fn adaptive_joins(&self) -> bool {
404        self.adaptive_joins.unwrap_or(false)
405    }
406    pub fn balancer_min_relative_improvement_threshold(&self) -> f64 {
407        self.balancer_min_relative_improvement_threshold
408            .unwrap_or(1.2)
409    }
410    pub fn balancer_min_absolute_improvement_threshold(&self) -> u64 {
411        self.balancer_min_absolute_improvement_threshold
412            .unwrap_or(10_000)
413    }
414    pub fn balancer_balance_tax(&self) -> f64 {
415        self.balancer_balance_tax.unwrap_or(1.1)
416    }
417    pub fn balancer_key_distribution_refresh_threshold(&self) -> f64 {
418        self.balancer_key_distribution_refresh_threshold
419            .unwrap_or(0.1)
420    }
421    pub fn bloom_false_positive_rate(&self) -> f64 {
422        self.bloom_false_positive_rate.unwrap_or(0.0001)
423    }
424    pub fn enable_roaring(&self) -> bool {
425        // Roaring is enabled by default, but `enable_roaring = false` remains
426        // available as a kill switch while the feature is still being tuned.
427        self.enable_roaring.unwrap_or(true)
428    }
429
430    /// Rejects settings outside their valid range, naming the field, the
431    /// value and the range.
432    ///
433    /// # Returns
434    ///
435    /// `Ok` if every setting is in range, otherwise the first one that is not,
436    /// described for the user who wrote it.
437    pub fn validate(&self) -> Result<(), String> {
438        for (name, value) in [
439            (
440                "accumulator_merge_threshold_batches",
441                self.accumulator_merge_threshold_batches,
442            ),
443            (
444                "integral_merge_threshold_batches",
445                self.integral_merge_threshold_batches,
446            ),
447        ] {
448            if let Some(value) = value
449                && value > MAX_MERGE_THRESHOLD_BATCHES
450            {
451                return Err(format!(
452                    "dev_tweaks.{name} is {value}, but the valid range is 0 through \
453                     {MAX_MERGE_THRESHOLD_BATCHES}; 0 keeps the built-in minimum"
454                ));
455            }
456        }
457        if let Some(fraction) = self.top_level_negative_weight_fraction
458            && !(0.0..=1.0).contains(&fraction)
459        {
460            return Err(format!(
461                "dev_tweaks.top_level_negative_weight_fraction is {fraction}, but the valid \
462                 range is 0 through 1"
463            ));
464        }
465        if let Some(bytes) = self.lazy_input_map_key_block_bytes
466            && !(bytes.is_power_of_two() && bytes >= MIN_KEY_BLOCK_BYTES)
467        {
468            return Err(format!(
469                "dev_tweaks.lazy_input_map_key_block_bytes is {bytes}, but it must be a \
470                 power of two and at least {MIN_KEY_BLOCK_BYTES}"
471            ));
472        }
473        Ok(())
474    }
475
476    /// Batches an accumulator's spine waits for above level 1; zero means the
477    /// built-in minimum.
478    pub fn accumulator_merge_threshold_batches(&self) -> u16 {
479        self.accumulator_merge_threshold_batches.unwrap_or(10)
480    }
481
482    /// Batches an integral's spine waits for above level 1; zero means the
483    /// built-in minimum.
484    pub fn integral_merge_threshold_batches(&self) -> u16 {
485        self.integral_merge_threshold_batches.unwrap_or(10)
486    }
487
488    pub fn negative_weight_multiplier(&self) -> u16 {
489        self.negative_weight_multiplier.unwrap_or(0)
490    }
491
492    /// The share of the records at a spine's highest level with negative
493    /// weights above which the level merges its batches.
494    pub fn top_level_negative_weight_fraction(&self) -> f64 {
495        self.top_level_negative_weight_fraction.unwrap_or(0.2)
496    }
497
498    pub fn disable_auto_transaction(&self) -> bool {
499        self.disable_auto_transaction.unwrap_or(false)
500    }
501
502    /// Configured `now_offset` as milliseconds since the Unix epoch,
503    /// or `None` if no override is set.
504    pub fn now_offset_ms(&self) -> Option<i64> {
505        self.now_offset.map(|target| target.timestamp_millis())
506    }
507
508    pub fn now_http_driven(&self) -> bool {
509        self.now_http_driven.unwrap_or(false)
510    }
511
512    pub fn streaming_exchange(&self) -> bool {
513        self.streaming_exchange.unwrap_or(true)
514    }
515
516    pub fn exchange_channel_capacity_bytes(&self) -> usize {
517        self.exchange_channel_capacity_bytes.unwrap_or(10_000_000)
518    }
519
520    pub fn optimize_input_during_commit(&self) -> bool {
521        self.optimize_input_during_commit.unwrap_or(true)
522    }
523}
524
525/// Selects which eviction strategy backs a cache instance.
526#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
527#[serde(rename_all = "snake_case")]
528pub enum BufferCacheStrategy {
529    /// Use the sharded S3-FIFO cache backed by `quick_cache`.
530    #[default]
531    S3Fifo,
532
533    /// Use the mutex-protected weighted LRU cache.
534    Lru,
535}
536
537/// Controls how caches are shared across a foreground/background worker pair.
538#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
539#[serde(rename_all = "snake_case")]
540pub enum BufferCacheAllocationStrategy {
541    /// Share one cache across a foreground/background worker pair.
542    #[default]
543    SharedPerWorkerPair,
544
545    /// Create a separate cache for each foreground/background thread.
546    PerThread,
547
548    /// Share one cache across all foreground/background threads.
549    Global,
550}
551
552/// Which merger to use.
553#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
554#[serde(rename_all = "snake_case")]
555pub enum MergerType {
556    /// Newer merger, which should be faster for high-latency storage, such as
557    /// object storage, but it likely needs tuning.
558    PushMerger,
559
560    /// The old standby, with known performance.
561    #[default]
562    ListMerger,
563}
564
565#[cfg(test)]
566mod tests {
567    use serde_json::json;
568
569    use crate::config::{PipelineConfig, RuntimeConfig};
570
571    use super::*;
572
573    /// Either merge threshold is accepted up to the bound and rejected past
574    /// it, by name, with the value and the range in the message.
575    #[test]
576    fn merge_thresholds_are_bounded() {
577        assert_eq!(DevTweaks::default().validate(), Ok(()));
578        for field in [
579            "accumulator_merge_threshold_batches",
580            "integral_merge_threshold_batches",
581        ] {
582            let with = |value: u16| {
583                let mut tweaks = DevTweaks::default();
584                if field == "accumulator_merge_threshold_batches" {
585                    tweaks.accumulator_merge_threshold_batches = Some(value);
586                } else {
587                    tweaks.integral_merge_threshold_batches = Some(value);
588                }
589                tweaks
590            };
591            assert_eq!(with(0).validate(), Ok(()), "{field} = 0");
592            assert_eq!(
593                with(MAX_MERGE_THRESHOLD_BATCHES).validate(),
594                Ok(()),
595                "{field} at the bound"
596            );
597            let error = with(MAX_MERGE_THRESHOLD_BATCHES + 1)
598                .validate()
599                .expect_err("a value past the bound must be rejected");
600            assert!(error.contains(field), "{error}");
601            assert!(error.contains("16"), "{error}");
602            assert!(error.contains("0 through 15"), "{error}");
603        }
604    }
605
606    /// The share of negative weights that merges a spine's highest level
607    /// defaults to a fifth, and is accepted from 0 through 1 and rejected
608    /// outside that range or when it is not a number at all.
609    #[test]
610    fn top_level_negative_weight_fraction_is_a_share() {
611        assert_eq!(
612            DevTweaks::default().top_level_negative_weight_fraction(),
613            0.2
614        );
615        let with = |fraction| DevTweaks {
616            top_level_negative_weight_fraction: Some(fraction),
617            ..DevTweaks::default()
618        };
619        for fraction in [0.0, 0.2, 1.0] {
620            assert_eq!(with(fraction).validate(), Ok(()), "{fraction}");
621        }
622        for fraction in [-0.1, 1.5, f64::INFINITY, f64::NAN] {
623            let error = with(fraction)
624                .validate()
625                .expect_err("a share outside 0 through 1 must be rejected");
626            assert!(
627                error.contains("top_level_negative_weight_fraction"),
628                "{error}"
629            );
630            assert!(error.contains("0 through 1"), "{error}");
631        }
632    }
633
634    /// The lazy map's key block size is accepted at the bound and above it on a
635    /// power of two, and rejected otherwise, by name and with the value.
636    ///
637    /// The writer asserts the same thing, but only a caller that reached it: a
638    /// value this rejects never gets that far, and the user is told which
639    /// setting of theirs is wrong instead of losing a pipeline to a panic.
640    #[test]
641    fn the_key_block_size_must_be_a_power_of_two() {
642        let with = |bytes: u64| DevTweaks {
643            lazy_input_map_key_block_bytes: Some(bytes),
644            ..DevTweaks::default()
645        };
646        for good in [MIN_KEY_BLOCK_BYTES, 8192, 32768, 1 << 30] {
647            assert_eq!(with(good).validate(), Ok(()), "{good} bytes");
648        }
649        for bad in [0, 1, 512, MIN_KEY_BLOCK_BYTES - 1, 5000, 6144, u64::MAX] {
650            let error = with(bad)
651                .validate()
652                .expect_err("a size off a power of two, or under the bound, must be rejected");
653            assert!(error.contains("lazy_input_map_key_block_bytes"), "{error}");
654            assert!(error.contains(&bad.to_string()), "{error}");
655            assert!(error.contains("power of two"), "{error}");
656            assert!(error.contains("4096"), "{error}");
657        }
658    }
659
660    /// Regression test: `Option<f64>` fields inside `DevTweaks` must
661    /// survive a JSON-string round-trip through `PipelineConfig`, which
662    /// uses `#[serde(flatten)]` on `RuntimeConfig`. With `serde_json`'s
663    /// `arbitrary_precision` feature enabled, the serde `Content` buffer
664    /// represents numbers as maps, which breaks plain `f64`
665    /// deserialization (serde-rs/json#1157). The `serde_via_value`
666    /// workaround on each `Option<f64>` field fixes this.
667    #[test]
668    fn dev_tweaks_f64_roundtrip_through_pipeline_config() {
669        let rc = RuntimeConfig {
670            dev_tweaks: DevTweaks {
671                bloom_false_positive_rate: Some(0.0),
672                balancer_balance_tax: Some(1.1),
673                balancer_min_relative_improvement_threshold: Some(1.2),
674                balancer_key_distribution_refresh_threshold: Some(0.1),
675                top_level_negative_weight_fraction: Some(0.25),
676                ..Default::default()
677            },
678            ..Default::default()
679        };
680        let pc = PipelineConfig {
681            global: rc,
682            multihost: None,
683            name: Some("test-pipeline".into()),
684            given_name: None,
685            storage_config: None,
686            secrets_dir: None,
687            inputs: Default::default(),
688            outputs: Default::default(),
689            program_ir: None,
690        };
691
692        // JSON string round-trip (the path the pipeline process takes).
693        let json = serde_json::to_string_pretty(&pc).unwrap();
694        let pc2: PipelineConfig = serde_json::from_str(&json)
695            .expect("JSON string round-trip of PipelineConfig with f64 dev_tweaks must succeed");
696        assert_eq!(pc2.global.dev_tweaks.bloom_false_positive_rate, Some(0.0));
697        assert_eq!(pc2.global.dev_tweaks.balancer_balance_tax, Some(1.1));
698        assert_eq!(
699            pc2.global
700                .dev_tweaks
701                .balancer_min_relative_improvement_threshold,
702            Some(1.2)
703        );
704        assert_eq!(
705            pc2.global
706                .dev_tweaks
707                .balancer_key_distribution_refresh_threshold,
708            Some(0.1)
709        );
710        assert_eq!(
711            pc2.global.dev_tweaks.top_level_negative_weight_fraction,
712            Some(0.25)
713        );
714
715        // serde_json::Value round-trip (the path the pipeline manager takes).
716        let value = serde_json::to_value(&pc).unwrap();
717        let pc3: PipelineConfig = serde_json::from_value(value)
718            .expect("Value round-trip of PipelineConfig with f64 dev_tweaks must succeed");
719        assert_eq!(pc3.global.dev_tweaks.bloom_false_positive_rate, Some(0.0));
720    }
721
722    #[test]
723    fn other_options() {
724        let dt =
725            serde_json::from_value::<DevTweaks>(json!({"xyzzy": 1.0, "foobar": {"key": "value"}}))
726                .unwrap();
727        assert_eq!(
728            &dt.other_options,
729            &BTreeMap::from_iter([
730                (String::from("xyzzy"), json!(1.0)),
731                (String::from("foobar"), json!({"key": "value"}))
732            ]),
733        );
734    }
735}