Skip to main content

feldera_types/config/
dev_tweaks.rs

1use std::collections::BTreeMap;
2
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5use utoipa::ToSchema;
6
7/// The largest value either merge threshold accepts.
8///
9/// A spine blocks its producer at 128 loose batches, and a level below its
10/// threshold never merges.  With threshold `n`, `14 + 7 * (n - 1)` batches
11/// can wait with no merge due, which reaches 128 at `n = 18`.  15 is a
12/// conservative choice; `merge_threshold_test` pins it.
13pub const MAX_MIN_MERGE_BATCHES: u16 = 15;
14
15/// Optional settings for tweaking Feldera internals.
16///
17/// These settings reflect experiments that may come and go and change from
18/// version to version.  Users should not consider them to be stable.
19#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
20#[serde(default)]
21pub struct DevTweaks {
22    /// Buffer-cache implementation to use for storage reads.
23    ///
24    /// The default is `s3_fifo`.
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub buffer_cache_strategy: Option<BufferCacheStrategy>,
27
28    /// Override the number of buckets/shards used by sharded buffer caches.
29    ///
30    /// This only applies when `buffer_cache_strategy = "s3_fifo"`. Values are
31    /// rounded up to the next power of two because the current implementation
32    /// shards by `hash(key) & (n - 1)`.
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub buffer_max_buckets: Option<usize>,
35
36    /// How S3-FIFO caches are assigned to foreground/background workers.
37    ///
38    /// This only applies when `buffer_cache_strategy = "s3_fifo"`. The
39    /// default is `shared_per_worker_pair`; LRU always uses `per_thread`.
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub buffer_cache_allocation_strategy: Option<BufferCacheAllocationStrategy>,
42
43    /// Target number of cached bytes retained in each `FBuf` slab size class.
44    ///
45    /// The default is 16 MiB.
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub fbuf_slab_bytes_per_class: Option<usize>,
48
49    /// Whether to asynchronously fetch keys needed for the join operator from
50    /// storage.  Asynchronous fetching should be faster for high-latency
51    /// storage, such as object storage, but it could use excessive amounts of
52    /// memory if the number of keys fetched is very large.
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub fetch_join: Option<bool>,
55
56    /// Whether to asynchronously fetch keys needed for the distinct operator
57    /// from storage.  Asynchronous fetching should be faster for high-latency
58    /// storage, such as object storage, but it could use excessive amounts of
59    /// memory if the number of keys fetched is very large.
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub fetch_distinct: Option<bool>,
62
63    /// Which merger to use.
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub merger: Option<MergerType>,
66
67    /// If set, the maximum amount of storage, in MiB, for the POSIX backend to
68    /// allow to be in use before failing all writes with `StorageFull`.  This
69    /// is useful for testing on top of storage that does not implement its own
70    /// quota mechanism.
71    #[serde(skip_serializing_if = "Option::is_none")]
72    pub storage_mb_max: Option<u64>,
73
74    /// Attempt to print a stack trace on stack overflow.
75    ///
76    /// To be used for debugging only; do not enable in production.
77    // NOTE: this flag is handled manually in `adapters/src/server.rs` before
78    // parsing DevTweaks. If the name or type of this field changes, make sure to
79    // adjust `server.rs` accordingly.
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub stack_overflow_backtrace: Option<bool>,
82
83    /// Controls the maximal number of records output by splitter operators
84    /// (joins, distinct, aggregation, rolling window and group operators) at
85    /// each step.
86    ///
87    /// The default value is 10,000 records.
88    // TODO: It would be better if the value were denominated in bytes rather
89    // than records, and if it were configurable per-operator.
90    #[serde(skip_serializing_if = "Option::is_none")]
91    pub splitter_chunk_size_records: Option<u64>,
92
93    /// Enable adaptive joins.
94    ///
95    /// Adaptive joins dynamically change their partitioning policy to avoid skew.
96    ///
97    /// Adaptive joins are disabled by default.
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub adaptive_joins: Option<bool>,
100
101    /// Evict eagerly from buffer caches as files get deleted.
102    ///
103    /// This is an optimization that drops files from
104    /// the cache as soon as they are deleted.
105    ///
106    /// It has unknown (no?) performance benefits from what I can tell.
107    ///
108    /// Historically it made sense to do this for two reasons:
109    /// a) we know with 100% guarantee that the file won't ever be
110    ///    read again.
111    /// b) we could do this in O(logn) time with the LRU cache.
112    ///    This is no longer true for s3-fifo where it is O(n).
113    ///
114    /// If the eviction is expensive, (many small objects in the cache)
115    /// this can cause a regression.
116    ///
117    /// New default disables this behavior by making it false.
118    ///
119    /// If this doesn't cause regression we will remove this option
120    /// in the future.
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub eager_evict: Option<bool>,
123
124    /// The minimum relative improvement threshold for the join balancer.
125    ///
126    /// The join balancer is a component that dynamically chooses an optimal
127    /// partitioning policy for adaptive join operators.  This parameter
128    /// prevents the join balancer from making changes to the partitioning
129    /// policy if the improvement is not significant, since the overhead of such
130    /// rebalancing, especially when performed frequently, can exceed the
131    /// benefits.
132    ///
133    /// A rebalancing is considered significant if the relative estimated
134    /// improvement across the collections whose partitioning policy the
135    /// rebalancing changes is at least this threshold. Collections that keep
136    /// their policy are excluded, since they cost the same either way.
137    ///
138    /// A rebalancing is applied if both this threshold and
139    /// `balancer_min_absolute_improvement_threshold` are met.
140    ///
141    /// The default value is 1.2.
142    #[serde(skip_serializing_if = "Option::is_none")]
143    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
144    pub balancer_min_relative_improvement_threshold: Option<f64>,
145
146    /// The minimum absolute improvement threshold for the balancer.
147    ///
148    /// The join balancer is a component that dynamically chooses an optimal
149    /// partitioning policy for adaptive join operators.  This parameter
150    /// prevents the join balancer from making changes to the partitioning
151    /// policy if the improvement is not significant, since the overhead of such
152    /// rebalancing, especially when performed frequently, can exceed the
153    /// benefits.
154    ///
155    /// A rebalancing is considered significant if the absolute estimated
156    /// improvement across the collections whose partitioning policy the
157    /// rebalancing changes is at least this threshold. The cost model used by the
158    /// balancer is based on the number of records in the largest partition of a
159    /// collection.
160    ///
161    /// A rebalancing is applied if both this threshold and
162    /// `balancer_min_relative_improvement_threshold` are met.
163    ///
164    /// The default value is 10,000.
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub balancer_min_absolute_improvement_threshold: Option<u64>,
167
168    /// Factor that discourages the use of the Balance policy in a perfectly balanced collection.
169    ///
170    /// Assuming a perfectly balanced key distribution, the Balance policy is slightly less efficient than Shard,
171    /// since it requires computing the hash of the entire key/value pair. This factor discourages the use of this policy
172    /// if the skew is `<balancer_balance_tax`.
173    ///
174    /// The default value is 1.1.
175    #[serde(skip_serializing_if = "Option::is_none")]
176    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
177    pub balancer_balance_tax: Option<f64>,
178
179    /// The balancer threshold for checking for an improved partitioning policy for a stream.
180    ///
181    /// Finding a good partitioning policy for a circuit involves solving an optimization problem,
182    /// which can be relatively expensive. Instead of doing this on every step, the balancer only
183    /// checks for an improved partitioning policy if the key distribution of a stream has changed
184    /// significantly since the current solution was computed.  Specifically, it only kicks in when
185    /// the size of at least one shard of at least one stream in the cluster has changed by more than
186    /// this threshold.
187    ///
188    /// The default value is 0.1.
189    #[serde(skip_serializing_if = "Option::is_none")]
190    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
191    pub balancer_key_distribution_refresh_threshold: Option<f64>,
192
193    /// False-positive rate for Bloom filters on batches on storage.
194    ///
195    /// Deprecated: use `storage.bloom_false_positive_rate` instead.
196    #[serde(skip_serializing_if = "Option::is_none")]
197    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
198    pub bloom_false_positive_rate: Option<f64>,
199
200    /// Whether file-backed batches may use roaring membership filters when the
201    /// key type supports them.
202    #[serde(skip_serializing_if = "Option::is_none")]
203    pub enable_roaring: Option<bool>,
204
205    /// Maximum batch size in records for level 0 merges.
206    #[serde(skip_serializing_if = "Option::is_none")]
207    pub max_level0_batch_size_records: Option<u16>,
208
209    /// Minimum number of batches an accumulator's spine merges at once,
210    /// at every level above level 1.
211    ///
212    /// Zero restores the built-in minimum.
213    #[serde(skip_serializing_if = "Option::is_none")]
214    pub min_accumulator_merge_batches: Option<u16>,
215
216    /// Minimum number of batches an integral's spine merges at once, at
217    /// every level above level 1.
218    ///
219    /// Unset or zero keeps the built-in minimum.
220    #[serde(skip_serializing_if = "Option::is_none")]
221    pub min_integral_merge_batches: Option<u16>,
222
223    /// The number of merger threads.
224    ///
225    /// The default value is equal to the number of worker threads.
226    #[serde(skip_serializing_if = "Option::is_none")]
227    pub merger_threads: Option<u16>,
228
229    /// Additional bias the merger assigns to records with negative weights
230    /// (retractions) to promote them to higher levels of the LSM tree sooner.
231    ///
232    /// Reasonable values for this parameter are in the range [0, 10].
233    ///
234    /// The default value is 0, which means that retractions are not given
235    /// any additional bias.
236    #[serde(skip_serializing_if = "Option::is_none")]
237    pub negative_weight_multiplier: Option<u16>,
238
239    /// Don't automatically start a transaction for every step.
240    #[serde(skip_serializing_if = "Option::is_none")]
241    pub disable_auto_transaction: Option<bool>,
242
243    /// Override the timestamp returned by SQL `NOW()` at pipeline start.
244    ///
245    /// When set, the clock connector anchors `NOW()` to this RFC 3339
246    /// timestamp the first time the pipeline starts and advances at
247    /// wall-clock cadence from there:
248    /// `NOW() = now_offset + (wall_clock - wall_clock_at_start)`.
249    ///
250    /// Any RFC 3339 timestamp parseable by `chrono::DateTime<Utc>` is
251    /// accepted (years `0001` through `9999`), in the past or future
252    /// relative to wall clock.
253    ///
254    /// This is a testing knob for queries that depend on `NOW()`.
255    ///
256    /// On resume the clock continues from the last journaled `NOW()`;
257    /// `now_offset`'s value is honored only on a fresh start:
258    ///
259    /// | Initial run | Resume from checkpoint | Post-replay `NOW()` |
260    /// |---|---|---|
261    /// | no offset | no offset | wall clock (unchanged) |
262    /// | offset    | offset    | wall-clock pace from the last journaled value; the new offset value is ignored |
263    /// | offset    | no offset | jumps to wall clock (explicit opt-out of the anchor) |
264    /// | no offset | offset    | wall-clock pace from the last journaled value; the new offset value is ignored |
265    #[serde(skip_serializing_if = "Option::is_none")]
266    pub now_offset: Option<DateTime<Utc>>,
267
268    /// Drive `NOW()` from an external HTTP endpoint instead of wall clock.
269    ///
270    /// When `true`, the clock connector emits one initial tick (using
271    /// `now_offset` if set, otherwise wall clock) and then holds that
272    /// value.  Subsequent calls to `POST /clock/advance` move `NOW()`
273    /// forward by the requested delta.  Negative deltas are rejected;
274    /// the clock is forward-only.
275    #[serde(skip_serializing_if = "Option::is_none")]
276    pub now_http_driven: Option<bool>,
277
278    /// Enable streaming exchange.
279    #[serde(skip_serializing_if = "Option::is_none")]
280    pub streaming_exchange: Option<bool>,
281
282    /// Maximum number of bytes of queued but unacknowledged exchange messages
283    /// per pair of remote host and message type.
284    ///
285    /// A sender that pushes past this budget waits for the receiver to
286    /// acknowledge earlier messages before it queues more.  There are three
287    /// message types, so a host buffers up to three times this many bytes for
288    /// each of the other hosts, plus any single message that exceeds the
289    /// budget on its own.
290    ///
291    /// The default is 10,000,000 bytes.
292    #[serde(skip_serializing_if = "Option::is_none")]
293    pub exchange_channel_capacity_bytes: Option<usize>,
294
295    /// Optimize input operators during transaction commit.
296    #[serde(skip_serializing_if = "Option::is_none")]
297    pub optimize_input_during_commit: Option<bool>,
298
299    /// Options not understood by this particular version.
300    ///
301    /// This allows the pipeline manager to take options that a custom or old
302    /// runtime version accepts.
303    #[serde(flatten)]
304    pub other_options: BTreeMap<String, serde_json::Value>,
305}
306
307impl DevTweaks {
308    pub fn buffer_cache_strategy(&self) -> BufferCacheStrategy {
309        self.buffer_cache_strategy.unwrap_or_default()
310    }
311    pub fn buffer_cache_allocation_strategy(&self) -> BufferCacheAllocationStrategy {
312        self.buffer_cache_allocation_strategy.unwrap_or_default()
313    }
314    pub fn effective_buffer_cache_allocation_strategy(&self) -> BufferCacheAllocationStrategy {
315        match self.buffer_cache_strategy() {
316            BufferCacheStrategy::S3Fifo => self.buffer_cache_allocation_strategy(),
317            BufferCacheStrategy::Lru => BufferCacheAllocationStrategy::PerThread,
318        }
319    }
320    pub fn fetch_join(&self) -> bool {
321        self.fetch_join.unwrap_or(false)
322    }
323    pub fn fetch_distinct(&self) -> bool {
324        self.fetch_distinct.unwrap_or(false)
325    }
326    pub fn merger(&self) -> MergerType {
327        self.merger.unwrap_or_default()
328    }
329    pub fn stack_overflow_backtrace(&self) -> bool {
330        self.stack_overflow_backtrace.unwrap_or(false)
331    }
332    pub fn splitter_chunk_size_records(&self) -> u64 {
333        self.splitter_chunk_size_records.unwrap_or(10_000)
334    }
335    pub fn adaptive_joins(&self) -> bool {
336        self.adaptive_joins.unwrap_or(false)
337    }
338    pub fn balancer_min_relative_improvement_threshold(&self) -> f64 {
339        self.balancer_min_relative_improvement_threshold
340            .unwrap_or(1.2)
341    }
342    pub fn balancer_min_absolute_improvement_threshold(&self) -> u64 {
343        self.balancer_min_absolute_improvement_threshold
344            .unwrap_or(10_000)
345    }
346    pub fn balancer_balance_tax(&self) -> f64 {
347        self.balancer_balance_tax.unwrap_or(1.1)
348    }
349    pub fn balancer_key_distribution_refresh_threshold(&self) -> f64 {
350        self.balancer_key_distribution_refresh_threshold
351            .unwrap_or(0.1)
352    }
353    pub fn bloom_false_positive_rate(&self) -> f64 {
354        self.bloom_false_positive_rate.unwrap_or(0.0001)
355    }
356    pub fn enable_roaring(&self) -> bool {
357        // Roaring is enabled by default, but `enable_roaring = false` remains
358        // available as a kill switch while the feature is still being tuned.
359        self.enable_roaring.unwrap_or(true)
360    }
361
362    /// Rejects settings outside their valid range, naming the field, the
363    /// value and the range.
364    pub fn validate(&self) -> Result<(), String> {
365        for (name, value) in [
366            (
367                "min_accumulator_merge_batches",
368                self.min_accumulator_merge_batches,
369            ),
370            (
371                "min_integral_merge_batches",
372                self.min_integral_merge_batches,
373            ),
374        ] {
375            if let Some(value) = value
376                && value > MAX_MIN_MERGE_BATCHES
377            {
378                return Err(format!(
379                    "dev_tweaks.{name} is {value}, but the valid range is 0 through \
380                     {MAX_MIN_MERGE_BATCHES}; 0 keeps the built-in minimum"
381                ));
382            }
383        }
384        Ok(())
385    }
386
387    /// Batches an accumulator's spine waits for above level 1; zero means the
388    /// built-in minimum.
389    pub fn min_accumulator_merge_batches(&self) -> u16 {
390        self.min_accumulator_merge_batches.unwrap_or(10)
391    }
392
393    /// Batches an integral's spine waits for above level 1; zero means the
394    /// built-in minimum.
395    pub fn min_integral_merge_batches(&self) -> u16 {
396        self.min_integral_merge_batches.unwrap_or(0)
397    }
398
399    pub fn negative_weight_multiplier(&self) -> u16 {
400        self.negative_weight_multiplier.unwrap_or(0)
401    }
402
403    pub fn disable_auto_transaction(&self) -> bool {
404        self.disable_auto_transaction.unwrap_or(false)
405    }
406
407    /// Configured `now_offset` as milliseconds since the Unix epoch,
408    /// or `None` if no override is set.
409    pub fn now_offset_ms(&self) -> Option<i64> {
410        self.now_offset.map(|target| target.timestamp_millis())
411    }
412
413    pub fn now_http_driven(&self) -> bool {
414        self.now_http_driven.unwrap_or(false)
415    }
416
417    pub fn streaming_exchange(&self) -> bool {
418        self.streaming_exchange.unwrap_or(true)
419    }
420
421    pub fn exchange_channel_capacity_bytes(&self) -> usize {
422        self.exchange_channel_capacity_bytes.unwrap_or(10_000_000)
423    }
424
425    pub fn optimize_input_during_commit(&self) -> bool {
426        self.optimize_input_during_commit.unwrap_or(true)
427    }
428}
429
430/// Selects which eviction strategy backs a cache instance.
431#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
432#[serde(rename_all = "snake_case")]
433pub enum BufferCacheStrategy {
434    /// Use the sharded S3-FIFO cache backed by `quick_cache`.
435    #[default]
436    S3Fifo,
437
438    /// Use the mutex-protected weighted LRU cache.
439    Lru,
440}
441
442/// Controls how caches are shared across a foreground/background worker pair.
443#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
444#[serde(rename_all = "snake_case")]
445pub enum BufferCacheAllocationStrategy {
446    /// Share one cache across a foreground/background worker pair.
447    #[default]
448    SharedPerWorkerPair,
449
450    /// Create a separate cache for each foreground/background thread.
451    PerThread,
452
453    /// Share one cache across all foreground/background threads.
454    Global,
455}
456
457/// Which merger to use.
458#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
459#[serde(rename_all = "snake_case")]
460pub enum MergerType {
461    /// Newer merger, which should be faster for high-latency storage, such as
462    /// object storage, but it likely needs tuning.
463    PushMerger,
464
465    /// The old standby, with known performance.
466    #[default]
467    ListMerger,
468}
469
470#[cfg(test)]
471mod tests {
472    use serde_json::json;
473
474    use crate::config::{PipelineConfig, RuntimeConfig};
475
476    use super::*;
477
478    /// Either merge threshold is accepted up to the bound and rejected past
479    /// it, by name, with the value and the range in the message.
480    #[test]
481    fn merge_thresholds_are_bounded() {
482        assert_eq!(DevTweaks::default().validate(), Ok(()));
483        for field in [
484            "min_accumulator_merge_batches",
485            "min_integral_merge_batches",
486        ] {
487            let with = |value: u16| {
488                let mut tweaks = DevTweaks::default();
489                if field == "min_accumulator_merge_batches" {
490                    tweaks.min_accumulator_merge_batches = Some(value);
491                } else {
492                    tweaks.min_integral_merge_batches = Some(value);
493                }
494                tweaks
495            };
496            assert_eq!(with(0).validate(), Ok(()), "{field} = 0");
497            assert_eq!(
498                with(MAX_MIN_MERGE_BATCHES).validate(),
499                Ok(()),
500                "{field} at the bound"
501            );
502            let error = with(MAX_MIN_MERGE_BATCHES + 1)
503                .validate()
504                .expect_err("a value past the bound must be rejected");
505            assert!(error.contains(field), "{error}");
506            assert!(error.contains("16"), "{error}");
507            assert!(error.contains("0 through 15"), "{error}");
508        }
509    }
510
511    /// Regression test: `Option<f64>` fields inside `DevTweaks` must
512    /// survive a JSON-string round-trip through `PipelineConfig`, which
513    /// uses `#[serde(flatten)]` on `RuntimeConfig`. With `serde_json`'s
514    /// `arbitrary_precision` feature enabled, the serde `Content` buffer
515    /// represents numbers as maps, which breaks plain `f64`
516    /// deserialization (serde-rs/json#1157). The `serde_via_value`
517    /// workaround on each `Option<f64>` field fixes this.
518    #[test]
519    fn dev_tweaks_f64_roundtrip_through_pipeline_config() {
520        let rc = RuntimeConfig {
521            dev_tweaks: DevTweaks {
522                bloom_false_positive_rate: Some(0.0),
523                balancer_balance_tax: Some(1.1),
524                balancer_min_relative_improvement_threshold: Some(1.2),
525                balancer_key_distribution_refresh_threshold: Some(0.1),
526                ..Default::default()
527            },
528            ..Default::default()
529        };
530        let pc = PipelineConfig {
531            global: rc,
532            multihost: None,
533            name: Some("test-pipeline".into()),
534            given_name: None,
535            storage_config: None,
536            secrets_dir: None,
537            inputs: Default::default(),
538            outputs: Default::default(),
539            program_ir: None,
540        };
541
542        // JSON string round-trip (the path the pipeline process takes).
543        let json = serde_json::to_string_pretty(&pc).unwrap();
544        let pc2: PipelineConfig = serde_json::from_str(&json)
545            .expect("JSON string round-trip of PipelineConfig with f64 dev_tweaks must succeed");
546        assert_eq!(pc2.global.dev_tweaks.bloom_false_positive_rate, Some(0.0));
547        assert_eq!(pc2.global.dev_tweaks.balancer_balance_tax, Some(1.1));
548        assert_eq!(
549            pc2.global
550                .dev_tweaks
551                .balancer_min_relative_improvement_threshold,
552            Some(1.2)
553        );
554        assert_eq!(
555            pc2.global
556                .dev_tweaks
557                .balancer_key_distribution_refresh_threshold,
558            Some(0.1)
559        );
560
561        // serde_json::Value round-trip (the path the pipeline manager takes).
562        let value = serde_json::to_value(&pc).unwrap();
563        let pc3: PipelineConfig = serde_json::from_value(value)
564            .expect("Value round-trip of PipelineConfig with f64 dev_tweaks must succeed");
565        assert_eq!(pc3.global.dev_tweaks.bloom_false_positive_rate, Some(0.0));
566    }
567
568    #[test]
569    fn other_options() {
570        let dt =
571            serde_json::from_value::<DevTweaks>(json!({"xyzzy": 1.0, "foobar": {"key": "value"}}))
572                .unwrap();
573        assert_eq!(
574            &dt.other_options,
575            &BTreeMap::from_iter([
576                (String::from("xyzzy"), json!(1.0)),
577                (String::from("foobar"), json!({"key": "value"}))
578            ]),
579        );
580    }
581}