Skip to main content

feldera_types/config/
dev_tweaks.rs

1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Serialize};
4use utoipa::ToSchema;
5
6/// Optional settings for tweaking Feldera internals.
7///
8/// These settings reflect experiments that may come and go and change from
9/// version to version.  Users should not consider them to be stable.
10#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
11#[serde(default)]
12pub struct DevTweaks {
13    /// Buffer-cache implementation to use for storage reads.
14    ///
15    /// The default is `s3_fifo`.
16    #[serde(skip_serializing_if = "Option::is_none")]
17    pub buffer_cache_strategy: Option<BufferCacheStrategy>,
18
19    /// Override the number of buckets/shards used by sharded buffer caches.
20    ///
21    /// This only applies when `buffer_cache_strategy = "s3_fifo"`. Values are
22    /// rounded up to the next power of two because the current implementation
23    /// shards by `hash(key) & (n - 1)`.
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub buffer_max_buckets: Option<usize>,
26
27    /// How S3-FIFO caches are assigned to foreground/background workers.
28    ///
29    /// This only applies when `buffer_cache_strategy = "s3_fifo"`. The
30    /// default is `shared_per_worker_pair`; LRU always uses `per_thread`.
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub buffer_cache_allocation_strategy: Option<BufferCacheAllocationStrategy>,
33
34    /// Target number of cached bytes retained in each `FBuf` slab size class.
35    ///
36    /// The default is 16 MiB.
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub fbuf_slab_bytes_per_class: Option<usize>,
39
40    /// Whether to asynchronously fetch keys needed for the join operator from
41    /// storage.  Asynchronous fetching should be faster for high-latency
42    /// storage, such as object storage, but it could use excessive amounts of
43    /// memory if the number of keys fetched is very large.
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub fetch_join: Option<bool>,
46
47    /// Whether to asynchronously fetch keys needed for the distinct operator
48    /// from storage.  Asynchronous fetching should be faster for high-latency
49    /// storage, such as object storage, but it could use excessive amounts of
50    /// memory if the number of keys fetched is very large.
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub fetch_distinct: Option<bool>,
53
54    /// Which merger to use.
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub merger: Option<MergerType>,
57
58    /// If set, the maximum amount of storage, in MiB, for the POSIX backend to
59    /// allow to be in use before failing all writes with [StorageFull].  This
60    /// is useful for testing on top of storage that does not implement its own
61    /// quota mechanism.
62    ///
63    /// [StorageFull]: std::io::ErrorKind::StorageFull
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub storage_mb_max: Option<u64>,
66
67    /// Attempt to print a stack trace on stack overflow.
68    ///
69    /// To be used for debugging only; do not enable in production.
70    // NOTE: this flag is handled manually in `adapters/src/server.rs` before
71    // parsing DevTweaks. If the name or type of this field changes, make sure to
72    // adjust `server.rs` accordingly.
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub stack_overflow_backtrace: Option<bool>,
75
76    /// Controls the maximal number of records output by splitter operators
77    /// (joins, distinct, aggregation, rolling window and group operators) at
78    /// each step.
79    ///
80    /// The default value is 10,000 records.
81    // TODO: It would be better if the value were denominated in bytes rather
82    // than records, and if it were configurable per-operator.
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub splitter_chunk_size_records: Option<u64>,
85
86    /// Enable adaptive joins.
87    ///
88    /// Adaptive joins dynamically change their partitioning policy to avoid skew.
89    ///
90    /// Adaptive joins are disabled by default.
91    #[serde(skip_serializing_if = "Option::is_none")]
92    pub adaptive_joins: Option<bool>,
93
94    /// Evict eagerly from buffer caches as files get deleted.
95    ///
96    /// This is an optimization that drops files from
97    /// the cache as soon as they are deleted.
98    ///
99    /// It has unknown (no?) performance benefits from what I can tell.
100    ///
101    /// Historically it made sense to do this for two reasons:
102    /// a) we know with 100% guarantee that the file won't ever be
103    ///    read again.
104    /// b) we could do this in O(logn) time with the LRU cache.
105    ///    This is no longer true for s3-fifo where it is O(n).
106    ///
107    /// If the eviction is expensive, (many small objects in the cache)
108    /// this can cause a regression.
109    ///
110    /// New default disables this behavior by making it false.
111    ///
112    /// If this doesn't cause regression we will remove this option
113    /// in the future.
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub eager_evict: Option<bool>,
116
117    /// The minimum relative improvement threshold for the join balancer.
118    ///
119    /// The join balancer is a component that dynamically chooses an optimal
120    /// partitioning policy for adaptive join operators.  This parameter
121    /// prevents the join balancer from making changes to the partitioning
122    /// policy if the improvement is not significant, since the overhead of such
123    /// rebalancing, especially when performed frequently, can exceed the
124    /// benefits.
125    ///
126    /// A rebalancing is considered significant if the relative estimated
127    /// improvement for the cluster of joins where the rebalancing is applied is
128    /// at least this threshold.
129    ///
130    /// A rebalancing is applied if both this threshold and
131    /// `balancer_min_absolute_improvement_threshold` are met.
132    ///
133    /// The default value is 1.2.
134    #[serde(skip_serializing_if = "Option::is_none")]
135    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
136    pub balancer_min_relative_improvement_threshold: Option<f64>,
137
138    /// The minimum absolute improvement threshold for the balancer.
139    ///
140    /// The join balancer is a component that dynamically chooses an optimal
141    /// partitioning policy for adaptive join operators.  This parameter
142    /// prevents the join balancer from making changes to the partitioning
143    /// policy if the improvement is not significant, since the overhead of such
144    /// rebalancing, especially when performed frequently, can exceed the
145    /// benefits.
146    ///
147    /// A rebalancing is considered significant if the absolute estimated
148    /// improvement for the cluster of joins where the rebalancing is applied is
149    /// at least this threshold. The cost model used by the balancer is based on
150    /// the number of records in the largest partition of a collection.
151    ///
152    /// A rebalancing is applied if both this threshold and
153    /// `balancer_min_relative_improvement_threshold` are met.
154    ///
155    /// The default value is 10,000.
156    #[serde(skip_serializing_if = "Option::is_none")]
157    pub balancer_min_absolute_improvement_threshold: Option<u64>,
158
159    /// Factor that discourages the use of the Balance policy in a perfectly balanced collection.
160    ///
161    /// Assuming a perfectly balanced key distribution, the Balance policy is slightly less efficient than Shard,
162    /// since it requires computing the hash of the entire key/value pair. This factor discourages the use of this policy
163    /// if the skew is `<balancer_balance_tax`.
164    ///
165    /// The default value is 1.1.
166    #[serde(skip_serializing_if = "Option::is_none")]
167    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
168    pub balancer_balance_tax: Option<f64>,
169
170    /// The balancer threshold for checking for an improved partitioning policy for a stream.
171    ///
172    /// Finding a good partitioning policy for a circuit involves solving an optimization problem,
173    /// which can be relatively expensive. Instead of doing this on every step, the balancer only
174    /// checks for an improved partitioning policy if the key distribution of a stream has changed
175    /// significantly since the current solution was computed.  Specifically, it only kicks in when
176    /// the size of at least one shard of at least one stream in the cluster has changed by more than
177    /// this threshold.
178    ///
179    /// The default value is 0.1.
180    #[serde(skip_serializing_if = "Option::is_none")]
181    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
182    pub balancer_key_distribution_refresh_threshold: Option<f64>,
183
184    /// False-positive rate for Bloom filters on batches on storage, as a
185    /// fraction f, where 0 < f < 1.
186    ///
187    /// The false-positive rate trades off between the amount of memory used by
188    /// Bloom filters and how frequently storage needs to be searched for keys
189    /// that are not actually present.  Typical false-positive rates and their
190    /// corresponding memory costs are:
191    ///
192    /// - 0.1: 4.8 bits per key
193    /// - 0.01: 9.6 bits per key
194    /// - 0.001: 14.4 bits per key
195    /// - 0.0001: 19.2 bits per key (default)
196    ///
197    /// Values outside the valid range, such as 0.0, disable Bloom filters.
198    #[serde(skip_serializing_if = "Option::is_none")]
199    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
200    pub bloom_false_positive_rate: Option<f64>,
201
202    /// Whether file-backed batches may use roaring membership filters when the
203    /// key type supports them.
204    #[serde(skip_serializing_if = "Option::is_none")]
205    pub enable_roaring: Option<bool>,
206
207    /// Maximum batch size in records for level 0 merges.
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub max_level0_batch_size_records: Option<u16>,
210
211    /// The number of merger threads.
212    ///
213    /// The default value is equal to the number of worker threads.
214    #[serde(skip_serializing_if = "Option::is_none")]
215    pub merger_threads: Option<u16>,
216
217    /// Additional bias the merger assigns to records with negative weights
218    /// (retractions) to promote them to higher levels of the LSM tree sooner.
219    ///
220    /// Reasonable values for this parameter are in the range [0, 10].
221    ///
222    /// The default value is 0, which means that retractions are not given
223    /// any additional bias.
224    #[serde(skip_serializing_if = "Option::is_none")]
225    pub negative_weight_multiplier: Option<u16>,
226
227    /// Don't automatically start a transaction for every step.
228    #[serde(skip_serializing_if = "Option::is_none")]
229    pub disable_auto_transaction: Option<bool>,
230
231    /// Options not understood by this particular version.
232    ///
233    /// This allows the pipeline manager to take options that a custom or old
234    /// runtime version accepts.
235    #[serde(flatten)]
236    pub other_options: BTreeMap<String, serde_json::Value>,
237}
238
239impl DevTweaks {
240    pub fn buffer_cache_strategy(&self) -> BufferCacheStrategy {
241        self.buffer_cache_strategy.unwrap_or_default()
242    }
243    pub fn buffer_cache_allocation_strategy(&self) -> BufferCacheAllocationStrategy {
244        self.buffer_cache_allocation_strategy.unwrap_or_default()
245    }
246    pub fn effective_buffer_cache_allocation_strategy(&self) -> BufferCacheAllocationStrategy {
247        match self.buffer_cache_strategy() {
248            BufferCacheStrategy::S3Fifo => self.buffer_cache_allocation_strategy(),
249            BufferCacheStrategy::Lru => BufferCacheAllocationStrategy::PerThread,
250        }
251    }
252    pub fn fetch_join(&self) -> bool {
253        self.fetch_join.unwrap_or(false)
254    }
255    pub fn fetch_distinct(&self) -> bool {
256        self.fetch_distinct.unwrap_or(false)
257    }
258    pub fn merger(&self) -> MergerType {
259        self.merger.unwrap_or_default()
260    }
261    pub fn stack_overflow_backtrace(&self) -> bool {
262        self.stack_overflow_backtrace.unwrap_or(false)
263    }
264    pub fn splitter_chunk_size_records(&self) -> u64 {
265        self.splitter_chunk_size_records.unwrap_or(10_000)
266    }
267    pub fn adaptive_joins(&self) -> bool {
268        self.adaptive_joins.unwrap_or(false)
269    }
270    pub fn balancer_min_relative_improvement_threshold(&self) -> f64 {
271        self.balancer_min_relative_improvement_threshold
272            .unwrap_or(1.2)
273    }
274    pub fn balancer_min_absolute_improvement_threshold(&self) -> u64 {
275        self.balancer_min_absolute_improvement_threshold
276            .unwrap_or(10_000)
277    }
278    pub fn balancer_balance_tax(&self) -> f64 {
279        self.balancer_balance_tax.unwrap_or(1.1)
280    }
281    pub fn balancer_key_distribution_refresh_threshold(&self) -> f64 {
282        self.balancer_key_distribution_refresh_threshold
283            .unwrap_or(0.1)
284    }
285    pub fn bloom_false_positive_rate(&self) -> f64 {
286        self.bloom_false_positive_rate.unwrap_or(0.0001)
287    }
288    pub fn enable_roaring(&self) -> bool {
289        // Roaring is enabled by default, but `enable_roaring = false` remains
290        // available as a kill switch while the feature is still being tuned.
291        self.enable_roaring.unwrap_or(true)
292    }
293    pub fn negative_weight_multiplier(&self) -> u16 {
294        self.negative_weight_multiplier.unwrap_or(0)
295    }
296
297    pub fn disable_auto_transaction(&self) -> bool {
298        self.disable_auto_transaction.unwrap_or(false)
299    }
300}
301
302/// Selects which eviction strategy backs a cache instance.
303#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
304#[serde(rename_all = "snake_case")]
305pub enum BufferCacheStrategy {
306    /// Use the sharded S3-FIFO cache backed by `quick_cache`.
307    #[default]
308    S3Fifo,
309
310    /// Use the mutex-protected weighted LRU cache.
311    Lru,
312}
313
314/// Controls how caches are shared across a foreground/background worker pair.
315#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
316#[serde(rename_all = "snake_case")]
317pub enum BufferCacheAllocationStrategy {
318    /// Share one cache across a foreground/background worker pair.
319    #[default]
320    SharedPerWorkerPair,
321
322    /// Create a separate cache for each foreground/background thread.
323    PerThread,
324
325    /// Share one cache across all foreground/background threads.
326    Global,
327}
328
329/// Which merger to use.
330#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
331#[serde(rename_all = "snake_case")]
332pub enum MergerType {
333    /// Newer merger, which should be faster for high-latency storage, such as
334    /// object storage, but it likely needs tuning.
335    PushMerger,
336
337    /// The old standby, with known performance.
338    #[default]
339    ListMerger,
340}
341
342#[cfg(test)]
343mod tests {
344    use serde_json::json;
345
346    use crate::config::{PipelineConfig, RuntimeConfig};
347
348    use super::*;
349
350    /// Regression test: `Option<f64>` fields inside `DevTweaks` must
351    /// survive a JSON-string round-trip through `PipelineConfig`, which
352    /// uses `#[serde(flatten)]` on `RuntimeConfig`. With `serde_json`'s
353    /// `arbitrary_precision` feature enabled, the serde `Content` buffer
354    /// represents numbers as maps, which breaks plain `f64`
355    /// deserialization (serde-rs/json#1157). The `serde_via_value`
356    /// workaround on each `Option<f64>` field fixes this.
357    #[test]
358    fn dev_tweaks_f64_roundtrip_through_pipeline_config() {
359        let mut rc = RuntimeConfig::default();
360        rc.dev_tweaks = DevTweaks {
361            bloom_false_positive_rate: Some(0.0),
362            balancer_balance_tax: Some(1.1),
363            balancer_min_relative_improvement_threshold: Some(1.2),
364            balancer_key_distribution_refresh_threshold: Some(0.1),
365            ..Default::default()
366        };
367        let pc = PipelineConfig {
368            global: rc,
369            multihost: None,
370            name: Some("test-pipeline".into()),
371            given_name: None,
372            storage_config: None,
373            secrets_dir: None,
374            inputs: Default::default(),
375            outputs: Default::default(),
376            program_ir: None,
377        };
378
379        // JSON string round-trip (the path the pipeline process takes).
380        let json = serde_json::to_string_pretty(&pc).unwrap();
381        let pc2: PipelineConfig = serde_json::from_str(&json)
382            .expect("JSON string round-trip of PipelineConfig with f64 dev_tweaks must succeed");
383        assert_eq!(pc2.global.dev_tweaks.bloom_false_positive_rate, Some(0.0));
384        assert_eq!(pc2.global.dev_tweaks.balancer_balance_tax, Some(1.1));
385        assert_eq!(
386            pc2.global
387                .dev_tweaks
388                .balancer_min_relative_improvement_threshold,
389            Some(1.2)
390        );
391        assert_eq!(
392            pc2.global
393                .dev_tweaks
394                .balancer_key_distribution_refresh_threshold,
395            Some(0.1)
396        );
397
398        // serde_json::Value round-trip (the path the pipeline manager takes).
399        let value = serde_json::to_value(&pc).unwrap();
400        let pc3: PipelineConfig = serde_json::from_value(value)
401            .expect("Value round-trip of PipelineConfig with f64 dev_tweaks must succeed");
402        assert_eq!(pc3.global.dev_tweaks.bloom_false_positive_rate, Some(0.0));
403    }
404
405    #[test]
406    fn other_options() {
407        let dt =
408            serde_json::from_value::<DevTweaks>(json!({"xyzzy": 1.0, "foobar": {"key": "value"}}))
409                .unwrap();
410        assert_eq!(
411            &dt.other_options,
412            &BTreeMap::from_iter([
413                (String::from("xyzzy"), json!(1.0)),
414                (String::from("foobar"), json!({"key": "value"}))
415            ]),
416        );
417    }
418}