Skip to main content

feldera_types/config/
dev_tweaks.rs

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