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