Skip to main content

feldera_types/
config.rs

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