Skip to main content

alien_core/deployment/
state.rs

1//! Deployment state, step results, and runtime metadata.
2
3use crate::{ObservedInventoryBatch, Platform, ResourceHeartbeat, StackState};
4use alien_error::AlienError;
5use bon::Builder;
6use indexmap::IndexMap;
7use serde::{Deserialize, Serialize};
8use std::collections::BTreeMap;
9
10use super::{DeploymentStatus, EnvironmentInfo, ReleaseInfo};
11
12/// Actor that owns structural work during the initial setup phase.
13#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
14#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
15#[serde(rename_all = "camelCase")]
16pub enum InitialSetupAuthority {
17    /// Setup state was registered by an external setup engine. Alien may only
18    /// continue controller states that the importer explicitly initialized.
19    #[default]
20    ImportedHandoff,
21    /// Alien is the setup engine and is running with administrator credentials.
22    DirectSetup,
23}
24
25/// One-shot authority for a setup re-import to replace setup-owned resources.
26#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
27#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
28#[serde(rename_all = "camelCase")]
29pub struct SetupUpdateAuthorization {
30    /// Unique revision used by persistence layers for compare-and-swap updates.
31    pub nonce: String,
32    /// Setup resources and permissions digest (`Stack::setup_update_digest`) of the last
33    /// successful deployment. The field name is retained for serialized compatibility.
34    pub baseline_frozen_digest: String,
35    /// Setup resources and permissions digest (`Stack::setup_update_digest`) of the stack
36    /// the setup re-import prepared.
37    pub target_frozen_digest: String,
38    /// Release whose stack was prepared by setup.
39    pub release_id: String,
40    /// Stable setup target recorded on the imported deployment.
41    pub setup_target: String,
42    /// Exact setup artifact revision that authored this authority.
43    pub setup_fingerprint: String,
44    /// Setup fingerprint contract version.
45    pub setup_fingerprint_version: u32,
46}
47
48/// A setup report the manager declined, for display next to the waiting update.
49#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
50#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
51#[serde(rename_all = "camelCase")]
52pub struct SetupReportRefusal {
53    /// Plain-language reason, safe to show to the customer.
54    pub reason: String,
55    /// Release the chart reported.
56    pub reported_release_id: String,
57    /// When the manager declined it.
58    pub at: chrono::DateTime<chrono::Utc>,
59}
60
61/// A waiting release whose setup change a Helm chart upgrade cannot carry. The
62/// manager works this out from the release and the installed setup, so every
63/// place that offers an upgrade agrees with the manager's report handling.
64#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
65#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
66#[serde(rename_all = "camelCase")]
67pub struct CloudSetupRequired {
68    /// The waiting release this applies to.
69    pub release_id: String,
70    /// Plain-language reason, safe to show to the customer.
71    pub reason: String,
72}
73
74/// The Helm release an Operator reports it was installed as, so the exact
75/// upgrade command can be shown. Reported, never trusted for authority.
76#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
77#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
78#[serde(rename_all = "camelCase")]
79pub struct InstalledHelmRelease {
80    /// Release name, as passed to `helm install`.
81    pub name: String,
82    /// Kubernetes namespace the release is installed in.
83    pub namespace: String,
84}
85
86/// A credential outage's durable retry window, scoped to its deployment phase.
87#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
88#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
89#[serde(rename_all = "camelCase")]
90pub struct CredentialRetry {
91    /// First credential failure in this phase; subsequent attempts keep this timestamp.
92    pub started_at: chrono::DateTime<chrono::Utc>,
93    /// Changing phase starts a new window instead of carrying a previous outage forward.
94    pub status: DeploymentStatus,
95}
96
97/// Explicit disposition of durable data when deleting a deployment.
98/// Missing values from older checkpoints always preserve data.
99#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
100#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
101#[serde(rename_all = "camelCase")]
102pub enum DeletionPolicy {
103    #[default]
104    Retain,
105    Erase,
106}
107
108/// When an air-gapped site's latest status was written and received.
109#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
110#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
111#[serde(rename_all = "camelCase")]
112pub struct AirgappedReportMetadata {
113    /// Site clock time; absent for reports from older clients.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub written_at: Option<chrono::DateTime<chrono::Utc>>,
116    /// Manager clock time when the report was accepted.
117    pub received_at: chrono::DateTime<chrono::Utc>,
118}
119
120/// Runtime metadata for deployment
121///
122/// Stores deployment state that needs to persist across step calls.
123#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
124#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
125#[serde(rename_all = "camelCase")]
126pub struct RuntimeMetadata {
127    /// User-authorized data disposition, persisted before deletion starts.
128    #[serde(default)]
129    pub deletion_policy: DeletionPolicy,
130
131    /// Most recent air-gapped report accepted by the manager.
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub airgapped_report: Option<AirgappedReportMetadata>,
134
135    /// Version of the Operator binary that last reported this deployment, set
136    /// by the manager from the sync request. Missing until an Operator that
137    /// reports its version has synced.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub operator_version: Option<String>,
140
141    /// Bounded credential retry state shared by all deployment drivers.
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub credential_retry: Option<CredentialRetry>,
144
145    /// Actor authorized to perform structural Frozen-resource work during
146    /// InitialSetup. Missing legacy values fail closed as ImportedHandoff.
147    #[serde(default)]
148    pub initial_setup_authority: InitialSetupAuthority,
149
150    /// Setup-owned grant to keep using the direct setup executor for updates.
151    /// Runtime settings and release contents must never create or change this grant.
152    #[serde(default, skip_serializing_if = "super::is_false")]
153    pub automatic_setup: bool,
154
155    /// An imported install whose machines have not been selected yet. Set when the setup
156    /// import registers the deployment; the first InitialSetup step picks machines from free
157    /// quota and clears it with the same result, so the pick happens once and a later step
158    /// never re-picks against quota that its own machines reduced. Deployments stored
159    /// without it deserialize as done.
160    #[serde(default, skip_serializing_if = "super::is_false")]
161    pub first_setup_machines_unselected: bool,
162
163    /// Hash of the environment variables snapshot that was last synced to the vault
164    /// Used to avoid redundant sync operations during incremental deployment
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub last_synced_env_vars_hash: Option<String>,
167
168    /// Exact vault keys owned by the deployment secret synchronizer. This
169    /// inventory lets a later snapshot delete removed keys without listing or
170    /// touching unrelated values in the same vault.
171    #[serde(default, skip_serializing_if = "Vec::is_empty")]
172    pub last_synced_secret_names: Vec<String>,
173
174    /// Credential revocation completed before resource teardown. A delete retry
175    /// can use this receipt after the vault or its binding is gone. Secret sync
176    /// clears it before a deployment can write runtime credentials again.
177    #[serde(default, skip_serializing_if = "is_false")]
178    pub vault_credentials_revoked: bool,
179
180    /// Digest of the installed data inventory whose runtime public-access and
181    /// expiry configuration was protected before cleanup. The serialized field
182    /// name is retained for compatibility. This is not a
183    /// receipt for effective expiry propagation or privileged setup teardown.
184    #[serde(default, skip_serializing_if = "Option::is_none")]
185    pub retained_storage_protection_hash: Option<String>,
186
187    /// UTC API-confirmation time for the matching data protection digest.
188    /// Provider propagation must be qualified separately before final retention.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub retained_storage_protection_confirmed_at: Option<chrono::DateTime<chrono::Utc>>,
191
192    /// Start of the bounded wait for retained data's expiry controls to disable.
193    /// Cleared on confirmation, explicit retry, or returning to normal execution.
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub retained_data_protection_started_at: Option<chrono::DateTime<chrono::Utc>>,
196
197    /// The prepared (mutated) stack from the last successful deployment phase
198    /// This is the stack AFTER mutations have been applied (with service accounts, vault, etc.)
199    /// Used for compatibility checks during updates to compare mutated stacks
200    #[serde(skip_serializing_if = "Option::is_none")]
201    pub prepared_stack: Option<crate::Stack>,
202
203    /// Canonical resolved answers for inputs that gate Frozen resources,
204    /// keyed by input id, recorded when the deployment is created or its
205    /// setup import registers.
206    ///
207    /// Manual installations keep these answers fixed. An installation with an
208    /// ongoing-management grant refreshes them when preparing a release. Live
209    /// resources sharing a gate use the same recorded answer as Frozen resources.
210    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
211    pub persisted_gate_answers: GateAnswers,
212
213    /// Prepared target for an update that has not reached Running yet. Keeping
214    /// it separate preserves the last successful baseline across retries.
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub pending_prepared_stack: Option<crate::Stack>,
217
218    /// Release the in-flight stack was prepared from: `pending_prepared_stack`
219    /// during updates, or `prepared_stack` during local first startup. The target can move
220    /// to a newer release while that stack is still being applied; this tells
221    /// the update which release actually converged.
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub pending_prepared_release_id: Option<String>,
224
225    /// One-shot setup update authority. It contains only non-secret identity
226    /// and canonical resource digests, never the imported payload or tokens.
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub setup_update_authorization: Option<SetupUpdateAuthorization>,
229
230    /// Why the manager last declined a setup report from the installed chart,
231    /// with when. Cleared when a report is accepted or no longer needed.
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub setup_report_refusal: Option<SetupReportRefusal>,
234
235    /// Set while the waiting release changes something only the cloud setup
236    /// can apply, so a chart upgrade is not offered for it.
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub cloud_setup_required: Option<CloudSetupRequired>,
239
240    /// The Helm release the Operator reported it runs as.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub installed_helm_release: Option<InstalledHelmRelease>,
243
244    /// Last generated CLI package revision whose direct setup was applied.
245    /// This lets a newer generated CLI refresh setup-owned infrastructure once
246    /// before handing runtime changes back to the hosted manager.
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub direct_setup_revision: Option<String>,
249
250    /// Whether cross-account registry access has been successfully granted.
251    /// Set to true after the manager successfully sets the ECR/GAR repo policy
252    /// for this deployment's target account. Prevents redundant API calls on
253    /// every reconcile tick.
254    #[serde(default, skip_serializing_if = "is_false")]
255    pub registry_access_granted: bool,
256
257    /// What that grant opened, compared against what the deployment needs now so a grant made
258    /// before a resource existed is finished rather than skipped, and the revoke names what was
259    /// granted. Absent on a grant recorded before this field existed.
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub registry_access: Option<RegistryAccess>,
262
263    /// What a direct setup created for resources it does not own, keyed by resource id. Setup
264    /// teardown removes exactly what is recorded here.
265    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
266    pub setup_scaffolding: BTreeMap<String, SetupScaffolding>,
267
268    /// What a direct setup created for each GCP sandbox, keyed by resource id. Teardown removes
269    /// exactly what is recorded here.
270    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
271    pub gcp_sandbox_scaffolding: BTreeMap<String, GcpSandboxScaffolding>,
272
273    /// Whether each vault-native deployer secret is in the customer's secret
274    /// store, with where it goes. Checked from metadata only; no value is ever
275    /// read or recorded here.
276    #[serde(default, skip_serializing_if = "Vec::is_empty")]
277    pub deployer_secrets: Vec<crate::DeployerSecretReport>,
278
279    /// What a one-token call with the customer admin's setup credentials said about each
280    /// model an AI resource declares. Written once, during setup; the AI controller's heartbeat
281    /// reports it. Absent when no model is declared or the setup could not check.
282    #[serde(default, skip_serializing_if = "Vec::is_empty")]
283    pub ai_access_checks: Vec<AiAccessCheck>,
284    /// When `deployer_secrets` was last read from the customer's secret store. While the
285    /// deployment waits for secrets the check is repeated at most every 30 seconds, because
286    /// the engine steps much faster than the store's rate limits allow.
287    #[serde(default, skip_serializing_if = "Option::is_none")]
288    pub deployer_secrets_checked_at: Option<chrono::DateTime<chrono::Utc>>,
289
290    /// Resources held back while a required deployer secret is missing: the ones that read
291    /// it and everything that depends on them. Everything else keeps installing. Empty once
292    /// no required secret is missing. An Operator that predates this field leaves it absent,
293    /// so readers must treat absence as unknown.
294    #[serde(default, skip_serializing_if = "Vec::is_empty")]
295    pub resources_waiting_for_secrets: Vec<String>,
296}
297
298/// The setup-time answer for one declared model.
299#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
300#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
301#[serde(rename_all = "camelCase")]
302pub struct AiAccessCheck {
303    /// The AI resource that declares the model.
304    pub resource_id: String,
305    /// The model id as the app uses it.
306    pub model_id: String,
307    /// `verified`, `refused` (the cloud refused the model) or `not-checked`.
308    pub result: AiAccessCheckResult,
309    /// The cloud's error code or the reason the check could not run.
310    #[serde(default, skip_serializing_if = "Option::is_none")]
311    pub detail: Option<String>,
312    pub tested_at: chrono::DateTime<chrono::Utc>,
313}
314
315#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
316#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
317#[serde(rename_all = "kebab-case")]
318pub enum AiAccessCheckResult {
319    Verified,
320    Refused,
321    NotChecked,
322}
323
324/// Cloud objects a direct setup created so a runtime-owned resource can run.
325#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
326#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
327#[serde(rename_all = "camelCase", tag = "type")]
328pub enum SetupScaffolding {
329    /// An AWS sandbox's image-build role, and for `egress: deny` its egress objects.
330    #[serde(rename_all = "camelCase")]
331    AwsSandbox {
332        /// IAM role the image build runs as.
333        build_role_name: String,
334        /// What `egress: deny` needs; absent for an open sandbox.
335        #[serde(default, skip_serializing_if = "Option::is_none")]
336        egress: Option<AwsSandboxEgressScaffolding>,
337        /// A Frozen sandbox's MicroVM image, built during setup. A Live one's image belongs to its
338        /// runtime controller.
339        #[serde(default, skip_serializing_if = "Option::is_none")]
340        image_arn: Option<String>,
341    },
342}
343
344/// A Frozen GCP sandbox's image repository and the manager's write access to it. Setup makes
345/// them because the runtime identity may write images into the repository but cannot create
346/// it or change who may; an image-only release then rolls without setup.
347///
348/// Kept in its own `RuntimeMetadata` field, not as a [`SetupScaffolding`] variant: a manager or
349/// CLI from before this record cannot read an unknown variant of that tagged enum, and would then
350/// fail to load the whole deployment state. An unknown field is ignored instead.
351#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
352#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
353#[serde(rename_all = "camelCase")]
354pub struct GcpSandboxScaffolding {
355    /// Artifact Registry repository the sandbox's image is copied into.
356    pub image_repository: String,
357    /// Custom role (no delete) the manager is granted on that repository.
358    pub write_role: String,
359    /// Whether the manager holds `write_role` on the repository.
360    #[serde(default)]
361    pub writer_granted: bool,
362}
363
364/// The objects that keep an AWS deny sandbox's sessions inside the VPC. Each id is recorded as
365/// soon as the object exists and cleared once it is deleted.
366#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
367#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
368#[serde(rename_all = "camelCase")]
369pub struct AwsSandboxEgressScaffolding {
370    /// IAM role Lambda assumes to place the connector's network interfaces.
371    pub operator_role_name: String,
372    /// Security group permitting egress to loopback only.
373    #[serde(default, skip_serializing_if = "Option::is_none")]
374    pub security_group_id: Option<String>,
375    /// `AWS::Lambda::NetworkConnector` the sessions start with.
376    #[serde(default, skip_serializing_if = "Option::is_none")]
377    pub connector_arn: Option<String>,
378    /// Cloud Control request creating or deleting the connector that AWS has not finished. Kept
379    /// so the request's outcome, and AWS's reason when it fails, is read on a later call.
380    #[serde(default, skip_serializing_if = "Option::is_none")]
381    pub connector_request: Option<String>,
382}
383
384impl SetupScaffolding {
385    /// Takes each object `found` names that this record does not, and keeps every one it does:
386    /// a recorded id is what setup last saw, and teardown must delete that one.
387    pub fn fill_missing(&mut self, found: SetupScaffolding) {
388        match (self, found) {
389            (
390                SetupScaffolding::AwsSandbox {
391                    egress, image_arn, ..
392                },
393                SetupScaffolding::AwsSandbox {
394                    egress: found_egress,
395                    image_arn: found_image_arn,
396                    ..
397                },
398            ) => {
399                if image_arn.is_none() {
400                    *image_arn = found_image_arn;
401                }
402                match (egress.as_mut(), found_egress) {
403                    (None, found_egress) => *egress = found_egress,
404                    (Some(recorded), Some(found)) => {
405                        if recorded.security_group_id.is_none() {
406                            recorded.security_group_id = found.security_group_id;
407                        }
408                        if recorded.connector_arn.is_none() {
409                            recorded.connector_arn = found.connector_arn;
410                        }
411                    }
412                    (Some(_), None) => {}
413                }
414            }
415        }
416    }
417}
418
419/// The cross-account read a manager opened on Alien's registry for one deployment.
420#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
421#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
422#[serde(rename_all = "camelCase")]
423pub struct RegistryAccess {
424    /// Repository identifiers the grant names, sorted.
425    #[serde(default, skip_serializing_if = "Vec::is_empty")]
426    pub repositories: Vec<String>,
427
428    /// Compute services the grant admits, sorted. Each pulls as its own principal, so a service
429    /// added later needs the policy rewritten.
430    #[serde(default, skip_serializing_if = "Vec::is_empty")]
431    pub service_types: Vec<String>,
432
433    /// A protected install's verifier, which deploys its functions from these images and so
434    /// reads them as well. `None` on an unprotected install.
435    #[serde(default, skip_serializing_if = "Option::is_none")]
436    pub verifier: Option<String>,
437}
438
439/// Deployment state
440///
441/// Represents the current state of deployed infrastructure, including release tracking.
442/// This is platform-agnostic - no backend IDs or database relationships.
443///
444/// The deployment engine manages releases internally: when a deployment succeeds,
445/// it promotes `target_release` to `current_release` and clears `target_release`.
446#[derive(Debug, Clone, Serialize, Deserialize, Builder)]
447#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
448#[serde(rename_all = "camelCase")]
449pub struct DeploymentState {
450    /// Current lifecycle phase
451    pub status: DeploymentStatus,
452    /// Target cloud platform (AWS, GCP, Azure, Kubernetes)
453    pub platform: Platform,
454    /// Currently deployed release (None for first deployment)
455    #[serde(skip_serializing_if = "Option::is_none")]
456    pub current_release: Option<ReleaseInfo>,
457    /// Target release to deploy (None when synced with current)
458    #[serde(skip_serializing_if = "Option::is_none")]
459    pub target_release: Option<ReleaseInfo>,
460    /// Infrastructure resource tracking (which resources exist, their status, outputs)
461    #[serde(skip_serializing_if = "Option::is_none")]
462    pub stack_state: Option<StackState>,
463    /// Deployment-level error for failures not owned by a specific resource.
464    ///
465    /// Resource controller failures belong in `stack_state.resources[*].error`.
466    #[serde(skip_serializing_if = "Option::is_none")]
467    pub error: Option<AlienError>,
468    /// Cloud account details (account ID, project number, region)
469    #[serde(skip_serializing_if = "Option::is_none")]
470    pub environment_info: Option<EnvironmentInfo>,
471    /// Deployment-specific data (prepared stacks, phase tracking, etc.)
472    #[serde(skip_serializing_if = "Option::is_none")]
473    pub runtime_metadata: Option<RuntimeMetadata>,
474    /// Whether a retry has been requested for a failed deployment
475    /// When true and status is a failed state, the deployment system will retry failed resources
476    #[serde(default, skip_serializing_if = "is_false")]
477    pub retry_requested: bool,
478    /// Protocol version for cross-actor compatibility.
479    /// All actors (manager, push client, agent) check this before stepping.
480    /// Mismatched versions produce a clear error instead of silent corruption.
481    /// See docs/02-manager/10-deployment-protocol.md.
482    pub protocol_version: u32,
483}
484
485impl DeploymentState {
486    /// Returns whether this state carries desired infrastructure for the
487    /// deployment runner to converge.
488    pub fn has_desired(&self) -> bool {
489        self.current_release.is_some()
490            || self.target_release.is_some()
491            || self.stack_state.is_some()
492    }
493
494    /// The stack an unfinished update is still applying after a newer target release arrived,
495    /// with the release it was prepared from. Such an update finishes on that stack before the
496    /// newer target is prepared, so its resources need that release's extensions, not the
497    /// target's. `None` when no update is unfinished or it applies the target release.
498    pub fn unfinished_update(&self) -> Option<(&str, &crate::Stack)> {
499        let metadata = self.runtime_metadata.as_ref()?;
500        let stack = metadata.pending_prepared_stack.as_ref()?;
501        let prepared_from = metadata.pending_prepared_release_id.as_deref()?;
502        let target = self.target_release.as_ref()?.release_id.as_deref()?;
503        (prepared_from != target).then_some((prepared_from, stack))
504    }
505
506    /// The stack whose resources the deployment applies: an unfinished update's, otherwise the
507    /// target release's, otherwise the current release's.
508    pub fn applied_stack(&self) -> Option<&crate::Stack> {
509        self.unfinished_update()
510            .map(|(_, stack)| stack)
511            .or(self.target_release.as_ref().map(|release| &release.stack))
512            .or(self.current_release.as_ref().map(|release| &release.stack))
513    }
514}
515
516/// Result of a deployment step
517///
518/// Contains the complete next deployment state along with hints for the platform.
519/// This replaces the old delta-based `DeploymentStateUpdate` approach.
520#[derive(Debug, Clone, Serialize, Deserialize)]
521#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
522#[serde(rename_all = "camelCase")]
523pub struct DeploymentStepResult {
524    /// The complete next deployment state
525    pub state: DeploymentState,
526
527    /// Suggested delay before next step (optimization hint)
528    /// - `None`: No suggested delay, can poll immediately
529    /// - `Some(ms)`: Wait this many milliseconds before next step
530    #[serde(skip_serializing_if = "Option::is_none")]
531    pub suggested_delay_ms: Option<u64>,
532
533    /// Whether to update heartbeat timestamp (monitoring signal)
534    /// - `false`: Don't update heartbeat (default for most steps)
535    /// - `true`: Update lastHeartbeatAt (for successful health checks in Running state)
536    #[serde(default, skip_serializing_if = "is_false")]
537    pub update_heartbeat: bool,
538
539    /// Managed Alien resource status samples emitted by controllers during this step.
540    #[serde(
541        default,
542        rename = "resourceHeartbeats",
543        skip_serializing_if = "Vec::is_empty"
544    )]
545    pub heartbeats: Vec<ResourceHeartbeat>,
546
547    /// Observed raw-resource inventory batches read during this step.
548    #[serde(
549        default,
550        rename = "observedInventoryBatches",
551        skip_serializing_if = "Vec::is_empty"
552    )]
553    pub observed_inventory_batches: Vec<ObservedInventoryBatch>,
554}
555
556pub(crate) fn is_false(b: &bool) -> bool {
557    !*b
558}
559
560/// Answers for inputs gating Frozen resources, keyed by input id.
561pub type GateAnswers = IndexMap<String, bool>;
562
563/// Oldest deployment protocol version this binary can read.
564pub const MIN_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION: u32 = 1;
565
566/// Deployment protocol written by actors with resumable protection, CORS and
567/// database update states and retained deletion. Older readers must be fenced
568/// before these states exist.
569pub const CURRENT_DEPLOYMENT_PROTOCOL_VERSION: u32 = 4;
570
571/// Latest state protocol this binary can execute.
572pub const MAX_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION: u32 = 4;
573
574/// GCP federation changes setup ownership and target credential semantics.
575pub const GCP_FEDERATION_DEPLOYMENT_PROTOCOL_VERSION: u32 = 2;
576
577pub fn deployment_protocol_version_for_platform(
578    _platform: crate::Platform,
579    _base_platform: Option<crate::Platform>,
580) -> u32 {
581    CURRENT_DEPLOYMENT_PROTOCOL_VERSION
582}
583
584/// Accept unchanged reports or the explicit upgrade to this writer protocol.
585/// Never permit downgrade or unknown protocols. Provider setup prerequisites
586/// remain separate from this checkpoint compatibility check.
587pub fn accepts_deployment_protocol_report(registered: u32, reported: u32) -> bool {
588    (MIN_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION..=MAX_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION)
589        .contains(&registered)
590        && (reported == registered
591            || (registered < CURRENT_DEPLOYMENT_PROTOCOL_VERSION
592                && reported == CURRENT_DEPLOYMENT_PROTOCOL_VERSION))
593}
594
595/// Backwards-compatible alias for older call sites.
596pub const DEPLOYMENT_PROTOCOL_VERSION: u32 = CURRENT_DEPLOYMENT_PROTOCOL_VERSION;
597
598#[cfg(test)]
599mod tests {
600    use super::*;
601    use crate::{Platform, ReleaseInfo, Stack, StackState};
602    use indexmap::IndexMap;
603
604    fn empty_stack() -> Stack {
605        Stack {
606            id: "stack_test".to_string(),
607            resources: IndexMap::new(),
608            inputs: vec![],
609            dynamic_container_repositories: Vec::new(),
610            dynamic_container_image_resources: Vec::new(),
611            extensions: Vec::new(),
612            operations: None,
613            built_architectures: Default::default(),
614            permissions: crate::PermissionsConfig::default(),
615            supported_platforms: None,
616        }
617    }
618
619    fn release_info(id: &str) -> ReleaseInfo {
620        ReleaseInfo {
621            release_id: Some(id.to_string()),
622            version: None,
623            description: None,
624            stack: empty_stack(),
625            signed: None,
626            signer_lists: Vec::new(),
627        }
628    }
629
630    fn state() -> DeploymentState {
631        DeploymentState {
632            status: DeploymentStatus::Pending,
633            platform: Platform::Kubernetes,
634            current_release: None,
635            target_release: None,
636            stack_state: None,
637            error: None,
638            environment_info: None,
639            runtime_metadata: None,
640            retry_requested: false,
641            protocol_version: DEPLOYMENT_PROTOCOL_VERSION,
642        }
643    }
644
645    #[test]
646    fn deployment_state_has_desired_when_release_or_stack_state_exists() {
647        let observe_only = state();
648        assert!(!observe_only.has_desired());
649
650        let mut current = state();
651        current.current_release = Some(release_info("rel_current"));
652        assert!(current.has_desired());
653
654        let mut target = state();
655        target.target_release = Some(release_info("rel_target"));
656        assert!(target.has_desired());
657
658        let mut imported = state();
659        imported.stack_state = Some(StackState::new(Platform::Kubernetes));
660        assert!(imported.has_desired());
661    }
662
663    /// An update still applying the stack of an earlier release, after a newer target arrived,
664    /// applies that stack until it finishes; once the update applies the target release, or
665    /// none is unfinished, the target release's stack is the one applied.
666    #[test]
667    fn an_unfinished_update_applies_the_stack_it_was_prepared_from() {
668        let mut in_flight = empty_stack();
669        in_flight.id = "in-flight".to_string();
670        let mut deployment = state();
671        deployment.current_release = Some(release_info("rel_a"));
672        deployment.target_release = Some(release_info("rel_c"));
673        assert_eq!(deployment.unfinished_update(), None);
674        assert_eq!(
675            deployment.applied_stack(),
676            Some(&deployment.target_release.as_ref().unwrap().stack)
677        );
678
679        deployment.runtime_metadata = Some(RuntimeMetadata {
680            pending_prepared_stack: Some(in_flight.clone()),
681            pending_prepared_release_id: Some("rel_b".to_string()),
682            ..Default::default()
683        });
684        assert_eq!(deployment.unfinished_update(), Some(("rel_b", &in_flight)));
685        assert_eq!(deployment.applied_stack(), Some(&in_flight));
686
687        // Prepared from the target itself: the update applies the target release.
688        deployment
689            .runtime_metadata
690            .as_mut()
691            .unwrap()
692            .pending_prepared_release_id = Some("rel_c".to_string());
693        assert_eq!(deployment.unfinished_update(), None);
694    }
695
696    #[test]
697    fn runtime_metadata_from_before_secret_inventory_defaults_to_empty() {
698        let metadata: RuntimeMetadata = serde_json::from_value(serde_json::json!({
699            "lastSyncedEnvVarsHash": "old-hash"
700        }))
701        .expect("old runtime metadata remains readable");
702
703        assert_eq!(
704            metadata.last_synced_env_vars_hash.as_deref(),
705            Some("old-hash")
706        );
707        assert!(metadata.last_synced_secret_names.is_empty());
708        assert!(!metadata.vault_credentials_revoked);
709        assert!(metadata.retained_storage_protection_hash.is_none());
710        assert!(metadata.retained_storage_protection_confirmed_at.is_none());
711        assert!(metadata.pending_prepared_stack.is_none());
712        assert!(metadata.setup_update_authorization.is_none());
713        assert!(metadata.setup_scaffolding.is_empty());
714    }
715
716    /// Teardown reads this record back from persisted state, so its wire form is a contract.
717    #[test]
718    fn setup_scaffolding_round_trips_in_its_persisted_form() {
719        let persisted = serde_json::json!({
720            "initialSetupAuthority": "directSetup",
721            "setupScaffolding": {
722                "agents": { "type": "awsSandbox", "buildRoleName": "acme-agents-build" }
723            }
724        });
725        let metadata: RuntimeMetadata =
726            serde_json::from_value(persisted.clone()).expect("persisted record reads");
727        assert_eq!(
728            metadata.setup_scaffolding["agents"],
729            SetupScaffolding::AwsSandbox {
730                build_role_name: "acme-agents-build".to_string(),
731                egress: None,
732                image_arn: None,
733            }
734        );
735        assert_eq!(metadata.deletion_policy, DeletionPolicy::Retain);
736        let mut expected = persisted;
737        expected["deletionPolicy"] = serde_json::json!("retain");
738        assert_eq!(serde_json::to_value(&metadata).unwrap(), expected);
739        assert!(
740            serde_json::to_value(RuntimeMetadata::default()).unwrap()["setupScaffolding"].is_null(),
741            "state with no scaffolding serializes as it did before the field existed"
742        );
743    }
744
745    /// The previous release's reader of the persisted record, copied as it was: a tagged enum
746    /// with no fallback for a variant it does not know.
747    #[derive(Debug, Deserialize)]
748    #[serde(rename_all = "camelCase", tag = "type")]
749    #[allow(dead_code)]
750    enum PreviousSetupScaffolding {
751        #[serde(rename_all = "camelCase")]
752        AwsSandbox { build_role_name: String },
753    }
754
755    #[derive(Debug, Deserialize)]
756    #[serde(rename_all = "camelCase")]
757    struct PreviousRuntimeMetadata {
758        #[serde(default)]
759        setup_scaffolding: BTreeMap<String, PreviousSetupScaffolding>,
760    }
761
762    /// A state written with a GCP sandbox's record must still load in a manager or CLI of the
763    /// previous release, which would otherwise fail on the whole deployment state.
764    #[test]
765    fn a_gcp_sandbox_record_loads_in_the_previous_release() {
766        let mut metadata = RuntimeMetadata::default();
767        metadata.gcp_sandbox_scaffolding.insert(
768            "agents".to_string(),
769            GcpSandboxScaffolding {
770                image_repository: "acme-agents-img".to_string(),
771                write_role: "acme_agents_image_write".to_string(),
772                writer_granted: true,
773            },
774        );
775        metadata.setup_scaffolding.insert(
776            "other".to_string(),
777            SetupScaffolding::AwsSandbox {
778                build_role_name: "acme-other-build".to_string(),
779                egress: None,
780                image_arn: None,
781            },
782        );
783        let written = serde_json::to_value(&metadata).unwrap();
784        let previous: PreviousRuntimeMetadata =
785            serde_json::from_value(written.clone()).expect("previous release reads the state");
786        assert_eq!(previous.setup_scaffolding.len(), 1);
787        let current: RuntimeMetadata = serde_json::from_value(written).unwrap();
788        assert_eq!(current, metadata);
789
790        // The shape an unknown variant of the tagged record would have had.
791        let as_a_variant = serde_json::json!({
792            "setupScaffolding": { "agents": { "type": "gcpSandbox", "imageRepository": "r" } }
793        });
794        assert!(
795            serde_json::from_value::<PreviousRuntimeMetadata>(as_a_variant).is_err(),
796            "the fixture reader refuses an unknown variant, which is why the record has its own field"
797        );
798    }
799
800    #[test]
801    fn filling_a_record_takes_only_what_it_lacks() {
802        let egress = |group: Option<&str>, connector: Option<&str>| AwsSandboxEgressScaffolding {
803            operator_role_name: "acme-agents-egress".to_string(),
804            security_group_id: group.map(str::to_string),
805            connector_arn: connector.map(str::to_string),
806            connector_request: None,
807        };
808        let record = |egress| SetupScaffolding::AwsSandbox {
809            build_role_name: "acme-agents-build".to_string(),
810            egress,
811            image_arn: None,
812        };
813
814        let mut partial = record(Some(egress(Some("sg-recorded"), None)));
815        partial.fill_missing(record(Some(egress(Some("sg-found"), Some("arn:found")))));
816        assert_eq!(
817            partial,
818            record(Some(egress(Some("sg-recorded"), Some("arn:found")))),
819            "a recorded id is the one teardown deletes"
820        );
821
822        let mut role_only = record(None);
823        role_only.fill_missing(record(Some(egress(Some("sg-found"), None))));
824        assert_eq!(role_only, record(Some(egress(Some("sg-found"), None))));
825
826        let image = |arn: Option<&str>| SetupScaffolding::AwsSandbox {
827            build_role_name: "acme-agents-build".to_string(),
828            egress: None,
829            image_arn: arn.map(str::to_string),
830        };
831        let mut without_image = image(None);
832        without_image.fill_missing(image(Some("arn:found")));
833        assert_eq!(without_image, image(Some("arn:found")));
834        let mut with_image = image(Some("arn:recorded"));
835        with_image.fill_missing(image(Some("arn:found")));
836        assert_eq!(with_image, image(Some("arn:recorded")));
837    }
838
839    /// A deny sandbox's record is written piece by piece, so a partial one must read back as is.
840    #[test]
841    fn a_partial_egress_record_round_trips_in_its_persisted_form() {
842        let persisted = serde_json::json!({
843            "type": "awsSandbox",
844            "buildRoleName": "acme-agents-build",
845            "egress": {
846                "operatorRoleName": "acme-agents-egress",
847                "securityGroupId": "sg-0123"
848            }
849        });
850        let record: SetupScaffolding =
851            serde_json::from_value(persisted.clone()).expect("persisted record reads");
852        assert_eq!(
853            record,
854            SetupScaffolding::AwsSandbox {
855                build_role_name: "acme-agents-build".to_string(),
856                egress: Some(AwsSandboxEgressScaffolding {
857                    operator_role_name: "acme-agents-egress".to_string(),
858                    security_group_id: Some("sg-0123".to_string()),
859                    connector_arn: None,
860                    connector_request: None,
861                }),
862                image_arn: None,
863            }
864        );
865        assert_eq!(serde_json::to_value(&record).unwrap(), persisted);
866    }
867}