Skip to main content

feldera_types/
config.rs

1//! Controller configuration.
2//!
3//! This module defines the controller configuration structure.  The leaves of
4//! this structure are individual transport-specific and data-format-specific
5//! endpoint configs.  We represent these configs as opaque JSON values, so
6//! that the entire configuration tree can be deserialized from a JSON file.
7
8use crate::duration::ConfigDuration;
9use crate::postprocess::PostprocessorConfig;
10use crate::preprocess::PreprocessorConfig;
11use crate::secret_ref::MaybeSecretRef;
12use crate::secret_resolver::default_secrets_directory;
13use crate::size::{ConfigSize, LegacySizeUnit};
14use crate::transport::adhoc::AdHocInputConfig;
15use crate::transport::clock::{ClockConfig, ClockTimezoneOffset};
16use crate::transport::datagen::DatagenInputConfig;
17use crate::transport::delta_table::{DeltaTableReaderConfig, DeltaTableWriterConfig};
18use crate::transport::dynamodb::DynamoDBWriterConfig;
19use crate::transport::file::{FileInputConfig, FileOutputConfig};
20use crate::transport::http::{HttpInputConfig, HttpOutputConfig};
21use crate::transport::iceberg::IcebergReaderConfig;
22use crate::transport::kafka::{KafkaInputConfig, KafkaOutputConfig};
23use crate::transport::nats::{NatsInputConfig, NatsOutputConfig};
24use crate::transport::nexmark::NexmarkInputConfig;
25use crate::transport::postgres::{
26    PostgresCdcReaderConfig, PostgresReaderConfig, PostgresWriterConfig,
27};
28use crate::transport::pubsub::PubSubInputConfig;
29use crate::transport::redis::RedisOutputConfig;
30use crate::transport::s2::{S2InputConfig, S2OutputConfig};
31use crate::transport::s3::S3InputConfig;
32use crate::transport::url::UrlInputConfig;
33use crate::{duration::LegacyUnit, duration_setting, nullable_duration_setting, size_setting};
34use core::fmt;
35use feldera_ir::{MirNode, MirNodeId};
36use serde::de::{self, MapAccess, Visitor};
37use serde::{Deserialize, Deserializer, Serialize};
38use serde_json::Value as JsonValue;
39use std::collections::HashMap;
40use std::fmt::Display;
41use std::path::Path;
42use std::str::FromStr;
43use std::time::Duration;
44use std::{borrow::Cow, cmp::max, collections::BTreeMap};
45use utoipa::ToSchema;
46use utoipa::openapi::{ObjectBuilder, OneOfBuilder, Ref, RefOr, Schema, SchemaType};
47
48pub mod dev_tweaks;
49pub mod ignored;
50pub use dev_tweaks::DevTweaks;
51
52const DEFAULT_MAX_PARALLEL_CONNECTOR_INIT: u64 = 10;
53
54/// Default maximum number of updates to be kept in the output buffer.
55const DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS: usize = 10_000_000;
56
57/// Default value of `ConnectorConfig::max_queued_records`.
58pub const fn default_max_queued_records() -> u64 {
59    1_000_000
60}
61
62pub const DEFAULT_MAX_WORKER_BATCH_SIZE: u64 = 10_000;
63
64/// Default resolution of the real-time clock that drives SQL `NOW()`.
65pub const DEFAULT_CLOCK_RESOLUTION: ConfigDuration = ConfigDuration::from_secs(1);
66
67/// Default interval between automatic checkpoints.
68pub const DEFAULT_CHECKPOINT_INTERVAL: ConfigDuration = ConfigDuration::from_secs(60);
69
70/// Default interval between standby checkpoint fetches.
71pub const DEFAULT_PULL_INTERVAL: ConfigDuration = ConfigDuration::from_secs(10);
72
73/// Default minimum age a checkpoint reaches before it may be deleted.
74pub const DEFAULT_RETENTION_MIN_AGE: ConfigDuration = ConfigDuration::from_days(30);
75
76// The defaults as the OpenAPI schema shows them, one function per
77// `#[schema(default = ...)]`.
78fn default_clock_resolution() -> String {
79    DEFAULT_CLOCK_RESOLUTION.to_string()
80}
81fn default_checkpoint_interval() -> String {
82    DEFAULT_CHECKPOINT_INTERVAL.to_string()
83}
84fn default_pull_interval() -> String {
85    DEFAULT_PULL_INTERVAL.to_string()
86}
87fn default_retention_min_age() -> String {
88    DEFAULT_RETENTION_MIN_AGE.to_string()
89}
90
91duration_setting!(
92    duration_standby_pull_interval,
93    "standby_pull_interval",
94    LegacyUnit::Secs
95);
96duration_setting!(
97    duration_checkpoint_push_interval,
98    "checkpoint_push_interval",
99    LegacyUnit::Secs
100);
101duration_setting!(duration_min_retention, "min_retention", LegacyUnit::Days);
102duration_setting!(duration_ioop_latency, "ioop_latency", LegacyUnit::Millis);
103duration_setting!(
104    duration_max_buffering_delay,
105    "max_buffering_delay",
106    LegacyUnit::Micros
107);
108duration_setting!(
109    duration_clock_resolution,
110    "clock_resolution",
111    LegacyUnit::Micros
112);
113duration_setting!(
114    duration_provisioning_timeout,
115    "provisioning_timeout",
116    LegacyUnit::Secs
117);
118nullable_duration_setting!(
119    duration_checkpoint_interval,
120    "checkpoint_interval",
121    LegacyUnit::Secs
122);
123duration_setting!(
124    duration_max_output_buffer_time,
125    "max_output_buffer_time",
126    LegacyUnit::Millis
127);
128size_setting!(size_max_rss, "max_rss", LegacySizeUnit::Megabytes);
129size_setting!(
130    size_datafusion_memory,
131    "datafusion_memory",
132    LegacySizeUnit::Megabytes
133);
134size_setting!(size_cache_size, "cache_size", LegacySizeUnit::Mebibytes);
135size_setting!(size_min_spill_size, "min_spill_size", LegacySizeUnit::Bytes);
136size_setting!(
137    size_min_step_spill_size,
138    "min_step_spill_size",
139    LegacySizeUnit::Bytes
140);
141size_setting!(size_memory_min, "memory_min", LegacySizeUnit::Megabytes);
142size_setting!(size_memory_max, "memory_max", LegacySizeUnit::Megabytes);
143size_setting!(size_storage_min, "storage_min", LegacySizeUnit::Megabytes);
144size_setting!(size_storage_max, "storage_max", LegacySizeUnit::Megabytes);
145size_setting!(
146    size_scale_threshold_available,
147    "scale_threshold_available",
148    LegacySizeUnit::Megabytes
149);
150size_setting!(
151    size_max_queued_size,
152    "max_queued_size",
153    LegacySizeUnit::Bytes
154);
155
156/// Program information included in the pipeline configuration.
157#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
158pub struct ProgramIr {
159    /// The MIR of the program.
160    pub mir: HashMap<MirNodeId, MirNode>,
161    /// Program schema.
162    pub program_schema: serde_json::Value,
163    /// The circuit IR (the compiler's JIT `allOperators` form) that the Gen-2
164    /// engine lowers onto the runtime to build the circuit. `None` for
165    /// Rust-compiled pipelines, whose circuit is statically linked into the binary.
166    #[serde(default)]
167    pub circuit_ir: Option<serde_json::Value>,
168    /// The program's Rust UDFs compiled to a native shared library (a Linux `cdylib`), which
169    /// the Gen-2 engine loads into its process. `None` when the program has no Rust UDFs, and
170    /// for Rust-compiled pipelines, which link their UDFs into the binary.
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub udf_library: Option<UdfLibrary>,
173}
174
175/// A program's UDF library, named by the same checksums as a pipeline binary.
176#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
177pub struct UdfLibrary {
178    /// Checksum of the sources the library was built from.
179    pub source_checksum: String,
180    /// sha256 checksum of the library file.
181    pub integrity_checksum: String,
182}
183
184/// Identity of a pipeline, used to record and check ownership of an S3
185/// checkpoint bucket.
186#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
187pub struct PipelineIdentity {
188    /// System-generated name of the pipeline (format `pipeline-<uuid>`).
189    pub name: String,
190    /// Name given to the pipeline by the tenant.
191    pub given_name: Option<String>,
192}
193
194impl Display for PipelineIdentity {
195    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196        match &self.given_name {
197            Some(given_name) => write!(f, "{given_name} (id: {})", self.name),
198            None => write!(f, "{}", self.name),
199        }
200    }
201}
202
203/// Pipeline deployment configuration.
204/// It represents configuration entries directly provided by the user
205/// (e.g., runtime configuration) and entries derived from the schema
206/// of the compiled program (e.g., connectors). Storage configuration,
207/// if applicable, is set by the runner.
208#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq)]
209pub struct PipelineConfig {
210    /// Global controller configuration.
211    #[serde(flatten)]
212    #[schema(inline)]
213    pub global: RuntimeConfig,
214
215    /// Configuration for multihost pipelines.
216    ///
217    /// The presence of this field indicates that the pipeline is running in
218    /// multihost mode.  In the pod with ordinal 0, this triggers starting the
219    /// coordinator process.  In all pods, this tells the pipeline process to
220    /// await a connection from the coordinator instead of initializing the
221    /// pipeline immediately.
222    pub multihost: Option<MultihostConfig>,
223
224    /// Unique system-generated name of the pipeline (format: `pipeline-<uuid>`).
225    /// It is unique across all tenants and cannot be changed.
226    ///
227    /// The `<uuid>` is also used in the naming of various resources that back the pipeline,
228    /// and as such this name is useful to find/identify corresponding resources.
229    pub name: Option<String>,
230
231    /// Name given by the tenant to the pipeline. It is only unique within the same tenant, and can
232    /// be changed by the tenant when the pipeline is stopped.
233    ///
234    /// Given a specific tenant, it can be used to find/identify a specific pipeline of theirs.
235    pub given_name: Option<String>,
236
237    /// Configuration for persistent storage
238    ///
239    /// If `global.storage` is `Some(_)`, this field must be set to some
240    /// [`StorageConfig`].  If `global.storage` is `None``, the pipeline ignores
241    /// this field.
242    #[serde(default)]
243    pub storage_config: Option<StorageConfig>,
244
245    /// Directory containing values of secrets.
246    ///
247    /// If this is not set, a default directory is used.
248    pub secrets_dir: Option<String>,
249
250    /// Input endpoint configuration.
251    #[serde(default)]
252    pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
253
254    /// Output endpoint configuration.
255    #[serde(default)]
256    pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
257
258    /// Program information.
259    #[serde(default)]
260    pub program_ir: Option<ProgramIr>,
261}
262
263impl PipelineConfig {
264    pub fn max_parallel_connector_init(&self) -> u64 {
265        max(
266            self.global
267                .max_parallel_connector_init
268                .unwrap_or(DEFAULT_MAX_PARALLEL_CONNECTOR_INIT),
269            1,
270        )
271    }
272
273    /// Extract the compiler-generated subset of the configuration (connectors
274    /// and program IR) used to compute pipeline diffs.
275    pub fn program_info_subset(&self) -> PipelineConfigProgramInfo {
276        PipelineConfigProgramInfo {
277            inputs: self.inputs.clone(),
278            outputs: self.outputs.clone(),
279            program_ir: self.program_ir.clone(),
280        }
281    }
282
283    pub fn with_storage(self, storage: Option<(StorageConfig, StorageOptions)>) -> Self {
284        let (storage_config, storage_options) = storage.unzip();
285        Self {
286            global: RuntimeConfig {
287                storage: storage_options,
288                ..self.global
289            },
290            storage_config,
291            ..self
292        }
293    }
294
295    pub fn storage(&self) -> Option<(&StorageConfig, &StorageOptions)> {
296        let storage_options = self.global.storage.as_ref();
297        let storage_config = self.storage_config.as_ref();
298        storage_config.zip(storage_options)
299    }
300
301    /// Returns this pipeline's [`PipelineIdentity`], used to identify the
302    /// pipeline that owns an S3 checkpoint bucket.
303    ///
304    /// Returns `None` when the pipeline has no system-generated [`name`](Self::name).
305    pub fn pipeline_identity(&self) -> Option<PipelineIdentity> {
306        self.name.as_ref().map(|name| PipelineIdentity {
307            name: name.clone(),
308            given_name: self.given_name.clone(),
309        })
310    }
311
312    /// Returns `self.secrets_dir`, or the default secrets directory if it isn't
313    /// set.
314    pub fn secrets_dir(&self) -> &Path {
315        match &self.secrets_dir {
316            Some(dir) => Path::new(dir.as_str()),
317            None => default_secrets_directory(),
318        }
319    }
320
321    /// Abbreviated config that can be printed in the log on pipeline startup.
322    pub fn display_summary(&self) -> String {
323        // TODO: we may want to further abbreviate connector config.
324        let summary = serde_json::json!({
325            "name": self.name,
326            "given_name": self.given_name,
327            "global": self.global,
328            "storage_config": self.storage_config,
329            "secrets_dir": self.secrets_dir,
330            "inputs": self.inputs,
331            "outputs": self.outputs
332        });
333
334        serde_json::to_string_pretty(&summary).unwrap_or_else(|_| "{}".to_string())
335    }
336}
337
338/// A subset of fields in `PipelineConfig` that are generated by the compiler.
339/// These fields are shipped to the pipeline by the compilation server along with
340/// the program binary.
341// Note: An alternative would be to embed these fields in the program binary itself
342// as static strings. This would work well for program IR, but it would require recompiling
343// the program anytime a connector config changes, whereas today connector changes
344// do not require recompilation.
345#[derive(Default, Deserialize, Serialize, Eq, PartialEq, Debug, Clone)]
346pub struct PipelineConfigProgramInfo {
347    /// Input endpoint configuration.
348    pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
349
350    /// Output endpoint configuration.
351    #[serde(default)]
352    pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
353
354    /// Program information.
355    #[serde(default)]
356    pub program_ir: Option<ProgramIr>,
357}
358
359/// Configuration for a multihost Feldera pipeline.
360///
361/// This configuration is primarily for the coordinator.
362#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
363pub struct MultihostConfig {
364    /// Number of hosts to launch.
365    ///
366    /// For the configuration to be truly multihost, this should be at least 2.
367    /// A value of 1 still runs the multihost coordinator but it only
368    /// coordinates a single host.
369    pub hosts: usize,
370}
371
372impl Default for MultihostConfig {
373    fn default() -> Self {
374        Self { hosts: 1 }
375    }
376}
377
378/// Configuration for persistent storage in a [`PipelineConfig`].
379#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
380pub struct StorageConfig {
381    /// A directory to keep pipeline state, as a path on the filesystem of the
382    /// machine or container where the pipeline will run.
383    ///
384    /// When storage is enabled, this directory stores the data for
385    /// [StorageBackendConfig::Default].
386    ///
387    /// When fault tolerance is enabled, this directory stores checkpoints and
388    /// the log.
389    pub path: String,
390
391    /// How to cache access to storage in this pipeline.
392    #[serde(default)]
393    pub cache: StorageCacheConfig,
394}
395
396impl StorageConfig {
397    pub fn path(&self) -> &Path {
398        Path::new(&self.path)
399    }
400}
401
402/// How to cache access to storage within a Feldera pipeline.
403#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
404#[serde(rename_all = "snake_case")]
405pub enum StorageCacheConfig {
406    /// Use the operating system's page cache as the primary storage cache.
407    ///
408    /// This is the default because it currently performs better than
409    /// `FelderaCache`.
410    #[default]
411    PageCache,
412
413    /// Use Feldera's internal cache implementation.
414    ///
415    /// This is under development. It will become the default when its
416    /// performance exceeds that of `PageCache`.
417    FelderaCache,
418}
419
420impl StorageCacheConfig {
421    #[cfg(unix)]
422    pub fn to_custom_open_flags(&self) -> i32 {
423        match self {
424            StorageCacheConfig::PageCache => (),
425            StorageCacheConfig::FelderaCache => {
426                #[cfg(target_os = "linux")]
427                return libc::O_DIRECT;
428            }
429        }
430        0
431    }
432}
433
434/// Storage configuration for a pipeline.
435#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
436#[serde(default)]
437pub struct StorageOptions {
438    /// How to connect to the underlying storage.
439    pub backend: StorageBackendConfig,
440
441    /// For a batch of data maintained as part of a persistent index during a
442    /// pipeline run, the minimum estimated size to write it to storage, such
443    /// as `"10Mi"`.
444    ///
445    /// This is provided for debugging and fine-tuning and should ordinarily be
446    /// left unset.
447    ///
448    /// A value of 0 will write even empty batches to storage, and nonzero
449    /// values provide a threshold.  A very large value effectively disables
450    /// storage for such batches.  The default is `"10Mi"`.
451    ///
452    /// Before release 0.367.0 this setting was `min_storage_bytes`, a number
453    /// of bytes. That name is deprecated but still read.
454    #[serde(
455        alias = "min_storage_bytes",
456        deserialize_with = "size_min_spill_size",
457        skip_serializing_if = "Option::is_none"
458    )]
459    #[schema(value_type = Option<String>)]
460    pub min_spill_size: Option<ConfigSize>,
461
462    /// For a batch of data passed through the pipeline during a single step,
463    /// the minimum estimated size to write it to storage, such as `"64Mi"`.
464    ///
465    /// This is provided for debugging and fine-tuning and should ordinarily be
466    /// left unset.  A value of 0 writes every batch that holds anything to
467    /// storage; an empty batch stays in memory, since it has nothing to spill
468    /// and a layer file is not free.  Nonzero values provide a threshold.
469    /// Unset, the default, effectively disables storage for such batches.
470    /// If it is set, it should ordinarily be greater than or equal to
471    /// `min_spill_size`.
472    ///
473    /// Before release 0.367.0 this setting was `min_step_storage_bytes`, a
474    /// number of bytes. That name is deprecated but still read.
475    #[serde(
476        alias = "min_step_storage_bytes",
477        deserialize_with = "size_min_step_spill_size",
478        skip_serializing_if = "Option::is_none"
479    )]
480    #[schema(value_type = Option<String>)]
481    pub min_step_spill_size: Option<ConfigSize>,
482
483    /// The form of compression to use in data batches.
484    ///
485    /// Compression has a CPU cost but it can take better advantage of limited
486    /// NVMe and network bandwidth, which means that it can increase overall
487    /// performance.
488    pub compression: StorageCompression,
489
490    /// Compression level, for compression algorithms that have one.
491    ///
492    /// Only `StorageCompression::Zstd` uses this. Higher levels compress
493    /// harder and more slowly; decompression speed is largely unaffected, so
494    /// the tradeoff is write throughput against stored size. Zstd accepts
495    /// roughly 1 to 22, and a value outside the range its build supports is
496    /// clamped into it.
497    ///
498    /// This is provided for fine-tuning and should ordinarily be left unset,
499    /// which selects the algorithm's own default.
500    pub compression_level: Option<i32>,
501
502    /// The maximum size of the in-memory storage cache, such as `"4Gi"`.
503    ///
504    /// If set, the specified cache size is spread across all the foreground and
505    /// background threads. If unset, each foreground or background thread cache
506    /// is limited to 256 MiB.
507    ///
508    /// Before release 0.367.0 this setting was `cache_mib`, a number of
509    /// mebibytes. That name is deprecated but still read.
510    #[serde(
511        alias = "cache_mib",
512        deserialize_with = "size_cache_size",
513        skip_serializing_if = "Option::is_none"
514    )]
515    #[schema(value_type = Option<String>)]
516    pub cache_size: Option<ConfigSize>,
517
518    /// False-positive rate for Bloom filters on batches on storage, as a
519    /// fraction f, where 0 < f < 1.
520    ///
521    /// The false-positive rate trades off between the amount of memory used by
522    /// Bloom filters and how frequently storage needs to be searched for keys
523    /// that are not actually present.  Typical false-positive rates and their
524    /// corresponding memory costs are:
525    ///
526    /// - 0.1: 4.8 bits per key
527    /// - 0.01: 9.6 bits per key
528    /// - 0.001: 14.4 bits per key
529    /// - 0.0001: 19.2 bits per key (default)
530    ///
531    /// Values outside the valid range, such as 0.0, disable Bloom filters.
532    #[serde(skip_serializing_if = "Option::is_none")]
533    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
534    pub bloom_false_positive_rate: Option<f64>,
535}
536
537// `f64` does not implement `Eq`, but `bloom_false_positive_rate` is always
538// finite, so `PartialEq` is an equivalence relation here.
539impl Eq for StorageOptions {}
540
541/// Backend storage configuration.
542#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
543#[serde(tag = "name", content = "config", rename_all = "snake_case")]
544pub enum StorageBackendConfig {
545    /// Use the default storage configuration.
546    ///
547    /// This currently uses the local file system.
548    #[default]
549    Default,
550
551    /// Use the local file system.
552    ///
553    /// This uses ordinary system file operations.
554    File(Box<FileBackendConfig>),
555
556    /// Object storage.
557    Object(ObjectStorageConfig),
558}
559
560impl Display for StorageBackendConfig {
561    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562        match self {
563            StorageBackendConfig::Default => write!(f, "default"),
564            StorageBackendConfig::File(_) => write!(f, "file"),
565            StorageBackendConfig::Object(_) => write!(f, "object"),
566        }
567    }
568}
569
570/// Storage compression algorithm.
571#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
572#[serde(rename_all = "snake_case")]
573pub enum StorageCompression {
574    /// Use Feldera's default compression algorithm, currently [`Self::Lz4`].
575    ///
576    /// The default may change as Feldera's performance is tuned and new
577    /// algorithms are introduced.
578    #[default]
579    Default,
580
581    /// Do not compress.
582    None,
583
584    /// Use [Snappy](https://en.wikipedia.org/wiki/Snappy_(compression)) compression.
585    Snappy,
586
587    /// Use [LZ4](https://en.wikipedia.org/wiki/LZ4_(compression_algorithm)) compression.
588    ///
589    /// Compresses better than Snappy and decompresses several times faster, at
590    /// a similar compression rate.
591    Lz4,
592
593    /// Use [Zstandard](https://en.wikipedia.org/wiki/Zstd) compression.
594    ///
595    /// Roughly halves LZ4's output at a comparable decompression rate, for
596    /// slower compression. `StorageOptions::compression_level` selects the
597    /// speed/size tradeoff.
598    Zstd,
599}
600
601#[derive(Debug, Clone, Eq, PartialEq)]
602pub enum StartFromCheckpoint {
603    Latest,
604    Uuid(uuid::Uuid),
605}
606
607impl ToSchema<'_> for StartFromCheckpoint {
608    fn schema() -> (
609        &'static str,
610        utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
611    ) {
612        (
613            "StartFromCheckpoint",
614            utoipa::openapi::RefOr::T(Schema::OneOf(
615                OneOfBuilder::new()
616                    .item(
617                        ObjectBuilder::new()
618                            .schema_type(SchemaType::String)
619                            .enum_values(Some(["latest"].into_iter()))
620                            .build(),
621                    )
622                    .item(
623                        ObjectBuilder::new()
624                            .schema_type(SchemaType::String)
625                            .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
626                                utoipa::openapi::KnownFormat::Uuid,
627                            )))
628                            .build(),
629                    )
630                    .nullable(true)
631                    .build(),
632            )),
633        )
634    }
635}
636
637impl<'de> Deserialize<'de> for StartFromCheckpoint {
638    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
639    where
640        D: Deserializer<'de>,
641    {
642        struct StartFromCheckpointVisitor;
643
644        impl<'de> Visitor<'de> for StartFromCheckpointVisitor {
645            type Value = StartFromCheckpoint;
646
647            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
648                formatter.write_str("a UUID string or the string \"latest\"")
649            }
650
651            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
652            where
653                E: de::Error,
654            {
655                if value == "latest" {
656                    Ok(StartFromCheckpoint::Latest)
657                } else {
658                    uuid::Uuid::parse_str(value)
659                        .map(StartFromCheckpoint::Uuid)
660                        .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(value), &self))
661                }
662            }
663        }
664
665        deserializer.deserialize_str(StartFromCheckpointVisitor)
666    }
667}
668
669impl Serialize for StartFromCheckpoint {
670    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
671    where
672        S: serde::Serializer,
673    {
674        match self {
675            StartFromCheckpoint::Latest => serializer.serialize_str("latest"),
676            StartFromCheckpoint::Uuid(uuid) => serializer.serialize_str(&uuid.to_string()),
677        }
678    }
679}
680
681#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
682pub struct SyncConfig {
683    /// The endpoint URL for the storage service.
684    ///
685    /// This is typically required for custom or local S3-compatible storage providers like MinIO.
686    /// Example: `http://localhost:9000`
687    ///
688    /// For a `gs://` bucket this is the Google Cloud Storage JSON API base URL;
689    /// a bare host gets `/storage/v1/` appended. Leave empty for the public service.
690    ///
691    /// Relevant rclone config key: [`endpoint`](https://rclone.org/s3/#s3-endpoint)
692    pub endpoint: Option<String>,
693
694    /// The name of the storage bucket.
695    ///
696    /// This may include a path to a folder inside the bucket (e.g., `my-bucket/data`).
697    ///
698    /// Prefix it with `gs://` to sync to Google Cloud Storage through its native
699    /// API instead of S3. `provider`, `access_key`, and `secret_key` are then
700    /// ignored; rclone authenticates with Application Default Credentials, for
701    /// example a GKE Workload Identity.
702    pub bucket: String,
703
704    /// The region that this bucket is in.
705    ///
706    /// Leave empty for Minio or the default region (`us-east-1` for AWS).
707    pub region: Option<String>,
708
709    /// The name of the cloud storage provider (e.g., `"AWS"`, `"Minio"`).
710    ///
711    /// Used for provider-specific behavior in rclone.
712    /// If omitted, defaults to `"Other"`.
713    ///
714    /// See [rclone S3 provider documentation](https://rclone.org/s3/#s3-provider)
715    pub provider: Option<String>,
716
717    /// The access key used to authenticate with the storage provider.
718    ///
719    /// If not provided, rclone will fall back to environment-based credentials, such as
720    /// `RCLONE_S3_ACCESS_KEY_ID`. In Kubernetes environments using IRSA (IAM Roles for Service Accounts),
721    /// this can be left empty to allow automatic authentication via the pod's service account.
722    pub access_key: Option<String>,
723
724    /// The secret key used together with the access key for authentication.
725    ///
726    /// If not provided, rclone will fall back to environment-based credentials, such as
727    /// `RCLONE_S3_SECRET_ACCESS_KEY`. In Kubernetes environments using IRSA (IAM Roles for Service Accounts),
728    /// this can be left empty to allow automatic authentication via the pod's service account.
729    pub secret_key: Option<String>,
730
731    /// When set, the pipeline will try fetch the specified checkpoint from the
732    /// object store.
733    ///
734    /// If `fail_if_no_checkpoint` is `true`, the pipeline will fail to initialize.
735    pub start_from_checkpoint: Option<StartFromCheckpoint>,
736
737    /// When true, the pipeline will fail to initialize if fetching the
738    /// specified checkpoint fails (missing, download error).
739    /// When false, the pipeline will start from scratch instead.
740    ///
741    /// False by default.
742    #[schema(default = std::primitive::bool::default)]
743    #[serde(default)]
744    pub fail_if_no_checkpoint: bool,
745
746    /// The number of file transfers to run in parallel.
747    /// Default: 20
748    pub transfers: Option<u8>,
749
750    /// The number of checkers to run in parallel.
751    /// Default: 20
752    pub checkers: Option<u8>,
753
754    /// Set to skip post copy check of checksums, and only check the file sizes.
755    /// This can significantly improve the throughput.
756    /// Defualt: false
757    pub ignore_checksum: Option<bool>,
758
759    /// Number of streams to use for multi-thread downloads.
760    /// Default: 10
761    pub multi_thread_streams: Option<u8>,
762
763    /// Use multi-thread download for files above this size.
764    /// Format: `[size][Suffix]` (Example: 1G, 500M)
765    /// Supported suffixes: k|M|G|T
766    /// Default: 100M
767    pub multi_thread_cutoff: Option<String>,
768
769    /// When true, checkpoint downloads use the maximum resources available on
770    /// the host: `transfers` and `checkers` are scaled to the number of CPUs,
771    /// and the download buffer is allowed to grow up to most of the available
772    /// memory. This maximizes download throughput at the cost of higher CPU and
773    /// memory usage during a pull.
774    ///
775    /// When false, downloads use the values configured via `transfers`,
776    /// `checkers`, and the rclone defaults instead.
777    ///
778    /// Default: true
779    #[schema(default = default_optimize_download_resources)]
780    #[serde(default = "default_optimize_download_resources")]
781    pub optimize_download_resources: bool,
782
783    /// The number of chunks of the same file that are uploaded for multipart uploads.
784    /// Default: 10
785    pub upload_concurrency: Option<u8>,
786
787    /// **Deprecated.** Use `initial=standby` when starting the pipeline instead.
788    #[deprecated(note = "Use `initial=standby` when starting the pipeline instead.")]
789    #[schema(default = std::primitive::bool::default)]
790    #[serde(default)]
791    pub standby: bool,
792
793    /// The interval between each attempt to fetch the latest checkpoint from
794    /// object store while in standby mode, for example `10s`.
795    ///
796    /// Applies only when `start_from_checkpoint` is set to `latest`. Unset
797    /// selects the default, `DEFAULT_PULL_INTERVAL`.
798    #[serde(
799        default,
800        alias = "pull_interval",
801        deserialize_with = "duration_standby_pull_interval",
802        skip_serializing_if = "Option::is_none"
803    )]
804    #[schema(value_type = Option<String>, default = default_pull_interval)]
805    pub standby_pull_interval: Option<ConfigDuration>,
806
807    /// The interval between each push of checkpoints to object store, for
808    /// example `1h`.
809    ///
810    /// The default is no periodic push; `null` disables periodic pushes
811    /// explicitly.
812    #[serde(
813        default,
814        alias = "push_interval",
815        deserialize_with = "duration_checkpoint_push_interval",
816        skip_serializing_if = "Option::is_none"
817    )]
818    #[schema(value_type = Option<String>)]
819    pub checkpoint_push_interval: Option<ConfigDuration>,
820
821    /// Extra flags to pass to `rclone`.
822    ///
823    /// WARNING: Supplying incorrect or conflicting flags can break `rclone`.
824    /// Use with caution.
825    ///
826    /// Refer to the docs to see the supported flags:
827    /// - [Global flags](https://rclone.org/flags/)
828    /// - [S3 specific flags](https://rclone.org/s3/)
829    pub flags: Option<Vec<String>>,
830
831    /// The minimum number of checkpoints to retain in object store.
832    /// No checkpoints will be deleted if the total count is below this threshold.
833    ///
834    /// Default: 10
835    #[schema(default = default_retention_min_count)]
836    #[serde(default = "default_retention_min_count")]
837    pub retention_min_count: u32,
838
839    /// The minimum age a checkpoint must reach before it becomes eligible for
840    /// deletion, for example `30d`. All younger checkpoints will be preserved.
841    /// Unset selects the default, `DEFAULT_RETENTION_MIN_AGE`.
842    #[serde(
843        default,
844        alias = "retention_min_age",
845        deserialize_with = "duration_min_retention",
846        skip_serializing_if = "Option::is_none"
847    )]
848    #[schema(value_type = Option<String>, default = default_retention_min_age)]
849    pub min_retention: Option<ConfigDuration>,
850
851    /// A read-only bucket used as a fallback checkpoint source.
852    ///
853    /// When the pipeline has no local checkpoint and `bucket` contains no
854    /// checkpoint either, it will attempt to fetch the checkpoint from this
855    /// location instead.  All connection settings (`endpoint`, `region`,
856    /// `provider`, `access_key`, `secret_key`) are shared with `bucket`. The
857    /// scheme is not: a `gs://` `bucket` needs a `gs://` `read_bucket` too,
858    /// because the prefix alone selects the object store.
859    ///
860    /// The pipeline **never writes** to `read_bucket`.
861    ///
862    /// Must point to a different location than `bucket`.
863    #[serde(default)]
864    pub read_bucket: Option<String>,
865
866    /// Take ownership of `bucket` when the pipeline starts, even if another
867    /// pipeline owns it.
868    ///
869    /// A pipeline records its ownership of `bucket` in an `owner.json` file
870    /// at the root of `bucket`, and a push fails without writing anything if
871    /// that file names a different pipeline.  When this is `true`, the
872    /// pipeline takes ownership as it starts (a standby pipeline, when it is
873    /// activated): it logs a warning naming the previous and new owners and
874    /// overwrites `owner.json`.  The previous owner's later pushes to
875    /// `bucket` then fail.
876    ///
877    /// This only applies at startup.  If another pipeline takes ownership of
878    /// `bucket` while this pipeline is running, this pipeline's pushes fail.
879    ///
880    /// Ownership changes before the pipeline opens its checkpoint, so it
881    /// sticks even if the pipeline then fails to start: the previous owner's
882    /// pushes keep failing.  To give `bucket` back, start the previous owner
883    /// with `take_bucket_ownership` set.
884    ///
885    /// Use this to hand a checkpoint location over to a pipeline that
886    /// replaces another one, e.g., after deleting and recreating a pipeline.
887    /// Stop the previous owner first, and set this on only one of the
888    /// pipelines that share a `bucket`.
889    ///
890    /// Default: false
891    #[schema(default = std::primitive::bool::default)]
892    #[serde(default)]
893    pub take_bucket_ownership: bool,
894}
895
896fn default_retention_min_count() -> u32 {
897    10
898}
899
900fn default_optimize_download_resources() -> bool {
901    true
902}
903
904impl SyncConfig {
905    /// The standby pull interval in effect, or [`DEFAULT_PULL_INTERVAL`].
906    ///
907    /// The enterprise crates read the sync durations through these accessors
908    /// rather than the fields, so that one version of them compiles against
909    /// every `feldera-types` a pinned runtime may bring: the accessors exist
910    /// with these names on both sides of the rename.
911    pub fn standby_pull_interval(&self) -> ConfigDuration {
912        self.standby_pull_interval.unwrap_or(DEFAULT_PULL_INTERVAL)
913    }
914
915    /// The interval between checkpoint pushes, or `None` for no periodic push.
916    pub fn checkpoint_push_interval(&self) -> Option<ConfigDuration> {
917        self.checkpoint_push_interval
918    }
919
920    /// The checkpoint retention age in effect, or
921    /// [`DEFAULT_RETENTION_MIN_AGE`].
922    pub fn min_retention(&self) -> ConfigDuration {
923        self.min_retention.unwrap_or(DEFAULT_RETENTION_MIN_AGE)
924    }
925
926    pub fn validate(&self) -> Result<(), String> {
927        #[allow(deprecated)]
928        if self.standby {
929            return Err(
930                "The `standby` config field has been deprecated. Use `initial=standby` when starting the pipeline instead.".to_owned()
931            );
932        }
933
934        if let Some(ref rb) = self.read_bucket {
935            if rb == &self.bucket {
936                return Err(
937                    "invalid sync config: `read_bucket` and `bucket` must point to different locations"
938                        .to_owned(),
939                );
940            }
941            // The `gs://` prefix selects the object store, so a mismatch would
942            // send the fallback pull to the wrong service.
943            if is_gcs_bucket(rb) != is_gcs_bucket(&self.bucket) {
944                return Err(format!(
945                    "invalid sync config: `bucket` ('{}') and `read_bucket` ('{}') must use the same object store; prefix both with `gs://` for Google Cloud Storage or neither for S3",
946                    self.bucket, rb
947                ));
948            }
949        }
950
951        Ok(())
952    }
953}
954
955/// Whether a sync `bucket` names Google Cloud Storage rather than S3.
956fn is_gcs_bucket(bucket: &str) -> bool {
957    bucket.starts_with("gs://")
958}
959
960/// Configuration for supplying a custom pipeline StatefulSet template via a Kubernetes ConfigMap.
961///
962/// Operators can provide a custom StatefulSet YAML that the Kubernetes runner will use when
963/// creating pipeline StatefulSets for a pipeline. The custom template must be stored as the
964/// value of a key in a ConfigMap in the same namespace as the pipeline; set `name` to the
965/// ConfigMap name and `key` to the entry that contains the template.
966///
967/// Recommendations and requirements:
968/// - **Start from the default template and modify it as needed.** The default template is present
969///   in ConfigMap named as `<release-name>-pipeline-template`, with key `pipelineTemplate` in the release
970///   namespace and should be used as a reference.
971/// - The template must contain a valid Kubernetes `StatefulSet` manifest in YAML form. The
972///   runner substitutes variables in the template before parsing; therefore the final YAML
973///   must be syntactically valid.
974/// - The runner performs simple string substitution for the following placeholders. Please ensure these
975///   placeholders are placed at appropriate location for their semantics:
976///   - `{id}`: pipeline Kubernetes name (used for object names and labels)
977///   - `{name}`: pipeline name as a quoted JSON string (use it only as a whole YAML value)
978///   - `{namespace}`: Kubernetes namespace where the pipeline runs
979///   - `{pipeline_executor_image}`: container image used to run the pipeline executor
980///   - `{binary_ref}`: program binary reference passed as an argument
981///   - `{program_info_ref}`: program info reference passed as an argument
982///   - `{pipeline_storage_path}`: mount path for persistent pipeline storage
983///   - `{storage_class_name}`: storage class name to use for PVCs (if applicable)
984///   - `{deployment_id}`: UUID identifying the deployment instance
985///   - `{deployment_initial}`: initial desired runtime status (e.g., `provisioning`)
986///   - `{bootstrap_policy}`: bootstrap policy value when applicable, otherwise `none`
987///   - `{silent_bootstrap}`: `yes` or `no`
988///   - `{concurrent_bootstrap}`: `yes` or `no`
989///   - `{hosts}`: number of hosts the pipeline runs on
990///   - `{multihost}`: `yes` or `no`
991///
992///   The substitution has no escape: do not use these names in braces as literal text.
993// Keep the placeholder list in sync with the table in
994// docs.feldera.com/docs/get-started/enterprise/helm-chart-reference.md.
995#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
996pub struct PipelineTemplateConfig {
997    /// Name of the ConfigMap containing the pipeline template.
998    pub name: String,
999    /// Key in the ConfigMap containing the pipeline template.
1000    ///
1001    /// If not set, defaults to `pipelineTemplate`.
1002    #[schema(default = default_pipeline_template_key)]
1003    #[serde(default = "default_pipeline_template_key")]
1004    pub key: String,
1005}
1006
1007fn default_pipeline_template_key() -> String {
1008    "pipelineTemplate".to_string()
1009}
1010
1011#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1012pub struct ObjectStorageConfig {
1013    /// URL.
1014    ///
1015    /// The following URL schemes are supported:
1016    ///
1017    /// * S3:
1018    ///   - `s3://<bucket>/<path>`
1019    ///   - `s3a://<bucket>/<path>`
1020    ///   - `https://s3.<region>.amazonaws.com/<bucket>`
1021    ///   - `https://<bucket>.s3.<region>.amazonaws.com`
1022    ///   - `https://ACCOUNT_ID.r2.cloudflarestorage.com/bucket`
1023    /// * Google Cloud Storage:
1024    ///   - `gs://<bucket>/<path>`
1025    /// * Microsoft Azure Blob Storage:
1026    ///   - `abfs[s]://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
1027    ///   - `abfs[s]://<file_system>@<account_name>.dfs.core.windows.net/<path>`
1028    ///   - `abfs[s]://<file_system>@<account_name>.dfs.fabric.microsoft.com/<path>`
1029    ///   - `az://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
1030    ///   - `adl://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
1031    ///   - `azure://<container>/<path>` (custom)
1032    ///   - `https://<account>.dfs.core.windows.net`
1033    ///   - `https://<account>.blob.core.windows.net`
1034    ///   - `https://<account>.blob.core.windows.net/<container>`
1035    ///   - `https://<account>.dfs.fabric.microsoft.com`
1036    ///   - `https://<account>.dfs.fabric.microsoft.com/<container>`
1037    ///   - `https://<account>.blob.fabric.microsoft.com`
1038    ///   - `https://<account>.blob.fabric.microsoft.com/<container>`
1039    ///
1040    /// Settings derived from the URL will override other settings.
1041    pub url: String,
1042
1043    /// Additional options as key-value pairs.
1044    ///
1045    /// The following keys are supported:
1046    ///
1047    /// * S3:
1048    ///   - `access_key_id`: AWS Access Key.
1049    ///   - `secret_access_key`: AWS Secret Access Key.
1050    ///   - `region`: Region.
1051    ///   - `default_region`: Default region.
1052    ///   - `endpoint`: Custom endpoint for communicating with S3,
1053    ///     e.g. `https://localhost:4566` for testing against a localstack
1054    ///     instance.
1055    ///   - `token`: Token to use for requests (passed to underlying provider).
1056    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html#variants).
1057    /// * Google Cloud Storage:
1058    ///   - `service_account`: Path to the service account file.
1059    ///   - `service_account_key`: The serialized service account key.
1060    ///   - `google_application_credentials`: Application credentials path.
1061    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html).
1062    /// * Microsoft Azure Blob Storage:
1063    ///   - `access_key`: Azure Access Key.
1064    ///   - `container_name`: Azure Container Name.
1065    ///   - `account`: Azure Account.
1066    ///   - `bearer_token_authorization`: Static bearer token for authorizing requests.
1067    ///   - `client_id`: Client ID for use in client secret or Kubernetes federated credential flow.
1068    ///   - `client_secret`: Client secret for use in client secret flow.
1069    ///   - `tenant_id`: Tenant ID for use in client secret or Kubernetes federated credential flow.
1070    ///   - `endpoint`: Override the endpoint for communicating with blob storage.
1071    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html#variants).
1072    ///
1073    /// Options set through the URL take precedence over those set with these
1074    /// options.
1075    #[serde(flatten)]
1076    pub other_options: BTreeMap<String, String>,
1077}
1078
1079/// Configuration for local file system access.
1080#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1081#[serde(default)]
1082pub struct FileBackendConfig {
1083    /// Whether to use background threads for file I/O.
1084    ///
1085    /// Background threads should improve performance, but they can reduce
1086    /// performance if too few cores are available. This is provided for
1087    /// debugging and fine-tuning and should ordinarily be left unset.
1088    pub async_threads: Option<bool>,
1089
1090    /// Per-I/O operation sleep duration, for example `5ms`.
1091    ///
1092    /// This is for simulating slow storage devices.  Do not use this in
1093    /// production.
1094    #[serde(
1095        default,
1096        alias = "ioop_delay",
1097        deserialize_with = "duration_ioop_latency",
1098        skip_serializing_if = "Option::is_none"
1099    )]
1100    #[schema(value_type = Option<String>)]
1101    pub ioop_latency: Option<ConfigDuration>,
1102
1103    /// Configuration to synchronize checkpoints to object store.
1104    pub sync: Option<SyncConfig>,
1105
1106    /// How to make files durable when committing a checkpoint.
1107    ///
1108    /// This is provided for debugging and fine-tuning and should ordinarily be
1109    /// left unset.
1110    pub sync_mode: Option<StorageSyncMode>,
1111}
1112
1113/// How a pipeline makes its files durable when it commits a checkpoint.
1114///
1115/// A checkpoint can hold tens of thousands of files, so committing them one at
1116/// a time is the dominant cost of making one. Both alternatives below fix that,
1117/// but they suit different deployments.
1118#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1119#[serde(rename_all = "snake_case")]
1120pub enum StorageSyncMode {
1121    /// Use `syncfs` when storage has a filesystem to itself, and fsync files in
1122    /// parallel otherwise.
1123    #[default]
1124    Auto,
1125
1126    /// Always `syncfs`.
1127    ///
1128    /// One syscall makes the whole filesystem durable, which is the cheapest
1129    /// option by far when storage is a dedicated volume. On a filesystem shared
1130    /// with anything else, it also writes back that other data.
1131    ///
1132    /// A pipeline falls back to `per_file` where `syncfs` cannot report a failed
1133    /// writeback, rather than honoring this setting: off Linux, and before Linux
1134    /// 5.8, where `syncfs` returned success and discarded the error.
1135    Syncfs,
1136
1137    /// Always fsync each file, spread across several threads.
1138    ///
1139    /// Slower than `syncfs` on a dedicated volume, but it touches only this
1140    /// pipeline's files.
1141    PerFile,
1142}
1143
1144/// Global pipeline configuration settings. This is the publicly
1145/// exposed type for users to configure pipelines.
1146#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1147#[serde(default)]
1148pub struct RuntimeConfig {
1149    /// Number of DBSP worker threads.
1150    ///
1151    /// Each DBSP "foreground" worker thread is paired with a "background"
1152    /// thread for LSM merging, making the total number of threads twice the
1153    /// specified number.
1154    ///
1155    /// The typical sweet spot for the number of workers is between 4 and 16.
1156    /// Each worker increases overall memory consumption for data structures
1157    /// used during a step.
1158    pub workers: u16,
1159
1160    /// The maximum amount of memory that the pipeline is allowed to use on
1161    /// each host, such as `"16G"` or `"16Gi"`.
1162    ///
1163    /// Setting this property activates memory pressure monitoring and backpressure
1164    /// mechanisms. The pipeline will track the amount of remaining memory and
1165    /// report the memory pressure level via the `memory_pressure` metric.
1166    ///
1167    /// As the memory pressure increases, the system will apply increasing backpressure
1168    /// to push state cached in memory to storage, preventing the pipeline from running
1169    /// out of memory at the cost of some performance degradation.
1170    ///
1171    /// It is strongly recommended to set this property to prevent the pipeline from
1172    /// running out of memory. The setting should not exceed the memory limit of the pipeline
1173    /// instance.
1174    ///
1175    /// If `resources.memory_max` is also set, the pipeline uses the smaller of
1176    /// the two as its memory cap. If only `resources.memory_max` is set, the
1177    /// pipeline uses it.
1178    ///
1179    /// The pipeline caps this limit at the memory available to it, which is the
1180    /// host's memory or the container's memory limit, whichever is smaller. It
1181    /// rechecks the available memory every second.
1182    ///
1183    /// Before release 0.367.0 this setting was `max_rss_mb`, a number of
1184    /// megabytes. That name is deprecated but still read.
1185    ///
1186    /// See [documentation on the pipeline's memory usage](https://docs.feldera.com/operations/memory)
1187    /// for more details.
1188    #[serde(
1189        default,
1190        alias = "max_rss_mb",
1191        deserialize_with = "size_max_rss",
1192        skip_serializing_if = "Option::is_none"
1193    )]
1194    #[schema(value_type = Option<String>)]
1195    pub max_rss: Option<ConfigSize>,
1196
1197    /// DataFusion memory pool size, such as `"1Gi"`, shared by the ad-hoc
1198    /// query engine and the Delta Lake / Iceberg connectors.
1199    ///
1200    /// Carved out of `max_rss` (falling back to `resources.memory_max`); the
1201    /// remainder goes to the DBSP circuit, so the two do not double-book RAM.
1202    ///
1203    /// Unset: defaults to 5% of the effective budget, capped at 2 GB.
1204    /// Pipelines that don't run heavy ad-hoc / Delta / Iceberg workloads
1205    /// can leave this unset.
1206    ///
1207    /// Set this explicitly for ad-hoc queries, or Delta / Iceberg scans,
1208    /// over data too large for the default share. A pool that cannot hold
1209    /// the query surfaces as `ResourcesExhausted` on that query alone; the
1210    /// pipeline keeps running.
1211    ///
1212    /// No pool limit applied if no overall budget is configured.
1213    ///
1214    /// Before release 0.367.0 this setting was `datafusion_memory_mb`, a
1215    /// number of megabytes. That name is deprecated but still read.
1216    ///
1217    /// See [documentation on the pipeline's memory usage](https://docs.feldera.com/operations/memory)
1218    /// for more details.
1219    #[serde(
1220        default,
1221        alias = "datafusion_memory_mb",
1222        deserialize_with = "size_datafusion_memory",
1223        skip_serializing_if = "Option::is_none"
1224    )]
1225    #[schema(value_type = Option<String>)]
1226    pub datafusion_memory: Option<ConfigSize>,
1227
1228    /// Number of DBSP hosts.
1229    ///
1230    /// The worker threads are evenly divided among the hosts.  For single-host
1231    /// deployments, this should be 1 (the default).
1232    ///
1233    /// Multihost pipelines are an enterprise-only preview feature.
1234    pub hosts: usize,
1235
1236    /// Storage configuration.
1237    ///
1238    /// - If this is `None`, the default, the pipeline's state is kept in
1239    ///   in-memory data-structures.  This is useful if the pipeline's state
1240    ///   will fit in memory and if the pipeline is ephemeral and does not need
1241    ///   to be recovered after a restart. The pipeline will most likely run
1242    ///   faster since it does not need to access storage.
1243    ///
1244    /// - If set, the pipeline's state is kept on storage.  This allows the
1245    ///   pipeline to work with state that will not fit into memory. It also
1246    ///   allows the state to be checkpointed and recovered across restarts.
1247    #[serde(deserialize_with = "deserialize_storage_options")]
1248    pub storage: Option<StorageOptions>,
1249
1250    /// Fault tolerance configuration.
1251    #[serde(deserialize_with = "deserialize_fault_tolerance")]
1252    pub fault_tolerance: FtConfig,
1253
1254    /// Enable CPU profiler.
1255    ///
1256    /// The default value is `true`.
1257    pub cpu_profiler: bool,
1258
1259    /// Enable pipeline tracing.
1260    pub tracing: bool,
1261
1262    /// Jaeger tracing endpoint to send tracing information to.
1263    pub tracing_endpoint_jaeger: String,
1264
1265    /// Minimal input batch size.
1266    ///
1267    /// The controller delays pushing input records to the circuit until at
1268    /// least `min_batch_size_records` records have been received (total
1269    /// across all endpoints) or `max_buffering_delay` has passed
1270    /// since the first input record was buffered.
1271    /// Defaults to 0.
1272    pub min_batch_size_records: u64,
1273
1274    /// Maximal delay to wait for `min_batch_size_records` to get buffered by
1275    /// the controller, for example `10ms`. Defaults to no delay.
1276    #[serde(
1277        default,
1278        alias = "max_buffering_delay_usecs",
1279        deserialize_with = "duration_max_buffering_delay",
1280        skip_serializing_if = "Option::is_none"
1281    )]
1282    #[schema(value_type = Option<String>)]
1283    pub max_buffering_delay: Option<ConfigDuration>,
1284
1285    /// Resource reservations and limits. This is enforced
1286    /// only in Feldera Cloud.
1287    pub resources: ResourceConfig,
1288
1289    /// Real-time clock resolution, for example `1s`.
1290    ///
1291    /// This parameter controls the execution of queries that use the `NOW()` function.  The output of such
1292    /// queries depends on the real-time clock and can change over time without any external
1293    /// inputs.  If the query uses `NOW()`, the pipeline will update the clock value and trigger incremental
1294    /// recomputation at most once per `clock_resolution`.  If the query does not use
1295    /// `NOW()`, then clock value updates are suppressed and the pipeline ignores this setting.
1296    ///
1297    /// Unset or `null` selects the default, `DEFAULT_CLOCK_RESOLUTION`.
1298    #[serde(
1299        default,
1300        alias = "clock_resolution_usecs",
1301        deserialize_with = "duration_clock_resolution",
1302        skip_serializing_if = "Option::is_none"
1303    )]
1304    #[schema(value_type = Option<String>, default = default_clock_resolution)]
1305    pub clock_resolution: Option<ConfigDuration>,
1306
1307    /// Fixed timezone offset for the SQL `NOW()` clock.
1308    ///
1309    /// An ISO-8601 UTC offset, for example `"+05:30"` or `"-08:00"`, that the
1310    /// clock connector adds to every `NOW()` value it emits, so `NOW()`
1311    /// returns local time in that fixed timezone instead of UTC.
1312    ///
1313    /// The offset is baked into the pipeline's checkpointed state and cannot
1314    /// be changed when the pipeline resumes from a checkpoint: the value from
1315    /// the checkpoint stays in effect, and a differing new value is ignored
1316    /// with a warning in the pipeline log.
1317    #[schema(value_type = Option<String>, example = "+05:30")]
1318    pub clock_timezone_offset: Option<ClockTimezoneOffset>,
1319
1320    /// Optionally, a list of CPU numbers for CPUs to which the pipeline may pin
1321    /// its worker threads.  Specify at least twice as many CPU numbers as
1322    /// workers.  CPUs are generally numbered starting from 0.  The pipeline
1323    /// might not be able to honor CPU pinning requests.
1324    ///
1325    /// CPU pinning can make pipelines run faster and perform more consistently,
1326    /// as long as different pipelines running on the same machine are pinned to
1327    /// different CPUs.
1328    pub pin_cpus: Vec<usize>,
1329
1330    /// Timeout for the `Provisioning` phase of the pipeline, for example `5m`.
1331    /// Setting this value will override the default of the runner.
1332    #[serde(
1333        default,
1334        alias = "provisioning_timeout_secs",
1335        deserialize_with = "duration_provisioning_timeout",
1336        skip_serializing_if = "Option::is_none"
1337    )]
1338    #[schema(value_type = Option<String>)]
1339    pub provisioning_timeout: Option<ConfigDuration>,
1340
1341    /// The maximum number of connectors initialized in parallel during pipeline
1342    /// startup.
1343    ///
1344    /// At startup, the pipeline must initialize all of its input and output connectors.
1345    /// Depending on the number and types of connectors, this can take a long time.
1346    /// To accelerate the process, multiple connectors are initialized concurrently.
1347    /// This option controls the maximum number of connectors that can be initialized
1348    /// in parallel.
1349    ///
1350    /// The default is 10.
1351    pub max_parallel_connector_init: Option<u64>,
1352
1353    /// Specification of additional (sidecar) containers.
1354    pub init_containers: Option<serde_json::Value>,
1355
1356    /// Deprecated: setting this true or false does not have an effect anymore.
1357    pub checkpoint_during_suspend: bool,
1358
1359    /// Sets the number of available runtime threads for the http server.
1360    ///
1361    /// In most cases, this does not need to be set explicitly and
1362    /// the default is sufficient. Can be increased in case the
1363    /// pipeline HTTP API operations are a bottleneck.
1364    ///
1365    /// If not specified, the default is set to `workers`.
1366    pub http_workers: Option<u64>,
1367
1368    /// Sets the number of available runtime threads for async IO tasks.
1369    ///
1370    /// This affects some networking and file I/O operations
1371    /// especially adapters and ad-hoc queries.
1372    ///
1373    /// In most cases, this does not need to be set explicitly and
1374    /// the default is sufficient. Can be increased in case
1375    /// ingress, egress or ad-hoc queries are a bottleneck.
1376    ///
1377    /// If not specified, the default is set to `workers`.
1378    pub io_workers: Option<u64>,
1379
1380    /// Environment variables for the pipeline process.
1381    ///
1382    /// These are key-value pairs injected into the pipeline process environment.
1383    /// Some variable names are reserved by the platform and cannot be overridden
1384    /// (for example `RUST_LOG`, and variables in the `FELDERA_`,
1385    /// `KUBERNETES_`, and `TOKIO_` namespaces).
1386    #[serde(default)]
1387    pub env: BTreeMap<String, String>,
1388
1389    /// Optional settings for tweaking Feldera internals.
1390    pub dev_tweaks: DevTweaks,
1391
1392    /// Log filtering directives.
1393    ///
1394    /// If set to a valid [tracing-subscriber] filter, this controls the log
1395    /// messages emitted by the pipeline process.  Otherwise, or if the filter
1396    /// has invalid syntax, messages at "info" severity and higher are written
1397    /// to the log and all others are discarded.
1398    ///
1399    /// [tracing-subscriber]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives
1400    pub logging: Option<String>,
1401
1402    /// ConfigMap containing a custom pipeline template (Enterprise only).
1403    ///
1404    /// This feature is only available in Feldera Enterprise. If set, the Kubernetes runner
1405    /// will read the template from the specified ConfigMap and use it instead of the default
1406    /// StatefulSet template for the configured pipeline.
1407    ///
1408    /// check [`PipelineTemplateConfig`] documentation for details.
1409    pub pipeline_template_configmap: Option<PipelineTemplateConfig>,
1410}
1411
1412/// Accepts "true" and "false" and converts them to the new format.
1413fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
1414where
1415    D: Deserializer<'de>,
1416{
1417    struct BoolOrStruct;
1418
1419    impl<'de> Visitor<'de> for BoolOrStruct {
1420        type Value = Option<StorageOptions>;
1421
1422        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1423            formatter.write_str("boolean or StorageOptions")
1424        }
1425
1426        fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1427        where
1428            E: de::Error,
1429        {
1430            match v {
1431                false => Ok(None),
1432                true => Ok(Some(StorageOptions::default())),
1433            }
1434        }
1435
1436        fn visit_unit<E>(self) -> Result<Self::Value, E>
1437        where
1438            E: de::Error,
1439        {
1440            Ok(None)
1441        }
1442
1443        fn visit_none<E>(self) -> Result<Self::Value, E>
1444        where
1445            E: de::Error,
1446        {
1447            Ok(None)
1448        }
1449
1450        fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
1451        where
1452            M: MapAccess<'de>,
1453        {
1454            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
1455        }
1456    }
1457
1458    deserializer.deserialize_any(BoolOrStruct)
1459}
1460
1461/// Accepts very old 'initial_state' and 'latest_checkpoint' as enabling fault
1462/// tolerance.
1463///
1464/// Accepts `null` as disabling fault tolerance.
1465///
1466/// Otherwise, deserializes [FtConfig] in the way that one might otherwise
1467/// expect.
1468fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
1469where
1470    D: Deserializer<'de>,
1471{
1472    struct StringOrStruct;
1473
1474    impl<'de> Visitor<'de> for StringOrStruct {
1475        type Value = FtConfig;
1476
1477        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1478            formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
1479        }
1480
1481        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1482        where
1483            E: de::Error,
1484        {
1485            match v {
1486                "initial_state" | "latest_checkpoint" => Ok(FtConfig {
1487                    model: Some(FtModel::default()),
1488                    ..FtConfig::default()
1489                }),
1490                _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
1491            }
1492        }
1493
1494        fn visit_unit<E>(self) -> Result<Self::Value, E>
1495        where
1496            E: de::Error,
1497        {
1498            Ok(FtConfig::default())
1499        }
1500
1501        fn visit_none<E>(self) -> Result<Self::Value, E>
1502        where
1503            E: de::Error,
1504        {
1505            Ok(FtConfig::default())
1506        }
1507
1508        fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
1509        where
1510            M: MapAccess<'de>,
1511        {
1512            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
1513        }
1514    }
1515
1516    deserializer.deserialize_any(StringOrStruct)
1517}
1518
1519impl Default for RuntimeConfig {
1520    fn default() -> Self {
1521        Self {
1522            workers: 8,
1523            max_rss: None,
1524            datafusion_memory: None,
1525            hosts: 1,
1526            storage: Some(StorageOptions::default()),
1527            fault_tolerance: FtConfig::default(),
1528            cpu_profiler: true,
1529            tracing: {
1530                // We discovered that the jaeger crate can use up gigabytes of RAM, so it's not harmless
1531                // to keep it on by default.
1532                false
1533            },
1534            tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
1535            min_batch_size_records: 0,
1536            max_buffering_delay: None,
1537            resources: ResourceConfig::default(),
1538            clock_resolution: None,
1539            clock_timezone_offset: None,
1540            pin_cpus: Vec::new(),
1541            provisioning_timeout: None,
1542            max_parallel_connector_init: None,
1543            init_containers: None,
1544            checkpoint_during_suspend: true,
1545            io_workers: None,
1546            http_workers: None,
1547            env: BTreeMap::default(),
1548            dev_tweaks: DevTweaks::default(),
1549            logging: None,
1550            pipeline_template_configmap: None,
1551        }
1552    }
1553}
1554
1555/// Upper bound on the default DataFusion pool size.
1556///
1557/// Spill-to-disk handles overflow; reserving more starves the circuit.
1558pub const DEFAULT_DATAFUSION_MEMORY_CEILING: ConfigSize = ConfigSize::from_mb(2048);
1559
1560/// Default DataFusion pool size as a percentage of the pipeline's
1561/// effective memory budget. The remainder is left for the DBSP circuit.
1562pub const DEFAULT_DATAFUSION_MEMORY_PERCENT: u64 = 5;
1563
1564impl RuntimeConfig {
1565    /// The input buffering delay in effect, or no delay.
1566    pub fn max_buffering_delay(&self) -> ConfigDuration {
1567        self.max_buffering_delay.unwrap_or(ConfigDuration::ZERO)
1568    }
1569
1570    /// The clock resolution in effect, or [`DEFAULT_CLOCK_RESOLUTION`].
1571    pub fn clock_resolution(&self) -> ConfigDuration {
1572        self.clock_resolution.unwrap_or(DEFAULT_CLOCK_RESOLUTION)
1573    }
1574
1575    /// Pipeline's effective memory budget: the smaller of `max_rss` and
1576    /// `resources.memory_max` (the k8s pod limit), or whichever is set.
1577    pub fn effective_memory(&self) -> Option<ConfigSize> {
1578        self.max_rss
1579            .into_iter()
1580            .chain(self.resources.memory_max)
1581            .min()
1582    }
1583
1584    /// Resolved DataFusion pool size: explicit `datafusion_memory` if set,
1585    /// else 5% of the effective budget capped at
1586    /// `DEFAULT_DATAFUSION_MEMORY_CEILING`. `None` if no budget is
1587    /// configured.
1588    pub fn resolved_datafusion_memory(&self) -> Option<ConfigSize> {
1589        if let Some(explicit) = self.datafusion_memory {
1590            return Some(explicit);
1591        }
1592        let effective = self.effective_memory()?.as_bytes();
1593        // In `u128`: a budget near `u64::MAX` times the percentage overflows.
1594        let fraction = u128::from(effective) * u128::from(DEFAULT_DATAFUSION_MEMORY_PERCENT) / 100;
1595        let fraction = u64::try_from(fraction).unwrap_or(u64::MAX);
1596        Some(ConfigSize::from_bytes(fraction).min(DEFAULT_DATAFUSION_MEMORY_CEILING))
1597    }
1598
1599    /// Returns the DataFusion pool and the memory budget if the pool leaves no
1600    /// memory for the circuit.
1601    pub fn datafusion_memory_exceeding_budget(&self) -> Option<(ConfigSize, ConfigSize)> {
1602        let budget = self.effective_memory()?;
1603        let datafusion = self.resolved_datafusion_memory()?;
1604        (datafusion >= budget).then_some((datafusion, budget))
1605    }
1606}
1607
1608/// Fault-tolerance configuration.
1609///
1610/// The default [FtConfig] (via [FtConfig::default]) disables fault tolerance,
1611/// which is the configuration that one gets if [RuntimeConfig] omits fault
1612/// tolerance configuration.
1613///
1614/// The default value for [FtConfig::model] enables fault tolerance, as
1615/// `Some(FtModel::default())`.  This is the configuration that one gets if
1616/// [RuntimeConfig] includes a fault tolerance configuration but does not
1617/// specify a particular model.
1618#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1619#[serde(rename_all = "snake_case")]
1620pub struct FtConfig {
1621    /// Fault tolerance model to use.
1622    #[serde(with = "none_as_string")]
1623    #[serde(default = "default_model")]
1624    #[schema(
1625        schema_with = none_as_string_schema::<FtModel>,
1626    )]
1627    pub model: Option<FtModel>,
1628
1629    /// Interval between automatic checkpoints, for example `60s`.
1630    ///
1631    /// Unset selects the default, `DEFAULT_CHECKPOINT_INTERVAL`; `null`
1632    /// disables periodic checkpointing.
1633    /// Values less than 1 second or greater than 1 hour will be forced into
1634    /// that range.
1635    #[serde(
1636        default,
1637        alias = "checkpoint_interval_secs",
1638        deserialize_with = "duration_checkpoint_interval",
1639        skip_serializing_if = "Option::is_none"
1640    )]
1641    #[schema(value_type = Option<String>, default = default_checkpoint_interval)]
1642    pub checkpoint_interval: Option<Option<ConfigDuration>>,
1643}
1644
1645fn default_model() -> Option<FtModel> {
1646    Some(FtModel::default())
1647}
1648
1649/// Rewrites the duration settings of a serialized pipeline configuration in the
1650/// spelling that Feldera releases before the duration rename read: under the
1651/// older key, as a whole number of the unit that key named.
1652///
1653/// `config` is a serialized [`RuntimeConfig`], or a serialized
1654/// [`PipelineConfig`], which flattens one and carries the connectors in
1655/// `inputs` and `outputs`; both levels are rewritten. The pipeline manager
1656/// applies this to the configuration it hands a pipeline pinned to another
1657/// runtime version, or compiled by a platform before the rename and not yet
1658/// updated: such a runtime may predate the rename, and a runtime that does
1659/// ignores the current names and silently runs on its defaults, or, for a
1660/// Kafka connector, rejects them. Every Feldera release so far accepts the
1661/// older spelling, so writing it is safe whichever runtime runs.
1662///
1663/// A duration that is not a whole number of the older unit rounds up to the
1664/// next one, so a positive duration never becomes a `0` the older runtime
1665/// reads as "no timeout" or "pull without pause", and is capped at the largest
1666/// value the older field holds; a value that does not parse is left as it is,
1667/// for the runtime to reject.
1668pub fn to_legacy_duration_spelling(config: &mut serde_json::Value) {
1669    use crate::duration::LegacyUnit;
1670    use serde_json::{Map, Value};
1671
1672    /// How one setting is spelled before the rename.
1673    struct Rule {
1674        new: &'static str,
1675        old: &'static str,
1676        unit: LegacyUnit,
1677        /// The largest number the older field holds.
1678        max: u64,
1679        /// Whether the older field took a `null`; where it did not, a `null`
1680        /// meant "unset" and the key is dropped.
1681        null_allowed: bool,
1682    }
1683    const fn rule(
1684        new: &'static str,
1685        old: &'static str,
1686        unit: LegacyUnit,
1687        max: u64,
1688        null_allowed: bool,
1689    ) -> Rule {
1690        Rule {
1691            new,
1692            old,
1693            unit,
1694            max,
1695            null_allowed,
1696        }
1697    }
1698    const U32: u64 = u32::MAX as u64;
1699    const U64: u64 = u64::MAX;
1700    use LegacyUnit::{Days, Micros, Millis, Secs};
1701
1702    fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
1703        for rule in rules {
1704            let Some(value) = object.remove(rule.new) else {
1705                continue;
1706            };
1707            let legacy = match &value {
1708                Value::String(text) => match text.parse::<ConfigDuration>() {
1709                    Ok(duration) => {
1710                        let nanos = std::time::Duration::from(duration).as_nanos();
1711                        let unit_nanos = u128::from(rule.unit.nanos());
1712                        let whole = nanos.div_ceil(unit_nanos);
1713                        Value::from(u64::try_from(whole).unwrap_or(U64).min(rule.max))
1714                    }
1715                    Err(_) => {
1716                        object.insert(rule.new.to_string(), value);
1717                        continue;
1718                    }
1719                },
1720                Value::Null if !rule.null_allowed => continue,
1721                // A bare number or a null already has the older meaning.
1722                other => other.clone(),
1723            };
1724            object.insert(rule.old.to_string(), legacy);
1725        }
1726    }
1727    fn child<'a>(
1728        object: &'a mut Map<String, Value>,
1729        key: &str,
1730    ) -> Option<&'a mut Map<String, Value>> {
1731        object.get_mut(key).and_then(Value::as_object_mut)
1732    }
1733    /// The NATS consumer's expiry was a `std::time::Duration`, which serde
1734    /// writes as `{secs, nanos}`, rather than a number.
1735    fn max_expiry(consumer: &mut Map<String, Value>) {
1736        let Some(Value::String(text)) = consumer.get("max_expiry") else {
1737            return;
1738        };
1739        let Ok(duration) = text.parse::<ConfigDuration>() else {
1740            return;
1741        };
1742        let duration = std::time::Duration::from(duration);
1743        consumer.remove("max_expiry");
1744        consumer.insert(
1745            "max_expires".to_string(),
1746            serde_json::json!({"secs": duration.as_secs(), "nanos": duration.subsec_nanos()}),
1747        );
1748    }
1749    /// The connection options both NATS transports share.
1750    fn nats_connection(transport: &mut Map<String, Value>) {
1751        if let Some(connection) = child(transport, "connection_config") {
1752            apply(
1753                connection,
1754                &[
1755                    rule(
1756                        "connection_timeout",
1757                        "connection_timeout_secs",
1758                        Secs,
1759                        U64,
1760                        false,
1761                    ),
1762                    rule("request_timeout", "request_timeout_secs", Secs, U64, false),
1763                ],
1764            );
1765        }
1766    }
1767    /// One connector of `inputs` or `outputs`.
1768    fn connector(endpoint: &mut Map<String, Value>) {
1769        apply(
1770            endpoint,
1771            &[rule(
1772                "max_output_buffer_time",
1773                "max_output_buffer_time_millis",
1774                Millis,
1775                U64,
1776                false,
1777            )],
1778        );
1779        let name = endpoint
1780            .get("transport")
1781            .and_then(|transport| transport.get("name"))
1782            .and_then(Value::as_str)
1783            .map(str::to_string);
1784        if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
1785            match name.as_deref() {
1786                Some("url_input") => apply(
1787                    transport,
1788                    &[rule("pause_linger", "pause_timeout", Secs, U32, false)],
1789                ),
1790                Some("kafka_input") => apply(
1791                    transport,
1792                    &[rule(
1793                        "group_join_timeout",
1794                        "group_join_timeout_secs",
1795                        Secs,
1796                        U32,
1797                        false,
1798                    )],
1799                ),
1800                Some("kafka_output") => apply(
1801                    transport,
1802                    &[rule(
1803                        "initialization_timeout",
1804                        "initialization_timeout_secs",
1805                        Secs,
1806                        U32,
1807                        false,
1808                    )],
1809                ),
1810                Some("clock_input") => apply(
1811                    transport,
1812                    &[rule(
1813                        "clock_resolution",
1814                        "clock_resolution_usecs",
1815                        Micros,
1816                        U64,
1817                        false,
1818                    )],
1819                ),
1820                Some("pub_sub_input") => apply(
1821                    transport,
1822                    &[
1823                        rule("timeout", "timeout_seconds", Secs, U32, true),
1824                        rule(
1825                            "connect_timeout",
1826                            "connect_timeout_seconds",
1827                            Secs,
1828                            U32,
1829                            true,
1830                        ),
1831                    ],
1832                ),
1833                Some("nats_input") => {
1834                    apply(
1835                        transport,
1836                        &[
1837                            rule(
1838                                "inactivity_timeout",
1839                                "inactivity_timeout_secs",
1840                                Secs,
1841                                U64,
1842                                false,
1843                            ),
1844                            rule("retry_interval", "retry_interval_secs", Secs, U64, false),
1845                        ],
1846                    );
1847                    nats_connection(transport);
1848                    if let Some(consumer) = child(transport, "consumer_config") {
1849                        max_expiry(consumer);
1850                    }
1851                }
1852                Some("nats_output") => {
1853                    apply(
1854                        transport,
1855                        &[rule(
1856                            "publish_timeout",
1857                            "publish_timeout_secs",
1858                            Secs,
1859                            U64,
1860                            false,
1861                        )],
1862                    );
1863                    nats_connection(transport);
1864                }
1865                _ => {}
1866            }
1867        }
1868        let is_avro = endpoint
1869            .get("format")
1870            .and_then(|format| format.get("name"))
1871            .and_then(Value::as_str)
1872            == Some("avro");
1873        if is_avro && let Some(format) = child(endpoint, "format").and_then(|f| child(f, "config"))
1874        {
1875            apply(
1876                format,
1877                &[rule(
1878                    "registry_timeout",
1879                    "registry_timeout_secs",
1880                    Secs,
1881                    U64,
1882                    true,
1883                )],
1884            );
1885        }
1886    }
1887
1888    let Some(global) = config.as_object_mut() else {
1889        return;
1890    };
1891    apply(
1892        global,
1893        &[
1894            rule(
1895                "clock_resolution",
1896                "clock_resolution_usecs",
1897                Micros,
1898                U64,
1899                true,
1900            ),
1901            rule(
1902                "max_buffering_delay",
1903                "max_buffering_delay_usecs",
1904                Micros,
1905                U64,
1906                false,
1907            ),
1908            rule(
1909                "provisioning_timeout",
1910                "provisioning_timeout_secs",
1911                Secs,
1912                U64,
1913                true,
1914            ),
1915        ],
1916    );
1917    if let Some(ft) = child(global, "fault_tolerance") {
1918        // An explicit null disables periodic checkpoints under either key.
1919        apply(
1920            ft,
1921            &[rule(
1922                "checkpoint_interval",
1923                "checkpoint_interval_secs",
1924                Secs,
1925                U64,
1926                true,
1927            )],
1928        );
1929    }
1930    let backend = child(global, "storage")
1931        .and_then(|storage| child(storage, "backend"))
1932        .filter(|backend| backend.get("name").and_then(Value::as_str) == Some("file"))
1933        .and_then(|backend| child(backend, "config"));
1934    if let Some(file) = backend {
1935        apply(
1936            file,
1937            &[rule("ioop_latency", "ioop_delay", Millis, U64, true)],
1938        );
1939        if let Some(sync) = child(file, "sync") {
1940            apply(
1941                sync,
1942                &[
1943                    rule("standby_pull_interval", "pull_interval", Secs, U64, false),
1944                    rule("checkpoint_push_interval", "push_interval", Secs, U64, true),
1945                    rule("min_retention", "retention_min_age", Days, U32, false),
1946                ],
1947            );
1948        }
1949    }
1950    for endpoints in ["inputs", "outputs"] {
1951        if let Some(endpoints) = child(global, endpoints) {
1952            for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
1953                connector(endpoint);
1954            }
1955        }
1956    }
1957}
1958
1959/// Which settings a runtime reads only in their older spelling, because it
1960/// predates the release that renamed them.
1961///
1962/// The pipeline manager computes this for the runtime a pipeline runs, and the
1963/// executors apply it to the configuration they hand the pipeline process.
1964#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1965pub struct LegacySpelling {
1966    /// The runtime predates the duration rename (release 0.366.0).
1967    pub durations: bool,
1968    /// The runtime predates the size rename (release 0.367.0).
1969    pub sizes: bool,
1970}
1971
1972impl LegacySpelling {
1973    /// A runtime that reads every current spelling.
1974    pub const NONE: LegacySpelling = LegacySpelling {
1975        durations: false,
1976        sizes: false,
1977    };
1978
1979    /// Whether any setting must be rewritten.
1980    pub fn any(self) -> bool {
1981        self.durations || self.sizes
1982    }
1983
1984    /// Rewrites `config`, a serialized [`RuntimeConfig`] or
1985    /// [`PipelineConfig`], in the spellings the runtime reads.
1986    pub fn apply(self, config: &mut serde_json::Value) {
1987        if self.durations {
1988            to_legacy_duration_spelling(config);
1989        }
1990        if self.sizes {
1991            to_legacy_size_spelling(config);
1992        }
1993    }
1994}
1995
1996/// Rewrites the size settings of a serialized pipeline configuration in the
1997/// spelling that Feldera releases before the size rename read: under the older
1998/// key, as a whole number of the unit that key named.
1999///
2000/// `config` is a serialized [`RuntimeConfig`] or [`PipelineConfig`], as for
2001/// [`to_legacy_duration_spelling`], and the pipeline manager applies it in the
2002/// same cases, to a runtime that may predate the rename. A size that is not a
2003/// whole number of the older unit rounds up to the next one, so a positive
2004/// limit never becomes a `0`; a value that does not parse is left as it is,
2005/// for the runtime to reject.
2006pub fn to_legacy_size_spelling(config: &mut serde_json::Value) {
2007    use crate::size::LegacySizeUnit::{self, Bytes, Mebibytes, Megabytes};
2008    use serde_json::{Map, Value};
2009
2010    /// How one setting is spelled before the rename.
2011    struct Rule {
2012        new: &'static str,
2013        old: &'static str,
2014        unit: LegacySizeUnit,
2015    }
2016    const fn rule(new: &'static str, old: &'static str, unit: LegacySizeUnit) -> Rule {
2017        Rule { new, old, unit }
2018    }
2019
2020    fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
2021        for rule in rules {
2022            let Some(value) = object.remove(rule.new) else {
2023                continue;
2024            };
2025            let legacy = match &value {
2026                Value::String(text) => match text.parse::<ConfigSize>() {
2027                    Ok(size) => Value::from(size.as_bytes().div_ceil(rule.unit.bytes())),
2028                    Err(_) => {
2029                        object.insert(rule.new.to_string(), value);
2030                        continue;
2031                    }
2032                },
2033                // The older keys took no `null`: it meant "unset".
2034                Value::Null => continue,
2035                // A bare number already has the older meaning.
2036                other => other.clone(),
2037            };
2038            object.insert(rule.old.to_string(), legacy);
2039        }
2040    }
2041    fn child<'a>(
2042        object: &'a mut Map<String, Value>,
2043        key: &str,
2044    ) -> Option<&'a mut Map<String, Value>> {
2045        object.get_mut(key).and_then(Value::as_object_mut)
2046    }
2047    /// One connector of `inputs` or `outputs`.
2048    fn connector(endpoint: &mut Map<String, Value>) {
2049        apply(
2050            endpoint,
2051            &[rule("max_queued_size", "max_queued_bytes", Bytes)],
2052        );
2053        let name = endpoint
2054            .get("transport")
2055            .and_then(|transport| transport.get("name"))
2056            .and_then(Value::as_str)
2057            .map(str::to_string);
2058        if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
2059            match name.as_deref() {
2060                Some("file_input") => apply(
2061                    transport,
2062                    &[rule("buffer_size", "buffer_size_bytes", Bytes)],
2063                ),
2064                Some("dynamodb_output" | "postgres_output") => apply(
2065                    transport,
2066                    &[rule("max_buffer_size", "max_buffer_size_bytes", Bytes)],
2067                ),
2068                Some("postgres_cdc_input") => {
2069                    if let Some(batch) = child(transport, "batch") {
2070                        apply(batch, &[rule("max_size", "max_bytes", Bytes)]);
2071                    }
2072                }
2073                _ => {}
2074            }
2075        }
2076    }
2077
2078    let Some(global) = config.as_object_mut() else {
2079        return;
2080    };
2081    apply(
2082        global,
2083        &[
2084            rule("max_rss", "max_rss_mb", Megabytes),
2085            rule("datafusion_memory", "datafusion_memory_mb", Megabytes),
2086        ],
2087    );
2088    if let Some(storage) = child(global, "storage") {
2089        apply(
2090            storage,
2091            &[
2092                rule("cache_size", "cache_mib", Mebibytes),
2093                rule("min_spill_size", "min_storage_bytes", Bytes),
2094                rule("min_step_spill_size", "min_step_storage_bytes", Bytes),
2095            ],
2096        );
2097    }
2098    if let Some(resources) = child(global, "resources") {
2099        apply(
2100            resources,
2101            &[
2102                rule("memory_min", "memory_mb_min", Megabytes),
2103                rule("memory_max", "memory_mb_max", Megabytes),
2104                rule("storage_min", "storage_mb_min", Megabytes),
2105                rule("storage_max", "storage_mb_max", Megabytes),
2106            ],
2107        );
2108        if let Some(storage) = child(resources, "autoscaling").and_then(|a| child(a, "storage")) {
2109            apply(
2110                storage,
2111                &[rule(
2112                    "scale_threshold_available",
2113                    "scale_threshold_available_mb",
2114                    Megabytes,
2115                )],
2116            );
2117        }
2118    }
2119    if let Some(tweaks) = child(global, "dev_tweaks") {
2120        apply(
2121            tweaks,
2122            &[
2123                rule("storage_max", "storage_mb_max", Mebibytes),
2124                rule(
2125                    "fbuf_slab_size_per_class",
2126                    "fbuf_slab_bytes_per_class",
2127                    Bytes,
2128                ),
2129                rule(
2130                    "lazy_input_map_key_block_size",
2131                    "lazy_input_map_key_block_bytes",
2132                    Bytes,
2133                ),
2134                rule(
2135                    "exchange_channel_capacity",
2136                    "exchange_channel_capacity_bytes",
2137                    Bytes,
2138                ),
2139            ],
2140        );
2141    }
2142    for endpoints in ["inputs", "outputs"] {
2143        if let Some(endpoints) = child(global, endpoints) {
2144            for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
2145                connector(endpoint);
2146            }
2147        }
2148    }
2149}
2150
2151#[cfg(test)]
2152mod test {
2153    use super::deserialize_fault_tolerance;
2154    use crate::config::{
2155        ConnectorConfig, DEFAULT_CLOCK_RESOLUTION, DEFAULT_DATAFUSION_MEMORY_CEILING,
2156        DEFAULT_PULL_INTERVAL, DEFAULT_RETENTION_MIN_AGE, FileBackendConfig, FtConfig, FtModel,
2157        OutputBufferConfig, PipelineConfig, ResourceConfig, RuntimeConfig, StorageBackendConfig,
2158        StorageOptions, SyncConfig, TransportConfig,
2159    };
2160    use crate::duration::ConfigDuration;
2161    use crate::size::ConfigSize;
2162    use serde::{Deserialize, Serialize};
2163    use serde_json::json;
2164    use std::time::Duration;
2165
2166    /// Reads `value` as a `T`, writes it back, and reads that again: the
2167    /// configuration Feldera stores must load the way the one it was given did.
2168    fn assert_reloads<T>(value: serde_json::Value)
2169    where
2170        T: Serialize + for<'de> Deserialize<'de>,
2171    {
2172        let first: T = serde_json::from_value(value.clone())
2173            .unwrap_or_else(|e| panic!("{value} does not load: {e}"));
2174        let written = serde_json::to_value(&first).unwrap();
2175        let second: T = serde_json::from_value(written.clone()).unwrap_or_else(|e| {
2176            panic!("{value} is written as {written}, which does not load: {e}")
2177        });
2178        assert_eq!(serde_json::to_value(&second).unwrap(), written, "{value}");
2179    }
2180
2181    /// Every size setting reloads from what Feldera writes back, whatever the
2182    /// size. Zero, and a size no named unit divides, are written in bytes,
2183    /// and a setting that once counted megabytes refuses a string without a
2184    /// unit, so that form must carry one.
2185    #[test]
2186    fn size_settings_reload_from_what_is_written() {
2187        use crate::transport::dynamodb::DynamoDBWriterConfig;
2188        use crate::transport::file::FileInputConfig;
2189        use crate::transport::postgres::{PostgresCdcBatchConfig, PostgresWriterConfig};
2190
2191        // Under the earlier names, a bare number in the earlier unit, as
2192        // `datafusion_memory_mb: 0` or `cache_mib: 0`.
2193        for number in [0u64, 1, 1_100, u64::MAX] {
2194            assert_reloads::<RuntimeConfig>(json!({
2195                "max_rss_mb": number,
2196                "datafusion_memory_mb": number,
2197                "storage": {"cache_mib": number, "min_storage_bytes": number},
2198                "resources": {"memory_mb_min": number, "storage_mb_max": number},
2199                "dev_tweaks": {"storage_mb_max": number},
2200            }));
2201        }
2202
2203        let max = format!("{}B", u64::MAX);
2204        for size in ["0B", "1B", "999B", "1.1Gi", "1.1G", "16G", "8Gi", &max] {
2205            assert_reloads::<RuntimeConfig>(json!({
2206                "max_rss": size,
2207                "datafusion_memory": size,
2208                "storage": {
2209                    "cache_size": size,
2210                    "min_spill_size": size,
2211                    "min_step_spill_size": size,
2212                },
2213                "resources": {
2214                    "memory_min": size,
2215                    "memory_max": size,
2216                    "storage_min": size,
2217                    "storage_max": size,
2218                    "autoscaling": {"storage": {"scale_threshold_available": size}},
2219                },
2220                "dev_tweaks": {
2221                    "storage_max": size,
2222                    "fbuf_slab_size_per_class": size,
2223                    "exchange_channel_capacity": size,
2224                },
2225            }));
2226            assert_reloads::<ConnectorConfig>(json!({
2227                "transport": {
2228                    "name": "file_input",
2229                    "config": {"path": "input.csv", "buffer_size": size},
2230                },
2231                "max_queued_size": size,
2232            }));
2233            assert_reloads::<FileInputConfig>(json!({"path": "input.csv", "buffer_size": size}));
2234            assert_reloads::<PostgresCdcBatchConfig>(json!({"max_size": size}));
2235            assert_reloads::<PostgresWriterConfig>(json!({
2236                "uri": "postgres://localhost/db",
2237                "table": "t",
2238                "max_buffer_size": size,
2239            }));
2240            assert_reloads::<DynamoDBWriterConfig>(json!({
2241                "table": "t",
2242                "region": "us-east-1",
2243                "max_buffer_size": size,
2244            }));
2245        }
2246    }
2247
2248    /// A configuration written by an older version of Feldera carries no
2249    /// `soft_delete` field, and a connector that does not use soft deletes
2250    /// serializes exactly as it did before the field existed.  This keeps
2251    /// configurations readable and writable across versions.
2252    #[test]
2253    fn soft_delete_is_backward_compatible() {
2254        let config: ConnectorConfig = serde_json::from_value(json!({
2255            "transport": {"name": "empty_input"}
2256        }))
2257        .unwrap();
2258        assert!(!config.soft_delete);
2259
2260        let serialized = serde_json::to_value(&config).unwrap();
2261        assert_eq!(serialized.get("soft_delete"), None);
2262
2263        let config: ConnectorConfig = serde_json::from_value(json!({
2264            "transport": {"name": "empty_input"},
2265            "soft_delete": true
2266        }))
2267        .unwrap();
2268        assert!(config.soft_delete);
2269        assert_eq!(
2270            serde_json::to_value(&config).unwrap().get("soft_delete"),
2271            Some(&json!(true))
2272        );
2273    }
2274
2275    /// Soft deletes change how input is interpreted, so flipping the flag must
2276    /// count as a connector change even where flow-control settings do not.
2277    #[test]
2278    fn soft_delete_invalidates_checkpointed_connector_state() {
2279        let config = ConnectorConfig::new(TransportConfig::EmptyInput, None);
2280        let mut soft_delete = config.clone();
2281        soft_delete.soft_delete = true;
2282
2283        assert!(config.equal_for_input_checkpoint_replay(&config));
2284        assert!(!config.equal_for_input_checkpoint_replay(&soft_delete));
2285    }
2286
2287    fn config_with_name(name: Option<&str>) -> PipelineConfig {
2288        PipelineConfig {
2289            global: RuntimeConfig::default(),
2290            multihost: None,
2291            name: name.map(str::to_string),
2292            given_name: None,
2293            storage_config: None,
2294            secrets_dir: None,
2295            inputs: Default::default(),
2296            outputs: Default::default(),
2297            program_ir: None,
2298        }
2299    }
2300
2301    #[test]
2302    fn pipeline_identity_uses_system_and_given_names() {
2303        let mut config = config_with_name(Some("pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"));
2304        config.given_name = Some("my-pipeline".to_string());
2305
2306        let metadata = config.pipeline_identity().unwrap();
2307        assert_eq!(
2308            metadata.name,
2309            "pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"
2310        );
2311        assert_eq!(metadata.given_name.as_deref(), Some("my-pipeline"));
2312    }
2313
2314    #[test]
2315    fn pipeline_identity_is_none_without_system_name() {
2316        assert_eq!(config_with_name(None).pipeline_identity(), None);
2317    }
2318
2319    #[test]
2320    fn resolved_datafusion_memory_explicit_passes_through() {
2321        let config = RuntimeConfig {
2322            max_rss: Some(ConfigSize::from_mb(8_000)),
2323            datafusion_memory: Some(ConfigSize::from_mb(1_500)),
2324            ..Default::default()
2325        };
2326        assert_eq!(
2327            config.resolved_datafusion_memory(),
2328            Some(ConfigSize::from_mb(1_500))
2329        );
2330    }
2331
2332    #[test]
2333    fn effective_memory_is_the_smaller_budget() {
2334        let mb = |mb: Option<u64>| mb.map(ConfigSize::from_mb);
2335        for (max_rss, memory_max, expected) in [
2336            (None, None, None),
2337            (Some(8_000), None, Some(8_000)),
2338            (None, Some(4_000), Some(4_000)),
2339            (Some(8_000), Some(4_000), Some(4_000)),
2340            (Some(2_000), Some(4_000), Some(2_000)),
2341        ] {
2342            let config = RuntimeConfig {
2343                max_rss: mb(max_rss),
2344                resources: ResourceConfig {
2345                    memory_max: mb(memory_max),
2346                    ..Default::default()
2347                },
2348                ..Default::default()
2349            };
2350            assert_eq!(
2351                config.effective_memory(),
2352                mb(expected),
2353                "{max_rss:?}, {memory_max:?}"
2354            );
2355        }
2356    }
2357
2358    #[test]
2359    fn resolved_datafusion_memory_unconfigured_returns_none() {
2360        let config = RuntimeConfig::default();
2361        assert!(config.max_rss.is_none());
2362        assert!(config.resources.memory_max.is_none());
2363        assert_eq!(config.resolved_datafusion_memory(), None);
2364    }
2365
2366    #[test]
2367    fn resolved_datafusion_memory_small_budget_scales_down() {
2368        // Small pipelines must provision cleanly; the default just shrinks.
2369        let config = RuntimeConfig {
2370            max_rss: Some(ConfigSize::from_mb(256)),
2371            ..Default::default()
2372        };
2373        assert_eq!(
2374            config.resolved_datafusion_memory(),
2375            Some(ConfigSize::from_bytes(12_800_000))
2376        );
2377
2378        let config = RuntimeConfig {
2379            max_rss: Some(ConfigSize::from_mb(512)),
2380            ..Default::default()
2381        };
2382        assert_eq!(
2383            config.resolved_datafusion_memory(),
2384            Some(ConfigSize::from_bytes(25_600_000))
2385        );
2386    }
2387
2388    #[test]
2389    fn resolved_datafusion_memory_clamps_to_ceiling_for_large_budgets() {
2390        // 5% of 64 GB = 3.2 GB, above the 2 GB ceiling.
2391        let config = RuntimeConfig {
2392            max_rss: Some(ConfigSize::from_mb(64_000)),
2393            ..Default::default()
2394        };
2395        assert_eq!(
2396            config.resolved_datafusion_memory(),
2397            Some(DEFAULT_DATAFUSION_MEMORY_CEILING),
2398        );
2399    }
2400
2401    #[test]
2402    fn resolved_datafusion_memory_midrange_uses_five_percent() {
2403        // 5% of 16 GB = 800 MB, inside the clamp range.
2404        let config = RuntimeConfig {
2405            max_rss: Some(ConfigSize::from_mb(16_000)),
2406            ..Default::default()
2407        };
2408        assert_eq!(
2409            config.resolved_datafusion_memory(),
2410            Some(ConfigSize::from_mb(800))
2411        );
2412    }
2413
2414    #[test]
2415    fn resolved_datafusion_memory_falls_back_to_resources() {
2416        // No max_rss, but resources.memory_max is set.
2417        let config = RuntimeConfig {
2418            max_rss: None,
2419            resources: ResourceConfig {
2420                memory_max: Some(ConfigSize::from_mb(16_000)),
2421                ..Default::default()
2422            },
2423            ..Default::default()
2424        };
2425        assert_eq!(
2426            config.resolved_datafusion_memory(),
2427            Some(ConfigSize::from_mb(800))
2428        );
2429    }
2430
2431    #[test]
2432    fn ft_config() {
2433        #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
2434        #[serde(default)]
2435        struct Wrapper {
2436            #[serde(deserialize_with = "deserialize_fault_tolerance")]
2437            config: FtConfig,
2438        }
2439
2440        // Omitting FtConfig, or specifying null, or specifying model "none",
2441        // disables fault tolerance.
2442        for s in [
2443            "{}",
2444            r#"{"config": null}"#,
2445            r#"{"config": {"model": "none"}}"#,
2446        ] {
2447            let config: Wrapper = serde_json::from_str(s).unwrap();
2448            assert_eq!(config.config.model, None);
2449            assert_eq!(config.config.checkpoint_interval(), None);
2450        }
2451
2452        // Serializing disabled FT produces explicit "none" form.
2453        let s = serde_json::to_string(&Wrapper {
2454            config: FtConfig::default(),
2455        })
2456        .unwrap();
2457        assert!(s.contains("\"none\""));
2458
2459        // `{}` for FtConfig, or `{...}` with an interval but no `model`,
2460        // enables fault tolerance with a 60 second interval.
2461        for s in [
2462            r#"{}"#,
2463            r#"{"checkpoint_interval": "60s"}"#,
2464            r#"{"checkpoint_interval_secs": 60}"#,
2465        ] {
2466            let config = serde_json::from_str::<FtConfig>(s).unwrap();
2467            assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2468            assert_eq!(
2469                config.checkpoint_interval(),
2470                Some(Duration::from_secs(60)),
2471                "parsing {s}"
2472            );
2473        }
2474
2475        // An explicit `null` interval disables periodic checkpointing, under
2476        // the current name and under the deprecated one.
2477        for s in [
2478            r#"{"checkpoint_interval": null}"#,
2479            r#"{"checkpoint_interval_secs": null}"#,
2480        ] {
2481            let config = serde_json::from_str::<FtConfig>(s).unwrap();
2482            assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2483            assert_eq!(config.checkpoint_interval(), None, "parsing {s}");
2484        }
2485
2486        // Both spellings reach one field, so writing both is a duplicate, not
2487        // a contest one of them wins.
2488        let error = serde_json::from_str::<FtConfig>(
2489            r#"{"checkpoint_interval": "5m", "checkpoint_interval_secs": 10}"#,
2490        )
2491        .unwrap_err()
2492        .to_string();
2493        assert!(error.contains("duplicate field"), "{error}");
2494
2495        // The interval is clamped to between one second and one hour.
2496        for (json, expected_secs) in [
2497            (r#"{"checkpoint_interval": "1ms"}"#, 1),
2498            (r#"{"checkpoint_interval": "10h"}"#, 3600),
2499        ] {
2500            assert_eq!(
2501                serde_json::from_str::<FtConfig>(json)
2502                    .unwrap()
2503                    .checkpoint_interval(),
2504                Some(Duration::from_secs(expected_secs)),
2505                "parsing {json}"
2506            );
2507        }
2508    }
2509
2510    /// The configuration handed to a pinned runtime carries every duration
2511    /// setting under its older key, in the older unit, and nothing under the
2512    /// current names, which a runtime older than the rename ignores.
2513    #[test]
2514    fn legacy_duration_spelling_uses_the_older_keys() {
2515        let mut config = serde_json::json!({
2516            "workers": 2,
2517            "clock_resolution": "250ms",
2518            "max_buffering_delay": "3ms",
2519            "provisioning_timeout": "15m",
2520            "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2521            "storage": {"backend": {"name": "file", "config": {
2522                "ioop_latency": "5ms",
2523                "sync": {"bucket": "b", "standby_pull_interval": "10s",
2524                         "checkpoint_push_interval": "1h", "min_retention": "30d"}}}},
2525        });
2526        super::to_legacy_duration_spelling(&mut config);
2527        assert_eq!(
2528            config,
2529            serde_json::json!({
2530                "workers": 2,
2531                "clock_resolution_usecs": 250_000,
2532                "max_buffering_delay_usecs": 3_000,
2533                "provisioning_timeout_secs": 900,
2534                "fault_tolerance": {"model": "at_least_once", "checkpoint_interval_secs": 20},
2535                "storage": {"backend": {"name": "file", "config": {
2536                    "ioop_delay": 5,
2537                    "sync": {"bucket": "b", "pull_interval": 10,
2538                             "push_interval": 3_600, "retention_min_age": 30}}}},
2539            })
2540        );
2541    }
2542
2543    /// Every connector that has a duration setting, in the current spelling.
2544    fn pipeline_with_every_duration_connector() -> serde_json::Value {
2545        serde_json::json!({
2546            "name": "p",
2547            "clock_resolution": "250ms",
2548            "inputs": {
2549                "t.kafka": {"stream": "t", "transport": {"name": "kafka_input", "config": {
2550                    "topic": "t", "group_join_timeout": "30s"}}},
2551                "t.url": {"stream": "t", "transport": {"name": "url_input", "config": {
2552                    "path": "http://x", "pause_linger": "7s"}}},
2553                "t.nats": {"stream": "t", "transport": {"name": "nats_input", "config": {
2554                    "connection_config": {"server_url": "nats://x",
2555                        "connection_timeout": "5s", "request_timeout": "6s"},
2556                    "stream_name": "s",
2557                    "consumer_config": {"deliver_policy": "All", "max_expiry": "45.5s"},
2558                    "inactivity_timeout": "90s", "retry_interval": "3s"}}},
2559                "t.pubsub": {"stream": "t", "transport": {"name": "pub_sub_input", "config": {
2560                    "subscription": "s", "timeout": "20s", "connect_timeout": "4s"}}},
2561            },
2562            "outputs": {
2563                "v.kafka": {"stream": "v",
2564                    "transport": {"name": "kafka_output", "config": {
2565                        "topic": "v", "initialization_timeout": "40s"}},
2566                    "format": {"name": "avro", "config": {"registry_urls": ["http://r"],
2567                        "registry_timeout": "8s"}},
2568                    "enable_output_buffer": true,
2569                    "max_output_buffer_time": "500ms"},
2570                "v.nats": {"stream": "v", "transport": {"name": "nats_output", "config": {
2571                    "connection_config": {"server_url": "nats://x",
2572                        "connection_timeout": "5s", "request_timeout": "6s"},
2573                    "subject": "s", "publish_timeout": "9s"}}},
2574            },
2575        })
2576    }
2577
2578    /// Connectors are rewritten too, each under the key and in the unit its
2579    /// transport used before the rename; the NATS expiry becomes the
2580    /// `{secs, nanos}` object it was.
2581    #[test]
2582    fn legacy_duration_spelling_rewrites_every_connector() {
2583        let mut config = pipeline_with_every_duration_connector();
2584        super::to_legacy_duration_spelling(&mut config);
2585        let i = &config["inputs"];
2586        assert_eq!(
2587            i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2588            30
2589        );
2590        assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 7);
2591        let nats = &i["t.nats"]["transport"]["config"];
2592        assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2593        assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2594        assert_eq!(nats["inactivity_timeout_secs"], 90);
2595        assert_eq!(nats["retry_interval_secs"], 3);
2596        assert_eq!(
2597            nats["consumer_config"]["max_expires"],
2598            serde_json::json!({"secs": 45, "nanos": 500_000_000})
2599        );
2600        let pubsub = &i["t.pubsub"]["transport"]["config"];
2601        assert_eq!(pubsub["timeout_seconds"], 20);
2602        assert_eq!(pubsub["connect_timeout_seconds"], 4);
2603        let out = &config["outputs"]["v.kafka"];
2604        assert_eq!(
2605            out["transport"]["config"]["initialization_timeout_secs"],
2606            40
2607        );
2608        assert_eq!(out["format"]["config"]["registry_timeout_secs"], 8);
2609        assert_eq!(out["max_output_buffer_time_millis"], 500);
2610        let nats = &config["outputs"]["v.nats"]["transport"]["config"];
2611        assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2612        assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2613        assert_eq!(nats["publish_timeout_secs"], 9);
2614
2615        // No current name survives anywhere in the file.
2616        let text = config.to_string();
2617        for new in [
2618            "\"group_join_timeout\"",
2619            "\"pause_linger\"",
2620            "\"connection_timeout\"",
2621            "\"request_timeout\"",
2622            "\"inactivity_timeout\"",
2623            "\"retry_interval\"",
2624            "\"max_expiry\"",
2625            "\"timeout\"",
2626            "\"connect_timeout\"",
2627            "\"initialization_timeout\"",
2628            "\"registry_timeout\"",
2629            "\"max_output_buffer_time\"",
2630            "\"publish_timeout\"",
2631            "\"clock_resolution\"",
2632        ] {
2633            assert!(!text.contains(new), "{new} survived in {text}");
2634        }
2635    }
2636
2637    /// The rewritten connectors mean the same to this release as the originals.
2638    #[test]
2639    fn legacy_duration_spelling_round_trips_connectors() {
2640        let original: PipelineConfig =
2641            serde_json::from_value(pipeline_with_every_duration_connector()).unwrap();
2642        let mut value = serde_json::to_value(&original).unwrap();
2643        super::to_legacy_duration_spelling(&mut value);
2644        let mut reread: PipelineConfig = serde_json::from_value(value).unwrap();
2645
2646        // The format config stays raw JSON until the encoder parses it, so
2647        // compare it the way the encoder reads it.
2648        let registry = |config: &PipelineConfig| {
2649            let format = config.outputs["v.kafka"]
2650                .connector_config
2651                .format
2652                .clone()
2653                .unwrap();
2654            serde_json::from_value::<crate::format::avro::AvroEncoderConfig>(format.config)
2655                .unwrap()
2656                .registry_config
2657                .registry_timeout
2658        };
2659        assert_eq!(registry(&reread), registry(&original));
2660        let mut original = original;
2661        for config in [&mut reread, &mut original] {
2662            config
2663                .outputs
2664                .get_mut("v.kafka")
2665                .unwrap()
2666                .connector_config
2667                .format = None;
2668        }
2669        assert_eq!(reread, original);
2670    }
2671
2672    /// A duration too long for the older field is capped at the largest value
2673    /// it holds, rather than wrapping; a bare number already under the current
2674    /// key keeps its value, since it already counts the older unit.
2675    #[test]
2676    fn legacy_duration_spelling_caps_and_keeps_bare_numbers() {
2677        let mut config = serde_json::json!({
2678            "inputs": {
2679                "t.kafka": {"transport": {"name": "kafka_input", "config": {
2680                    "group_join_timeout": "100000000000s"}}},
2681                "t.url": {"transport": {"name": "url_input", "config": {"pause_linger": 9}}},
2682            },
2683            "storage": {"backend": {"name": "file", "config": {
2684                "sync": {"min_retention": "100000000000d"}}}},
2685        });
2686        super::to_legacy_duration_spelling(&mut config);
2687        let i = &config["inputs"];
2688        assert_eq!(
2689            i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2690            u64::from(u32::MAX)
2691        );
2692        assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 9);
2693        assert_eq!(
2694            config["storage"]["backend"]["config"]["sync"]["retention_min_age"],
2695            u64::from(u32::MAX)
2696        );
2697    }
2698
2699    /// The older spelling means the same settings to this release, so the
2700    /// rewrite changes what an older runtime reads without changing what a
2701    /// newer one does.
2702    #[test]
2703    fn legacy_duration_spelling_round_trips() {
2704        let original: RuntimeConfig = serde_json::from_value(serde_json::json!({
2705            "clock_resolution": "250ms",
2706            "max_buffering_delay": "3ms",
2707            "provisioning_timeout": "15m",
2708            "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2709        }))
2710        .unwrap();
2711        let mut value = serde_json::to_value(&original).unwrap();
2712        super::to_legacy_duration_spelling(&mut value);
2713        let reread: RuntimeConfig = serde_json::from_value(value).unwrap();
2714        assert_eq!(reread.clock_resolution(), original.clock_resolution());
2715        assert_eq!(reread.max_buffering_delay(), original.max_buffering_delay());
2716        assert_eq!(reread.provisioning_timeout, original.provisioning_timeout);
2717        assert_eq!(
2718            reread.fault_tolerance.checkpoint_interval(),
2719            original.fault_tolerance.checkpoint_interval()
2720        );
2721    }
2722
2723    /// Durations that are not a whole number of the older unit round up, so a
2724    /// short timeout never becomes a zero one; a disabled checkpoint stays
2725    /// disabled; an unset required field is dropped rather than written as
2726    /// `null`; a value that does not parse is left for the runtime to reject.
2727    #[test]
2728    fn legacy_duration_spelling_edge_cases() {
2729        let mut config = serde_json::json!({
2730            "max_buffering_delay": null,
2731            "provisioning_timeout": "1.5s",
2732            "fault_tolerance": {"checkpoint_interval": null},
2733            "clock_resolution": "10sec",
2734            "storage": {"backend": {"name": "file", "config": {
2735                "ioop_latency": "400us",
2736                "sync": {"bucket": "b", "min_retention": "11h", "standby_pull_interval": "400ms"}}}},
2737        });
2738        super::to_legacy_duration_spelling(&mut config);
2739        assert_eq!(
2740            config,
2741            serde_json::json!({
2742                "provisioning_timeout_secs": 2,
2743                "fault_tolerance": {"checkpoint_interval_secs": null},
2744                "clock_resolution": "10sec",
2745                "storage": {"backend": {"name": "file", "config": {
2746                    "ioop_delay": 1,
2747                    "sync": {"bucket": "b", "retention_min_age": 1, "pull_interval": 1}}}},
2748            })
2749        );
2750
2751        // A zero stays a zero: only a positive duration is pushed up to one unit.
2752        let mut zero = serde_json::json!({"provisioning_timeout": "0"});
2753        super::to_legacy_duration_spelling(&mut zero);
2754        assert_eq!(zero, serde_json::json!({"provisioning_timeout_secs": 0}));
2755
2756        // Already in the older spelling: nothing to do.
2757        let legacy = serde_json::json!({"clock_resolution_usecs": 5, "workers": 1});
2758        let mut again = legacy.clone();
2759        super::to_legacy_duration_spelling(&mut again);
2760        assert_eq!(again, legacy);
2761    }
2762
2763    /// The configuration handed to a runtime from before the size rename
2764    /// carries every size setting under its older key, as a whole number of
2765    /// the older unit rounded up, and nothing under the current names.
2766    #[test]
2767    fn legacy_size_spelling_uses_the_older_keys() {
2768        let mut config = serde_json::json!({
2769            "workers": 2,
2770            "max_rss": "16G",
2771            "datafusion_memory": "1.5G",
2772            "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi", "min_step_spill_size": "0"},
2773            "resources": {
2774                "memory_min": "4G", "memory_max": "16Gi",
2775                "storage_min": "100G", "storage_max": "400Gi",
2776                "autoscaling": {"storage": {"scale_threshold_available": "10G", "scale_factor": 2.0}}
2777            },
2778            "dev_tweaks": {
2779                "storage_max": "1Gi", "fbuf_slab_size_per_class": "16Mi",
2780                "lazy_input_map_key_block_size": "32Ki", "exchange_channel_capacity": "10M"
2781            },
2782            "inputs": {
2783                "t.file": {"stream": "t", "max_queued_size": "1Mi",
2784                    "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}},
2785                "t.cdc": {"stream": "t",
2786                    "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_size": "32Mi"}}}},
2787            },
2788            "outputs": {
2789                "v.ddb": {"stream": "v",
2790                    "transport": {"name": "dynamodb_output", "config": {"max_buffer_size": "1Mi"}}},
2791                "v.pg": {"stream": "v",
2792                    "transport": {"name": "postgres_output", "config": {"max_buffer_size": "2Mi"}}},
2793            },
2794        });
2795        super::to_legacy_size_spelling(&mut config);
2796        assert_eq!(
2797            config,
2798            serde_json::json!({
2799                "workers": 2,
2800                "max_rss_mb": 16_000,
2801                "datafusion_memory_mb": 1_500,
2802                "storage": {"cache_mib": 4096, "min_storage_bytes": 10 * 1024 * 1024, "min_step_storage_bytes": 0},
2803                "resources": {
2804                    // 16Gi and 400Gi are not whole megabytes: they round up.
2805                    "memory_mb_min": 4_000, "memory_mb_max": 17_180,
2806                    "storage_mb_min": 100_000, "storage_mb_max": 429_497,
2807                    "autoscaling": {"storage": {"scale_threshold_available_mb": 10_000, "scale_factor": 2.0}}
2808                },
2809                "dev_tweaks": {
2810                    "storage_mb_max": 1024, "fbuf_slab_bytes_per_class": 16 * 1024 * 1024,
2811                    "lazy_input_map_key_block_bytes": 32 * 1024, "exchange_channel_capacity_bytes": 10_000_000
2812                },
2813                "inputs": {
2814                    "t.file": {"stream": "t", "max_queued_bytes": 1024 * 1024,
2815                        "transport": {"name": "file_input", "config": {"path": "x", "buffer_size_bytes": 64 * 1024}}},
2816                    "t.cdc": {"stream": "t",
2817                        "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_bytes": 32 * 1024 * 1024}}}},
2818                },
2819                "outputs": {
2820                    "v.ddb": {"stream": "v",
2821                        "transport": {"name": "dynamodb_output", "config": {"max_buffer_size_bytes": 1024 * 1024}}},
2822                    "v.pg": {"stream": "v",
2823                        "transport": {"name": "postgres_output", "config": {"max_buffer_size_bytes": 2 * 1024 * 1024}}},
2824                },
2825            })
2826        );
2827    }
2828
2829    /// The older size spelling means the same settings to this release, so a
2830    /// configuration survives the trip out to a pinned runtime and back.
2831    #[test]
2832    fn legacy_size_spelling_round_trips() {
2833        let config: PipelineConfig = serde_json::from_value(serde_json::json!({
2834            "name": "p",
2835            "max_rss": "16G",
2836            // Whole megabytes, mebibytes and bytes: a size the older unit
2837            // cannot express rounds up and does not come back the same.
2838            "datafusion_memory": "1G",
2839            "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi"},
2840            "resources": {"memory_max": "16G", "storage_max": "400G"},
2841            "dev_tweaks": {"lazy_input_map_key_block_size": "32Ki"},
2842            "inputs": {"t.file": {"stream": "t", "max_queued_size": "1Mi",
2843                "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}}},
2844            "outputs": {},
2845        }))
2846        .unwrap();
2847        let mut value = serde_json::to_value(&config).unwrap();
2848        super::to_legacy_size_spelling(&mut value);
2849        assert_eq!(value["max_rss_mb"], serde_json::json!(16_000));
2850        assert_eq!(
2851            value["inputs"]["t.file"]["max_queued_bytes"],
2852            serde_json::json!(1024 * 1024)
2853        );
2854        let reread: PipelineConfig = serde_json::from_value(value).unwrap();
2855        assert_eq!(reread, config);
2856    }
2857
2858    /// The executors rewrite only what the runtime needs: a runtime from
2859    /// between the two renames gets the current durations and the older sizes.
2860    #[test]
2861    fn legacy_spelling_applies_each_rename_separately() {
2862        let current = serde_json::json!({"clock_resolution": "1s", "max_rss": "16G"});
2863        let mut both = current.clone();
2864        super::LegacySpelling {
2865            durations: true,
2866            sizes: true,
2867        }
2868        .apply(&mut both);
2869        assert_eq!(
2870            both,
2871            serde_json::json!({"clock_resolution_usecs": 1_000_000, "max_rss_mb": 16_000})
2872        );
2873        let mut sizes_only = current.clone();
2874        super::LegacySpelling {
2875            durations: false,
2876            sizes: true,
2877        }
2878        .apply(&mut sizes_only);
2879        assert_eq!(
2880            sizes_only,
2881            serde_json::json!({"clock_resolution": "1s", "max_rss_mb": 16_000})
2882        );
2883        let mut none = current.clone();
2884        super::LegacySpelling::NONE.apply(&mut none);
2885        assert_eq!(none, current);
2886        assert!(!super::LegacySpelling::NONE.any());
2887    }
2888
2889    #[test]
2890    fn legacy_size_spelling_edge_cases() {
2891        // A value that does not parse stays under the current key, for the
2892        // runtime to reject, and a `null` meant "unset" under either key.
2893        let mut config = serde_json::json!({
2894            "max_rss": "lots",
2895            "resources": {"memory_max": null, "memory_min": 4000}
2896        });
2897        super::to_legacy_size_spelling(&mut config);
2898        assert_eq!(
2899            config,
2900            serde_json::json!({"max_rss": "lots", "resources": {"memory_mb_min": 4000}})
2901        );
2902
2903        // A fraction of the older unit rounds up, so a small cap never
2904        // becomes a `0` the older runtime reads as no cap.
2905        let mut small = serde_json::json!({"max_rss": "1"});
2906        super::to_legacy_size_spelling(&mut small);
2907        assert_eq!(small, serde_json::json!({"max_rss_mb": 1}));
2908
2909        // Already in the older spelling: nothing to do.
2910        let legacy = serde_json::json!({"max_rss_mb": 5, "workers": 1});
2911        let mut again = legacy.clone();
2912        super::to_legacy_size_spelling(&mut again);
2913        assert_eq!(again, legacy);
2914    }
2915
2916    /// A connector nobody touched compares equal across the rename.
2917    ///
2918    /// A configuration stored by an older release carries each duration at its
2919    /// default, because the fields it used could not be absent. A freshly
2920    /// parsed one leaves them out. Both mean the same thing, and the diff that
2921    /// decides whether to keep a connector's checkpointed position has to agree
2922    /// with that: otherwise the connector reads as modified and the controller
2923    /// restarts its ingestion from the beginning.
2924    #[test]
2925    fn a_stored_default_matches_an_omitted_one() {
2926        let stored: ConnectorConfig = serde_json::from_value(serde_json::json!({
2927            "transport": {
2928                "name": "url_input",
2929                "config": {"path": "http://example.com/x", "pause_timeout": 60},
2930            }
2931        }))
2932        .unwrap();
2933        let fresh: ConnectorConfig = serde_json::from_value(serde_json::json!({
2934            "transport": {
2935                "name": "url_input",
2936                "config": {"path": "http://example.com/x"},
2937            }
2938        }))
2939        .unwrap();
2940
2941        // The two differ field by field, which is what the derived `PartialEq`
2942        // sees, yet they configure the same connector.
2943        assert_ne!(stored, fresh);
2944        assert!(stored.equal_for_input_checkpoint_replay(&fresh));
2945
2946        // A real difference still reads as one.
2947        let changed: ConnectorConfig = serde_json::from_value(serde_json::json!({
2948            "transport": {
2949                "name": "url_input",
2950                "config": {"path": "http://example.com/x", "pause_linger": "90s"},
2951            }
2952        }))
2953        .unwrap();
2954        assert!(!stored.equal_for_input_checkpoint_replay(&changed));
2955    }
2956
2957    /// An Avro schema registry timeout compares equal across the rename.
2958    ///
2959    /// The format configuration stays raw JSON until the format parses it, so
2960    /// the connector comparison has to read the timeout the way the format
2961    /// does: otherwise following the deprecation warning, from
2962    /// `registry_timeout_secs: 10` to `registry_timeout: "10s"`, reads as a
2963    /// modified connector and an Avro input is read again from the beginning.
2964    #[test]
2965    fn an_avro_registry_timeout_compares_equal_across_the_rename() {
2966        let connector = |registry: serde_json::Value| -> ConnectorConfig {
2967            let mut format = serde_json::json!({"registry_urls": ["http://registry:8081"]});
2968            format
2969                .as_object_mut()
2970                .unwrap()
2971                .extend(registry.as_object().unwrap().clone());
2972            serde_json::from_value(serde_json::json!({
2973                "transport": {
2974                    "name": "url_input",
2975                    "config": {"path": "http://example.com/x"},
2976                },
2977                "format": {"name": "avro", "config": format},
2978            }))
2979            .unwrap()
2980        };
2981        let stored = connector(serde_json::json!({"registry_timeout_secs": 10}));
2982        let current = connector(serde_json::json!({"registry_timeout": "10s"}));
2983        let spelled_out = connector(serde_json::json!({"registry_timeout": "10000ms"}));
2984        let changed = connector(serde_json::json!({"registry_timeout": "11s"}));
2985        let unset = connector(serde_json::json!({}));
2986
2987        assert!(stored.equal_modulo_paused(&current));
2988        assert!(stored.equal_for_input_checkpoint_replay(&current));
2989        assert!(current.equal_modulo_paused(&spelled_out));
2990        assert!(!stored.equal_modulo_paused(&changed));
2991        assert!(!stored.equal_modulo_paused(&unset));
2992        // The other formats carry no duration and are left alone.
2993        let json: ConnectorConfig = serde_json::from_value(serde_json::json!({
2994            "transport": {"name": "url_input", "config": {"path": "http://example.com/x"}},
2995            "format": {"name": "json", "config": {"registry_timeout_secs": 10}},
2996        }))
2997        .unwrap();
2998        assert!(!json.equal_modulo_paused(&stored));
2999    }
3000
3001    /// The defaults an older release wrote out still load.
3002    ///
3003    /// `max_output_buffer_time_millis` defaulted to `usize::MAX` and was
3004    /// serialized into every output connector, so scaling it into nanoseconds
3005    /// has to survive rather than reject the configuration.
3006    #[test]
3007    fn the_largest_legacy_defaults_still_load() {
3008        let buffer: OutputBufferConfig = serde_json::from_value(serde_json::json!({
3009            "enable_output_buffer": false,
3010            "max_output_buffer_time_millis": u64::MAX,
3011            "max_output_buffer_size_records": 10_000_000u64,
3012        }))
3013        .unwrap();
3014        assert_eq!(
3015            buffer.max_output_buffer_time,
3016            Some(ConfigDuration::from_millis(u64::MAX))
3017        );
3018
3019        // The widest legacy unit, days, also survives.
3020        let sync: SyncConfig =
3021            serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 4000000000}"#).unwrap();
3022        assert_eq!(
3023            sync.min_retention(),
3024            ConfigDuration::from_days(4_000_000_000)
3025        );
3026    }
3027
3028    /// A legacy number too large for a `u64` of seconds saturates at the
3029    /// longest duration there is rather than failing to load: an older
3030    /// release accepted it.
3031    #[test]
3032    fn a_legacy_number_past_u64_seconds_saturates() {
3033        let sync: SyncConfig =
3034            serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 18446744073709551615}"#)
3035                .unwrap();
3036        assert_eq!(
3037            sync.min_retention(),
3038            ConfigDuration::from(std::time::Duration::MAX)
3039        );
3040    }
3041
3042    /// Kafka input and NATS connectors stored by an older release carry their
3043    /// duration defaults spelled out; a fresh configuration leaves them out.
3044    /// The checkpoint replay comparison must see the two as the same connector.
3045    #[test]
3046    fn spelled_out_defaults_match_for_kafka_input_and_nats() {
3047        fn connector(value: serde_json::Value) -> ConnectorConfig {
3048            serde_json::from_value(value).unwrap()
3049        }
3050        fn secs(duration: ConfigDuration) -> u64 {
3051            std::time::Duration::from(duration).as_secs()
3052        }
3053        let fresh_kafka = connector(serde_json::json!({
3054            "transport": {"name": "kafka_input", "config": {"topic": "t"}}}));
3055        let TransportConfig::KafkaInput(kafka) = &fresh_kafka.transport else {
3056            unreachable!()
3057        };
3058        let stored_kafka = connector(serde_json::json!({
3059            "transport": {"name": "kafka_input", "config": {
3060                "topic": "t",
3061                "group_join_timeout_secs": secs(kafka.group_join_timeout())}}}));
3062        assert_ne!(stored_kafka, fresh_kafka);
3063        assert!(stored_kafka.equal_for_input_checkpoint_replay(&fresh_kafka));
3064
3065        let base = serde_json::json!({
3066            "connection_config": {"server_url": "nats://x"},
3067            "stream_name": "s",
3068            "consumer_config": {"deliver_policy": "All"}});
3069        let fresh_nats = connector(serde_json::json!({
3070            "transport": {"name": "nats_input", "config": base.clone()}}));
3071        let TransportConfig::NatsInput(nats) = &fresh_nats.transport else {
3072            unreachable!()
3073        };
3074        let mut spelled_out = base;
3075        spelled_out["inactivity_timeout_secs"] = secs(nats.inactivity_timeout()).into();
3076        spelled_out["retry_interval_secs"] = secs(nats.retry_interval()).into();
3077        spelled_out["connection_config"]["connection_timeout_secs"] =
3078            secs(nats.connection_config.connection_timeout()).into();
3079        spelled_out["connection_config"]["request_timeout_secs"] =
3080            secs(nats.connection_config.request_timeout()).into();
3081        let stored_nats = connector(serde_json::json!({
3082            "transport": {"name": "nats_input", "config": spelled_out}}));
3083        assert_ne!(stored_nats, fresh_nats);
3084        assert!(stored_nats.equal_for_input_checkpoint_replay(&fresh_nats));
3085    }
3086
3087    /// A configuration written before the rename converts itself: the manager
3088    /// deserializes it and writes it back (`validate_runtime_config`, then
3089    /// `serde_json::to_value`), so the superseded keys disappear and the
3090    /// current ones take their place with the same lengths of time. Only then
3091    /// does the pipeline stop warning about a configuration nobody has edited.
3092    #[test]
3093    fn superseded_keys_are_normalised_by_a_round_trip() {
3094        let stored = serde_json::json!({
3095            "workers": 4,
3096            "clock_resolution_usecs": 100_000,
3097            "max_buffering_delay_usecs": 0,
3098            "provisioning_timeout_secs": 300,
3099        });
3100
3101        let config: RuntimeConfig = serde_json::from_value(stored).unwrap();
3102        let written = serde_json::to_value(&config).unwrap();
3103
3104        assert_eq!(written["clock_resolution"], "100ms");
3105        assert_eq!(written["max_buffering_delay"], "0s");
3106        assert_eq!(written["provisioning_timeout"], "5m");
3107        for superseded in [
3108            "clock_resolution_usecs",
3109            "max_buffering_delay_usecs",
3110            "provisioning_timeout_secs",
3111        ] {
3112            assert!(
3113                written.get(superseded).is_none(),
3114                "`{superseded}` survived the round trip: {written}"
3115            );
3116        }
3117
3118        // The round trip is a fixed point: reading what was written back gives
3119        // the same document, so a configuration converts once and then settles.
3120        let reparsed: RuntimeConfig = serde_json::from_value(written.clone()).unwrap();
3121        assert_eq!(serde_json::to_value(&reparsed).unwrap(), written);
3122    }
3123
3124    /// The simulated per-I/O delay reads back from both spellings. Its
3125    /// superseded name counted milliseconds, one of only two settings that
3126    /// did, so the unit is worth pinning: `ioop_delay: 5` is five
3127    /// milliseconds, not five seconds.
3128    #[test]
3129    fn ioop_latency_accepts_both_spellings() {
3130        for (json, expected) in [
3131            (r#"{"name": "file", "config": {}}"#, None),
3132            (
3133                r#"{"name": "file", "config": {"ioop_latency": "5ms"}}"#,
3134                Some(ConfigDuration::from_millis(5)),
3135            ),
3136            (
3137                r#"{"name": "file", "config": {"ioop_delay": 5}}"#,
3138                Some(ConfigDuration::from_millis(5)),
3139            ),
3140            (
3141                r#"{"name": "file", "config": {"ioop_latency": "1s"}}"#,
3142                Some(ConfigDuration::from_secs(1)),
3143            ),
3144        ] {
3145            let backend: StorageBackendConfig = serde_json::from_str(json).unwrap();
3146            let StorageBackendConfig::File(file) = backend else {
3147                panic!("expected the file backend, parsing {json}");
3148            };
3149            assert_eq!(file.ioop_latency, expected, "parsing {json}");
3150        }
3151    }
3152
3153    /// The clock resolution reads back from both the current field and the one
3154    /// it deprecates. An explicit `null` selects the default, which is what the
3155    /// deprecated field did before it gained a replacement.
3156    #[test]
3157    fn clock_resolution_falls_back_to_the_deprecated_field() {
3158        for (json, expected) in [
3159            (r#"{}"#, DEFAULT_CLOCK_RESOLUTION),
3160            (
3161                r#"{"clock_resolution": "100ms"}"#,
3162                ConfigDuration::from_millis(100),
3163            ),
3164            (
3165                r#"{"clock_resolution_usecs": 100000}"#,
3166                ConfigDuration::from_millis(100),
3167            ),
3168            (r#"{"clock_resolution": null}"#, DEFAULT_CLOCK_RESOLUTION),
3169            (
3170                r#"{"clock_resolution_usecs": null}"#,
3171                DEFAULT_CLOCK_RESOLUTION,
3172            ),
3173        ] {
3174            assert_eq!(
3175                serde_json::from_str::<RuntimeConfig>(json)
3176                    .unwrap()
3177                    .clock_resolution(),
3178                expected,
3179                "parsing {json}"
3180            );
3181        }
3182    }
3183
3184    /// Every duration field reads back from the field it deprecates, in the
3185    /// unit that field used.
3186    #[test]
3187    fn deprecated_duration_fields_still_work() {
3188        let runtime: RuntimeConfig = serde_json::from_str(
3189            r#"{"max_buffering_delay_usecs": 5000, "provisioning_timeout_secs": 1200}"#,
3190        )
3191        .unwrap();
3192        assert_eq!(
3193            runtime.max_buffering_delay(),
3194            ConfigDuration::from_millis(5)
3195        );
3196        assert_eq!(
3197            runtime.provisioning_timeout,
3198            Some(ConfigDuration::from_secs(1200))
3199        );
3200
3201        let sync: SyncConfig = serde_json::from_str(
3202            r#"{"bucket": "b", "pull_interval": 30, "push_interval": 300, "retention_min_age": 7}"#,
3203        )
3204        .unwrap();
3205        assert_eq!(sync.standby_pull_interval(), ConfigDuration::from_secs(30));
3206        assert_eq!(
3207            sync.checkpoint_push_interval(),
3208            Some(ConfigDuration::from_secs(300))
3209        );
3210        assert_eq!(sync.min_retention(), ConfigDuration::from_days(7));
3211
3212        let storage: FileBackendConfig = serde_json::from_str(r#"{"ioop_delay": 5}"#).unwrap();
3213        assert_eq!(storage.ioop_latency, Some(ConfigDuration::from_millis(5)));
3214
3215        let buffer: OutputBufferConfig =
3216            serde_json::from_str(r#"{"max_output_buffer_time_millis": 250}"#).unwrap();
3217        assert_eq!(
3218            buffer.max_output_buffer_time(),
3219            ConfigDuration::from_millis(250)
3220        );
3221    }
3222
3223    /// Defaults apply when neither the current field nor the deprecated one is
3224    /// set.
3225    #[test]
3226    fn duration_fields_default_when_unset() {
3227        let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "b"}"#).unwrap();
3228        assert_eq!(sync.standby_pull_interval(), DEFAULT_PULL_INTERVAL);
3229        assert_eq!(sync.checkpoint_push_interval(), None);
3230        assert_eq!(sync.min_retention(), DEFAULT_RETENTION_MIN_AGE);
3231
3232        let runtime = RuntimeConfig::default();
3233        assert_eq!(runtime.max_buffering_delay(), ConfigDuration::ZERO);
3234        assert_eq!(runtime.clock_resolution(), DEFAULT_CLOCK_RESOLUTION);
3235        assert_eq!(runtime.provisioning_timeout, None);
3236    }
3237
3238    /// Regression test: `Option<f64>` fields inside `StorageOptions` must
3239    /// survive a JSON-string round-trip through `PipelineConfig`, which uses
3240    /// `#[serde(flatten)]` on `RuntimeConfig`.
3241    #[test]
3242    fn storage_options_f64_roundtrip_through_pipeline_config() {
3243        let pc = PipelineConfig {
3244            global: RuntimeConfig {
3245                storage: Some(StorageOptions {
3246                    bloom_false_positive_rate: Some(0.01),
3247                    ..Default::default()
3248                }),
3249                ..Default::default()
3250            },
3251            multihost: None,
3252            name: Some("test-pipeline".into()),
3253            given_name: None,
3254            storage_config: None,
3255            secrets_dir: None,
3256            inputs: Default::default(),
3257            outputs: Default::default(),
3258            program_ir: None,
3259        };
3260
3261        // JSON string round-trip (the path the pipeline process takes).
3262        let json = serde_json::to_string_pretty(&pc).unwrap();
3263        let pc2: PipelineConfig = serde_json::from_str(&json).expect(
3264            "JSON string round-trip of PipelineConfig with f64 StorageOptions must succeed",
3265        );
3266        assert_eq!(
3267            pc2.global.storage.unwrap().bloom_false_positive_rate,
3268            Some(0.01)
3269        );
3270
3271        // serde_json::Value round-trip (the path the pipeline manager takes).
3272        let value = serde_json::to_value(&pc).unwrap();
3273        let pc3: PipelineConfig = serde_json::from_value(value)
3274            .expect("Value round-trip of PipelineConfig with f64 StorageOptions must succeed");
3275        assert_eq!(
3276            pc3.global.storage.unwrap().bloom_false_positive_rate,
3277            Some(0.01)
3278        );
3279    }
3280}
3281
3282impl FtConfig {
3283    pub fn is_enabled(&self) -> bool {
3284        self.model.is_some()
3285    }
3286
3287    /// Returns the checkpoint interval, if fault tolerance is enabled, and
3288    /// otherwise `None`.
3289    ///
3290    /// Falls back to the deprecated `checkpoint_interval_secs` and then to
3291    /// [`DEFAULT_CHECKPOINT_INTERVAL`]. The interval is clamped to between one
3292    /// second and one hour.
3293    pub fn checkpoint_interval(&self) -> Option<Duration> {
3294        if !self.is_enabled() {
3295            return None;
3296        }
3297
3298        let interval = self
3299            .checkpoint_interval
3300            .unwrap_or(Some(DEFAULT_CHECKPOINT_INTERVAL))?;
3301
3302        Some(Duration::from(interval).clamp(Duration::from_secs(1), Duration::from_secs(3600)))
3303    }
3304}
3305
3306/// Serde implementation for de/serializing a string into `Option<T>` where
3307/// `"none"` indicates `None` and any other string indicates `Some`.
3308///
3309/// This could be extended to handle non-strings by adding more forwarding
3310/// `visit_*` methods to the Visitor implementation.  I don't see a way to write
3311/// them automatically.
3312mod none_as_string {
3313    use std::marker::PhantomData;
3314
3315    use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
3316    use serde::ser::{Serialize, Serializer};
3317
3318    pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
3319    where
3320        S: Serializer,
3321        T: Serialize,
3322    {
3323        match value.as_ref() {
3324            Some(value) => value.serialize(serializer),
3325            None => "none".serialize(serializer),
3326        }
3327    }
3328
3329    struct NoneAsString<T>(PhantomData<fn() -> T>);
3330
3331    impl<'de, T> Visitor<'de> for NoneAsString<T>
3332    where
3333        T: Deserialize<'de>,
3334    {
3335        type Value = Option<T>;
3336
3337        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
3338            formatter.write_str("string")
3339        }
3340
3341        fn visit_none<E>(self) -> Result<Self::Value, E>
3342        where
3343            E: serde::de::Error,
3344        {
3345            Ok(None)
3346        }
3347
3348        fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
3349        where
3350            E: serde::de::Error,
3351        {
3352            if &value.to_ascii_lowercase() == "none" {
3353                Ok(None)
3354            } else {
3355                Ok(Some(T::deserialize(value.into_deserializer())?))
3356            }
3357        }
3358    }
3359
3360    pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
3361    where
3362        D: Deserializer<'de>,
3363        T: Deserialize<'de>,
3364    {
3365        deserializer.deserialize_str(NoneAsString(PhantomData))
3366    }
3367}
3368
3369/// Generates an OpenAPI schema for an `Option<T>` field serialized with `none_as_string`.
3370/// The schema is a `oneOf` with a reference to `T`'s schema and a `"none"` string enum.
3371fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
3372    Schema::OneOf(
3373        OneOfBuilder::new()
3374            .item(RefOr::Ref(Ref::new(format!(
3375                "#/components/schemas/{}",
3376                T::schema().0
3377            ))))
3378            .item(
3379                ObjectBuilder::new()
3380                    .schema_type(SchemaType::String)
3381                    .enum_values(Some(vec!["none"])),
3382            )
3383            .default(Some(
3384                serde_json::to_value(T::default()).expect("Failed to serialize default value"),
3385            ))
3386            .build(),
3387    )
3388}
3389
3390/// Fault tolerance model.
3391///
3392/// The ordering is significant: we consider [Self::ExactlyOnce] to be a "higher
3393/// level" of fault tolerance than [Self::AtLeastOnce].
3394#[derive(
3395    Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
3396)]
3397#[serde(rename_all = "snake_case")]
3398pub enum FtModel {
3399    /// Each record is output at least once.  Crashes may duplicate output, but
3400    /// no input or output is dropped.
3401    AtLeastOnce,
3402
3403    /// Each record is output exactly once.  Crashes do not drop or duplicate
3404    /// input or output.
3405    #[default]
3406    ExactlyOnce,
3407}
3408
3409impl FtModel {
3410    pub fn option_as_str(value: Option<FtModel>) -> &'static str {
3411        value.map_or("no", |model| model.as_str())
3412    }
3413
3414    pub fn as_str(&self) -> &'static str {
3415        match self {
3416            FtModel::AtLeastOnce => "at_least_once",
3417            FtModel::ExactlyOnce => "exactly_once",
3418        }
3419    }
3420}
3421
3422/// The string does not name a fault tolerance model.
3423#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3424pub struct FtModelUnknown;
3425
3426impl std::fmt::Display for FtModelUnknown {
3427    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3428        f.write_str("expected `exactly_once` or `at_least_once`")
3429    }
3430}
3431
3432impl std::error::Error for FtModelUnknown {}
3433
3434impl FromStr for FtModel {
3435    type Err = FtModelUnknown;
3436
3437    fn from_str(s: &str) -> Result<Self, Self::Err> {
3438        match s.to_ascii_lowercase().as_str() {
3439            "exactly_once" => Ok(Self::ExactlyOnce),
3440            "at_least_once" => Ok(Self::AtLeastOnce),
3441            _ => Err(FtModelUnknown),
3442        }
3443    }
3444}
3445
3446/// Describes an input connector configuration
3447#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3448pub struct InputEndpointConfig {
3449    /// The name of the input stream of the circuit that this endpoint is
3450    /// connected to.
3451    pub stream: Cow<'static, str>,
3452
3453    /// Connector configuration.
3454    #[serde(flatten)]
3455    pub connector_config: ConnectorConfig,
3456}
3457
3458impl InputEndpointConfig {
3459    pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
3460        Self {
3461            stream: stream.into(),
3462            connector_config,
3463        }
3464    }
3465}
3466
3467/// Deserialize the `start_after` property of a connector configuration.
3468/// It requires a non-standard deserialization because we want to accept
3469/// either a string or an array of strings.
3470fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
3471where
3472    D: Deserializer<'de>,
3473{
3474    let value = Option::<JsonValue>::deserialize(deserializer)?;
3475    match value {
3476        Some(JsonValue::String(s)) => Ok(Some(vec![s])),
3477        Some(JsonValue::Array(arr)) => {
3478            let vec = arr
3479                .into_iter()
3480                .map(|item| {
3481                    item.as_str()
3482                        .map(|s| s.to_string())
3483                        .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
3484                })
3485                .collect::<Result<Vec<String>, _>>()?;
3486            Ok(Some(vec))
3487        }
3488        Some(JsonValue::Null) | None => Ok(None),
3489        _ => Err(serde::de::Error::custom(
3490            "invalid 'start_after' property: expected a string, an array of strings, or null",
3491        )),
3492    }
3493}
3494
3495#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3496pub struct ConnectorConfig {
3497    /// Send a full snapshot of a materialized view when the connector first
3498    /// starts. Valid for output connectors only.
3499    ///
3500    /// When `true`, the pipeline emits the current contents of the view as the
3501    /// initial batch the first time the connector runs. The view must be
3502    /// materialized (declared with `CREATE MATERIALIZED VIEW`).
3503    ///
3504    /// The snapshot is sent exactly once per connector lifetime: it does not
3505    /// fire again when the pipeline resumes from a checkpoint. Modifying the
3506    /// connector configuration or invoking the reset API triggers a fresh
3507    /// snapshot when the connector supports reset (e.g., Delta Lake in
3508    /// `truncate` mode and Postgres).
3509    #[serde(default)]
3510    pub send_snapshot: bool,
3511
3512    /// Ingest deletions as insertions, recording the original polarity in the
3513    /// `is_delete` metadata attribute. Valid for input connectors only.
3514    ///
3515    /// When `true`, a delete received by the connector is pushed to the table
3516    /// as an insertion of the same record, and the connector attaches the
3517    /// `is_delete` metadata attribute set to `true` to it. Insertions carry no
3518    /// `is_delete` attribute, so a column declared as
3519    /// `DEFAULT CAST(CONNECTOR_METADATA()['is_delete'] AS BOOLEAN)` is `NULL`
3520    /// for them. The table then contains the entire history of the input
3521    /// stream instead of tracking its current contents.
3522    ///
3523    /// Only tables without a primary key support this mode, since deletions in
3524    /// a table with a primary key delete a key rather than a record.
3525    ///
3526    /// Versions of Feldera that predate this option ignore it and apply
3527    /// deletions as regular deletions.
3528    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3529    pub soft_delete: bool,
3530
3531    /// Transport endpoint configuration.
3532    pub transport: TransportConfig,
3533
3534    /// Optional preprocessor configuration
3535    #[serde(skip_serializing_if = "Option::is_none")]
3536    pub preprocessor: Option<Vec<PreprocessorConfig>>,
3537
3538    /// Parser configuration.
3539    pub format: Option<FormatConfig>,
3540
3541    /// Optional postprocessor configuration
3542    #[serde(skip_serializing_if = "Option::is_none")]
3543    pub postprocessor: Option<Vec<PostprocessorConfig>>,
3544
3545    /// Name of the index that the connector is attached to.
3546    ///
3547    /// This property is valid for output connectors only.  It is used with data
3548    /// transports and formats that expect output updates in the form of key/value
3549    /// pairs, where the key typically represents a unique id associated with the
3550    /// table or view.
3551    ///
3552    /// To support such output formats, an output connector can be attached to an
3553    /// index created using the SQL CREATE INDEX statement.  An index of a table
3554    /// or view contains the same updates as the table or view itself, indexed by
3555    /// one or more key columns.
3556    ///
3557    /// See individual connector documentation for details on how they work
3558    /// with indexes.
3559    pub index: Option<String>,
3560
3561    /// Output buffer configuration.
3562    #[serde(flatten)]
3563    pub output_buffer_config: OutputBufferConfig,
3564
3565    /// Maximum number of records from this connector to process in a single batch.
3566    ///
3567    /// When set, this caps how many records are taken from the connector’s input
3568    /// buffer and pushed through the circuit at once.
3569    ///
3570    /// This is typically configured lower than `max_queued_records` to allow the
3571    /// connector time to restart and refill its buffer while a batch is being
3572    /// processed.
3573    ///
3574    /// Not all input adapters honor this limit.
3575    ///
3576    /// If this is not set, the batch size is derived from `max_worker_batch_size`.
3577    #[serde(skip_serializing_if = "Option::is_none")]
3578    pub max_batch_size: Option<u64>,
3579
3580    /// Maximum number of records processed per batch, per worker thread.
3581    ///
3582    /// When `max_batch_size` is not set, this setting is used to cap
3583    /// the number of records that can be taken from the connector’s input
3584    /// buffer and pushed through the circuit at once.  The effective batch size is computed as:
3585    /// `max_worker_batch_size × workers`.
3586    ///
3587    /// This provides an alternative to `max_batch_size` that automatically adjusts batch
3588    /// size as the number of worker threads changes to maintain constant amount of
3589    /// work per worker per batch.
3590    ///
3591    /// Defaults to 10,000 records per worker.
3592    #[serde(skip_serializing_if = "Option::is_none")]
3593    pub max_worker_batch_size: Option<u64>,
3594
3595    /// Backpressure threshold, in records.
3596    ///
3597    /// Maximal number of records queued by the endpoint before the endpoint
3598    /// is paused by the backpressure mechanism.
3599    ///
3600    /// For input endpoints, this setting bounds the number of records that have
3601    /// been received from the input transport but haven't yet been consumed by
3602    /// the circuit, since the circuit is still busy processing previous inputs.
3603    /// For a distributed input connector, the bound applies to the connector as
3604    /// a whole, and each host queues its share of it.
3605    ///
3606    /// For output endpoints, this setting bounds the number of records that have
3607    /// been produced by the circuit but not yet sent via the output transport endpoint
3608    /// nor stored in the output buffer (see `enable_output_buffer`).
3609    ///
3610    /// Note that this is not a hard bound: there can be a small delay between
3611    /// the backpressure mechanism is triggered and the endpoint is paused, during
3612    /// which more data may be queued.
3613    ///
3614    /// The default is 1 million.
3615    #[serde(default = "default_max_queued_records")]
3616    pub max_queued_records: u64,
3617
3618    /// Backpressure threshold, in bytes.
3619    ///
3620    /// Maximal number of bytes queued by the endpoint before the endpoint
3621    /// is paused by the backpressure mechanism.
3622    ///
3623    /// For input endpoints, this setting bounds the number of bytes that have
3624    /// been received from the input transport but haven't yet been consumed by
3625    /// the circuit since the circuit, since the circuit is still busy processing
3626    /// previous inputs.  For a distributed input connector, the bound applies
3627    /// to the connector as a whole, and each host queues its share of it.
3628    ///
3629    /// This setting is not yet implemented for output endpoints.
3630    ///
3631    /// Note that this is not a hard bound: there can be a small delay between
3632    /// the backpressure mechanism is triggered and the endpoint is paused, during
3633    /// which more data may be queued.
3634    ///
3635    /// When this is unspecified, it defaults to `1000 * max_queued_records`
3636    /// bytes.
3637    ///
3638    /// Before release 0.367.0 this setting was `max_queued_bytes`, a number
3639    /// of bytes. That name is deprecated but still read.
3640    #[serde(
3641        default,
3642        alias = "max_queued_bytes",
3643        deserialize_with = "size_max_queued_size",
3644        skip_serializing_if = "Option::is_none"
3645    )]
3646    #[schema(value_type = Option<String>)]
3647    pub max_queued_size: Option<ConfigSize>,
3648
3649    /// Create connector in paused state.
3650    ///
3651    /// A paused input connector does not fetch data from its source. A paused
3652    /// output connector discards the output it receives instead of sending it
3653    /// to its sink.
3654    ///
3655    /// A connector is started at runtime with the `start` action of the
3656    /// connector API and paused again with `pause`.
3657    ///
3658    /// The default is `false`.
3659    #[serde(default)]
3660    pub paused: bool,
3661
3662    /// Arbitrary user-defined text labels associated with the connector.
3663    ///
3664    /// These labels can be used in conjunction with the `start_after` property
3665    /// to control the start order of connectors.
3666    #[serde(default)]
3667    pub labels: Vec<String>,
3668
3669    /// Start the connector after all connectors with specified labels.
3670    ///
3671    /// This property is used to control the start order of connectors.
3672    /// The connector will not start until all connectors with the specified
3673    /// labels have finished processing all inputs.
3674    #[serde(deserialize_with = "deserialize_start_after")]
3675    #[serde(default)]
3676    pub start_after: Option<Vec<String>>,
3677
3678    /// Divide the input of this connector among the hosts of a multihost
3679    /// pipeline. Valid for input connectors only.
3680    ///
3681    /// When `false` (the default), the connector runs on one host, which
3682    /// reads all of its input. When `true`, the connector runs on every host,
3683    /// and each host reads a different part of the input. Only the Kafka,
3684    /// Delta Lake, and Iceberg input transports support this setting.
3685    ///
3686    /// In a single-host pipeline, this setting has no effect.
3687    ///
3688    /// Versions of Feldera that predate this option ignore it.
3689    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3690    pub distributed: bool,
3691}
3692
3693impl ConnectorConfig {
3694    pub fn new(transport: TransportConfig, format: Option<FormatConfig>) -> Self {
3695        Self {
3696            send_snapshot: false,
3697            soft_delete: false,
3698            transport,
3699            preprocessor: None,
3700            format,
3701            postprocessor: None,
3702            index: None,
3703            output_buffer_config: Default::default(),
3704            max_batch_size: None,
3705            max_worker_batch_size: None,
3706            max_queued_records: default_max_queued_records(),
3707            max_queued_size: None,
3708            paused: false,
3709            labels: Vec::new(),
3710            start_after: None,
3711            distributed: false,
3712        }
3713    }
3714
3715    pub fn with_max_batch_size(mut self, max_batch_size: Option<u64>) -> Self {
3716        self.max_batch_size = max_batch_size;
3717        self
3718    }
3719
3720    pub fn with_max_queued_records(mut self, max_queued_records: u64) -> Self {
3721        self.max_queued_records = max_queued_records;
3722        self
3723    }
3724
3725    /// Checks the backpressure thresholds.
3726    ///
3727    /// A threshold of 0 makes the queue always full, so backpressure never
3728    /// lets the connector run.
3729    pub fn validate_queue_limits(&self) -> Result<(), String> {
3730        if self.max_queued_records == 0 {
3731            return Err("'max_queued_records' must be greater than 0".to_string());
3732        }
3733        if self.max_queued_size.is_some() && self.max_queued_bytes() == 0 {
3734            return Err("'max_queued_size' must be greater than 0".to_string());
3735        }
3736        Ok(())
3737    }
3738
3739    /// Compare two configs modulo the `paused` field and how their duration
3740    /// settings are spelled.
3741    ///
3742    /// Used to compare checkpointed and current connector configs.
3743    pub fn equal_modulo_paused(&self, other: &Self) -> bool {
3744        let mut a = self.clone();
3745        let mut b = other.clone();
3746        a.paused = false;
3747        b.paused = false;
3748        a.normalize_durations();
3749        b.normalize_durations();
3750        a == b
3751    }
3752
3753    /// Writes each duration setting out as the value in effect.
3754    ///
3755    /// A setting left out and the same setting written explicitly at its
3756    /// default mean the same thing, but the derived `PartialEq` sees `None`
3757    /// against `Some(default)` and calls them different. Configurations stored
3758    /// before the rename carry the defaults explicitly, because the fields they
3759    /// used had no way to be absent: every output connector, for instance,
3760    /// carries `max_output_buffer_time_millis` at `u64::MAX`. Without this a
3761    /// connector nobody touched compares as modified, and the pipeline diff that
3762    /// follows an upgrade is never empty.
3763    fn normalize_durations(&mut self) {
3764        self.transport.normalize_durations();
3765        self.output_buffer_config.max_output_buffer_time =
3766            Some(self.output_buffer_config.max_output_buffer_time());
3767        if let Some(format) = &mut self.format {
3768            format.normalize_durations();
3769        }
3770    }
3771
3772    /// Compare two input connector configs modulo fields that only affect
3773    /// runtime flow control and do not invalidate checkpointed connector state.
3774    pub fn equal_for_input_checkpoint_replay(&self, other: &Self) -> bool {
3775        let mut a = self.clone();
3776        let mut b = other.clone();
3777        a.normalize_for_input_checkpoint_replay();
3778        b.normalize_for_input_checkpoint_replay();
3779        a == b
3780    }
3781
3782    fn normalize_for_input_checkpoint_replay(&mut self) {
3783        self.paused = false;
3784        self.max_batch_size = None;
3785        self.max_worker_batch_size = None;
3786        self.max_queued_records = default_max_queued_records();
3787        self.max_queued_size = None;
3788        self.normalize_durations();
3789    }
3790
3791    /// Adopt input connector settings that are safe to change while replaying
3792    /// checkpointed connector state.
3793    pub fn apply_input_checkpoint_replay_config_from(&mut self, other: &Self) {
3794        self.max_batch_size = other.max_batch_size;
3795        self.max_worker_batch_size = other.max_worker_batch_size;
3796        self.max_queued_records = other.max_queued_records;
3797        self.max_queued_size = other.max_queued_size;
3798    }
3799
3800    /// Returns `max_queued_records` or, if it is not set, the default.
3801    pub fn max_queued_records(&self) -> u64 {
3802        self.max_queued_records
3803    }
3804
3805    /// Returns `max_queued_size` in bytes or, if it is not set, the default
3806    /// based on `max_queued_records`.
3807    pub fn max_queued_bytes(&self) -> u64 {
3808        self.max_queued_size
3809            .map(ConfigSize::as_bytes)
3810            .unwrap_or_else(|| self.max_queued_records().saturating_mul(1000))
3811    }
3812}
3813
3814#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3815#[serde(default)]
3816pub struct OutputBufferConfig {
3817    /// Enable output buffering.
3818    ///
3819    /// The output buffering mechanism allows decoupling the rate at which the pipeline
3820    /// pushes changes to the output transport from the rate of input changes.
3821    ///
3822    /// By default, output updates produced by the pipeline are pushed directly to
3823    /// the output transport. Some destinations may prefer to receive updates in fewer
3824    /// bigger batches. For instance, when writing Parquet files, producing
3825    /// one bigger file every few minutes is usually better than creating
3826    /// small files every few milliseconds.
3827    ///
3828    /// To achieve such input/output decoupling, users can enable output buffering by
3829    /// setting the `enable_output_buffer` flag to `true`.  When buffering is enabled, output
3830    /// updates produced by the pipeline are consolidated in an internal buffer and are
3831    /// pushed to the output transport when one of several conditions is satisfied:
3832    ///
3833    /// * data has been accumulated in the buffer for longer than
3834    ///   `max_output_buffer_time`.
3835    /// * buffer size exceeds `max_output_buffer_size_records` records.
3836    ///
3837    /// This flag is `false` by default.
3838    // TODO: on-demand output triggered via the API.
3839    pub enable_output_buffer: bool,
3840
3841    /// Maximum time data is kept in the output buffer, for example `500ms`.
3842    ///
3843    /// By default, data is kept in the buffer indefinitely until one of
3844    /// the other output conditions is satisfied.  When this option is
3845    /// set the buffer will be flushed at least that often.
3846    ///
3847    /// NOTE: this configuration option requires the `enable_output_buffer` flag
3848    /// to be set.
3849    #[serde(
3850        default,
3851        alias = "max_output_buffer_time_millis",
3852        deserialize_with = "duration_max_output_buffer_time",
3853        skip_serializing_if = "Option::is_none"
3854    )]
3855    #[schema(value_type = Option<String>)]
3856    pub max_output_buffer_time: Option<ConfigDuration>,
3857
3858    /// Maximum number of updates to be kept in the output buffer.
3859    ///
3860    /// This parameter bounds the maximal size of the buffer.
3861    /// Note that the size of the buffer is not always equal to the
3862    /// total number of updates output by the pipeline. Updates to the
3863    /// same record can overwrite or cancel previous updates.
3864    ///
3865    /// The default is 10,000,000.
3866    ///
3867    /// NOTE: this configuration option requires the `enable_output_buffer` flag
3868    /// to be set.
3869    pub max_output_buffer_size_records: usize,
3870}
3871
3872impl OutputBufferConfig {
3873    /// The output buffering time limit in effect, or no limit.
3874    pub fn max_output_buffer_time(&self) -> ConfigDuration {
3875        self.max_output_buffer_time
3876            .unwrap_or(ConfigDuration::from_millis(u64::MAX))
3877    }
3878}
3879
3880impl Default for OutputBufferConfig {
3881    fn default() -> Self {
3882        Self {
3883            enable_output_buffer: false,
3884            max_output_buffer_size_records: DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS,
3885            max_output_buffer_time: None,
3886        }
3887    }
3888}
3889
3890/// Describes an output connector configuration
3891#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3892pub struct OutputEndpointConfig {
3893    /// The name of the output stream of the circuit that this endpoint is
3894    /// connected to.
3895    pub stream: Cow<'static, str>,
3896
3897    /// Connector configuration.
3898    #[serde(flatten)]
3899    pub connector_config: ConnectorConfig,
3900}
3901
3902impl OutputEndpointConfig {
3903    pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
3904        Self {
3905            stream: stream.into(),
3906            connector_config,
3907        }
3908    }
3909}
3910
3911/// Transport-specific endpoint configuration passed to
3912/// `crate::OutputTransport::new_endpoint`
3913/// and `crate::InputTransport::new_endpoint`.
3914#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3915#[serde(tag = "name", content = "config", rename_all = "snake_case")]
3916pub enum TransportConfig {
3917    FileInput(FileInputConfig),
3918    FileOutput(FileOutputConfig),
3919    // Boxed: `NatsInputConfig` is far larger than any other variant, and an
3920    // unboxed copy would set the size of every `TransportConfig`.
3921    NatsInput(Box<NatsInputConfig>),
3922    NatsOutput(NatsOutputConfig),
3923    KafkaInput(KafkaInputConfig),
3924    KafkaOutput(KafkaOutputConfig),
3925    PubSubInput(PubSubInputConfig),
3926    UrlInput(UrlInputConfig),
3927    S3Input(S3InputConfig),
3928    DeltaTableInput(DeltaTableReaderConfig),
3929    DeltaTableOutput(DeltaTableWriterConfig),
3930    // Snake case would rename "DynamoDBOutput" to `dynamo_db_output`.
3931    // However, DynamoDB is a single word, so override the tag to `dynamodb_output`.
3932    #[serde(rename = "dynamodb_output")]
3933    DynamoDBOutput(DynamoDBWriterConfig),
3934    RedisOutput(RedisOutputConfig),
3935    // Prevent rust from complaining about large size difference between enum variants.
3936    IcebergInput(Box<IcebergReaderConfig>),
3937    PostgresInput(PostgresReaderConfig),
3938    PostgresCdcInput(PostgresCdcReaderConfig),
3939    PostgresOutput(PostgresWriterConfig),
3940    Datagen(DatagenInputConfig),
3941    Nexmark(NexmarkInputConfig),
3942    /// Direct HTTP input: cannot be instantiated through API
3943    HttpInput(HttpInputConfig),
3944    /// Direct HTTP output: cannot be instantiated through API
3945    HttpOutput(HttpOutputConfig),
3946    /// Ad hoc input: cannot be instantiated through API
3947    AdHocInput(AdHocInputConfig),
3948    ClockInput(ClockConfig),
3949    S2Input(S2InputConfig),
3950    S2Output(S2OutputConfig),
3951    /// Output connector that discards all data.
3952    NullOutput,
3953    /// Input connector that produces no data.
3954    EmptyInput,
3955}
3956
3957/// When set to any value except `false`, `0` or empty, the pipeline refuses connector paths
3958/// on its local filesystem.
3959pub const REFUSE_LOCAL_FILE_URIS_ENV: &str = "FELDERA_REFUSE_LOCAL_FILE_URIS";
3960
3961/// A `file:` URL, or a string without a URL scheme. A one-letter scheme is a Windows drive.
3962fn is_local_file_uri(location: &str) -> bool {
3963    let Some((scheme, _)) = location.split_once(':') else {
3964        return true;
3965    };
3966    let valid_scheme = scheme.len() > 1
3967        && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
3968        && scheme
3969            .chars()
3970            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
3971    !valid_scheme || scheme.eq_ignore_ascii_case("file")
3972}
3973
3974impl TransportConfig {
3975    /// The local paths of a Delta Lake or Iceberg connector, as (property, value) pairs.
3976    /// Before references are `resolved`, skips them. After, checks every value, because a
3977    /// resolved value can look like a reference.
3978    pub fn local_file_uris(&self, resolved: bool) -> Vec<(&'static str, &str)> {
3979        let locations = match self {
3980            TransportConfig::DeltaTableInput(config) => vec![("uri", Some(&*config.uri))],
3981            TransportConfig::DeltaTableOutput(config) => vec![("uri", Some(&*config.uri))],
3982            TransportConfig::IcebergInput(config) => vec![
3983                ("metadata_location", config.metadata_location.as_deref()),
3984                (
3985                    "glue.warehouse",
3986                    config.glue_catalog_config.warehouse.as_deref(),
3987                ),
3988            ],
3989            _ => Vec::new(),
3990        };
3991        locations
3992            .into_iter()
3993            .filter_map(|(property, location)| Some((property, location?)))
3994            .filter(|(_, location)| {
3995                (resolved
3996                    || matches!(
3997                        MaybeSecretRef::new(location.to_string()),
3998                        Ok(MaybeSecretRef::String(_))
3999                    ))
4000                    && is_local_file_uri(location)
4001            })
4002            .collect()
4003    }
4004
4005    /// Writes each of the transport's duration settings out as the value in
4006    /// effect; see `ConnectorConfig::normalize_durations`.
4007    pub fn normalize_durations(&mut self) {
4008        match self {
4009            TransportConfig::UrlInput(config) => {
4010                config.pause_linger = Some(config.pause_linger());
4011            }
4012            TransportConfig::KafkaInput(config) => {
4013                config.group_join_timeout = Some(config.group_join_timeout());
4014            }
4015            TransportConfig::KafkaOutput(config) => {
4016                config.initialization_timeout = Some(config.initialization_timeout());
4017            }
4018            TransportConfig::NatsInput(config) => {
4019                config.connection_config.connection_timeout =
4020                    Some(config.connection_config.connection_timeout());
4021                config.connection_config.request_timeout =
4022                    Some(config.connection_config.request_timeout());
4023                config.inactivity_timeout = Some(config.inactivity_timeout());
4024                config.retry_interval = Some(config.retry_interval());
4025            }
4026            TransportConfig::NatsOutput(config) => {
4027                config.connection_config.connection_timeout =
4028                    Some(config.connection_config.connection_timeout());
4029                config.connection_config.request_timeout =
4030                    Some(config.connection_config.request_timeout());
4031                config.publish_timeout = Some(config.publish_timeout());
4032            }
4033            _ => {}
4034        }
4035    }
4036
4037    pub fn name(&self) -> String {
4038        match self {
4039            TransportConfig::FileInput(_) => "file_input".to_string(),
4040            TransportConfig::FileOutput(_) => "file_output".to_string(),
4041            TransportConfig::NatsInput(_) => "nats_input".to_string(),
4042            TransportConfig::NatsOutput(_) => "nats_output".to_string(),
4043            TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
4044            TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
4045            TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
4046            TransportConfig::UrlInput(_) => "url_input".to_string(),
4047            TransportConfig::S3Input(_) => "s3_input".to_string(),
4048            TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
4049            TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
4050            TransportConfig::DynamoDBOutput(_) => "dynamodb_output".to_string(),
4051            TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
4052            TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
4053            TransportConfig::PostgresCdcInput(_) => "postgres_cdc_input".to_string(),
4054            TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
4055            TransportConfig::Datagen(_) => "datagen".to_string(),
4056            TransportConfig::Nexmark(_) => "nexmark".to_string(),
4057            TransportConfig::HttpInput(_) => "http_input".to_string(),
4058            TransportConfig::HttpOutput(_) => "http_output".to_string(),
4059            TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
4060            TransportConfig::RedisOutput(_) => "redis_output".to_string(),
4061            TransportConfig::ClockInput(_) => "clock".to_string(),
4062            TransportConfig::S2Input(_) => "s2_input".to_string(),
4063            TransportConfig::S2Output(_) => "s2_output".to_string(),
4064            TransportConfig::NullOutput => "null_output".to_string(),
4065            TransportConfig::EmptyInput => "empty_input".to_string(),
4066        }
4067    }
4068
4069    /// Returns a mutable reference to the transport's metadata map, if the
4070    /// transport supports arbitrary key-value metadata (e.g., NATS consumer
4071    /// metadata). The controller uses this to inject pipeline identity into
4072    /// transport-level metadata without transport-specific knowledge.
4073    pub fn transport_metadata_mut(&mut self) -> Option<&mut HashMap<String, String>> {
4074        match self {
4075            TransportConfig::NatsInput(cfg) => Some(&mut cfg.consumer_config.metadata),
4076            _ => None,
4077        }
4078    }
4079
4080    /// Returns true if the connector is transient, i.e., is created and destroyed
4081    /// at runtime on demand, rather than being configured as part of the pipeline.
4082    pub fn is_transient(&self) -> bool {
4083        matches!(
4084            self,
4085            TransportConfig::AdHocInput(_)
4086                | TransportConfig::HttpInput(_)
4087                | TransportConfig::HttpOutput(_)
4088                | TransportConfig::ClockInput(_)
4089        )
4090    }
4091
4092    pub fn is_http_input(&self) -> bool {
4093        matches!(self, TransportConfig::HttpInput(_))
4094    }
4095
4096    /// Returns true if an input connector with this transport can divide its
4097    /// input among the hosts of a multihost pipeline (see
4098    /// [`ConnectorConfig::distributed`]).
4099    pub fn supports_distribution(&self) -> bool {
4100        matches!(
4101            self,
4102            TransportConfig::KafkaInput(_)
4103                | TransportConfig::DeltaTableInput(_)
4104                | TransportConfig::IcebergInput(_)
4105        )
4106    }
4107
4108    /// Returns true if host 0 of a distributed input connector with this
4109    /// transport must choose a value for all of the hosts before they read any
4110    /// input.
4111    ///
4112    /// For example, the hosts of a Delta Lake connector must read the snapshot
4113    /// at the same table version, and the hosts of an Iceberg connector at the
4114    /// same snapshot ID, or they could lose or duplicate records.
4115    /// Host 0 chooses the value, and the coordinator passes it to the other
4116    /// hosts in [CoordinationActivate::input_choices].
4117    ///
4118    /// [CoordinationActivate::input_choices]: crate::coordination::CoordinationActivate::input_choices
4119    pub fn needs_input_choice(&self) -> bool {
4120        matches!(
4121            self,
4122            TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_)
4123        )
4124    }
4125
4126    /// Returns how to combine the completed frontiers' metadata that the hosts
4127    /// of a distributed input connector with this transport report.
4128    pub fn frontier_merge(&self) -> crate::adapter_stats::FrontierMerge {
4129        use crate::adapter_stats::FrontierMerge;
4130        match self {
4131            TransportConfig::KafkaInput(_) => FrontierMerge::Partitioned,
4132            TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_) => {
4133                FrontierMerge::Shared
4134            }
4135            _ => FrontierMerge::Opaque,
4136        }
4137    }
4138}
4139
4140/// Data format specification used to parse raw data received from the
4141/// endpoint or to encode data sent to the endpoint.
4142#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
4143pub struct FormatConfig {
4144    /// Format name, e.g., "csv", "json", "bincode", etc.
4145    pub name: Cow<'static, str>,
4146
4147    /// Format-specific parser or encoder configuration.
4148    #[serde(default)]
4149    #[schema(value_type = Object)]
4150    pub config: JsonValue,
4151}
4152
4153impl FormatConfig {
4154    /// Writes the Avro schema registry timeout, the one duration a format
4155    /// carries, in one spelling; see `ConnectorConfig::normalize_durations`.
4156    ///
4157    /// The format configuration stays raw JSON until the format parses it, so
4158    /// the timeout is read the way the format reads it and written back under
4159    /// the current key. A configuration the format would reject is left alone.
4160    pub fn normalize_durations(&mut self) {
4161        if self.name != "avro" {
4162            return;
4163        }
4164        let has_timeout = self.config.as_object().is_some_and(|object| {
4165            object.contains_key("registry_timeout") || object.contains_key("registry_timeout_secs")
4166        });
4167        if !has_timeout {
4168            return;
4169        }
4170        let Ok(registry) = serde_json::from_value::<crate::format::avro::AvroSchemaRegistryConfig>(
4171            self.config.clone(),
4172        ) else {
4173            return;
4174        };
4175        let object = self.config.as_object_mut().unwrap();
4176        object.remove("registry_timeout_secs");
4177        match registry.registry_timeout {
4178            Some(timeout) => object.insert(
4179                "registry_timeout".to_string(),
4180                JsonValue::String(timeout.to_string()),
4181            ),
4182            None => object.remove("registry_timeout"),
4183        };
4184    }
4185}
4186
4187/// The part of a pipeline's config that can change while the pipeline runs.
4188#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
4189#[serde(deny_unknown_fields)]
4190pub struct DynamicConfig {
4191    #[serde(default)]
4192    pub resources: DynamicResources,
4193}
4194
4195/// CPU, memory, storage, and the volume attributes class, the only fields that can change while
4196/// the pipeline runs.
4197#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
4198#[serde(deny_unknown_fields)]
4199pub struct DynamicResources {
4200    pub cpu_cores_min: Option<f64>,
4201    pub cpu_cores_max: Option<f64>,
4202    /// The minimum memory, such as `"4Gi"`. `memory_mb_min`, a number of
4203    /// megabytes, is a deprecated alias.
4204    #[serde(default, alias = "memory_mb_min", deserialize_with = "size_memory_min")]
4205    #[schema(value_type = Option<String>)]
4206    pub memory_min: Option<ConfigSize>,
4207    /// The maximum memory, such as `"16Gi"`. `memory_mb_max`, a number of
4208    /// megabytes, is a deprecated alias.
4209    #[serde(default, alias = "memory_mb_max", deserialize_with = "size_memory_max")]
4210    #[schema(value_type = Option<String>)]
4211    pub memory_max: Option<ConfigSize>,
4212    /// Storage grows to `storage_min`, else `storage_max`. With both set, storage autoscaling
4213    /// expands it up to `storage_max`. A change can only increase a field that is already set.
4214    /// `storage_mb_min`, a number of megabytes, is a deprecated alias.
4215    /// Not serialized when unset, so that a pipeline on an older runtime accepts a memory update.
4216    #[serde(
4217        default,
4218        alias = "storage_mb_min",
4219        deserialize_with = "size_storage_min",
4220        skip_serializing_if = "Option::is_none"
4221    )]
4222    #[schema(value_type = Option<String>)]
4223    pub storage_min: Option<ConfigSize>,
4224    /// The maximum storage, such as `"400Gi"`. `storage_mb_max`, a number of megabytes, is a
4225    /// deprecated alias.
4226    #[serde(
4227        default,
4228        alias = "storage_mb_max",
4229        deserialize_with = "size_storage_max",
4230        skip_serializing_if = "Option::is_none"
4231    )]
4232    #[schema(value_type = Option<String>)]
4233    pub storage_max: Option<ConfigSize>,
4234    /// The Kubernetes volume attributes class of the storage, which sets its IOPS and
4235    /// throughput. A change cannot remove it.
4236    #[serde(default, skip_serializing_if = "Option::is_none")]
4237    pub volume_attributes_class: Option<String>,
4238}
4239
4240#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4241#[serde(default)]
4242pub struct ResourceConfig {
4243    /// The minimum number of CPU cores to reserve
4244    /// for an instance of this pipeline
4245    #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4246    pub cpu_cores_min: Option<f64>,
4247
4248    /// The maximum number of CPU cores to reserve
4249    /// for an instance of this pipeline
4250    #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4251    pub cpu_cores_max: Option<f64>,
4252
4253    /// The minimum memory to reserve for an instance of this pipeline, such
4254    /// as `"4Gi"`.
4255    ///
4256    /// Before release 0.367.0 this setting was `memory_mb_min`, a number of
4257    /// megabytes. That name is deprecated but still read.
4258    #[serde(
4259        alias = "memory_mb_min",
4260        deserialize_with = "size_memory_min",
4261        skip_serializing_if = "Option::is_none"
4262    )]
4263    #[schema(value_type = Option<String>)]
4264    pub memory_min: Option<ConfigSize>,
4265
4266    /// The maximum memory to reserve for an instance of this pipeline, such
4267    /// as `"16Gi"`.
4268    ///
4269    /// Before release 0.367.0 this setting was `memory_mb_max`, a number of
4270    /// megabytes. That name is deprecated but still read.
4271    #[serde(
4272        alias = "memory_mb_max",
4273        deserialize_with = "size_memory_max",
4274        skip_serializing_if = "Option::is_none"
4275    )]
4276    #[schema(value_type = Option<String>)]
4277    pub memory_max: Option<ConfigSize>,
4278
4279    /// The initial storage to reserve for an instance of this pipeline, such
4280    /// as `"100Gi"`. Set together with `storage_max` to enable storage
4281    /// autoscaling.
4282    ///
4283    /// Before release 0.367.0 this setting was `storage_mb_min`, a number of
4284    /// megabytes. That name is deprecated but still read.
4285    #[serde(
4286        alias = "storage_mb_min",
4287        deserialize_with = "size_storage_min",
4288        skip_serializing_if = "Option::is_none"
4289    )]
4290    #[schema(value_type = Option<String>)]
4291    pub storage_min: Option<ConfigSize>,
4292
4293    /// The maximum storage for an instance of this pipeline, such as
4294    /// `"400Gi"`.
4295    ///
4296    /// Without `storage_min`, this much storage is reserved up front.
4297    ///
4298    /// With `storage_min`, storage starts there and autoscaling expands it up
4299    /// to this limit.
4300    ///
4301    /// Before release 0.367.0 this setting was `storage_mb_max`, a number of
4302    /// megabytes. That name is deprecated but still read.
4303    #[serde(
4304        alias = "storage_mb_max",
4305        deserialize_with = "size_storage_max",
4306        skip_serializing_if = "Option::is_none"
4307    )]
4308    #[schema(value_type = Option<String>)]
4309    pub storage_max: Option<ConfigSize>,
4310
4311    /// Autoscaling policy for an instance of this pipeline.
4312    #[serde(skip_serializing_if = "Option::is_none")]
4313    pub autoscaling: Option<AutoscalingConfig>,
4314
4315    /// Storage class to use for an instance of this pipeline.
4316    /// The class determines storage performance such as IOPS and throughput.
4317    pub storage_class: Option<String>,
4318
4319    /// Kubernetes volume attributes class to use for the storage of an
4320    /// instance of this pipeline. The class sets mutable storage parameters
4321    /// such as IOPS and throughput. Requires Kubernetes 1.34 or later (or
4322    /// the `VolumeAttributesClass` feature gate) and CSI driver support.
4323    /// A change takes effect on the next start, also for existing storage, or
4324    /// while the pipeline runs through a `PATCH` of its `deployment_config`.
4325    #[serde(skip_serializing_if = "Option::is_none")]
4326    pub volume_attributes_class: Option<String>,
4327
4328    /// Kubernetes service account name to use for an instance of this pipeline.
4329    /// The account determines permissions and access controls.
4330    pub service_account_name: Option<String>,
4331
4332    /// Kubernetes namespace to use for an instance of this pipeline.
4333    /// The namespace determines the scope of names for resources created
4334    /// for the pipeline.
4335    /// If not set, the pipeline will be deployed in the same namespace
4336    /// as the control-plane.
4337    // The type of this field should not be backward incompatibly changed, and its location in the
4338    // runtime configuration JSON (`runtime_config.resources.namespace`) should not be changed.
4339    pub namespace: Option<String>,
4340}
4341
4342/// Autoscaling policy for an instance of a pipeline.
4343#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4344#[serde(default)]
4345pub struct AutoscalingConfig {
4346    /// Storage autoscaling policy.
4347    #[serde(skip_serializing_if = "Option::is_none")]
4348    pub storage: Option<StorageAutoscalingConfig>,
4349}
4350
4351/// Storage autoscaling policy: expand storage from `storage_min` toward
4352/// `storage_max` as it fills up.
4353#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4354#[serde(default)]
4355pub struct StorageAutoscalingConfig {
4356    /// Usage fraction that triggers expansion. Defaults to 0.8.
4357    #[serde(
4358        deserialize_with = "crate::serde_via_value::deserialize",
4359        skip_serializing_if = "Option::is_none"
4360    )]
4361    pub scale_threshold: Option<f64>,
4362
4363    /// Expand storage when available space falls below this size, such as
4364    /// `"10Gi"`, even if usage is still under `scale_threshold`. Either
4365    /// condition triggers expansion. Unset by default.
4366    ///
4367    /// Before release 0.367.0 this setting was `scale_threshold_available_mb`,
4368    /// a number of megabytes. That name is deprecated but still read.
4369    #[serde(
4370        alias = "scale_threshold_available_mb",
4371        deserialize_with = "size_scale_threshold_available",
4372        skip_serializing_if = "Option::is_none"
4373    )]
4374    #[schema(value_type = Option<String>)]
4375    pub scale_threshold_available: Option<ConfigSize>,
4376
4377    /// Expansion multiplier. Defaults to 2.0.
4378    #[serde(
4379        deserialize_with = "crate::serde_via_value::deserialize",
4380        skip_serializing_if = "Option::is_none"
4381    )]
4382    pub scale_factor: Option<f64>,
4383}
4384
4385#[cfg(test)]
4386mod resource_config_tests {
4387    use super::{
4388        AutoscalingConfig, DynamicConfig, DynamicResources, ResourceConfig,
4389        StorageAutoscalingConfig,
4390    };
4391    use crate::size::ConfigSize;
4392    use serde_json::json;
4393
4394    /// The memory update a pipeline gets leaves out unset storage, which an older runtime
4395    /// refuses as an unknown field.
4396    #[test]
4397    fn dynamic_config_leaves_out_unset_storage() {
4398        let update = DynamicConfig {
4399            resources: DynamicResources {
4400                memory_max: Some(ConfigSize::from_mb(1000)),
4401                ..Default::default()
4402            },
4403        };
4404        assert_eq!(
4405            serde_json::to_value(&update).unwrap(),
4406            json!({"resources": {
4407                "cpu_cores_min": null, "cpu_cores_max": null,
4408                "memory_min": null, "memory_max": "1G",
4409            }})
4410        );
4411        let resize = json!({"resources": {"storage_mb_min": 1000, "storage_max": "8G"}});
4412        let resize: DynamicConfig = serde_json::from_value(resize).unwrap();
4413        assert_eq!(
4414            resize.resources.storage_min,
4415            Some(ConfigSize::from_mb(1000))
4416        );
4417        assert_eq!(
4418            resize.resources.storage_max,
4419            Some(ConfigSize::from_mb(8000))
4420        );
4421    }
4422
4423    #[test]
4424    fn storage_autoscaling_round_trips_through_json() {
4425        let input = json!({
4426            "storage_min": "1G",
4427            "storage_max": "8G",
4428            "autoscaling": {
4429                "storage": {
4430                    "scale_threshold": 0.8,
4431                    "scale_threshold_available": "10G",
4432                    "scale_factor": 2.0
4433                }
4434            }
4435        });
4436        let config: ResourceConfig = serde_json::from_value(input).unwrap();
4437        assert_eq!(config.storage_min, Some(ConfigSize::from_mb(1000)));
4438        assert_eq!(config.storage_max, Some(ConfigSize::from_mb(8000)));
4439        assert_eq!(
4440            config.autoscaling,
4441            Some(AutoscalingConfig {
4442                storage: Some(StorageAutoscalingConfig {
4443                    scale_threshold: Some(0.8),
4444                    scale_threshold_available: Some(ConfigSize::from_mb(10000)),
4445                    scale_factor: Some(2.0),
4446                }),
4447            })
4448        );
4449        let output = serde_json::to_value(&config).unwrap();
4450        assert_eq!(output["storage_min"], json!("1G"));
4451        assert_eq!(
4452            output["autoscaling"]["storage"]["scale_threshold"],
4453            json!(0.8)
4454        );
4455        assert_eq!(
4456            output["autoscaling"]["storage"]["scale_threshold_available"],
4457            json!("10G")
4458        );
4459        assert_eq!(output["autoscaling"]["storage"]["scale_factor"], json!(2.0));
4460    }
4461
4462    #[test]
4463    fn autoscaling_fields_default_to_none() {
4464        let config: ResourceConfig = serde_json::from_value(json!({})).unwrap();
4465        assert_eq!(config.storage_min, None);
4466        assert_eq!(config.autoscaling, None);
4467
4468        // Unset autoscaling fields stay out of the serialized config so they
4469        // do not clutter configs of users who never touch them.
4470        let output = serde_json::to_value(&config).unwrap();
4471        assert!(output.get("storage_min").is_none());
4472        assert!(output.get("autoscaling").is_none());
4473        assert!(output.get("storage_max").is_none());
4474
4475        // A partially set policy serializes only the fields the user set.
4476        let input = json!({ "autoscaling": { "storage": { "scale_threshold": 0.9 } } });
4477        let config: ResourceConfig = serde_json::from_value(input.clone()).unwrap();
4478        let output = serde_json::to_value(&config).unwrap();
4479        assert_eq!(output["autoscaling"], input["autoscaling"]);
4480
4481        // A policy object with no storage section is accepted as-is.
4482        let config: ResourceConfig = serde_json::from_value(json!({ "autoscaling": {} })).unwrap();
4483        assert_eq!(config.autoscaling, Some(AutoscalingConfig::default()));
4484    }
4485
4486    #[test]
4487    fn autoscaling_rejects_non_numeric_values() {
4488        let input = json!({ "autoscaling": { "storage": { "scale_threshold": "high" } } });
4489        assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4490        let input = json!({ "autoscaling": { "storage": { "scale_threshold_available_mb": -1 } } });
4491        assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4492        let input = json!({ "storage_mb_min": -1 });
4493        assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4494    }
4495}
4496
4497#[cfg(test)]
4498mod sync_config_tests {
4499    use super::SyncConfig;
4500
4501    fn config(bucket: &str, read_bucket: Option<&str>) -> SyncConfig {
4502        SyncConfig {
4503            bucket: bucket.to_owned(),
4504            read_bucket: read_bucket.map(str::to_owned),
4505            ..Default::default()
4506        }
4507    }
4508
4509    #[test]
4510    fn read_bucket_must_differ_from_bucket() {
4511        let err = config("ckpts/a", Some("ckpts/a")).validate().unwrap_err();
4512        assert!(err.contains("different locations"), "{err}");
4513    }
4514
4515    #[test]
4516    fn read_bucket_must_use_the_same_object_store() {
4517        let err = config("gs://ckpts/a", Some("ckpts/b"))
4518            .validate()
4519            .unwrap_err();
4520        assert!(err.contains("same object store"), "{err}");
4521        let err = config("ckpts/a", Some("gs://ckpts/b"))
4522            .validate()
4523            .unwrap_err();
4524        assert!(err.contains("same object store"), "{err}");
4525    }
4526
4527    #[test]
4528    fn matching_object_stores_are_accepted() {
4529        config("gs://ckpts/a", Some("gs://ckpts/b"))
4530            .validate()
4531            .unwrap();
4532        config("ckpts/a", Some("s3://ckpts/b")).validate().unwrap();
4533        config("gs://ckpts/a", None).validate().unwrap();
4534    }
4535
4536    #[test]
4537    fn take_bucket_ownership_defaults_to_false() {
4538        let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "ckpts/a"}"#).unwrap();
4539        assert!(!sync.take_bucket_ownership);
4540
4541        let sync: SyncConfig =
4542            serde_json::from_str(r#"{"bucket": "ckpts/a", "take_bucket_ownership": true}"#)
4543                .unwrap();
4544        assert!(sync.take_bucket_ownership);
4545    }
4546}
4547
4548#[cfg(test)]
4549mod queue_limit_tests {
4550    use super::ConnectorConfig;
4551    use serde_json::json;
4552
4553    fn connector(extra: serde_json::Value) -> ConnectorConfig {
4554        let mut value = json!({"transport": {"name": "datagen", "config": {}}});
4555        value
4556            .as_object_mut()
4557            .unwrap()
4558            .extend(extra.as_object().unwrap().clone());
4559        serde_json::from_value(value).unwrap()
4560    }
4561
4562    #[test]
4563    fn zero_queue_limits_are_rejected() {
4564        let err = connector(json!({"max_queued_records": 0}))
4565            .validate_queue_limits()
4566            .unwrap_err();
4567        assert!(err.contains("max_queued_records"), "{err}");
4568
4569        for size in [json!(0), json!("0"), json!("0Mi")] {
4570            let err = connector(json!({"max_queued_size": size}))
4571                .validate_queue_limits()
4572                .unwrap_err();
4573            assert!(err.contains("max_queued_size"), "{err}");
4574        }
4575        let err = connector(json!({"max_queued_bytes": 0}))
4576            .validate_queue_limits()
4577            .unwrap_err();
4578        assert!(err.contains("max_queued_size"), "{err}");
4579    }
4580
4581    #[test]
4582    fn nonzero_queue_limits_are_accepted() {
4583        connector(json!({})).validate_queue_limits().unwrap();
4584        connector(json!({"max_queued_records": 1, "max_queued_size": 1}))
4585            .validate_queue_limits()
4586            .unwrap();
4587    }
4588}
4589
4590#[cfg(test)]
4591mod transport_metadata_tests {
4592    use super::TransportConfig;
4593    use serde_json::json;
4594
4595    fn nats_input(metadata: serde_json::Value) -> TransportConfig {
4596        serde_json::from_value(json!({
4597            "name": "nats_input",
4598            "config": {
4599                "connection_config": { "server_url": "nats://127.0.0.1:4222" },
4600                "stream_name": "orders",
4601                "consumer_config": { "deliver_policy": "All", "metadata": metadata },
4602            },
4603        }))
4604        .unwrap()
4605    }
4606
4607    #[test]
4608    fn nats_input_exposes_consumer_metadata() {
4609        let mut transport = nats_input(json!({ "team": "ingest" }));
4610        let metadata = transport.transport_metadata_mut().unwrap();
4611        assert_eq!(metadata.get("team").map(String::as_str), Some("ingest"));
4612
4613        metadata.insert("pipeline".to_string(), "orders_pipeline".to_string());
4614        let TransportConfig::NatsInput(config) = &transport else {
4615            unreachable!()
4616        };
4617        assert_eq!(
4618            config
4619                .consumer_config
4620                .metadata
4621                .get("pipeline")
4622                .map(String::as_str),
4623            Some("orders_pipeline"),
4624            "writes through the returned map must reach the consumer config"
4625        );
4626    }
4627
4628    #[test]
4629    fn transports_without_metadata_return_none() {
4630        let mut transport: TransportConfig = serde_json::from_value(json!({
4631            "name": "file_input",
4632            "config": { "path": "/tmp/input.csv" },
4633        }))
4634        .unwrap();
4635        assert!(transport.transport_metadata_mut().is_none());
4636    }
4637}
4638
4639#[cfg(test)]
4640mod local_file_uri_tests {
4641    use super::TransportConfig;
4642    use serde_json::json;
4643
4644    #[test]
4645    fn local_file_uris() {
4646        let delta = |uri: &str| -> TransportConfig {
4647            serde_json::from_value(
4648                json!({"name": "delta_table_input", "config": {"uri": uri, "mode": "snapshot"}}),
4649            )
4650            .unwrap()
4651        };
4652        for uri in [
4653            "file:///etc",
4654            "FILE:/etc",
4655            "/etc",
4656            "./t",
4657            "",
4658            "c:/t",
4659            " file:///etc",
4660        ] {
4661            assert_eq!(delta(uri).local_file_uris(false), vec![("uri", uri)]);
4662        }
4663        for uri in [
4664            "s3://b/t",
4665            "gs://b/t",
4666            "az://c/t",
4667            "abfss://c@a/t",
4668            "uc://c.s.t",
4669        ] {
4670            assert!(delta(uri).local_file_uris(false).is_empty(), "{uri}");
4671        }
4672        // A reference is checked after resolution. Its resolved value can look like a reference.
4673        assert!(delta("${env:X}").local_file_uris(false).is_empty());
4674        assert_eq!(
4675            delta("${env:X}").local_file_uris(true),
4676            vec![("uri", "${env:X}")]
4677        );
4678
4679        let iceberg: TransportConfig = serde_json::from_value(json!({"name": "iceberg_input",
4680            "config": {"mode": "snapshot", "metadata_location": "file:///t/m.json"}}))
4681        .unwrap();
4682        assert_eq!(
4683            iceberg.local_file_uris(false),
4684            vec![("metadata_location", "file:///t/m.json")]
4685        );
4686    }
4687}