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