Skip to main content

feldera_types/config/
dev_tweaks.rs

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