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    /// Where a multihost pipeline keeps the state of its materialized views
411    /// and indexes.  See [ViewIntegralsLayout].  The default is `auto`.
412    ///
413    /// A pipeline that restarts from a checkpoint with another layout moves
414    /// that state, which is a bootstrap of those views.
415    #[serde(skip_serializing_if = "Option::is_none")]
416    pub view_integrals: Option<ViewIntegralsLayout>,
417
418    /// Options not understood by this particular version.
419    ///
420    /// This allows the pipeline manager to take options that a custom or old
421    /// runtime version accepts.
422    #[serde(flatten)]
423    pub other_options: BTreeMap<String, serde_json::Value>,
424}
425
426impl DevTweaks {
427    pub fn buffer_cache_strategy(&self) -> BufferCacheStrategy {
428        self.buffer_cache_strategy.unwrap_or_default()
429    }
430    pub fn buffer_cache_allocation_strategy(&self) -> BufferCacheAllocationStrategy {
431        self.buffer_cache_allocation_strategy.unwrap_or_default()
432    }
433    pub fn effective_buffer_cache_allocation_strategy(&self) -> BufferCacheAllocationStrategy {
434        match self.buffer_cache_strategy() {
435            BufferCacheStrategy::S3Fifo => self.buffer_cache_allocation_strategy(),
436            BufferCacheStrategy::Lru => BufferCacheAllocationStrategy::PerThread,
437        }
438    }
439    pub fn fetch_join(&self) -> bool {
440        self.fetch_join.unwrap_or(false)
441    }
442    pub fn fetch_distinct(&self) -> bool {
443        self.fetch_distinct.unwrap_or(false)
444    }
445    pub fn merger(&self) -> MergerType {
446        self.merger.unwrap_or_default()
447    }
448    pub fn stack_overflow_backtrace(&self) -> bool {
449        self.stack_overflow_backtrace.unwrap_or(false)
450    }
451    pub fn splitter_chunk_size_records(&self) -> u64 {
452        self.splitter_chunk_size_records.unwrap_or(10_000)
453    }
454    pub fn lazy_input_map_keys_per_step(&self) -> u64 {
455        self.lazy_input_map_keys_per_step.unwrap_or(100_000)
456    }
457    pub fn lazy_input_map_key_block_bytes(&self) -> u64 {
458        self.lazy_input_map_key_block_size
459            .unwrap_or(ConfigSize::from_kib(32))
460            .as_bytes()
461    }
462    pub fn fbuf_slab_bytes_per_class(&self) -> usize {
463        self.fbuf_slab_size_per_class
464            .map(ConfigSize::as_usize)
465            .unwrap_or(16 << 20)
466    }
467    pub fn layer_file_read_ahead_blocks(&self) -> u64 {
468        self.layer_file_read_ahead_blocks.unwrap_or(8)
469    }
470    pub fn adaptive_joins(&self) -> bool {
471        self.adaptive_joins.unwrap_or(false)
472    }
473    pub fn balancer_min_relative_improvement_threshold(&self) -> f64 {
474        self.balancer_min_relative_improvement_threshold
475            .unwrap_or(1.2)
476    }
477    pub fn balancer_min_absolute_improvement_threshold(&self) -> u64 {
478        self.balancer_min_absolute_improvement_threshold
479            .unwrap_or(10_000)
480    }
481    pub fn balancer_balance_tax(&self) -> f64 {
482        self.balancer_balance_tax.unwrap_or(1.1)
483    }
484    pub fn balancer_key_distribution_refresh_threshold(&self) -> f64 {
485        self.balancer_key_distribution_refresh_threshold
486            .unwrap_or(0.1)
487    }
488    pub fn bloom_false_positive_rate(&self) -> f64 {
489        self.bloom_false_positive_rate.unwrap_or(0.0001)
490    }
491    pub fn enable_roaring(&self) -> bool {
492        // Roaring is enabled by default, but `enable_roaring = false` remains
493        // available as a kill switch while the feature is still being tuned.
494        self.enable_roaring.unwrap_or(true)
495    }
496
497    /// Rejects settings outside their valid range, naming the field, the
498    /// value and the range.
499    ///
500    /// # Returns
501    ///
502    /// `Ok` if every setting is in range, otherwise the first one that is not,
503    /// described for the user who wrote it.
504    pub fn validate(&self) -> Result<(), String> {
505        for (name, value) in [
506            (
507                "accumulator_merge_threshold_batches",
508                self.accumulator_merge_threshold_batches,
509            ),
510            (
511                "integral_merge_threshold_batches",
512                self.integral_merge_threshold_batches,
513            ),
514        ] {
515            if let Some(value) = value
516                && value > MAX_MERGE_THRESHOLD_BATCHES
517            {
518                return Err(format!(
519                    "dev_tweaks.{name} is {value}, but the valid range is 0 through \
520                     {MAX_MERGE_THRESHOLD_BATCHES}; 0 keeps the built-in minimum"
521                ));
522            }
523        }
524        if let Some(fraction) = self.top_level_negative_weight_fraction
525            && !(0.0..=1.0).contains(&fraction)
526        {
527            return Err(format!(
528                "dev_tweaks.top_level_negative_weight_fraction is {fraction}, but the valid \
529                 range is 0 through 1"
530            ));
531        }
532        if let Some(size) = self.lazy_input_map_key_block_size
533            && let bytes = size.as_bytes()
534            && !(bytes.is_power_of_two() && bytes >= MIN_KEY_BLOCK_BYTES)
535        {
536            return Err(format!(
537                "dev_tweaks.lazy_input_map_key_block_size is {bytes} bytes, but it must be a \
538                 power of two and at least {MIN_KEY_BLOCK_BYTES}"
539            ));
540        }
541        Ok(())
542    }
543
544    /// Batches an accumulator's spine waits for above level 1; zero means the
545    /// built-in minimum.
546    pub fn accumulator_merge_threshold_batches(&self) -> u16 {
547        self.accumulator_merge_threshold_batches.unwrap_or(10)
548    }
549
550    /// Batches an integral's spine waits for above level 1; zero means the
551    /// built-in minimum.
552    pub fn integral_merge_threshold_batches(&self) -> u16 {
553        self.integral_merge_threshold_batches.unwrap_or(10)
554    }
555
556    pub fn negative_weight_multiplier(&self) -> u16 {
557        self.negative_weight_multiplier.unwrap_or(0)
558    }
559
560    /// The share of the records at a spine's highest level with negative
561    /// weights above which the level merges its batches.
562    pub fn top_level_negative_weight_fraction(&self) -> f64 {
563        self.top_level_negative_weight_fraction.unwrap_or(0.2)
564    }
565
566    /// Whether to start a transaction automatically for every step, which is
567    /// the opposite of the `disable_auto_transaction` field.
568    pub fn enable_auto_transaction(&self) -> bool {
569        !self.disable_auto_transaction.unwrap_or(false)
570    }
571
572    /// Configured `now_offset` as milliseconds since the Unix epoch,
573    /// or `None` if no override is set.
574    pub fn now_offset_ms(&self) -> Option<i64> {
575        self.now_offset.map(|target| target.timestamp_millis())
576    }
577
578    pub fn now_http_driven(&self) -> bool {
579        self.now_http_driven.unwrap_or(false)
580    }
581
582    pub fn streaming_exchange(&self) -> bool {
583        self.streaming_exchange.unwrap_or(true)
584    }
585
586    pub fn exchange_channel_capacity_bytes(&self) -> usize {
587        self.exchange_channel_capacity
588            .map(ConfigSize::as_usize)
589            .unwrap_or(10_000_000)
590    }
591
592    pub fn optimize_input_during_commit(&self) -> bool {
593        self.optimize_input_during_commit.unwrap_or(true)
594    }
595
596    pub fn tls_exchange(&self) -> bool {
597        self.tls_exchange.unwrap_or(true)
598    }
599
600    pub fn view_integrals(&self) -> ViewIntegralsLayout {
601        self.view_integrals.unwrap_or_default()
602    }
603}
604
605/// Selects which eviction strategy backs a cache instance.
606#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
607#[serde(rename_all = "snake_case")]
608pub enum BufferCacheStrategy {
609    /// Use the sharded S3-FIFO cache backed by `quick_cache`.
610    #[default]
611    S3Fifo,
612
613    /// Use the mutex-protected weighted LRU cache.
614    Lru,
615}
616
617/// Controls how caches are shared across a foreground/background worker pair.
618#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
619#[serde(rename_all = "snake_case")]
620pub enum BufferCacheAllocationStrategy {
621    /// Share one cache across a foreground/background worker pair.
622    #[default]
623    SharedPerWorkerPair,
624
625    /// Create a separate cache for each foreground/background thread.
626    PerThread,
627
628    /// Share one cache across all foreground/background threads.
629    Global,
630}
631
632/// Where a multihost pipeline keeps the state of its materialized views and
633/// indexes.
634#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
635#[serde(rename_all = "snake_case")]
636pub enum ViewIntegralsLayout {
637    /// `one_host` for a pipeline that restarts from a checkpoint with that
638    /// layout, which includes every checkpoint written before this setting
639    /// existed, and otherwise `all_hosts`.
640    #[default]
641    Auto,
642
643    /// Each view's state on the host that runs its output connectors.  That
644    /// host does all of the view's work.
645    OneHost,
646
647    /// Each view's state sharded over all of the workers of all of the hosts,
648    /// so that a large view's work spreads over all of them.
649    AllHosts,
650}
651
652/// Which merger to use.
653#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
654#[serde(rename_all = "snake_case")]
655pub enum MergerType {
656    /// Newer merger, which should be faster for high-latency storage, such as
657    /// object storage, but it likely needs tuning.
658    PushMerger,
659
660    /// The old standby, with known performance.
661    #[default]
662    ListMerger,
663}
664
665#[cfg(test)]
666mod tests {
667    use serde_json::json;
668
669    use crate::config::{PipelineConfig, RuntimeConfig};
670
671    use super::*;
672
673    /// Either merge threshold is accepted up to the bound and rejected past
674    /// it, by name, with the value and the range in the message.
675    #[test]
676    fn merge_thresholds_are_bounded() {
677        assert_eq!(DevTweaks::default().validate(), Ok(()));
678        for field in [
679            "accumulator_merge_threshold_batches",
680            "integral_merge_threshold_batches",
681        ] {
682            let with = |value: u16| {
683                let mut tweaks = DevTweaks::default();
684                if field == "accumulator_merge_threshold_batches" {
685                    tweaks.accumulator_merge_threshold_batches = Some(value);
686                } else {
687                    tweaks.integral_merge_threshold_batches = Some(value);
688                }
689                tweaks
690            };
691            assert_eq!(with(0).validate(), Ok(()), "{field} = 0");
692            assert_eq!(
693                with(MAX_MERGE_THRESHOLD_BATCHES).validate(),
694                Ok(()),
695                "{field} at the bound"
696            );
697            let error = with(MAX_MERGE_THRESHOLD_BATCHES + 1)
698                .validate()
699                .expect_err("a value past the bound must be rejected");
700            assert!(error.contains(field), "{error}");
701            assert!(error.contains("16"), "{error}");
702            assert!(error.contains("0 through 15"), "{error}");
703        }
704    }
705
706    /// The share of negative weights that merges a spine's highest level
707    /// defaults to a fifth, and is accepted from 0 through 1 and rejected
708    /// outside that range or when it is not a number at all.
709    #[test]
710    fn top_level_negative_weight_fraction_is_a_share() {
711        assert_eq!(
712            DevTweaks::default().top_level_negative_weight_fraction(),
713            0.2
714        );
715        let with = |fraction| DevTweaks {
716            top_level_negative_weight_fraction: Some(fraction),
717            ..DevTweaks::default()
718        };
719        for fraction in [0.0, 0.2, 1.0] {
720            assert_eq!(with(fraction).validate(), Ok(()), "{fraction}");
721        }
722        for fraction in [-0.1, 1.5, f64::INFINITY, f64::NAN] {
723            let error = with(fraction)
724                .validate()
725                .expect_err("a share outside 0 through 1 must be rejected");
726            assert!(
727                error.contains("top_level_negative_weight_fraction"),
728                "{error}"
729            );
730            assert!(error.contains("0 through 1"), "{error}");
731        }
732    }
733
734    /// The lazy map's key block size is accepted at the bound and above it on a
735    /// power of two, and rejected otherwise, by name and with the value.
736    ///
737    /// The writer asserts the same thing, but only a caller that reached it: a
738    /// value this rejects never gets that far, and the user is told which
739    /// setting of theirs is wrong instead of losing a pipeline to a panic.
740    #[test]
741    fn the_key_block_size_must_be_a_power_of_two() {
742        let with = |bytes: u64| DevTweaks {
743            lazy_input_map_key_block_size: Some(ConfigSize::from_bytes(bytes)),
744            ..DevTweaks::default()
745        };
746        for good in [MIN_KEY_BLOCK_BYTES, 8192, 32768, 1 << 30] {
747            assert_eq!(with(good).validate(), Ok(()), "{good} bytes");
748        }
749        for bad in [0, 1, 512, MIN_KEY_BLOCK_BYTES - 1, 5000, 6144, u64::MAX] {
750            let error = with(bad)
751                .validate()
752                .expect_err("a size off a power of two, or under the bound, must be rejected");
753            assert!(error.contains("lazy_input_map_key_block_size"), "{error}");
754            assert!(error.contains(&bad.to_string()), "{error}");
755            assert!(error.contains("power of two"), "{error}");
756            assert!(error.contains("4096"), "{error}");
757        }
758    }
759
760    /// Regression test: `Option<f64>` fields inside `DevTweaks` must
761    /// survive a JSON-string round-trip through `PipelineConfig`, which
762    /// uses `#[serde(flatten)]` on `RuntimeConfig`. With `serde_json`'s
763    /// `arbitrary_precision` feature enabled, the serde `Content` buffer
764    /// represents numbers as maps, which breaks plain `f64`
765    /// deserialization (serde-rs/json#1157). The `serde_via_value`
766    /// workaround on each `Option<f64>` field fixes this.
767    #[test]
768    fn dev_tweaks_f64_roundtrip_through_pipeline_config() {
769        let rc = RuntimeConfig {
770            dev_tweaks: DevTweaks {
771                bloom_false_positive_rate: Some(0.0),
772                balancer_balance_tax: Some(1.1),
773                balancer_min_relative_improvement_threshold: Some(1.2),
774                balancer_key_distribution_refresh_threshold: Some(0.1),
775                top_level_negative_weight_fraction: Some(0.25),
776                ..Default::default()
777            },
778            ..Default::default()
779        };
780        let pc = PipelineConfig {
781            global: rc,
782            multihost: None,
783            name: Some("test-pipeline".into()),
784            given_name: None,
785            storage_config: None,
786            secrets_dir: None,
787            inputs: Default::default(),
788            outputs: Default::default(),
789            program_ir: None,
790        };
791
792        // JSON string round-trip (the path the pipeline process takes).
793        let json = serde_json::to_string_pretty(&pc).unwrap();
794        let pc2: PipelineConfig = serde_json::from_str(&json)
795            .expect("JSON string round-trip of PipelineConfig with f64 dev_tweaks must succeed");
796        assert_eq!(pc2.global.dev_tweaks.bloom_false_positive_rate, Some(0.0));
797        assert_eq!(pc2.global.dev_tweaks.balancer_balance_tax, Some(1.1));
798        assert_eq!(
799            pc2.global
800                .dev_tweaks
801                .balancer_min_relative_improvement_threshold,
802            Some(1.2)
803        );
804        assert_eq!(
805            pc2.global
806                .dev_tweaks
807                .balancer_key_distribution_refresh_threshold,
808            Some(0.1)
809        );
810        assert_eq!(
811            pc2.global.dev_tweaks.top_level_negative_weight_fraction,
812            Some(0.25)
813        );
814
815        // serde_json::Value round-trip (the path the pipeline manager takes).
816        let value = serde_json::to_value(&pc).unwrap();
817        let pc3: PipelineConfig = serde_json::from_value(value)
818            .expect("Value round-trip of PipelineConfig with f64 dev_tweaks must succeed");
819        assert_eq!(pc3.global.dev_tweaks.bloom_false_positive_rate, Some(0.0));
820    }
821
822    #[test]
823    fn other_options() {
824        let dt =
825            serde_json::from_value::<DevTweaks>(json!({"xyzzy": 1.0, "foobar": {"key": "value"}}))
826                .unwrap();
827        assert_eq!(
828            &dt.other_options,
829            &BTreeMap::from_iter([
830                (String::from("xyzzy"), json!(1.0)),
831                (String::from("foobar"), json!({"key": "value"}))
832            ]),
833        );
834    }
835
836    #[test]
837    fn auto_transactions_are_enabled_unless_disabled() {
838        let enable = |config| {
839            serde_json::from_value::<DevTweaks>(config)
840                .unwrap()
841                .enable_auto_transaction()
842        };
843        assert!(enable(json!({})));
844        assert!(enable(json!({"disable_auto_transaction": false})));
845        assert!(!enable(json!({"disable_auto_transaction": true})));
846    }
847}