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