Skip to main content

stateknot_testkit/
environment.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7const MAX_LABEL_BYTES: usize = 128;
8const MAX_DATABASE_RTT_MICROS: u64 = 60_000_000;
9const GIB: u64 = 1_073_741_824;
10
11/// Invalid or incomplete qualification-environment metadata.
12#[derive(Clone, Debug, Eq, Error, PartialEq)]
13pub enum EnvironmentError {
14    /// A fixed-width hexadecimal identity is invalid.
15    #[error("{field} must be {width} lowercase hexadecimal characters")]
16    InvalidHex {
17        /// Field name.
18        field: &'static str,
19        /// Required width.
20        width: usize,
21    },
22    /// A label is empty, oversized or contains a control character.
23    #[error("{0} is not a bounded printable label")]
24    InvalidLabel(&'static str),
25    /// A numeric field is outside its supported bound.
26    #[error("{0} is outside its supported bound")]
27    InvalidNumber(&'static str),
28}
29
30/// Immutable source and input identities for one qualification run.
31#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
32#[serde(deny_unknown_fields)]
33pub struct SourceIdentity {
34    source_commit: String,
35    source_tree: String,
36    cargo_lock_sha256: String,
37    dataset_sha256: String,
38    configuration_sha256: String,
39}
40
41impl SourceIdentity {
42    /// Creates and validates the source identity.
43    pub fn new(
44        source_commit: impl Into<String>,
45        source_tree: impl Into<String>,
46        cargo_lock_sha256: impl Into<String>,
47        dataset_sha256: impl Into<String>,
48        configuration_sha256: impl Into<String>,
49    ) -> Result<Self, EnvironmentError> {
50        let value = Self {
51            source_commit: source_commit.into(),
52            source_tree: source_tree.into(),
53            cargo_lock_sha256: cargo_lock_sha256.into(),
54            dataset_sha256: dataset_sha256.into(),
55            configuration_sha256: configuration_sha256.into(),
56        };
57        value.validate()?;
58        Ok(value)
59    }
60
61    /// Returns the exact Git commit.
62    pub fn source_commit(&self) -> &str {
63        &self.source_commit
64    }
65
66    /// Returns the exact Git tree.
67    pub fn source_tree(&self) -> &str {
68        &self.source_tree
69    }
70
71    pub(crate) fn validate(&self) -> Result<(), EnvironmentError> {
72        valid_hex("source_commit", &self.source_commit, 40)?;
73        valid_hex("source_tree", &self.source_tree, 40)?;
74        valid_hex("cargo_lock_sha256", &self.cargo_lock_sha256, 64)?;
75        valid_hex("dataset_sha256", &self.dataset_sha256, 64)?;
76        valid_hex("configuration_sha256", &self.configuration_sha256, 64)
77    }
78}
79
80/// Recorded resources for each application or database node.
81#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
82#[serde(deny_unknown_fields)]
83pub struct MachineEnvironment {
84    logical_cpus: u16,
85    memory_bytes: u64,
86    cpu_model: String,
87    storage_class: String,
88    kernel: String,
89    container_runtime: String,
90}
91
92impl MachineEnvironment {
93    /// Creates bounded machine metadata.
94    pub fn new(
95        logical_cpus: u16,
96        memory_bytes: u64,
97        cpu_model: impl Into<String>,
98        storage_class: impl Into<String>,
99        kernel: impl Into<String>,
100        container_runtime: impl Into<String>,
101    ) -> Result<Self, EnvironmentError> {
102        let value = Self {
103            logical_cpus,
104            memory_bytes,
105            cpu_model: cpu_model.into(),
106            storage_class: storage_class.into(),
107            kernel: kernel.into(),
108            container_runtime: container_runtime.into(),
109        };
110        value.validate()?;
111        Ok(value)
112    }
113
114    fn validate(&self) -> Result<(), EnvironmentError> {
115        if self.logical_cpus == 0 || self.logical_cpus > 1_024 {
116            return Err(EnvironmentError::InvalidNumber("logical_cpus"));
117        }
118        if self.memory_bytes == 0 || self.memory_bytes > 16 * 1_024 * GIB {
119            return Err(EnvironmentError::InvalidNumber("memory_bytes"));
120        }
121        valid_label("cpu_model", &self.cpu_model)?;
122        valid_label("storage_class", &self.storage_class)?;
123        valid_label("kernel", &self.kernel)?;
124        valid_label("container_runtime", &self.container_runtime)
125    }
126}
127
128/// Database standby mode recorded by a qualification run.
129#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
130#[serde(rename_all = "snake_case")]
131pub enum StandbyMode {
132    /// No standby was configured.
133    None,
134    /// A standby existed without synchronous acknowledgement.
135    Asynchronous,
136    /// At least one synchronous standby acknowledged commits.
137    Synchronous,
138}
139
140/// `PostgreSQL` configuration relevant to the qualification contract.
141#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
142#[serde(deny_unknown_fields)]
143pub struct PostgresEnvironment {
144    major_version: u16,
145    synchronous_commit: bool,
146    standby_mode: StandbyMode,
147}
148
149impl PostgresEnvironment {
150    /// Creates bounded `PostgreSQL` metadata.
151    pub fn new(
152        major_version: u16,
153        synchronous_commit: bool,
154        standby_mode: StandbyMode,
155    ) -> Result<Self, EnvironmentError> {
156        let value = Self {
157            major_version,
158            synchronous_commit,
159            standby_mode,
160        };
161        value.validate()?;
162        Ok(value)
163    }
164
165    fn validate(&self) -> Result<(), EnvironmentError> {
166        if !(12..=99).contains(&self.major_version) {
167            return Err(EnvironmentError::InvalidNumber("postgres_major_version"));
168        }
169        Ok(())
170    }
171}
172
173/// Process topology used by the Agent host qualification scenario.
174#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
175#[serde(deny_unknown_fields)]
176pub struct Topology {
177    application_nodes: u16,
178    api_processes: u16,
179    scheduler_processes: u16,
180    worker_processes: u16,
181}
182
183impl Topology {
184    /// Creates a bounded topology description.
185    pub fn new(
186        application_nodes: u16,
187        api_processes: u16,
188        scheduler_processes: u16,
189        worker_processes: u16,
190    ) -> Result<Self, EnvironmentError> {
191        let value = Self {
192            application_nodes,
193            api_processes,
194            scheduler_processes,
195            worker_processes,
196        };
197        value.validate()?;
198        Ok(value)
199    }
200
201    fn validate(&self) -> Result<(), EnvironmentError> {
202        for (name, value) in [
203            ("application_nodes", self.application_nodes),
204            ("api_processes", self.api_processes),
205            ("scheduler_processes", self.scheduler_processes),
206            ("worker_processes", self.worker_processes),
207        ] {
208            if value == 0 || value > 4_096 {
209                return Err(EnvironmentError::InvalidNumber(name));
210            }
211        }
212        Ok(())
213    }
214}
215
216/// Complete bounded environment record embedded in qualification evidence.
217#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
218#[serde(deny_unknown_fields)]
219pub struct QualificationEnvironment {
220    source: SourceIdentity,
221    application_machine: MachineEnvironment,
222    database_machine: MachineEnvironment,
223    postgres: PostgresEnvironment,
224    topology: Topology,
225    median_database_rtt_micros: u64,
226}
227
228impl QualificationEnvironment {
229    /// Creates a qualification environment after validating every component.
230    pub fn new(
231        source: SourceIdentity,
232        application_machine: MachineEnvironment,
233        database_machine: MachineEnvironment,
234        postgres: PostgresEnvironment,
235        topology: Topology,
236        median_database_rtt_micros: u64,
237    ) -> Result<Self, EnvironmentError> {
238        let value = Self {
239            source,
240            application_machine,
241            database_machine,
242            postgres,
243            topology,
244            median_database_rtt_micros,
245        };
246        value.validate()?;
247        Ok(value)
248    }
249
250    /// Returns the exact source identity.
251    pub fn source(&self) -> &SourceIdentity {
252        &self.source
253    }
254
255    /// Validates internal bounds after construction or deserialization.
256    pub fn validate(&self) -> Result<(), EnvironmentError> {
257        self.source.validate()?;
258        self.application_machine.validate()?;
259        self.database_machine.validate()?;
260        self.postgres.validate()?;
261        self.topology.validate()?;
262        if self.median_database_rtt_micros == 0
263            || self.median_database_rtt_micros > MAX_DATABASE_RTT_MICROS
264        {
265            return Err(EnvironmentError::InvalidNumber(
266                "median_database_rtt_micros",
267            ));
268        }
269        Ok(())
270    }
271
272    /// Returns every reason this environment is not the documented reference profile.
273    pub fn reference_violations(&self) -> Vec<ReferenceEnvironmentViolation> {
274        let mut violations = Vec::new();
275        if !matches!(self.postgres.major_version, 16 | 17) {
276            violations.push(ReferenceEnvironmentViolation::PostgresVersion);
277        }
278        if !self.postgres.synchronous_commit {
279            violations.push(ReferenceEnvironmentViolation::SynchronousCommit);
280        }
281        if self.postgres.standby_mode != StandbyMode::Synchronous {
282            violations.push(ReferenceEnvironmentViolation::SynchronousStandby);
283        }
284        if self.application_machine.logical_cpus < 8
285            || self.application_machine.memory_bytes < 16 * GIB
286        {
287            violations.push(ReferenceEnvironmentViolation::ApplicationResources);
288        }
289        if self.database_machine.logical_cpus < 8 || self.database_machine.memory_bytes < 32 * GIB {
290            violations.push(ReferenceEnvironmentViolation::DatabaseResources);
291        }
292        if self.topology.application_nodes < 3
293            || self.topology.api_processes < 3
294            || self.topology.scheduler_processes < 3
295            || self.topology.worker_processes < 6
296        {
297            violations.push(ReferenceEnvironmentViolation::Topology);
298        }
299        if self.median_database_rtt_micros > 2_000 {
300            violations.push(ReferenceEnvironmentViolation::DatabaseRtt);
301        }
302        violations
303    }
304}
305
306/// Stable reason that an environment does not satisfy the reference profile.
307#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
308#[serde(rename_all = "snake_case")]
309pub enum ReferenceEnvironmentViolation {
310    /// `PostgreSQL` is not version 16 or 17.
311    PostgresVersion,
312    /// Synchronous commit is disabled.
313    SynchronousCommit,
314    /// No synchronous standby is present.
315    SynchronousStandby,
316    /// Application nodes are smaller than 8 vCPU and 16 GiB.
317    ApplicationResources,
318    /// The database node is smaller than 8 vCPU and 32 GiB.
319    DatabaseResources,
320    /// The role topology is below the reference counts.
321    Topology,
322    /// Median application-to-database RTT exceeds 2 ms.
323    DatabaseRtt,
324}
325
326fn valid_hex(field: &'static str, value: &str, width: usize) -> Result<(), EnvironmentError> {
327    if value.len() != width
328        || !value
329            .bytes()
330            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
331    {
332        return Err(EnvironmentError::InvalidHex { field, width });
333    }
334    Ok(())
335}
336
337fn valid_label(field: &'static str, value: &str) -> Result<(), EnvironmentError> {
338    if value.is_empty() || value.len() > MAX_LABEL_BYTES || value.chars().any(char::is_control) {
339        return Err(EnvironmentError::InvalidLabel(field));
340    }
341    Ok(())
342}
343
344#[cfg(test)]
345pub(crate) fn test_environment(reference: bool) -> QualificationEnvironment {
346    let hex40 = "a".repeat(40);
347    let hex64 = "b".repeat(64);
348    QualificationEnvironment::new(
349        SourceIdentity::new(&hex40, &hex40, &hex64, &hex64, &hex64).unwrap(),
350        MachineEnvironment::new(
351            if reference { 8 } else { 2 },
352            16 * GIB,
353            "test-cpu",
354            "nvme",
355            "linux",
356            "none",
357        )
358        .unwrap(),
359        MachineEnvironment::new(8, 32 * GIB, "test-cpu", "nvme", "linux", "none").unwrap(),
360        PostgresEnvironment::new(
361            17,
362            reference,
363            if reference {
364                StandbyMode::Synchronous
365            } else {
366                StandbyMode::None
367            },
368        )
369        .unwrap(),
370        Topology::new(if reference { 3 } else { 1 }, 3, 3, 6).unwrap(),
371        1_000,
372    )
373    .unwrap()
374}
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379
380    #[test]
381    fn reference_validation_is_explicit() {
382        assert!(test_environment(true).reference_violations().is_empty());
383        assert_eq!(
384            test_environment(false).reference_violations(),
385            vec![
386                ReferenceEnvironmentViolation::SynchronousCommit,
387                ReferenceEnvironmentViolation::SynchronousStandby,
388                ReferenceEnvironmentViolation::ApplicationResources,
389                ReferenceEnvironmentViolation::Topology,
390            ]
391        );
392    }
393
394    #[test]
395    fn identities_and_labels_are_bounded() {
396        assert!(matches!(
397            SourceIdentity::new(
398                "A".repeat(40),
399                "a".repeat(40),
400                "b".repeat(64),
401                "b".repeat(64),
402                "b".repeat(64)
403            ),
404            Err(EnvironmentError::InvalidHex {
405                field: "source_commit",
406                ..
407            })
408        ));
409        assert!(
410            MachineEnvironment::new(1, GIB, "test-cpu", "nvme\nsecret", "linux", "none").is_err()
411        );
412    }
413}