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