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 /// The minimum relative improvement threshold for the join balancer.
95 ///
96 /// The join balancer is a component that dynamically chooses an optimal
97 /// partitioning policy for adaptive join operators. This parameter
98 /// prevents the join balancer from making changes to the partitioning
99 /// policy if the improvement is not significant, since the overhead of such
100 /// rebalancing, especially when performed frequently, can exceed the
101 /// benefits.
102 ///
103 /// A rebalancing is considered significant if the relative estimated
104 /// improvement for the cluster of joins where the rebalancing is applied is
105 /// at least this threshold.
106 ///
107 /// A rebalancing is applied if both this threshold and
108 /// `balancer_min_absolute_improvement_threshold` are met.
109 ///
110 /// The default value is 1.2.
111 #[serde(skip_serializing_if = "Option::is_none")]
112 #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
113 pub balancer_min_relative_improvement_threshold: Option<f64>,
114
115 /// The minimum absolute improvement threshold for the balancer.
116 ///
117 /// The join balancer is a component that dynamically chooses an optimal
118 /// partitioning policy for adaptive join operators. This parameter
119 /// prevents the join balancer from making changes to the partitioning
120 /// policy if the improvement is not significant, since the overhead of such
121 /// rebalancing, especially when performed frequently, can exceed the
122 /// benefits.
123 ///
124 /// A rebalancing is considered significant if the absolute estimated
125 /// improvement for the cluster of joins where the rebalancing is applied is
126 /// at least this threshold. The cost model used by the balancer is based on
127 /// the number of records in the largest partition of a collection.
128 ///
129 /// A rebalancing is applied if both this threshold and
130 /// `balancer_min_relative_improvement_threshold` are met.
131 ///
132 /// The default value is 10,000.
133 #[serde(skip_serializing_if = "Option::is_none")]
134 pub balancer_min_absolute_improvement_threshold: Option<u64>,
135
136 /// Factor that discourages the use of the Balance policy in a perfectly balanced collection.
137 ///
138 /// Assuming a perfectly balanced key distribution, the Balance policy is slightly less efficient than Shard,
139 /// since it requires computing the hash of the entire key/value pair. This factor discourages the use of this policy
140 /// if the skew is `<balancer_balance_tax`.
141 ///
142 /// The default value is 1.1.
143 #[serde(skip_serializing_if = "Option::is_none")]
144 #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
145 pub balancer_balance_tax: Option<f64>,
146
147 /// The balancer threshold for checking for an improved partitioning policy for a stream.
148 ///
149 /// Finding a good partitioning policy for a circuit involves solving an optimization problem,
150 /// which can be relatively expensive. Instead of doing this on every step, the balancer only
151 /// checks for an improved partitioning policy if the key distribution of a stream has changed
152 /// significantly since the current solution was computed. Specifically, it only kicks in when
153 /// the size of at least one shard of at least one stream in the cluster has changed by more than
154 /// this threshold.
155 ///
156 /// The default value is 0.1.
157 #[serde(skip_serializing_if = "Option::is_none")]
158 #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
159 pub balancer_key_distribution_refresh_threshold: Option<f64>,
160
161 /// False-positive rate for Bloom filters on batches on storage, as a
162 /// fraction f, where 0 < f < 1.
163 ///
164 /// The false-positive rate trades off between the amount of memory used by
165 /// Bloom filters and how frequently storage needs to be searched for keys
166 /// that are not actually present. Typical false-positive rates and their
167 /// corresponding memory costs are:
168 ///
169 /// - 0.1: 4.8 bits per key
170 /// - 0.01: 9.6 bits per key
171 /// - 0.001: 14.4 bits per key
172 /// - 0.0001: 19.2 bits per key (default)
173 ///
174 /// Values outside the valid range, such as 0.0, disable Bloom filters.
175 #[serde(skip_serializing_if = "Option::is_none")]
176 #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
177 pub bloom_false_positive_rate: Option<f64>,
178
179 /// Maximum batch size in records for level 0 merges.
180 #[serde(skip_serializing_if = "Option::is_none")]
181 pub max_level0_batch_size_records: Option<u16>,
182
183 /// The number of merger threads.
184 ///
185 /// The default value is equal to the number of worker threads.
186 #[serde(skip_serializing_if = "Option::is_none")]
187 pub merger_threads: Option<u16>,
188
189 /// Additional bias the merger assigns to records with negative weights
190 /// (retractions) to promote them to higher levels of the LSM tree sooner.
191 ///
192 /// Reasonable values for this parameter are in the range [0, 10].
193 ///
194 /// The default value is 0, which means that retractions are not given
195 /// any additional bias.
196 #[serde(skip_serializing_if = "Option::is_none")]
197 pub negative_weight_multiplier: Option<u16>,
198
199 /// Options not understood by this particular version.
200 ///
201 /// This allows the pipeline manager to take options that a custom or old
202 /// runtime version accepts.
203 #[serde(flatten)]
204 pub other_options: BTreeMap<String, serde_json::Value>,
205}
206
207impl DevTweaks {
208 pub fn buffer_cache_strategy(&self) -> BufferCacheStrategy {
209 self.buffer_cache_strategy.unwrap_or_default()
210 }
211 pub fn buffer_cache_allocation_strategy(&self) -> BufferCacheAllocationStrategy {
212 self.buffer_cache_allocation_strategy.unwrap_or_default()
213 }
214 pub fn effective_buffer_cache_allocation_strategy(&self) -> BufferCacheAllocationStrategy {
215 match self.buffer_cache_strategy() {
216 BufferCacheStrategy::S3Fifo => self.buffer_cache_allocation_strategy(),
217 BufferCacheStrategy::Lru => BufferCacheAllocationStrategy::PerThread,
218 }
219 }
220 pub fn fetch_join(&self) -> bool {
221 self.fetch_join.unwrap_or(false)
222 }
223 pub fn fetch_distinct(&self) -> bool {
224 self.fetch_distinct.unwrap_or(false)
225 }
226 pub fn merger(&self) -> MergerType {
227 self.merger.unwrap_or_default()
228 }
229 pub fn stack_overflow_backtrace(&self) -> bool {
230 self.stack_overflow_backtrace.unwrap_or(false)
231 }
232 pub fn splitter_chunk_size_records(&self) -> u64 {
233 self.splitter_chunk_size_records.unwrap_or(10_000)
234 }
235 pub fn adaptive_joins(&self) -> bool {
236 self.adaptive_joins.unwrap_or(false)
237 }
238 pub fn balancer_min_relative_improvement_threshold(&self) -> f64 {
239 self.balancer_min_relative_improvement_threshold
240 .unwrap_or(1.2)
241 }
242 pub fn balancer_min_absolute_improvement_threshold(&self) -> u64 {
243 self.balancer_min_absolute_improvement_threshold
244 .unwrap_or(10_000)
245 }
246 pub fn balancer_balance_tax(&self) -> f64 {
247 self.balancer_balance_tax.unwrap_or(1.1)
248 }
249 pub fn balancer_key_distribution_refresh_threshold(&self) -> f64 {
250 self.balancer_key_distribution_refresh_threshold
251 .unwrap_or(0.1)
252 }
253 pub fn bloom_false_positive_rate(&self) -> f64 {
254 self.bloom_false_positive_rate.unwrap_or(0.0001)
255 }
256 pub fn negative_weight_multiplier(&self) -> u16 {
257 self.negative_weight_multiplier.unwrap_or(0)
258 }
259}
260
261/// Selects which eviction strategy backs a cache instance.
262#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
263#[serde(rename_all = "snake_case")]
264pub enum BufferCacheStrategy {
265 /// Use the sharded S3-FIFO cache backed by `quick_cache`.
266 #[default]
267 S3Fifo,
268
269 /// Use the mutex-protected weighted LRU cache.
270 Lru,
271}
272
273/// Controls how caches are shared across a foreground/background worker pair.
274#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
275#[serde(rename_all = "snake_case")]
276pub enum BufferCacheAllocationStrategy {
277 /// Share one cache across a foreground/background worker pair.
278 #[default]
279 SharedPerWorkerPair,
280
281 /// Create a separate cache for each foreground/background thread.
282 PerThread,
283
284 /// Share one cache across all foreground/background threads.
285 Global,
286}
287
288/// Which merger to use.
289#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
290#[serde(rename_all = "snake_case")]
291pub enum MergerType {
292 /// Newer merger, which should be faster for high-latency storage, such as
293 /// object storage, but it likely needs tuning.
294 PushMerger,
295
296 /// The old standby, with known performance.
297 #[default]
298 ListMerger,
299}
300
301#[cfg(test)]
302mod tests {
303 use serde_json::json;
304
305 use crate::config::{PipelineConfig, RuntimeConfig};
306
307 use super::*;
308
309 /// Regression test: `Option<f64>` fields inside `DevTweaks` must
310 /// survive a JSON-string round-trip through `PipelineConfig`, which
311 /// uses `#[serde(flatten)]` on `RuntimeConfig`. With `serde_json`'s
312 /// `arbitrary_precision` feature enabled, the serde `Content` buffer
313 /// represents numbers as maps, which breaks plain `f64`
314 /// deserialization (serde-rs/json#1157). The `serde_via_value`
315 /// workaround on each `Option<f64>` field fixes this.
316 #[test]
317 fn dev_tweaks_f64_roundtrip_through_pipeline_config() {
318 let mut rc = RuntimeConfig::default();
319 rc.dev_tweaks = DevTweaks {
320 bloom_false_positive_rate: Some(0.0),
321 balancer_balance_tax: Some(1.1),
322 balancer_min_relative_improvement_threshold: Some(1.2),
323 balancer_key_distribution_refresh_threshold: Some(0.1),
324 ..Default::default()
325 };
326 let pc = PipelineConfig {
327 global: rc,
328 multihost: None,
329 name: Some("test-pipeline".into()),
330 given_name: None,
331 storage_config: None,
332 secrets_dir: None,
333 inputs: Default::default(),
334 outputs: Default::default(),
335 program_ir: None,
336 };
337
338 // JSON string round-trip (the path the pipeline process takes).
339 let json = serde_json::to_string_pretty(&pc).unwrap();
340 let pc2: PipelineConfig = serde_json::from_str(&json)
341 .expect("JSON string round-trip of PipelineConfig with f64 dev_tweaks must succeed");
342 assert_eq!(pc2.global.dev_tweaks.bloom_false_positive_rate, Some(0.0));
343 assert_eq!(pc2.global.dev_tweaks.balancer_balance_tax, Some(1.1));
344 assert_eq!(
345 pc2.global
346 .dev_tweaks
347 .balancer_min_relative_improvement_threshold,
348 Some(1.2)
349 );
350 assert_eq!(
351 pc2.global
352 .dev_tweaks
353 .balancer_key_distribution_refresh_threshold,
354 Some(0.1)
355 );
356
357 // serde_json::Value round-trip (the path the pipeline manager takes).
358 let value = serde_json::to_value(&pc).unwrap();
359 let pc3: PipelineConfig = serde_json::from_value(value)
360 .expect("Value round-trip of PipelineConfig with f64 dev_tweaks must succeed");
361 assert_eq!(pc3.global.dev_tweaks.bloom_false_positive_rate, Some(0.0));
362 }
363
364 #[test]
365 fn other_options() {
366 let dt =
367 serde_json::from_value::<DevTweaks>(json!({"xyzzy": 1.0, "foobar": {"key": "value"}}))
368 .unwrap();
369 assert_eq!(
370 &dt.other_options,
371 &BTreeMap::from_iter([
372 (String::from("xyzzy"), json!(1.0)),
373 (String::from("foobar"), json!({"key": "value"}))
374 ]),
375 );
376 }
377}