From cebe4259cefddb1b9014106cf986ac01938af459 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Sep 2026 21:02:30 +0200 Subject: [PATCH] Simplify Idunn deployment authority contracts --- crates/idunn-daemon/src/deployment.rs | 730 ++++---- crates/idunn-daemon/src/deployment_plan.rs | 1751 ++++++++++---------- docs/idunn-deployment-authority.md | 226 ++- docs/idunn.md | 627 ++----- vendor/cultnet-rs | 2 +- 5 files changed, 1639 insertions(+), 1697 deletions(-) diff --git a/crates/idunn-daemon/src/deployment.rs b/crates/idunn-daemon/src/deployment.rs index 56fae5b..51e4245 100644 --- a/crates/idunn-daemon/src/deployment.rs +++ b/crates/idunn-daemon/src/deployment.rs @@ -6,7 +6,6 @@ use serde::{Deserialize, Serialize}; pub const TARGET_DECLARATION_SCHEMA: &str = "gamecult.idunn.target_declaration.v1"; pub const OPERATOR_BINDING_SCHEMA: &str = "gamecult.idunn.operator_binding.v1"; -pub const PINNED_TAR_MEMBER_SCHEMA: &str = "gamecult.idunn.pinned_tar_member.v1"; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -19,10 +18,11 @@ pub struct TargetDeclaration { #[serde(default)] pub steps: Vec, #[serde(default)] - pub external_artifacts: Vec, + pub external_inputs: Vec, pub artifacts: Vec, pub service: ServiceDeclaration, - pub state: StateDeclaration, + #[serde(default)] + pub state: Option, #[serde(default)] pub provides: Vec, #[serde(default)] @@ -36,9 +36,7 @@ pub struct TargetDeclaration { pub enum RunnerAffordance { SourceRead, ArtifactWrite, - DependencyNetwork, BuildCache, - PrivateCapabilityAccess, SecretRead, } @@ -70,39 +68,12 @@ pub enum RecipePhase { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct ExternalArtifact { +pub struct ExternalInput { pub id: String, - pub runner: String, - pub manifest: PathBuf, - pub destination: PathBuf, - #[serde(default)] - pub executable: bool, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct PinnedTarMemberManifest { - pub schema: String, pub url: String, - pub archive_sha256: String, - pub member: PathBuf, - pub member_sha256: String, -} - -impl PinnedTarMemberManifest { - pub fn parse(input: &str) -> Result { - let manifest: Self = - toml::from_str(input).context("decoding strict pinned tar-member manifest")?; - ensure!( - manifest.schema == PINNED_TAR_MEMBER_SCHEMA, - "unsupported pinned artifact schema" - ); - https_host(&manifest.url)?; - require_sha256(&manifest.archive_sha256, "archive sha256")?; - require_relative_path(&manifest.member, "archive member", false)?; - require_sha256(&manifest.member_sha256, "member sha256")?; - Ok(manifest) - } + pub sha256: String, + pub runner: String, + pub destination: PathBuf, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -114,6 +85,8 @@ pub struct ArtifactOutput { pub source: PathBuf, pub destination: PathBuf, #[serde(default)] + pub expected_sha256: Option, + #[serde(default)] pub executable: bool, } @@ -146,15 +119,6 @@ pub struct ServiceDeclaration { #[serde(deny_unknown_fields)] pub struct HealthDeclaration { pub contract: String, - pub staged: HealthState, - pub ready: HealthState, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct HealthState { - pub state: String, - pub detail: String, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -176,7 +140,7 @@ pub enum LaunchArgument { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct StateDeclaration { - pub generation: String, + pub schema_generation: String, pub slots: Vec, pub migration: Option, } @@ -227,7 +191,8 @@ pub enum StateRecovery { #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum StateStartup { - CreateOrOpenAfterAdmission, + CreateOrOpenAfterWriteLease, + OpenAtStart, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -291,10 +256,13 @@ pub struct OperatorBinding { pub repository: RepositoryBinding, pub runners: BTreeMap, pub workload: WorkloadBinding, + pub runtime_identity: RuntimeIdentityBinding, pub route: Option, - pub admission: AdmissionBinding, + #[serde(default)] + pub process_write_lease: Option, pub brakes: BrakeBinding, - pub state_transition: StateTransitionBinding, + #[serde(default)] + pub state_transition: Option, pub rollout: RolloutBinding, pub placement: PlacementBinding, #[serde(default)] @@ -341,14 +309,13 @@ pub struct RunnerBinding { pub affordances: BTreeSet, pub cache_root: Option, #[serde(default)] - pub allowed_https_hosts: BTreeSet, - #[serde(default)] pub allowed_programs: BTreeSet, #[serde(default)] pub environment: BTreeMap, #[serde(default)] pub secret_files: BTreeMap, - pub network: RunnerNetwork, + #[serde(default)] + pub network_profile: Option, pub memory_mebibytes: u32, pub cpu_quota_percent: u32, } @@ -359,14 +326,6 @@ pub enum RunnerDriver { Docker, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum RunnerNetwork { - None, - DependencyEgress, - HostPrivate, -} - #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct WorkloadBinding { @@ -375,7 +334,8 @@ pub struct WorkloadBinding { pub group: String, pub unit_prefix: String, pub release_root: PathBuf, - pub state_root: PathBuf, + #[serde(default)] + pub state_root: Option, pub runtime_root: PathBuf, pub network: WorkloadNetwork, pub hardening: WorkloadHardening, @@ -418,16 +378,24 @@ pub enum WorkloadHardening { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct AdmissionBinding { - pub driver: AdmissionDriver, - pub record_path: PathBuf, - pub lock_path: PathBuf, +pub struct RuntimeIdentityBinding { + pub runtime_id: String, + pub expected_signer_identity_id: String, + pub trust_anchor_store: PathBuf, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum AdmissionDriver { - AtomicFile, +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProcessWriteLeaseBinding { + pub record_path: PathBuf, +} + +impl ProcessWriteLeaseBinding { + pub fn lock_path(&self) -> PathBuf { + let mut lock_path = self.record_path.as_os_str().to_os_string(); + lock_path.push(".lock"); + PathBuf::from(lock_path) + } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -497,9 +465,12 @@ pub struct PlacementBinding { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ExternalCapabilityBinding { + pub provider_id: String, pub capability: String, pub schema: String, pub compatibility: String, + #[serde(default = "one")] + pub capacity: u32, pub endpoint: String, } @@ -554,6 +525,9 @@ impl TargetDeclaration { ); require_relative_path(&artifact.source, "artifact source", false)?; require_leaf_path(&artifact.destination, "artifact destination")?; + if let Some(expected_sha256) = &artifact.expected_sha256 { + require_sha256(expected_sha256, "expected artifact sha256")?; + } ensure!( destinations.insert(artifact.destination.as_path()), "artifact destination {} is declared twice", @@ -574,21 +548,32 @@ impl TargetDeclaration { ), } } - for artifact in &self.external_artifacts { - require_id(&artifact.id, "external artifact")?; + let mut external_input_ids = BTreeSet::new(); + let mut external_input_destinations = BTreeSet::new(); + for input in &self.external_inputs { + require_id(&input.id, "external input")?; ensure!( - artifact_ids.insert(artifact.id.as_str()), - "artifact id {} is declared twice", - artifact.id + external_input_ids.insert(input.id.as_str()), + "external input id {} is declared twice", + input.id ); - require_id(&artifact.runner, "external artifact runner class")?; - runner_ids.insert(artifact.runner.as_str()); - require_relative_path(&artifact.manifest, "external artifact manifest", false)?; - require_leaf_path(&artifact.destination, "external artifact destination")?; ensure!( - destinations.insert(artifact.destination.as_path()), - "artifact destination {} is declared twice", - artifact.destination.display() + !artifact_ids.contains(input.id.as_str()), + "external input id {} collides with an artifact id", + input.id + ); + require_value(&input.url, "external input URL")?; + https_host(&input.url)?; + require_sha256(&input.sha256, "external input sha256")?; + require_id(&input.runner, "external input runner class")?; + runner_ids.insert(input.runner.as_str()); + require_relative_path(&input.destination, "external input destination", false)?; + ensure!( + external_input_destinations + .insert((input.runner.as_str(), input.destination.as_path())), + "external input destination {} is declared twice for runner {}", + input.destination.display(), + input.runner ); } ensure!( @@ -610,17 +595,6 @@ impl TargetDeclaration { validate_launch_argument(argument)?; } require_capability(&self.service.health.contract, "health contract")?; - for (label, health) in [ - ("staged health", &self.service.health.staged), - ("ready health", &self.service.health.ready), - ] { - require_value(&health.state, label)?; - require_value(&health.detail, label)?; - } - ensure!( - self.service.health.staged != self.service.health.ready, - "staged and ready health states are identical" - ); for name in &self.service.required_environment { require_environment_name(name)?; } @@ -632,59 +606,71 @@ impl TargetDeclaration { ); } - require_capability(&self.state.generation, "state generation")?; - let slot_ids = unique_ids( - self.state.slots.iter().map(|slot| slot.id.as_str()), - "state slot", - )?; - let mut slot_paths = BTreeSet::new(); - for slot in &self.state.slots { - require_relative_path(&slot.relative_path, "state slot path", false)?; - ensure!( - slot_paths.insert(slot.relative_path.as_path()), - "state slot path {} is declared twice", - slot.relative_path.display() - ); - require_capability(&slot.schema, "state slot schema")?; - if slot.writer == StateWriter::ProcessBoundSingleWriter { + if let Some(state) = &self.state { + require_capability(&state.schema_generation, "state schema generation")?; + ensure!(!state.slots.is_empty(), "state contract has no slots"); + let slot_ids = unique_ids( + state.slots.iter().map(|slot| slot.id.as_str()), + "state slot", + )?; + let mut slot_paths = BTreeSet::::new(); + for slot in &state.slots { + require_relative_path(&slot.relative_path, "state slot path", false)?; ensure!( - slot.startup == StateStartup::CreateOrOpenAfterAdmission, - "writable state slot {} must open after write admission", - slot.id + slot_paths + .iter() + .all(|other| !paths_overlap(other, &slot.relative_path)), + "state slot path {} overlaps another declared slot", + slot.relative_path.display() ); - } - if slot.recovery == StateRecovery::ExternalAuthority { ensure!( - slot.writer == StateWriter::None, - "externally authoritative state slot {} cannot name the service as writer", - slot.id + slot_paths.insert(slot.relative_path.clone()), + "state slot path {} is declared twice", + slot.relative_path.display() ); + require_capability(&slot.schema, "state slot schema")?; + match slot.writer { + StateWriter::ProcessBoundSingleWriter => ensure!( + slot.startup == StateStartup::CreateOrOpenAfterWriteLease, + "writable state slot {} must open after its write lease", + slot.id + ), + StateWriter::None => ensure!( + slot.startup == StateStartup::OpenAtStart, + "non-writable state slot {} cannot wait for a write lease", + slot.id + ), + } + if slot.recovery == StateRecovery::ExternalAuthority { + ensure!( + slot.writer == StateWriter::None, + "externally authoritative state slot {} cannot name the service as writer", + slot.id + ); + } } + if let Some(migration) = state.migration.as_ref() { + ensure!( + artifact_ids.contains(migration.executable_artifact.as_str()), + "migration executable artifact is not declared" + ); + ensure!( + !migration.from_generations.is_empty(), + "migration has no source generations" + ); + for generation in &migration.from_generations { + require_capability(generation, "migration source generation")?; + } + ensure!( + migration.to_generation == state.schema_generation, + "migration destination differs from state generation" + ); + for argument in &migration.arguments { + validate_launch_argument(argument)?; + } + } + ensure!(slot_ids.len() == state.slots.len(), "duplicate state slot"); } - if let Some(migration) = self.state.migration.as_ref() { - ensure!( - artifact_ids.contains(migration.executable_artifact.as_str()), - "migration executable artifact is not declared" - ); - ensure!( - !migration.from_generations.is_empty(), - "migration has no source generations" - ); - for generation in &migration.from_generations { - require_capability(generation, "migration source generation")?; - } - ensure!( - migration.to_generation == self.state.generation, - "migration destination differs from state generation" - ); - for argument in &migration.arguments { - validate_launch_argument(argument)?; - } - } - ensure!( - slot_ids.len() == self.state.slots.len(), - "duplicate state slot" - ); let mut provided = BTreeSet::new(); for capability in &self.provides { @@ -714,6 +700,13 @@ impl TargetDeclaration { dependency.minimum_capacity > 0, "dependency capacity must be positive" ); + if dependency.kind == DependencyKind::Bootstrap { + ensure!( + dependency.startup == StartupOrder::BeforeStart, + "bootstrap dependency {} must be available before start", + dependency.capability + ); + } ensure!( required.insert((dependency.kind, dependency.capability.as_str())), "dependency {} is declared twice for the same kind", @@ -726,6 +719,15 @@ impl TargetDeclaration { } Ok(()) } + + pub fn write_lease_required(&self) -> bool { + self.state.as_ref().is_some_and(|state| { + state + .slots + .iter() + .any(|slot| slot.writer == StateWriter::ProcessBoundSingleWriter) + }) + } } impl OperatorBinding { @@ -819,32 +821,8 @@ impl OperatorBinding { !runner.allowed_programs.is_empty(), "runner {id} has no allowed programs" ); - for host in &runner.allowed_https_hosts { - require_host(host)?; - } - match runner.network { - RunnerNetwork::None => ensure!( - runner.allowed_https_hosts.is_empty(), - "network-none runner {id} has HTTPS hosts" - ), - RunnerNetwork::DependencyEgress => { - ensure!( - runner - .affordances - .contains(&RunnerAffordance::DependencyNetwork), - "dependency-egress runner {id} does not grant dependency-network" - ); - ensure!( - !runner.allowed_https_hosts.is_empty(), - "dependency-egress runner {id} has no allowed hosts" - ); - } - RunnerNetwork::HostPrivate => ensure!( - runner - .affordances - .contains(&RunnerAffordance::PrivateCapabilityAccess), - "host-private runner {id} does not grant private-capability-access" - ), + if let Some(profile) = &runner.network_profile { + require_capability(profile, "runner network profile")?; } for name in runner.environment.keys().chain(runner.secret_files.keys()) { require_environment_name(name)?; @@ -858,25 +836,44 @@ impl OperatorBinding { "build-cache runner {id} has no cache root" ); } + ensure!( + runner.affordances.contains(&RunnerAffordance::BuildCache) + == runner.cache_root.is_some(), + "runner {id} cache root and build-cache affordance disagree" + ); + ensure!( + runner.affordances.contains(&RunnerAffordance::SecretRead) + == !runner.secret_files.is_empty(), + "runner {id} secret files and secret-read affordance disagree" + ); } require_identity(&self.workload.user, "workload user")?; require_identity(&self.workload.group, "workload group")?; require_id(&self.workload.unit_prefix, "workload unit prefix")?; + require_id(&self.runtime_identity.runtime_id, "runtime id")?; + require_id( + &self.runtime_identity.expected_signer_identity_id, + "expected signer identity id", + )?; + require_absolute_path( + &self.runtime_identity.trust_anchor_store, + "trust anchor store", + )?; for (label, path) in [ ("release root", &self.workload.release_root), - ("state root", &self.workload.state_root), ("runtime root", &self.workload.runtime_root), - ("admission record", &self.admission.record_path), - ("admission lock", &self.admission.lock_path), ("deployment brake", &self.brakes.deployment_store), ("lifecycle brake", &self.brakes.lifecycle_store), ] { require_absolute_path(path, label)?; } - ensure!( - self.admission.record_path != self.admission.lock_path, - "admission record and lock paths are identical" - ); + if let Some(state_root) = &self.workload.state_root { + require_absolute_path(state_root, "state root")?; + } + if let Some(write_lease) = &self.process_write_lease { + require_absolute_path(&write_lease.record_path, "process write-lease record")?; + require_absolute_path(&write_lease.lock_path(), "process write-lease lock")?; + } ensure!( self.brakes.deployment_store != self.brakes.lifecycle_store, "deployment and lifecycle brakes are identical" @@ -898,6 +895,15 @@ impl OperatorBinding { { require_absolute_path(path, "workload path")?; } + for path in &self.workload.read_write_paths { + if let Some(state_root) = &self.workload.state_root { + ensure!( + !paths_overlap(path, state_root), + "workload read-write path {} overlaps the write-lease-controlled state root", + path.display() + ); + } + } for capability in &self.workload.capabilities { require_value(capability, "workload capability")?; } @@ -933,42 +939,62 @@ impl OperatorBinding { require_absolute_path(&route.config_path, "route config")?; require_unit(&route.reload_unit, "route reload unit")?; } - match self.state_transition.policy { - StateTransitionPolicy::Preserve => {} - StateTransitionPolicy::FencedMigration => ensure!( - self.state_transition.backup_root.is_some(), - "fenced migration has no backup root" - ), - StateTransitionPolicy::FreshRoot => ensure!( - self.state_transition.archive_root.is_some(), - "fresh-root transition has no whole-root archive" - ), - } - if let Some(path) = self.state_transition.archive_root.as_ref() { - require_absolute_path(path, "state archive root")?; - } - if let Some(path) = self.state_transition.backup_root.as_ref() { - require_absolute_path(path, "state backup root")?; + if let Some(transition) = &self.state_transition { + match transition.policy { + StateTransitionPolicy::Preserve => {} + StateTransitionPolicy::FencedMigration => ensure!( + transition.backup_root.is_some(), + "fenced migration has no backup root" + ), + StateTransitionPolicy::FreshRoot => ensure!( + transition.archive_root.is_some(), + "fresh-root transition has no whole-root archive" + ), + } + if let Some(path) = transition.archive_root.as_ref() { + require_absolute_path(path, "state archive root")?; + } + if let Some(path) = transition.backup_root.as_ref() { + require_absolute_path(path, "state backup root")?; + } } ensure!( self.rollout.retain_releases >= 2, "candidate rollout must retain at least current and prior releases" ); ensure!( - self.placement.desired_replicas > 0, - "desired replicas must be positive" + self.placement.desired_replicas == 1, + "operator binding v1 admits exactly one replica" + ); + ensure!( + self.placement.nodes.len() == 1, + "operator binding v1 admits exactly one node" ); - ensure!(!self.placement.nodes.is_empty(), "placement has no nodes"); for node in &self.placement.nodes { require_id(node, "placement node")?; } + let mut external_contracts = BTreeSet::new(); for capability in &self.external_capabilities { + require_id(&capability.provider_id, "external provider id")?; require_capability_contract( &capability.capability, &capability.schema, &capability.compatibility, )?; + ensure!( + capability.capacity > 0, + "external capability capacity must be positive" + ); require_value(&capability.endpoint, "external capability endpoint")?; + ensure!( + external_contracts.insert(( + capability.provider_id.as_str(), + capability.capability.as_str(), + capability.schema.as_str(), + capability.compatibility.as_str(), + )), + "external provider capability is declared twice" + ); } for profile in &self.profiles { require_capability(profile, "profile")?; @@ -992,9 +1018,9 @@ impl OperatorBinding { .map(|step| step.runner.as_str()) .chain( declaration - .external_artifacts + .external_inputs .iter() - .map(|artifact| artifact.runner.as_str()), + .map(|input| input.runner.as_str()), ) .chain( declaration @@ -1008,6 +1034,18 @@ impl OperatorBinding { declared_runners == bound_runners, "operator runner classes do not exactly match the target recipe" ); + ensure!( + self.process_write_lease.is_some() == declaration.write_lease_required(), + "process write-lease binding must exist exactly when writable state requires it" + ); + ensure!( + self.workload.state_root.is_some() == declaration.state.is_some(), + "state root binding must exist exactly when the recipe declares state" + ); + ensure!( + self.state_transition.is_some() == declaration.state.is_some(), + "state-transition binding must exist exactly when the recipe declares state" + ); for step in &declaration.steps { let binding = &self.runners[&step.runner]; ensure!( @@ -1051,32 +1089,24 @@ impl OperatorBinding { artifact.id ); } - for artifact in &declaration.external_artifacts { - let binding = &self.runners[&artifact.runner]; + for input in &declaration.external_inputs { + let binding = &self.runners[&input.runner]; ensure!( binding.affordances.contains(&RunnerAffordance::SourceRead), - "external artifact {} runner cannot read the frozen source", - artifact.id + "external input {} runner cannot read the frozen source", + input.id ); ensure!( binding .affordances .contains(&RunnerAffordance::ArtifactWrite), - "external artifact {} runner cannot publish artifacts", - artifact.id + "external input {} runner cannot materialize inputs", + input.id ); ensure!( - binding - .affordances - .contains(&RunnerAffordance::DependencyNetwork), - "external artifact {} runner has no dependency-network affordance", - artifact.id - ); - ensure!( - binding.network == RunnerNetwork::DependencyEgress - && !binding.allowed_https_hosts.is_empty(), - "external artifact {} runner has no admitted egress hosts", - artifact.id + binding.network_profile.is_some(), + "external input {} runner has no operator-bound network profile", + input.id ); } let available_environment: BTreeSet<_> = self @@ -1121,20 +1151,41 @@ impl OperatorBinding { match ( declaration.service.route_required, declaration.service.transport, - self.route.as_ref().map(|route| route.driver), + self.route.as_ref(), ) { - (true, ServiceTransport::Http, Some(RouteDriver::NginxHttp)) - | (true, ServiceTransport::Tcp, Some(RouteDriver::NginxStreamTcp)) - | (false, _, None) => {} + (true, ServiceTransport::Http, Some(route)) + if route.driver == RouteDriver::NginxHttp => + { + ensure!( + route.stable_endpoint.starts_with("http://") + || route.stable_endpoint.starts_with("https://"), + "HTTP stable endpoint is not an HTTP URI" + ); + } + (true, ServiceTransport::Tcp, Some(route)) + if route.driver == RouteDriver::NginxStreamTcp => + { + ensure!( + route.stable_endpoint.starts_with("tcp://"), + "TCP stable endpoint is not a TCP URI" + ); + } + (false, _, None) => {} _ => bail!("route binding does not match the launch contract"), } - match self.state_transition.policy { - StateTransitionPolicy::Preserve => {} - StateTransitionPolicy::FencedMigration => ensure!( - declaration.state.migration.is_some(), - "binding requests migration but target declares no migrator" - ), - StateTransitionPolicy::FreshRoot => {} + if let Some(transition) = &self.state_transition { + match transition.policy { + StateTransitionPolicy::Preserve => {} + StateTransitionPolicy::FencedMigration => ensure!( + declaration + .state + .as_ref() + .and_then(|state| state.migration.as_ref()) + .is_some(), + "binding requests migration but target declares no migrator" + ), + StateTransitionPolicy::FreshRoot => {} + } } for dependency in declaration .dependencies @@ -1150,7 +1201,7 @@ impl OperatorBinding { &binding.capability, &binding.schema, &binding.compatibility, - ) + ) && binding.capacity >= dependency.minimum_capacity }), "external capability {} has no compatible operator binding", dependency.capability @@ -1158,33 +1209,6 @@ impl OperatorBinding { } Ok(()) } - - pub fn admit_external_artifact_manifest( - &self, - declaration: &TargetDeclaration, - artifact_id: &str, - manifest_input: &str, - ) -> Result { - let artifact = declaration - .external_artifacts - .iter() - .find(|artifact| artifact.id == artifact_id) - .with_context(|| format!("target declares no external artifact {artifact_id}"))?; - let runner = self.runners.get(&artifact.runner).with_context(|| { - format!("external artifact runner {} is not bound", artifact.runner) - })?; - ensure!( - runner.network == RunnerNetwork::DependencyEgress, - "external artifact runner has no dependency egress" - ); - let manifest = PinnedTarMemberManifest::parse(manifest_input)?; - let host = https_host(&manifest.url)?; - ensure!( - runner.allowed_https_hosts.contains(host), - "external artifact host {host} is not admitted" - ); - Ok(manifest) - } } pub fn capability_compatible( @@ -1328,6 +1352,10 @@ fn require_absolute_path(path: &Path, label: &str) -> Result<()> { Ok(()) } +fn paths_overlap(left: &Path, right: &Path) -> bool { + left.starts_with(right) || right.starts_with(left) +} + fn require_sha1(value: &str, label: &str) -> Result<()> { require_lower_hex(value, 40, label) } @@ -1402,12 +1430,12 @@ phase = "build" runner = "rust" argv = ["cargo", "build", "--locked", "--release", "-p", "test-service"] -[[external_artifacts]] +[[external_inputs]] id = "tool" +url = "https://registry.npmjs.org/tool.tgz" +sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" runner = "rust" -manifest = "deployment/tool.toml" -destination = "tool" -executable = true +destination = "inputs/tool.tgz" [[artifacts]] id = "daemon" @@ -1415,6 +1443,7 @@ source_kind = "runner-output" runner = "rust" source = "target/release/test-service" destination = "test-service" +expected_sha256 = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" executable = true [service] @@ -1431,16 +1460,8 @@ required_environment = ["TEST_SERVICE_BIND"] [service.health] contract = "test-service.cultnet-service-health" -[service.health.staged] -state = "warming" -detail = "traffic-admission-pending" - -[service.health.ready] -state = "active" -detail = "serving" - [state] -generation = "v1" +schema_generation = "v1" [[state.slots]] id = "world" @@ -1449,7 +1470,7 @@ kind = "cultcache-file" schema = "test-service.state.v1" writer = "process-bound-single-writer" recovery = "preserve" -startup = "create-or-open-after-admission" +startup = "create-or-open-after-write-lease" [[provides]] capability = "test-service.runtime" @@ -1480,11 +1501,10 @@ recipe_path = "deployment/idunn/recipe.toml" [runners.rust] driver = "docker" image = "rust@sha256:4c2fd73ef19c5ef9d54bee03b06b2839a392604fbfcd578ed948b71b37c1d7fb" -affordances = ["source-read", "artifact-write", "dependency-network", "build-cache"] +affordances = ["source-read", "artifact-write", "build-cache"] cache_root = "/srv/ghostlight/build-cache" -allowed_https_hosts = ["crates.io", "github.com"] allowed_programs = ["cargo"] -network = "dependency-egress" +network_profile = "build-dependency-egress" memory_mebibytes = 8192 cpu_quota_percent = 400 @@ -1507,6 +1527,11 @@ TEST_SERVICE_BIND = "idunn.private_endpoint" [workload.argument_bindings] state_root = "/var/lib/gamecult/test-service" +[runtime_identity] +runtime_id = "test-service-yggdrasil" +expected_signer_identity_id = "test-service-runtime-signer" +trust_anchor_store = "/etc/gamecult/trust/test-service.cc" + [route] driver = "nginx-http" route_id = "test-service-public" @@ -1517,10 +1542,8 @@ private_port_end = 18839 config_path = "/etc/nginx/idunn-routes/test-service.conf" reload_unit = "nginx.service" -[admission] -driver = "atomic-file" -record_path = "/etc/gamecult/test-service/runtime/process-admission.cc" -lock_path = "/etc/gamecult/test-service/runtime/process-admission.cc.lock" +[process_write_lease] +record_path = "/etc/gamecult/test-service/runtime/process-write-lease.cc" [brakes] deployment_store = "/var/lib/gamecult/idunn-authority/test-service-deployment-brake.cc" @@ -1562,19 +1585,41 @@ nodes = ["yggdrasil"] fn operator_cannot_omit_an_affordance_derived_from_the_recipe() { let recipe = TargetDeclaration::parse(RECIPE).unwrap(); let input = BINDING.replace( - "affordances = [\"source-read\", \"artifact-write\", \"dependency-network\", \"build-cache\"]", - "affordances = [\"source-read\", \"dependency-network\", \"build-cache\"]", + "affordances = [\"source-read\", \"artifact-write\", \"build-cache\"]", + "affordances = [\"source-read\", \"build-cache\"]", ); let binding = OperatorBinding::parse(&input).unwrap(); assert!(binding.admit(&recipe).is_err()); } + #[test] + fn runner_mounts_require_their_exact_operator_affordance() { + let cache_without_affordance = BINDING.replace( + "affordances = [\"source-read\", \"artifact-write\", \"build-cache\"]", + "affordances = [\"source-read\", \"artifact-write\"]", + ); + assert!(OperatorBinding::parse(&cache_without_affordance).is_err()); + + let affordance_without_secret = BINDING.replace( + "affordances = [\"source-read\", \"artifact-write\", \"build-cache\"]", + "affordances = [\"source-read\", \"artifact-write\", \"build-cache\", \"secret-read\"]", + ); + assert!(OperatorBinding::parse(&affordance_without_secret).is_err()); + } + #[test] fn route_transport_mismatch_is_rejected() { let recipe = TargetDeclaration::parse(RECIPE).unwrap(); let binding = OperatorBinding::parse(&BINDING.replace("nginx-http", "nginx-stream-tcp")).unwrap(); assert!(binding.admit(&recipe).is_err()); + + let binding = OperatorBinding::parse(&BINDING.replace( + "https://yggdrasil.gamecult.org/test-service/", + "tcp://yggdrasil.gamecult.org:443", + )) + .unwrap(); + assert!(binding.admit(&recipe).is_err()); } #[test] @@ -1598,13 +1643,16 @@ nodes = ["yggdrasil"] } #[test] - fn fresh_root_keeps_target_preservation_semantics_inside_the_new_generation() { + fn fresh_root_keeps_slot_preservation_semantics_inside_the_new_state_root() { let recipe = TargetDeclaration::parse(RECIPE).unwrap(); let binding = OperatorBinding::parse(BINDING).unwrap(); binding.admit(&recipe).unwrap(); - assert_eq!(recipe.state.slots[0].recovery, StateRecovery::Preserve); assert_eq!( - binding.state_transition.policy, + recipe.state.as_ref().unwrap().slots[0].recovery, + StateRecovery::Preserve + ); + assert_eq!( + binding.state_transition.as_ref().unwrap().policy, StateTransitionPolicy::FreshRoot ); } @@ -1619,29 +1667,123 @@ nodes = ["yggdrasil"] } #[test] - fn pinned_artifact_host_must_be_operator_admitted() { + fn state_slots_cannot_claim_overlapping_paths() { + let input = RECIPE.replace( + "startup = \"create-or-open-after-write-lease\"", + "startup = \"create-or-open-after-write-lease\"\n\n[[state.slots]]\nid = \"nested\"\nrelative_path = \"world.cc/index.cc\"\nkind = \"cultcache-file\"\nschema = \"test-service.index.v1\"\nwriter = \"process-bound-single-writer\"\nrecovery = \"preserve\"\nstartup = \"create-or-open-after-write-lease\"", + ); + assert!(TargetDeclaration::parse(&input).is_err()); + } + + #[test] + fn workload_mount_cannot_bypass_write_lease_controlled_state() { + let input = BINDING.replace( + "cpu_quota_percent = 200\n\n[workload.environment]", + "cpu_quota_percent = 200\nread_write_paths = [\"/var/lib/gamecult/test-service/world\"]\n\n[workload.environment]", + ); + assert!(OperatorBinding::parse(&input).is_err()); + } + + #[test] + fn v1_binding_is_explicitly_singleton() { + assert!( + OperatorBinding::parse( + &BINDING.replace("desired_replicas = 1", "desired_replicas = 2") + ) + .is_err() + ); + assert!( + OperatorBinding::parse(&BINDING.replace( + "nodes = [\"yggdrasil\"]", + "nodes = [\"yggdrasil\", \"raven\"]" + )) + .is_err() + ); + } + + #[test] + fn external_input_uses_an_operator_bound_network_profile() { let recipe = TargetDeclaration::parse(RECIPE).unwrap(); let binding = OperatorBinding::parse(BINDING).unwrap(); - let manifest = r#" -schema = "gamecult.idunn.pinned_tar_member.v1" -url = "https://registry.npmjs.org/tool.tgz" -archive_sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -member = "package/bin/tool" -member_sha256 = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" -"#; - assert!( - binding - .admit_external_artifact_manifest(&recipe, "tool", manifest) - .is_err() + binding.admit(&recipe).unwrap(); + let isolated = BINDING.replace("network_profile = \"build-dependency-egress\"\n", ""); + let binding = OperatorBinding::parse(&isolated).unwrap(); + assert!(binding.admit(&recipe).is_err()); + } + + #[test] + fn process_write_lease_exists_exactly_for_process_writable_state() { + let recipe = TargetDeclaration::parse(RECIPE).unwrap(); + let without_lease = BINDING.replace( + "[process_write_lease]\nrecord_path = \"/etc/gamecult/test-service/runtime/process-write-lease.cc\"\n\n", + "", ); - let admitted = BINDING.replace( - "allowed_https_hosts = [\"crates.io\", \"github.com\"]", - "allowed_https_hosts = [\"crates.io\", \"github.com\", \"registry.npmjs.org\"]", + let binding = OperatorBinding::parse(&without_lease).unwrap(); + assert!(binding.admit(&recipe).is_err()); + + let read_only_recipe = TargetDeclaration::parse( + &RECIPE + .replace( + "writer = \"process-bound-single-writer\"", + "writer = \"none\"", + ) + .replace( + "startup = \"create-or-open-after-write-lease\"", + "startup = \"open-at-start\"", + ), + ) + .unwrap(); + binding.admit(&read_only_recipe).unwrap(); + + let binding = OperatorBinding::parse(BINDING).unwrap(); + assert_eq!( + binding.process_write_lease.as_ref().unwrap().lock_path(), + PathBuf::from("/etc/gamecult/test-service/runtime/process-write-lease.cc.lock") ); - let binding = OperatorBinding::parse(&admitted).unwrap(); - binding - .admit_external_artifact_manifest(&recipe, "tool", manifest) - .unwrap(); + assert!(binding.admit(&read_only_recipe).is_err()); + } + + #[test] + fn stateless_target_has_no_state_binding_or_generation() { + let mut recipe_text = RECIPE.replace( + "arguments = [\n { kind = \"literal\", value = \"--state-root\" },\n { kind = \"binding\", name = \"state_root\" },\n]", + "arguments = []", + ); + let state_start = recipe_text.find("\n[state]\n").unwrap(); + let state_end = recipe_text.find("\n[[provides]]\n").unwrap(); + recipe_text.replace_range(state_start..state_end, ""); + let recipe = TargetDeclaration::parse(&recipe_text).unwrap(); + assert!(recipe.state.is_none()); + + let binding_text = BINDING + .replace("state_root = \"/var/lib/gamecult/test-service\"\n", "") + .replace( + "[workload.argument_bindings]\nstate_root = \"/var/lib/gamecult/test-service\"\n\n", + "", + ) + .replace( + "[process_write_lease]\nrecord_path = \"/etc/gamecult/test-service/runtime/process-write-lease.cc\"\n\n", + "", + ) + .replace( + "[state_transition]\npolicy = \"fresh-root\"\narchive_root = \"/var/lib/gamecult/test-service-cold-archive\"\n\n", + "", + ); + let binding = OperatorBinding::parse(&binding_text).unwrap(); + binding.admit(&recipe).unwrap(); + assert!(binding.workload.state_root.is_none()); + assert!(binding.state_transition.is_none()); + } + + #[test] + fn bootstrap_dependency_must_be_available_before_start() { + let invalid = RECIPE.replace("kind = \"shared-infrastructure\"", "kind = \"bootstrap\""); + assert!(TargetDeclaration::parse(&invalid).is_err()); + let valid = invalid.replace( + "startup = \"before-promotion\"", + "startup = \"before-start\"", + ); + TargetDeclaration::parse(&valid).unwrap(); } #[test] diff --git a/crates/idunn-daemon/src/deployment_plan.rs b/crates/idunn-daemon/src/deployment_plan.rs index 583059f..a6415ab 100644 --- a/crates/idunn-daemon/src/deployment_plan.rs +++ b/crates/idunn-daemon/src/deployment_plan.rs @@ -7,146 +7,178 @@ use sha2::{Digest, Sha256}; use crate::deployment::{ CapabilityDependency, DependencyKind, ExternalCapabilityBinding, OperatorBinding, - ProvidedCapability, TargetDeclaration, capability_compatible, + ProvidedCapability, ServiceTransport, SourceSelectionPolicy, StateDeclaration, + TargetDeclaration, capability_compatible, }; +pub const SOURCE_SELECTION_FACTS_SCHEMA: &str = "idunn.source_selection_facts.v1"; pub const COMPILED_DEPLOYMENT_PLAN_SCHEMA: &str = "idunn.compiled_deployment_plan.v1"; -pub const SEALED_DEPLOYMENT_SCHEMA: &str = "idunn.sealed_deployment.v1"; -pub const EXPECTED_GENERATION_SCHEMA: &str = "idunn.expected_generation.v1"; -pub const GENERATION_CORRELATION_SCHEMA: &str = "idunn.generation_correlation.v1"; -pub const PROMOTION_TRANSACTION_SCHEMA: &str = "idunn.promotion_transaction.v1"; -pub const ADMITTED_GENERATION_SCHEMA: &str = "idunn.admitted_generation.v1"; +pub const EXPECTED_INCARNATION_SCHEMA: &str = "idunn.expected_incarnation.v1"; +pub const SEALED_RELEASE_SCHEMA: &str = "idunn.sealed_release.v1"; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct ResolvedGitlink { +pub struct GitlinkTreeFact { pub origin: String, pub revision: String, + pub tree_entry_revision: String, } +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "policy", rename_all = "kebab-case", deny_unknown_fields)] +pub enum SourceSelection { + PinnedObject, + RefHead, + SignedRelease { release_authority_id: String }, +} + +/// Private facts emitted by the future narrow source driver. Structural +/// validation here does not prove Git ancestry, signatures, or object custody. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct ExactSource { +pub struct SourceSelectionFacts { + pub schema: String, pub origin: String, pub admitted_ref: String, pub revision: String, - pub minimum_revision: String, - pub selection_receipt_sha256: String, - pub gitlinks: BTreeMap, + pub source_tree: String, + pub recipe_path: PathBuf, + pub recipe_blob_sha256: String, + pub gitlinks: BTreeMap, + pub selection: SourceSelection, + pub selected_at_unix_millis: u64, } -impl ExactSource { +impl SourceSelectionFacts { pub fn validate_against(&self, binding: &OperatorBinding) -> Result<()> { + binding.validate()?; + ensure!( + self.schema == SOURCE_SELECTION_FACTS_SCHEMA, + "unsupported source-selection facts schema" + ); ensure!( self.origin == binding.repository.origin, - "exact source origin differs from binding" + "selected origin differs from binding" ); ensure!( self.admitted_ref == binding.repository.admitted_ref, - "exact source ref differs from binding" + "selected ref differs from binding" ); - require_sha1(&self.revision, "exact source revision")?; + require_sha1(&self.revision, "selected revision")?; + require_sha1(&self.source_tree, "selected source tree")?; ensure!( - self.minimum_revision == binding.repository.minimum_revision, - "exact source floor differs from binding" + self.recipe_path == binding.repository.recipe_path, + "selected recipe path differs from binding" ); - require_sha1(&self.minimum_revision, "exact source floor")?; - require_sha256(&self.selection_receipt_sha256, "source-selection receipt")?; + require_sha256(&self.recipe_blob_sha256, "selected recipe blob")?; + ensure!( + self.selected_at_unix_millis > 0, + "source-selection facts have no time" + ); + + match (&binding.repository.selection, &self.selection) { + (SourceSelectionPolicy::PinnedObject, SourceSelection::PinnedObject) => { + let pinned_revision = binding + .repository + .pinned_revision + .as_deref() + .context("validated pinned binding has no revision")?; + ensure!( + self.revision == pinned_revision, + "selected source differs from the pinned revision" + ); + } + (SourceSelectionPolicy::RefHead, SourceSelection::RefHead) => {} + ( + SourceSelectionPolicy::SignedRelease, + SourceSelection::SignedRelease { + release_authority_id, + }, + ) => { + require_token(release_authority_id, "release authority id")?; + } + _ => bail!("source-selection facts do not match operator policy"), + } + let expected_paths: BTreeSet<_> = binding.repository.gitlinks.keys().cloned().collect(); let observed_paths: BTreeSet<_> = self.gitlinks.keys().cloned().collect(); ensure!( expected_paths == observed_paths, - "resolved Gitlinks differ from binding" + "Gitlink tree facts differ from binding" ); - for (path, observed) in &self.gitlinks { + for (path, receipt) in &self.gitlinks { let expected = &binding.repository.gitlinks[path]; ensure!( - observed.origin == expected.origin, + receipt.origin == expected.origin, "Gitlink {} origin differs from binding", path.display() ); - require_sha1(&observed.revision, "Gitlink revision")?; + require_sha1(&receipt.revision, "Gitlink revision")?; + require_sha1(&receipt.tree_entry_revision, "Gitlink tree entry")?; + ensure!( + receipt.revision == receipt.tree_entry_revision, + "Gitlink {} revision differs from the selected tree entry", + path.display() + ); } Ok(()) } } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum ProviderOrigin { - ManagedRuntime, - ExternalOperatorBinding, +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)] +pub enum ExpectedProviderAuthority { + ManagedIncarnation { + target: String, + incarnation_id: String, + plan_id: String, + sealed_release_id: String, + expected_projection_sha256: String, + }, + ExternalOperatorBinding { + binding_target: String, + }, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct ProviderObservation { +pub struct ExpectedProviderRef { pub provider_id: String, - pub provider_target: Option, - pub origin: ProviderOrigin, - pub generation: String, - pub deployment_id: Option, + pub authority: ExpectedProviderAuthority, pub capability: String, pub schema: String, pub compatibility: String, pub capacity: u32, - pub endpoint: String, - pub expected: bool, - pub present: bool, - pub ready: bool, - pub observation_sha256: Option, + pub endpoint: Option, } -impl ProviderObservation { +impl ExpectedProviderRef { pub fn validate(&self) -> Result<()> { - require_token(&self.provider_id, "provider id")?; - if let Some(target) = &self.provider_target { - require_token(target, "provider target")?; - } - require_token(&self.generation, "provider generation")?; - if let Some(deployment_id) = &self.deployment_id { - require_token(deployment_id, "provider deployment id")?; - } + require_token(&self.provider_id, "expected provider id")?; require_contract(&self.capability, &self.schema, &self.compatibility)?; - ensure!(self.capacity > 0, "provider capacity is zero"); - require_value(&self.endpoint, "provider endpoint")?; - ensure!( - !self.present || self.expected, - "provider is present without expected admission" - ); - ensure!( - !self.ready || self.present, - "provider is ready without signed presence" - ); - match self.origin { - ProviderOrigin::ManagedRuntime => { - ensure!( - self.provider_target.is_some(), - "managed provider has no target" - ); - if self.present { - ensure!( - self.deployment_id.is_some(), - "present managed provider has no deployment identity" - ); - require_sha256( - self.observation_sha256.as_deref().unwrap_or_default(), - "managed provider observation", - )?; - } + ensure!(self.capacity > 0, "expected provider capacity is zero"); + if let Some(endpoint) = &self.endpoint { + require_value(endpoint, "expected provider endpoint")?; + } + match &self.authority { + ExpectedProviderAuthority::ManagedIncarnation { + target, + incarnation_id, + plan_id, + sealed_release_id, + expected_projection_sha256, + } => { + require_token(target, "managed provider target")?; + require_token(incarnation_id, "managed provider incarnation")?; + require_sha256(plan_id, "managed provider plan")?; + require_sha256(sealed_release_id, "managed provider sealed release")?; + require_sha256(expected_projection_sha256, "managed expected projection")?; } - ProviderOrigin::ExternalOperatorBinding => { + ExpectedProviderAuthority::ExternalOperatorBinding { binding_target } => { + require_token(binding_target, "external binding target")?; ensure!( - self.provider_target.is_none(), - "external binding impersonates a managed target" - ); - ensure!( - !self.present && !self.ready, - "external configuration impersonates runtime observation" - ); - ensure!( - self.observation_sha256.is_none(), - "external configuration carries a runtime observation digest" + self.endpoint.is_some(), + "external binding has no configured endpoint" ); } } @@ -163,69 +195,140 @@ impl ProviderObservation { &self.compatibility, ) && self.capacity >= dependency.minimum_capacity } + + fn is_external_binding(&self) -> bool { + matches!( + &self.authority, + ExpectedProviderAuthority::ExternalOperatorBinding { .. } + ) + } +} + +pub fn external_binding_provider_refs( + binding: &OperatorBinding, +) -> Result> { + binding.validate()?; + let providers = binding + .external_capabilities + .iter() + .map(|capability| expected_external_provider(&binding.target, capability)) + .collect::>(); + for provider in &providers { + provider.validate()?; + } + Ok(providers) +} + +fn expected_external_provider( + binding_target: &str, + capability: &ExternalCapabilityBinding, +) -> ExpectedProviderRef { + ExpectedProviderRef { + provider_id: capability.provider_id.clone(), + authority: ExpectedProviderAuthority::ExternalOperatorBinding { + binding_target: binding_target.to_owned(), + }, + capability: capability.capability.clone(), + schema: capability.schema.clone(), + compatibility: capability.compatibility.clone(), + capacity: capability.capacity, + endpoint: Some(capability.endpoint.clone()), + } +} + +fn managed_expected_provider_refs( + expected_incarnations: &[ExpectedIncarnation], +) -> Result> { + let mut providers = Vec::new(); + for expected in expected_incarnations { + expected.validate()?; + let expected_projection_sha256 = expected.canonical_sha256()?; + let endpoint = expected + .route + .as_ref() + .map(|route| route.candidate_endpoint.clone()); + for capability in &expected.capabilities { + providers.push(ExpectedProviderRef { + provider_id: expected.runtime_id.clone(), + authority: ExpectedProviderAuthority::ManagedIncarnation { + target: expected.target.clone(), + incarnation_id: expected.incarnation_id.clone(), + plan_id: expected.plan_id.clone(), + sealed_release_id: expected.sealed_release_id.clone(), + expected_projection_sha256: expected_projection_sha256.clone(), + }, + capability: capability.capability.clone(), + schema: capability.schema.clone(), + compatibility: capability.compatibility.clone(), + capacity: capability.capacity, + endpoint: endpoint.clone(), + }); + } + } + Ok(providers) } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct DependencyResolution { +pub struct DependencySelection { pub requirement: CapabilityDependency, - pub provider: Option, + pub provider: Option, } -impl DependencyResolution { - pub fn blocks_start(&self) -> bool { - self.requirement.startup == crate::deployment::StartupOrder::BeforeStart - && self.requirement.kind != DependencyKind::Optional - && !self - .provider - .as_ref() - .is_some_and(|provider| provider.ready) - } - - pub fn blocks_promotion(&self) -> bool { - self.requirement.kind != DependencyKind::Optional - && !self - .provider - .as_ref() - .is_some_and(|provider| provider.ready) +impl DependencySelection { + fn validate(&self) -> Result<()> { + require_contract( + &self.requirement.capability, + &self.requirement.schema, + &self.requirement.compatibility, + )?; + ensure!( + self.requirement.minimum_capacity > 0, + "dependency capacity is zero" + ); + if let Some(provider) = &self.provider { + provider.validate()?; + ensure!( + provider.compatible_with(&self.requirement), + "selected provider is incompatible" + ); + ensure!( + (self.requirement.kind == DependencyKind::ExternalOperatorBinding) + == provider.is_external_binding(), + "selected provider authority does not match dependency kind" + ); + } else { + ensure!( + self.requirement.kind == DependencyKind::Optional, + "required dependency is unresolved" + ); + } + Ok(()) } } -pub fn external_binding_observations( - bindings: &[ExternalCapabilityBinding], -) -> Vec { - bindings - .iter() - .map(|binding| ProviderObservation { - provider_id: format!("operator:{}", binding.capability), - provider_target: None, - origin: ProviderOrigin::ExternalOperatorBinding, - generation: "operator-bound".into(), - deployment_id: None, - capability: binding.capability.clone(), - schema: binding.schema.clone(), - compatibility: binding.compatibility.clone(), - capacity: 1, - endpoint: binding.endpoint.clone(), - expected: true, - present: false, - ready: false, - observation_sha256: None, - }) - .collect() -} - -pub fn resolve_dependencies( +pub fn select_dependencies( declaration: &TargetDeclaration, - observations: &[ProviderObservation], -) -> Result> { - for observation in observations { - observation.validate()?; + providers: &[ExpectedProviderRef], +) -> Result> { + declaration.validate()?; + let mut unique_contracts = BTreeSet::new(); + for provider in providers { + provider.validate()?; + ensure!( + unique_contracts.insert(( + provider.provider_id.as_str(), + provider.capability.as_str(), + provider.schema.as_str(), + provider.compatibility.as_str(), + )), + "expected provider contract is duplicated" + ); } for conflict in &declaration.conflicts { - if observations + if providers .iter() - .any(|provider| provider.expected && provider.capability == conflict.capability) + .any(|provider| provider.capability == conflict.capability) { bail!( "capability conflict {}: {}", @@ -238,23 +341,19 @@ pub fn resolve_dependencies( .dependencies .iter() .map(|dependency| { - let mut candidates = observations + let mut candidates = providers .iter() - .filter(|provider| provider.expected && provider.compatible_with(dependency)) + .filter(|provider| provider.compatible_with(dependency)) + .filter(|provider| { + (dependency.kind == DependencyKind::ExternalOperatorBinding) + == provider.is_external_binding() + }) .cloned() .collect::>(); - if dependency.kind == DependencyKind::ExternalOperatorBinding { - candidates - .retain(|provider| provider.origin == ProviderOrigin::ExternalOperatorBinding); - } else { - candidates.retain(|provider| provider.origin == ProviderOrigin::ManagedRuntime); - } candidates.sort_by(|left, right| { - right - .ready - .cmp(&left.ready) - .then_with(|| right.present.cmp(&left.present)) - .then_with(|| left.provider_id.cmp(&right.provider_id)) + left.provider_id + .cmp(&right.provider_id) + .then_with(|| left.endpoint.cmp(&right.endpoint)) }); let provider = candidates.into_iter().next(); if provider.is_none() && dependency.kind != DependencyKind::Optional { @@ -265,38 +364,108 @@ pub fn resolve_dependencies( dependency.compatibility ); } - Ok(DependencyResolution { + let selection = DependencySelection { requirement: dependency.clone(), provider, - }) + }; + selection.validate()?; + Ok(selection) }) .collect() } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct ExpectedGeneration { - pub schema: String, - pub target: String, - pub generation: String, - pub deployment_id: String, - pub source_revision: String, - pub candidate_endpoint: Option, - pub capabilities: Vec, +pub struct ExpectedRoute { + pub route_id: String, + pub transport: ServiceTransport, + pub stable_endpoint: String, + pub candidate_endpoint: String, } -impl ExpectedGeneration { +impl ExpectedRoute { + fn validate(&self) -> Result<()> { + require_token(&self.route_id, "expected route id")?; + require_value(&self.stable_endpoint, "expected stable endpoint")?; + require_value(&self.candidate_endpoint, "expected candidate endpoint")?; + match self.transport { + ServiceTransport::Http => ensure!( + self.stable_endpoint.starts_with("http://") + || self.stable_endpoint.starts_with("https://"), + "expected HTTP stable endpoint is not an HTTP URI" + ), + ServiceTransport::Tcp => ensure!( + self.stable_endpoint.starts_with("tcp://"), + "expected TCP stable endpoint is not a TCP URI" + ), + _ => bail!("routed expected incarnation has a non-routable transport"), + } + ensure!( + self.candidate_endpoint + .starts_with(&format!("{}://", endpoint_scheme(self.transport)?)), + "expected candidate endpoint transport disagrees" + ); + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExpectedIncarnation { + pub schema: String, + pub plan_id: String, + pub sealed_release_id: String, + pub target: String, + pub incarnation_id: String, + pub runtime_id: String, + pub expected_signer_identity_id: String, + pub health_contract: String, + pub executable_artifact_sha256: String, + pub state_schema_generation: Option, + pub state_contract_sha256: Option, + pub write_lease_required: bool, + pub source_revision: String, + pub node: String, + pub route: Option, + pub capabilities: Vec, + pub dependencies: Vec, +} + +impl ExpectedIncarnation { pub fn validate(&self) -> Result<()> { ensure!( - self.schema == EXPECTED_GENERATION_SCHEMA, - "unsupported expected-generation schema" + self.schema == EXPECTED_INCARNATION_SCHEMA, + "unsupported expected-incarnation schema" ); + require_sha256(&self.plan_id, "expected plan")?; + require_sha256(&self.sealed_release_id, "expected sealed release")?; require_token(&self.target, "expected target")?; - require_token(&self.generation, "expected generation")?; - require_token(&self.deployment_id, "expected deployment")?; + require_token(&self.incarnation_id, "expected incarnation")?; + require_token(&self.runtime_id, "expected runtime id")?; + require_token( + &self.expected_signer_identity_id, + "expected signer identity id", + )?; + require_token(&self.health_contract, "expected health contract")?; + require_sha256( + &self.executable_artifact_sha256, + "expected executable artifact", + )?; + match (&self.state_schema_generation, &self.state_contract_sha256) { + (Some(generation), Some(contract)) => { + require_token(generation, "expected state schema generation")?; + require_sha256(contract, "expected state contract")?; + } + (None, None) => ensure!( + !self.write_lease_required, + "stateless expected incarnation requires a write lease" + ), + _ => bail!("expected state generation and contract digest disagree"), + } require_sha1(&self.source_revision, "expected source revision")?; - if let Some(endpoint) = &self.candidate_endpoint { - require_value(endpoint, "candidate endpoint")?; + require_token(&self.node, "expected node")?; + if let Some(route) = &self.route { + route.validate()?; } let mut capabilities = BTreeSet::new(); for capability in &self.capabilities { @@ -311,31 +480,43 @@ impl ExpectedGeneration { ); ensure!( capabilities.insert(( - &capability.capability, - &capability.schema, - &capability.compatibility + capability.capability.as_str(), + capability.schema.as_str(), + capability.compatibility.as_str(), )), "expected capability is duplicated" ); } + for dependency in &self.dependencies { + dependency.validate()?; + } Ok(()) } + + pub fn canonical_sha256(&self) -> Result { + self.validate()?; + Ok(sha256_id( + &rmp_serde::to_vec(self).context("encoding managed expected projection")?, + )) + } } +/// Private Idunn control-plane state. This contains host binding details and is +/// never an Odin/CultMesh projection. `ExpectedIncarnation` is the sanitized +/// topology projection derived only after a release validates against this +/// plan. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct CompiledDeploymentPlan { pub schema: String, pub plan_id: String, - pub deployment_id: String, + pub incarnation_id: String, pub created_at_unix_millis: u64, - pub source: ExactSource, - pub recipe_sha256: String, - pub binding_sha256: String, - pub declaration: TargetDeclaration, - pub binding: OperatorBinding, - pub dependencies: Vec, - pub expected: ExpectedGeneration, + pub source: SourceSelectionFacts, + pub recipe_blob: Vec, + pub binding_blob: Vec, + pub dependencies: Vec, + pub candidate_port: Option, } impl CompiledDeploymentPlan { @@ -345,61 +526,40 @@ impl CompiledDeploymentPlan { "unsupported deployment-plan schema" ); require_sha256(&self.plan_id, "plan id")?; - require_token(&self.deployment_id, "deployment id")?; + require_token(&self.incarnation_id, "plan incarnation")?; ensure!( - self.created_at_unix_millis > 0, - "deployment plan has no creation time" + self.created_at_unix_millis >= self.source.selected_at_unix_millis, + "deployment plan predates source selection" ); - self.declaration.validate()?; - self.binding.validate()?; - self.binding.admit(&self.declaration)?; - self.source.validate_against(&self.binding)?; - require_sha256(&self.recipe_sha256, "recipe digest")?; - require_sha256(&self.binding_sha256, "binding digest")?; - self.expected.validate()?; + let (declaration, binding) = self.parsed_inputs()?; + self.source.validate_against(&binding)?; ensure!( - self.expected.target == self.declaration.target, - "expected target differs from recipe" + sha256_id(&self.recipe_blob) == self.source.recipe_blob_sha256, + "selected recipe blob differs from the exact plan recipe bytes" ); - ensure!( - self.expected.generation == self.declaration.state.generation, - "expected generation differs from recipe" - ); - ensure!( - self.expected.deployment_id == self.deployment_id, - "expected deployment differs from plan" - ); - ensure!( - self.expected.source_revision == self.source.revision, - "expected source differs from plan" - ); - ensure!( - self.expected.capabilities == self.declaration.provides, - "expected capabilities differ from recipe" - ); - let resolved_requirements: Vec<_> = self + let declared_requirements: Vec<_> = declaration.dependencies.iter().collect(); + let selected_requirements: Vec<_> = self .dependencies .iter() - .map(|resolution| &resolution.requirement) + .map(|selection| &selection.requirement) .collect(); - let declared_requirements: Vec<_> = self.declaration.dependencies.iter().collect(); ensure!( - resolved_requirements == declared_requirements, - "resolved graph differs from recipe dependencies" + declared_requirements == selected_requirements, + "selected graph differs from recipe dependencies" ); - for resolution in &self.dependencies { - if let Some(provider) = &resolution.provider { - provider.validate()?; + for selection in &self.dependencies { + selection.validate()?; + } + match (&binding.route, self.candidate_port) { + (Some(bound), Some(port)) => { ensure!( - provider.compatible_with(&resolution.requirement), - "resolved provider is incompatible" - ); - } else { - ensure!( - resolution.requirement.kind == DependencyKind::Optional, - "required dependency is unresolved" + (bound.private_port_start..=bound.private_port_end).contains(&port), + "candidate port is outside the operator range" ); } + (None, None) => {} + (Some(_), None) => bail!("routed deployment has no candidate port"), + (None, Some(_)) => bail!("private deployment selected a routed candidate port"), } ensure!( self.plan_id == self.recomputed_plan_id()?, @@ -408,6 +568,17 @@ impl CompiledDeploymentPlan { Ok(()) } + fn parsed_inputs(&self) -> Result<(TargetDeclaration, OperatorBinding)> { + let recipe_text = std::str::from_utf8(&self.recipe_blob) + .context("stored deployment recipe is not UTF-8")?; + let binding_text = std::str::from_utf8(&self.binding_blob) + .context("stored operator binding is not UTF-8")?; + let declaration = TargetDeclaration::parse(recipe_text)?; + let binding = OperatorBinding::parse(binding_text)?; + binding.admit(&declaration)?; + Ok((declaration, binding)) + } + fn recomputed_plan_id(&self) -> Result { let mut unsigned = self.clone(); unsigned.plan_id.clear(); @@ -419,64 +590,43 @@ impl CompiledDeploymentPlan { #[allow(clippy::too_many_arguments)] pub fn compile_deployment_plan( - declaration: TargetDeclaration, - binding: OperatorBinding, - source: ExactSource, recipe_bytes: &[u8], binding_bytes: &[u8], - deployment_id: impl Into, + source: SourceSelectionFacts, + incarnation_id: impl Into, candidate_port: Option, created_at_unix_millis: u64, - observed_providers: &[ProviderObservation], + managed_expected_incarnations: &[ExpectedIncarnation], ) -> Result { - declaration.validate()?; - binding.validate()?; + let recipe_text = std::str::from_utf8(recipe_bytes).context("recipe is not UTF-8")?; + let binding_text = std::str::from_utf8(binding_bytes).context("binding is not UTF-8")?; + let declaration = TargetDeclaration::parse(recipe_text)?; + let binding = OperatorBinding::parse(binding_text)?; binding.admit(&declaration)?; source.validate_against(&binding)?; - let deployment_id = deployment_id.into(); - require_token(&deployment_id, "deployment id")?; ensure!( - created_at_unix_millis > 0, - "deployment plan has no creation time" + sha256_id(recipe_bytes) == source.recipe_blob_sha256, + "selected recipe blob differs from compiled recipe bytes" ); - let candidate_endpoint = match (&binding.route, candidate_port) { - (Some(route), Some(port)) => { - ensure!( - (route.private_port_start..=route.private_port_end).contains(&port), - "candidate port is outside the operator range" - ); - Some(format!("{}:{port}", route.private_host)) - } - (None, None) => None, - (Some(_), None) => bail!("routed deployment has no candidate port"), - (None, Some(_)) => bail!("private deployment cannot select a routed candidate port"), - }; - let mut providers = observed_providers.to_vec(); - providers.extend(external_binding_observations( - &binding.external_capabilities, - )); - let dependencies = resolve_dependencies(&declaration, &providers)?; - let expected = ExpectedGeneration { - schema: EXPECTED_GENERATION_SCHEMA.into(), - target: declaration.target.clone(), - generation: declaration.state.generation.clone(), - deployment_id: deployment_id.clone(), - source_revision: source.revision.clone(), - candidate_endpoint, - capabilities: declaration.provides.clone(), - }; + let incarnation_id = incarnation_id.into(); + require_token(&incarnation_id, "deployment incarnation")?; + ensure!( + created_at_unix_millis >= source.selected_at_unix_millis, + "deployment plan predates source selection" + ); + let mut providers = managed_expected_provider_refs(managed_expected_incarnations)?; + providers.extend(external_binding_provider_refs(&binding)?); + let dependencies = select_dependencies(&declaration, &providers)?; let mut plan = CompiledDeploymentPlan { schema: COMPILED_DEPLOYMENT_PLAN_SCHEMA.into(), plan_id: String::new(), - deployment_id, + incarnation_id, created_at_unix_millis, source, - recipe_sha256: sha256_id(recipe_bytes), - binding_sha256: sha256_id(binding_bytes), - declaration, - binding, + recipe_blob: recipe_bytes.to_vec(), + binding_blob: binding_bytes.to_vec(), dependencies, - expected, + candidate_port, }; plan.plan_id = plan.recomputed_plan_id()?; plan.validate()?; @@ -485,7 +635,7 @@ pub fn compile_deployment_plan( #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct ArtifactSeal { +pub struct ArtifactReceipt { pub artifact_id: String, pub destination: PathBuf, pub sha256: String, @@ -493,459 +643,277 @@ pub struct ArtifactSeal { pub executable: bool, } +impl ArtifactReceipt { + fn validate(&self, declaration: &TargetDeclaration) -> Result<()> { + require_token(&self.artifact_id, "artifact receipt id")?; + require_sha256(&self.sha256, "artifact digest")?; + ensure!(self.size_bytes > 0, "sealed artifact is empty"); + let declared = declaration + .artifacts + .iter() + .find(|artifact| artifact.id == self.artifact_id) + .with_context(|| format!("plan declares no artifact {}", self.artifact_id))?; + ensure!( + self.destination == declared.destination && self.executable == declared.executable, + "artifact receipt differs from declared output" + ); + if let Some(expected_sha256) = &declared.expected_sha256 { + ensure!( + self.sha256 == prefixed_sha256(expected_sha256), + "artifact receipt differs from the recipe-pinned digest" + ); + } + Ok(()) + } +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct SealedDeployment { +pub struct ExternalInputMaterializationReceipt { + pub input_id: String, + pub url: String, + pub sha256: String, + pub runner: String, + pub destination: PathBuf, + pub size_bytes: u64, +} + +impl ExternalInputMaterializationReceipt { + fn validate(&self, declaration: &TargetDeclaration) -> Result<()> { + require_token(&self.input_id, "external input receipt id")?; + require_sha256(&self.sha256, "external input materialized digest")?; + ensure!(self.size_bytes > 0, "materialized external input is empty"); + let declared = declaration + .external_inputs + .iter() + .find(|input| input.id == self.input_id) + .with_context(|| format!("plan declares no external input {}", self.input_id))?; + ensure!( + self.url == declared.url + && self.sha256 == prefixed_sha256(&declared.sha256) + && self.runner == declared.runner + && self.destination == declared.destination, + "external input receipt differs from its pinned declaration" + ); + Ok(()) + } +} + +/// Private Idunn release state. The content address covers the exact plan ID, +/// sorted full artifact receipts, and sorted full external-input +/// materialization receipts. The plan remains a separate private record and is +/// supplied explicitly for validation. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SealedRelease { pub schema: String, - pub release_id: String, - pub plan: CompiledDeploymentPlan, - pub plan_sha256: String, - pub artifacts: Vec, + pub sealed_release_id: String, + pub plan_id: String, + pub artifacts: Vec, + pub external_inputs: Vec, pub sealed_at_unix_millis: u64, } -impl SealedDeployment { +impl SealedRelease { pub fn new( - plan: CompiledDeploymentPlan, - release_id: impl Into, - artifacts: Vec, + plan: &CompiledDeploymentPlan, + mut artifacts: Vec, + mut external_inputs: Vec, sealed_at_unix_millis: u64, ) -> Result { plan.validate()?; - let mut sealed = Self { - schema: SEALED_DEPLOYMENT_SCHEMA.into(), - release_id: release_id.into(), - plan_sha256: sha256_id(&rmp_serde::to_vec(&plan)?), - plan, + artifacts.sort_by(|left, right| left.artifact_id.cmp(&right.artifact_id)); + external_inputs.sort_by(|left, right| left.input_id.cmp(&right.input_id)); + let mut release = Self { + schema: SEALED_RELEASE_SCHEMA.into(), + sealed_release_id: String::new(), + plan_id: plan.plan_id.clone(), artifacts, + external_inputs, sealed_at_unix_millis, }; - sealed.validate()?; - sealed - .artifacts - .sort_by(|left, right| left.artifact_id.cmp(&right.artifact_id)); - sealed.validate()?; - Ok(sealed) + release.validate_contents(plan)?; + release.sealed_release_id = release.recomputed_release_id()?; + release.validate_against(plan)?; + Ok(release) } - pub fn validate(&self) -> Result<()> { + pub fn validate_against(&self, plan: &CompiledDeploymentPlan) -> Result<()> { + require_sha256(&self.sealed_release_id, "sealed release id")?; + self.validate_contents(plan)?; ensure!( - self.schema == SEALED_DEPLOYMENT_SCHEMA, - "unsupported sealed-deployment schema" + self.sealed_release_id == self.recomputed_release_id()?, + "sealed release content address is wrong" ); - require_token(&self.release_id, "release id")?; - ensure!( - self.sealed_at_unix_millis >= self.plan.created_at_unix_millis, - "deployment was sealed before it was planned" - ); - self.plan.validate()?; - ensure!( - self.plan_sha256 == sha256_id(&rmp_serde::to_vec(&self.plan)?), - "sealed plan digest is wrong" - ); - let declared = self - .plan - .declaration + Ok(()) + } + + pub fn expected_projection( + &self, + plan: &CompiledDeploymentPlan, + ) -> Result { + self.validate_against(plan)?; + let (declaration, binding) = plan.parsed_inputs()?; + let node = binding + .placement + .nodes + .iter() + .next() + .context("validated singleton binding has no node")? + .clone(); + let route = match (&binding.route, plan.candidate_port) { + (Some(bound), Some(port)) => Some(ExpectedRoute { + route_id: bound.route_id.clone(), + transport: declaration.service.transport, + stable_endpoint: bound.stable_endpoint.clone(), + candidate_endpoint: format!( + "{}://{}:{port}", + endpoint_scheme(declaration.service.transport)?, + bound.private_host + ), + }), + (None, None) => None, + _ => bail!("plan route and candidate port disagree"), + }; + let executable_artifact_sha256 = self .artifacts .iter() - .map(|artifact| { - ( - artifact.id.as_str(), - artifact.destination.as_path(), - artifact.executable, - ) - }) - .chain( - self.plan - .declaration - .external_artifacts - .iter() - .map(|artifact| { - ( - artifact.id.as_str(), - artifact.destination.as_path(), - artifact.executable, - ) - }), - ) - .collect::>(); - let mut observed = BTreeSet::new(); - for artifact in &self.artifacts { - require_token(&artifact.artifact_id, "artifact seal id")?; - require_sha256(&artifact.sha256, "artifact seal digest")?; - ensure!(artifact.size_bytes > 0, "sealed artifact is empty"); - ensure!( - observed.insert(( - artifact.artifact_id.as_str(), - artifact.destination.as_path(), - artifact.executable - )), - "artifact seal is duplicated" - ); - } - ensure!( - declared == observed, - "sealed artifacts differ from declared outputs" - ); - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct RuntimePresence { - pub target: String, - pub generation: String, - pub deployment_id: String, - pub source_revision: String, - pub endpoint: Option, - pub capabilities: Vec, - pub runtime_id: String, - pub signer_identity_id: String, - pub signed_statement_sha256: String, -} - -impl RuntimePresence { - pub fn validate(&self) -> Result<()> { - require_token(&self.target, "presence target")?; - require_token(&self.generation, "presence generation")?; - require_token(&self.deployment_id, "presence deployment")?; - require_sha1(&self.source_revision, "presence source revision")?; - if let Some(endpoint) = &self.endpoint { - require_value(endpoint, "presence endpoint")?; - } - require_token(&self.runtime_id, "presence runtime")?; - require_token(&self.signer_identity_id, "presence signer")?; - require_sha256(&self.signed_statement_sha256, "presence statement")?; - let mut capabilities = BTreeSet::new(); - for capability in &self.capabilities { - require_contract( - &capability.capability, - &capability.schema, - &capability.compatibility, - )?; - ensure!( - capability.capacity > 0, - "presence capability capacity is zero" - ); - ensure!( - capabilities.insert(( - &capability.capability, - &capability.schema, - &capability.compatibility, - )), - "presence capability is duplicated" - ); - } - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct HealthObservation { - pub contract: String, - pub state: String, - pub detail: String, - pub signed_statement_sha256: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct GenerationCorrelation { - pub schema: String, - pub target: String, - pub generation: String, - pub expected: bool, - pub present: bool, - pub ready: bool, - pub disagreements: Vec, -} - -pub fn correlate_generation( - plan: &CompiledDeploymentPlan, - presence: Option<&RuntimePresence>, - health: Option<&HealthObservation>, -) -> Result { - plan.validate()?; - let mut disagreements = Vec::new(); - let mut present = false; - if let Some(presence) = presence { - presence.validate()?; - for (matches, code) in [ - (presence.target == plan.expected.target, "target-mismatch"), - ( - presence.generation == plan.expected.generation, - "generation-mismatch", - ), - ( - presence.deployment_id == plan.expected.deployment_id, - "deployment-mismatch", - ), - ( - presence.source_revision == plan.expected.source_revision, - "source-mismatch", - ), - ( - presence.endpoint == plan.expected.candidate_endpoint, - "endpoint-mismatch", - ), - ( - capability_set(&presence.capabilities) - == capability_set(&plan.expected.capabilities), - "capability-mismatch", - ), - ] { - if !matches { - disagreements.push(code.into()); - } - } - present = disagreements.is_empty(); - } else { - disagreements.push("runtime-presence-missing".into()); - } - let mut health_ready = false; - if let (Some(presence), Some(health)) = (presence, health) { - require_token(&health.contract, "health contract")?; - require_value(&health.state, "health state")?; - require_value(&health.detail, "health detail")?; - require_sha256(&health.signed_statement_sha256, "health statement")?; - if health.signed_statement_sha256 != presence.signed_statement_sha256 { - disagreements.push("health-presence-statement-mismatch".into()); - } else if health.contract != plan.declaration.service.health.contract { - disagreements.push("health-contract-mismatch".into()); - } else if health.state != plan.declaration.service.health.ready.state { - disagreements.push("health-state-not-ready".into()); - } else if health.detail != plan.declaration.service.health.ready.detail { - disagreements.push("health-detail-not-ready".into()); - } else { - health_ready = true; - } - } else if health.is_none() { - disagreements.push("health-missing".into()); - } - if plan - .dependencies - .iter() - .any(DependencyResolution::blocks_promotion) - { - disagreements.push("dependency-graph-not-ready".into()); - } - disagreements.sort(); - disagreements.dedup(); - Ok(GenerationCorrelation { - schema: GENERATION_CORRELATION_SCHEMA.into(), - target: plan.expected.target.clone(), - generation: plan.expected.generation.clone(), - expected: true, - present, - ready: present && health_ready && disagreements.is_empty(), - disagreements, - }) -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum PromotionPhase { - Planned, - Materialized, - Sealed, - CandidateStarted, - Staged, - Fenced, - RouteObserved, - WriteAdmitted, - Active, - Draining, - Complete, -} - -impl PromotionPhase { - pub fn next(self) -> Option { - Some(match self { - Self::Planned => Self::Materialized, - Self::Materialized => Self::Sealed, - Self::Sealed => Self::CandidateStarted, - Self::CandidateStarted => Self::Staged, - Self::Staged => Self::Fenced, - Self::Fenced => Self::RouteObserved, - Self::RouteObserved => Self::WriteAdmitted, - Self::WriteAdmitted => Self::Active, - Self::Active => Self::Draining, - Self::Draining => Self::Complete, - Self::Complete => return None, - }) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct PromotionTransaction { - pub schema: String, - pub transaction_id: String, - pub plan_id: String, - pub target: String, - pub phase: PromotionPhase, - pub revision: u64, - pub updated_at_unix_millis: u64, -} - -impl PromotionTransaction { - pub fn new( - transaction_id: impl Into, - plan: &CompiledDeploymentPlan, - created_at_unix_millis: u64, - ) -> Result { - plan.validate()?; - let transaction = Self { - schema: PROMOTION_TRANSACTION_SCHEMA.into(), - transaction_id: transaction_id.into(), + .find(|artifact| artifact.artifact_id == declaration.service.executable_artifact) + .context("sealed release has no executable service artifact")? + .sha256 + .clone(); + let expected = ExpectedIncarnation { + schema: EXPECTED_INCARNATION_SCHEMA.into(), plan_id: plan.plan_id.clone(), - target: plan.declaration.target.clone(), - phase: PromotionPhase::Planned, - revision: 0, - updated_at_unix_millis: created_at_unix_millis, + sealed_release_id: self.sealed_release_id.clone(), + target: declaration.target.clone(), + incarnation_id: plan.incarnation_id.clone(), + runtime_id: binding.runtime_identity.runtime_id.clone(), + expected_signer_identity_id: binding + .runtime_identity + .expected_signer_identity_id + .clone(), + health_contract: declaration.service.health.contract.clone(), + executable_artifact_sha256, + state_schema_generation: declaration + .state + .as_ref() + .map(|state| state.schema_generation.clone()), + state_contract_sha256: declaration + .state + .as_ref() + .map(canonical_state_contract_sha256) + .transpose()?, + write_lease_required: declaration.write_lease_required(), + source_revision: plan.source.revision.clone(), + node, + route, + capabilities: declaration.provides.clone(), + dependencies: plan.dependencies.clone(), }; - transaction.validate()?; - Ok(transaction) + expected.validate()?; + Ok(expected) } - pub fn validate(&self) -> Result<()> { + fn validate_contents(&self, plan: &CompiledDeploymentPlan) -> Result<()> { ensure!( - self.schema == PROMOTION_TRANSACTION_SCHEMA, - "unsupported promotion transaction schema" + self.schema == SEALED_RELEASE_SCHEMA, + "unsupported sealed-release schema" ); - require_token(&self.transaction_id, "promotion transaction")?; - require_sha256(&self.plan_id, "promotion plan")?; - require_token(&self.target, "promotion target")?; + plan.validate()?; + let (declaration, _) = plan.parsed_inputs()?; + require_sha256(&self.plan_id, "sealed plan id")?; ensure!( - self.updated_at_unix_millis > 0, - "promotion transaction has no update time" + self.plan_id == plan.plan_id, + "sealed release refers to a different plan" ); + ensure!( + self.sealed_at_unix_millis >= plan.created_at_unix_millis, + "release was sealed before it was planned" + ); + ensure!( + self.artifacts + .windows(2) + .all(|pair| pair[0].artifact_id < pair[1].artifact_id), + "artifact receipts are not in canonical order" + ); + ensure!( + self.external_inputs + .windows(2) + .all(|pair| pair[0].input_id < pair[1].input_id), + "external input receipts are not in canonical order" + ); + let declared_ids = declaration + .artifacts + .iter() + .map(|artifact| artifact.id.as_str()) + .collect::>(); + let observed_ids = self + .artifacts + .iter() + .map(|artifact| artifact.artifact_id.as_str()) + .collect::>(); + ensure!( + declared_ids == observed_ids && observed_ids.len() == self.artifacts.len(), + "artifact receipts differ from declared outputs" + ); + for artifact in &self.artifacts { + artifact.validate(&declaration)?; + } + let declared_input_ids = declaration + .external_inputs + .iter() + .map(|input| input.id.as_str()) + .collect::>(); + let observed_input_ids = self + .external_inputs + .iter() + .map(|input| input.input_id.as_str()) + .collect::>(); + ensure!( + declared_input_ids == observed_input_ids + && observed_input_ids.len() == self.external_inputs.len(), + "external input receipts differ from pinned declarations" + ); + for input in &self.external_inputs { + input.validate(&declaration)?; + } Ok(()) } - pub fn advance(&self, phase: PromotionPhase, updated_at_unix_millis: u64) -> Result { - self.validate()?; - ensure!( - self.phase.next() == Some(phase), - "promotion phase transition is not adjacent" - ); - ensure!( - updated_at_unix_millis >= self.updated_at_unix_millis, - "promotion time moved backwards" - ); - let next = Self { - schema: self.schema.clone(), - transaction_id: self.transaction_id.clone(), - plan_id: self.plan_id.clone(), - target: self.target.clone(), - phase, - revision: self - .revision - .checked_add(1) - .context("promotion revision overflow")?, - updated_at_unix_millis, - }; - next.validate()?; - Ok(next) + fn recomputed_release_id(&self) -> Result { + Ok(sha256_id( + &rmp_serde::to_vec(&( + self.schema.as_str(), + self.plan_id.as_str(), + &self.artifacts, + &self.external_inputs, + )) + .context("encoding sealed release identity")?, + )) } } -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct AdmittedGeneration { - pub schema: String, - pub target: String, - pub generation: String, - pub deployment_id: String, - pub plan_id: String, - pub release_id: String, - pub source_revision: String, - pub workload_unit: String, - pub process_id: u32, - pub process_starttime_ticks: u64, - pub private_endpoint: Option, - pub route_id: Option, - pub route_observation_sha256: Option, - pub write_admission_sha256: String, - pub admitted_at_unix_millis: u64, +fn canonical_state_contract_sha256(state: &StateDeclaration) -> Result { + Ok(sha256_id( + &rmp_serde::to_vec(state).context("encoding canonical state contract")?, + )) } -impl AdmittedGeneration { - pub fn validate_against(&self, sealed: &SealedDeployment) -> Result<()> { - ensure!( - self.schema == ADMITTED_GENERATION_SCHEMA, - "unsupported admitted-generation schema" - ); - sealed.validate()?; - require_token(&self.target, "admitted target")?; - require_token(&self.generation, "admitted generation")?; - require_token(&self.deployment_id, "admitted deployment")?; - require_sha256(&self.plan_id, "admitted plan")?; - require_token(&self.release_id, "admitted release")?; - require_sha1(&self.source_revision, "admitted source")?; - require_token(&self.workload_unit, "admitted workload unit")?; - ensure!(self.process_id > 0, "admitted process id is zero"); - ensure!( - self.process_starttime_ticks > 0, - "admitted process start time is zero" - ); - if let Some(endpoint) = &self.private_endpoint { - require_value(endpoint, "admitted private endpoint")?; +fn endpoint_scheme(transport: ServiceTransport) -> Result<&'static str> { + match transport { + ServiceTransport::Http => Ok("http"), + ServiceTransport::Tcp => Ok("tcp"), + ServiceTransport::Rudp | ServiceTransport::Private => { + bail!("service transport has no stable route scheme") } - match (&self.route_id, &self.route_observation_sha256) { - (Some(route_id), Some(digest)) => { - require_token(route_id, "admitted route")?; - require_sha256(digest, "route observation")?; - } - (None, None) => {} - _ => bail!("admitted route identity and observation are incomplete"), - } - require_sha256(&self.write_admission_sha256, "write admission")?; - ensure!(self.admitted_at_unix_millis > 0, "admission has no time"); - ensure!( - self.target == sealed.plan.declaration.target, - "admitted target differs from sealed plan" - ); - ensure!( - self.generation == sealed.plan.declaration.state.generation, - "admitted generation differs from sealed plan" - ); - ensure!( - self.deployment_id == sealed.plan.deployment_id, - "admitted deployment differs from sealed plan" - ); - ensure!( - self.plan_id == sealed.plan.plan_id, - "admitted plan differs from sealed plan" - ); - ensure!( - self.release_id == sealed.release_id, - "admitted release differs from sealed plan" - ); - ensure!( - self.source_revision == sealed.plan.source.revision, - "admitted source differs from sealed plan" - ); - ensure!( - self.private_endpoint == sealed.plan.expected.candidate_endpoint, - "admitted endpoint differs from expected plan" - ); - match &sealed.plan.binding.route { - Some(route) => ensure!( - self.route_id.as_deref() == Some(route.route_id.as_str()), - "admitted route differs from binding" - ), - None => ensure!( - self.route_id.is_none(), - "private deployment carries a route" - ), - } - Ok(()) } } +fn prefixed_sha256(raw_sha256: &str) -> String { + format!("sha256-{raw_sha256}") +} + fn require_token(value: &str, label: &str) -> Result<()> { ensure!( !value.is_empty() && value.len() <= 128, @@ -967,20 +935,6 @@ fn require_contract(capability: &str, schema: &str, compatibility: &str) -> Resu require_token(compatibility, "capability compatibility") } -fn capability_set(capabilities: &[ProvidedCapability]) -> BTreeSet<(&str, &str, &str, u32)> { - capabilities - .iter() - .map(|capability| { - ( - capability.capability.as_str(), - capability.schema.as_str(), - capability.compatibility.as_str(), - capability.capacity, - ) - }) - .collect() -} - fn require_value(value: &str, label: &str) -> Result<()> { ensure!( !value.trim().is_empty() && value == value.trim(), @@ -1029,7 +983,6 @@ fn sha256_id(bytes: &[u8]) -> String { #[cfg(test)] mod tests { use super::*; - use crate::deployment::{OperatorBinding, TargetDeclaration}; const RECIPE: &str = r#" schema = "gamecult.idunn.target_declaration.v1" @@ -1042,12 +995,20 @@ phase = "build" runner = "rust" argv = ["cargo", "build", "--locked"] +[[external_inputs]] +id = "toolchain-index" +url = "https://example.invalid/toolchain-index" +sha256 = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" +runner = "rust" +destination = "inputs/toolchain-index" + [[artifacts]] id = "daemon" source_kind = "runner-output" runner = "rust" source = "target/release/service" destination = "service" +expected_sha256 = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" executable = true [service] @@ -1059,16 +1020,17 @@ required_environment = ["SERVICE_BIND"] [service.health] contract = "service.health" -[service.health.staged] -state = "warming" -detail = "traffic-admission-pending" - -[service.health.ready] -state = "active" -detail = "serving" - [state] -generation = "v1" +schema_generation = "v1" + +[[state.slots]] +id = "runtime-cache" +relative_path = "runtime-cache.cc" +kind = "cultcache-file" +schema = "service.runtime-cache.v1" +writer = "none" +recovery = "rebuildable" +startup = "open-at-start" [[provides]] capability = "service.runtime" @@ -1099,7 +1061,7 @@ driver = "docker" image = "rust@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" affordances = ["source-read", "artifact-write"] allowed_programs = ["cargo"] -network = "none" +network_profile = "build-dependency-egress" memory_mebibytes = 2048 cpu_quota_percent = 200 @@ -1119,6 +1081,11 @@ cpu_quota_percent = 100 [workload.environment] SERVICE_BIND = "idunn.private_endpoint" +[runtime_identity] +runtime_id = "service-yggdrasil" +expected_signer_identity_id = "service-runtime-signer" +trust_anchor_store = "/etc/gamecult/trust/service.cc" + [route] driver = "nginx-http" route_id = "service" @@ -1129,11 +1096,6 @@ private_port_end = 18009 config_path = "/etc/nginx/idunn-routes/service.conf" reload_unit = "nginx.service" -[admission] -driver = "atomic-file" -record_path = "/run/gamecult/idunn/service/admission.cc" -lock_path = "/run/gamecult/idunn/service/admission.cc.lock" - [brakes] deployment_store = "/var/lib/gamecult/idunn/service-deployment-brake.cc" lifecycle_store = "/var/lib/gamecult/idunn/service-lifecycle-brake.cc" @@ -1151,172 +1113,275 @@ desired_replicas = 1 nodes = ["yggdrasil"] "#; - fn provider(ready: bool) -> ProviderObservation { - ProviderObservation { - provider_id: "odin-yggdrasil".into(), - provider_target: Some("odin".into()), - origin: ProviderOrigin::ManagedRuntime, - generation: "odin-v1".into(), - deployment_id: Some("odin-deployment-1".into()), - capability: "odin.verse-rendezvous".into(), - schema: "odin.verse-topology.v1".into(), - compatibility: "v1".into(), - capacity: 1, - endpoint: "10.77.0.1:17871".into(), - expected: true, - present: ready, - ready, - observation_sha256: ready.then(|| format!("sha256-{}", "a".repeat(64))), + fn digest(byte: u8) -> String { + format!("sha256-{}", char::from(byte).to_string().repeat(64)) + } + + fn source(recipe: &str) -> SourceSelectionFacts { + SourceSelectionFacts { + schema: SOURCE_SELECTION_FACTS_SCHEMA.into(), + origin: "https://github.com/GameCult/Service.git".into(), + admitted_ref: "refs/heads/main".into(), + revision: "2222222222222222222222222222222222222222".into(), + source_tree: "3333333333333333333333333333333333333333".into(), + recipe_path: "deployment/idunn/recipe.toml".into(), + recipe_blob_sha256: sha256_id(recipe.as_bytes()), + gitlinks: BTreeMap::new(), + selection: SourceSelection::RefHead, + selected_at_unix_millis: 100, } } - fn plan(provider: ProviderObservation) -> CompiledDeploymentPlan { + fn odin() -> ExpectedIncarnation { + ExpectedIncarnation { + schema: EXPECTED_INCARNATION_SCHEMA.into(), + plan_id: digest(b'a'), + sealed_release_id: digest(b'e'), + target: "odin".into(), + incarnation_id: "odin-incarnation-1".into(), + runtime_id: "odin-yggdrasil".into(), + expected_signer_identity_id: "odin-runtime-signer".into(), + health_contract: "odin.cultnet-service-health".into(), + executable_artifact_sha256: digest(b'f'), + state_schema_generation: None, + state_contract_sha256: None, + write_lease_required: false, + source_revision: "2222222222222222222222222222222222222222".into(), + node: "yggdrasil".into(), + route: Some(ExpectedRoute { + route_id: "odin-private".into(), + transport: ServiceTransport::Tcp, + stable_endpoint: "tcp://10.77.0.1:17871".into(), + candidate_endpoint: "tcp://127.0.0.1:17871".into(), + }), + capabilities: vec![ProvidedCapability { + capability: "odin.verse-rendezvous".into(), + schema: "odin.verse-topology.v1".into(), + compatibility: "v1".into(), + capacity: 1, + }], + dependencies: Vec::new(), + } + } + + fn plan() -> CompiledDeploymentPlan { compile_deployment_plan( - TargetDeclaration::parse(RECIPE).unwrap(), - OperatorBinding::parse(BINDING).unwrap(), - ExactSource { - origin: "https://github.com/GameCult/Service.git".into(), - admitted_ref: "refs/heads/main".into(), - revision: "2222222222222222222222222222222222222222".into(), - minimum_revision: "1111111111111111111111111111111111111111".into(), - selection_receipt_sha256: format!("sha256-{}", "d".repeat(64)), - gitlinks: BTreeMap::new(), - }, RECIPE.as_bytes(), BINDING.as_bytes(), - "deployment-1", + source(RECIPE), + "service-incarnation-1", Some(18001), - 100, - &[provider], + 110, + &[odin()], ) .unwrap() } - #[test] - fn compilation_is_deterministic_and_configuration_does_not_supply_readiness() { - let first = plan(provider(true)); - let second = plan(provider(true)); - assert_eq!(first, second); - assert!(!first.dependencies[0].blocks_promotion()); + fn artifact_receipt() -> ArtifactReceipt { + ArtifactReceipt { + artifact_id: "daemon".into(), + destination: "service".into(), + sha256: digest(b'c'), + size_bytes: 42, + executable: true, + } + } - let external = ExternalCapabilityBinding { - capability: "odin.verse-rendezvous".into(), - schema: "odin.verse-topology.v1".into(), - compatibility: "v1".into(), - endpoint: "10.77.0.1:17871".into(), - }; - let observations = external_binding_observations(&[external]); - assert!(!observations[0].present); - assert!(!observations[0].ready); + fn external_input_receipt() -> ExternalInputMaterializationReceipt { + ExternalInputMaterializationReceipt { + input_id: "toolchain-index".into(), + url: "https://example.invalid/toolchain-index".into(), + sha256: digest(b'd'), + runner: "rust".into(), + destination: "inputs/toolchain-index".into(), + size_bytes: 17, + } } #[test] - fn shared_infrastructure_reuses_the_ready_provider() { - let mut weaker = provider(false); - weaker.provider_id = "odin-candidate".into(); - let resolved = resolve_dependencies( - &TargetDeclaration::parse(RECIPE).unwrap(), - &[weaker, provider(true)], - ) - .unwrap(); + fn compiler_parses_the_exact_bytes_it_receipts() { + let first = plan(); + let second = plan(); + assert_eq!(first, second); + assert_eq!(first.recipe_blob.as_slice(), RECIPE.as_bytes()); + assert_eq!(first.binding_blob.as_slice(), BINDING.as_bytes()); assert_eq!( - resolved[0].provider.as_ref().unwrap().provider_id, + sha256_id(&first.recipe_blob), + first.source.recipe_blob_sha256 + ); + let changed = RECIPE.replace( + "contract = \"service.health\"", + "contract = \"service.health.v2\"", + ); + assert!( + compile_deployment_plan( + changed.as_bytes(), + BINDING.as_bytes(), + source(RECIPE), + "service-incarnation-2", + Some(18002), + 111, + &[odin()], + ) + .is_err() + ); + let mut corrupted = first; + corrupted + .binding_blob + .extend_from_slice(b"\nunknown = true\n"); + assert!(corrupted.validate().is_err()); + } + + #[test] + fn pinned_policy_requires_the_exact_operator_pin() { + let pinned_binding = BINDING.replace( + "selection = \"ref-head\"", + "selection = \"pinned-object\"\npinned_revision = \"2222222222222222222222222222222222222222\"", + ); + let binding = OperatorBinding::parse(&pinned_binding).unwrap(); + assert!(source(RECIPE).validate_against(&binding).is_err()); + let mut facts = source(RECIPE); + facts.selection = SourceSelection::PinnedObject; + facts.validate_against(&binding).unwrap(); + } + + #[test] + fn gitlink_fact_must_match_the_selected_superproject_tree() { + let recipe = RECIPE.replace( + "source_stamp_environment = \"SERVICE_BUILD_COMMIT\"", + "source_stamp_environment = \"SERVICE_BUILD_COMMIT\"\nrequired_gitlinks = [\"vendor/lib\"]", + ); + let binding_text = BINDING.replace( + "recipe_path = \"deployment/idunn/recipe.toml\"", + "recipe_path = \"deployment/idunn/recipe.toml\"\ngitlinks = { \"vendor/lib\" = { origin = \"https://github.com/GameCult/Lib.git\" } }", + ); + let binding = OperatorBinding::parse(&binding_text).unwrap(); + binding + .admit(&TargetDeclaration::parse(&recipe).unwrap()) + .unwrap(); + let mut facts = source(&recipe); + facts.gitlinks.insert( + "vendor/lib".into(), + GitlinkTreeFact { + origin: "https://github.com/GameCult/Lib.git".into(), + revision: "4444444444444444444444444444444444444444".into(), + tree_entry_revision: "4444444444444444444444444444444444444444".into(), + }, + ); + facts.validate_against(&binding).unwrap(); + facts + .gitlinks + .get_mut(&PathBuf::from("vendor/lib")) + .unwrap() + .tree_entry_revision = "5555555555555555555555555555555555555555".into(); + assert!(facts.validate_against(&binding).is_err()); + } + + #[test] + fn dependency_selection_uses_expected_identity_without_readiness() { + let declaration = TargetDeclaration::parse(RECIPE).unwrap(); + let mut later = odin(); + later.runtime_id = "odin-z".into(); + let providers = managed_expected_provider_refs(&[later, odin()]).unwrap(); + let selected = select_dependencies(&declaration, &providers).unwrap(); + assert_eq!( + selected[0].provider.as_ref().unwrap().provider_id, "odin-yggdrasil" ); } #[test] - fn present_and_ready_are_distinct_from_expected() { - let plan = plan(provider(true)); - let presence = RuntimePresence { - target: "service".into(), - generation: "v1".into(), - deployment_id: "deployment-1".into(), - source_revision: "2222222222222222222222222222222222222222".into(), - endpoint: Some("127.0.0.1:18001".into()), - capabilities: plan.expected.capabilities.clone(), - runtime_id: "service-runtime".into(), - signer_identity_id: "signer-1".into(), - signed_statement_sha256: format!("sha256-{}", "b".repeat(64)), - }; - let health = HealthObservation { - contract: "service.health".into(), - state: "active".into(), - detail: "serving".into(), - signed_statement_sha256: presence.signed_statement_sha256.clone(), - }; - let absent = correlate_generation(&plan, None, None).unwrap(); - assert!(absent.expected); - assert!(!absent.present); - assert!(!absent.ready); - let ready = correlate_generation(&plan, Some(&presence), Some(&health)).unwrap(); - assert!(ready.present); - assert!(ready.ready); - } - - #[test] - fn disagreement_remains_visible_and_blocks_readiness() { - let plan = plan(provider(true)); - let presence = RuntimePresence { - target: "service".into(), - generation: "wrong-generation".into(), - deployment_id: "deployment-1".into(), - source_revision: "2222222222222222222222222222222222222222".into(), - endpoint: Some("127.0.0.1:18001".into()), - capabilities: plan.expected.capabilities.clone(), - runtime_id: "service-runtime".into(), - signer_identity_id: "signer-1".into(), - signed_statement_sha256: format!("sha256-{}", "b".repeat(64)), - }; - let health = HealthObservation { - contract: "service.health".into(), - state: "active".into(), - detail: "serving".into(), - signed_statement_sha256: presence.signed_statement_sha256.clone(), - }; - let correlation = correlate_generation(&plan, Some(&presence), Some(&health)).unwrap(); - assert!(!correlation.present); - assert!(!correlation.ready); - assert!( - correlation - .disagreements - .contains(&"generation-mismatch".into()) + fn external_binding_produces_expected_configuration_only() { + let input = BINDING.replace( + "[placement]", + "[[external_capabilities]]\nprovider_id = \"operator-archive\"\ncapability = \"archive.store\"\nschema = \"archive.store.v1\"\ncompatibility = \"v1\"\ncapacity = 2\nendpoint = \"s3://operator-bound\"\n\n[placement]", + ); + let binding = OperatorBinding::parse(&input).unwrap(); + let providers = external_binding_provider_refs(&binding).unwrap(); + let declaration = TargetDeclaration::parse(&RECIPE.replace( + "kind = \"shared-infrastructure\"\ncapability = \"odin.verse-rendezvous\"\nschema = \"odin.verse-topology.v1\"", + "kind = \"external-operator-binding\"\ncapability = \"archive.store\"\nschema = \"archive.store.v1\"", + )) + .unwrap(); + binding.admit(&declaration).unwrap(); + let selected = select_dependencies(&declaration, &providers).unwrap(); + assert!(matches!( + &providers[0].authority, + ExpectedProviderAuthority::ExternalOperatorBinding { .. } + )); + assert_eq!(providers[0].capacity, 2); + assert_eq!( + selected[0].provider.as_ref().unwrap().provider_id, + "operator-archive" ); } #[test] - fn sealed_artifacts_and_promotion_phases_are_exact() { - let plan = plan(provider(true)); - let sealed = SealedDeployment::new( - plan.clone(), - "release-1", - vec![ArtifactSeal { - artifact_id: "daemon".into(), - destination: "service".into(), - sha256: format!("sha256-{}", "c".repeat(64)), - size_bytes: 42, - executable: true, - }], - 110, + fn expected_projection_is_sanitized_and_names_the_selected_graph() { + let plan = plan(); + let release = SealedRelease::new( + &plan, + vec![artifact_receipt()], + vec![external_input_receipt()], + 120, ) .unwrap(); - sealed.validate().unwrap(); - let transaction = PromotionTransaction { - schema: PROMOTION_TRANSACTION_SCHEMA.into(), - transaction_id: "transaction-1".into(), - plan_id: plan.plan_id, - target: "service".into(), - phase: PromotionPhase::Planned, - revision: 0, - updated_at_unix_millis: 100, - }; - assert!(transaction.advance(PromotionPhase::Sealed, 101).is_err()); + let expected = release.expected_projection(&plan).unwrap(); + assert_eq!(expected.plan_id, plan.plan_id); + assert_eq!(expected.sealed_release_id, release.sealed_release_id); + assert_eq!(expected.incarnation_id, "service-incarnation-1"); + assert_eq!(expected.runtime_id, "service-yggdrasil"); assert_eq!( - transaction - .advance(PromotionPhase::Materialized, 101) - .unwrap() - .phase, - PromotionPhase::Materialized + expected.expected_signer_identity_id, + "service-runtime-signer" ); + assert_eq!(expected.health_contract, "service.health"); + assert_eq!(expected.executable_artifact_sha256, digest(b'c')); + assert_eq!(expected.state_schema_generation.as_deref(), Some("v1")); + assert!(expected.state_contract_sha256.is_some()); + assert!(!expected.write_lease_required); + assert_eq!(expected.node, "yggdrasil"); + assert_eq!( + expected.dependencies[0] + .provider + .as_ref() + .unwrap() + .provider_id, + "odin-yggdrasil" + ); + assert_eq!( + expected.route.as_ref().unwrap().candidate_endpoint, + "http://127.0.0.1:18001" + ); + assert!(expected.canonical_sha256().unwrap().starts_with("sha256-")); + let mut invalid_release = release; + invalid_release.artifacts[0].size_bytes += 1; + assert!(invalid_release.expected_projection(&plan).is_err()); + } + + #[test] + fn sealed_release_address_covers_artifacts_and_external_inputs() { + let receipt = artifact_receipt(); + let input = external_input_receipt(); + let plan = plan(); + let mut wrong_artifact = receipt.clone(); + wrong_artifact.sha256 = digest(b'f'); + assert!(SealedRelease::new(&plan, vec![wrong_artifact], vec![input.clone()], 120).is_err()); + assert!(SealedRelease::new(&plan, vec![receipt.clone()], vec![], 120).is_err()); + let release = + SealedRelease::new(&plan, vec![receipt.clone()], vec![input.clone()], 120).unwrap(); + let later_receipt_time = + SealedRelease::new(&plan, vec![receipt], vec![input], 130).unwrap(); + release.validate_against(&plan).unwrap(); + assert_eq!( + release.sealed_release_id, + later_receipt_time.sealed_release_id + ); + let mut changed = release.clone(); + changed.artifacts[0].size_bytes = 43; + assert!(changed.validate_against(&plan).is_err()); + let mut changed = release; + changed.external_inputs[0].size_bytes = 18; + assert!(changed.validate_against(&plan).is_err()); } } diff --git a/docs/idunn-deployment-authority.md b/docs/idunn-deployment-authority.md index 7d1bce6..fafa1f2 100644 --- a/docs/idunn-deployment-authority.md +++ b/docs/idunn-deployment-authority.md @@ -10,7 +10,7 @@ The architectural test is simple: - Where and how a workload runs is generic infrastructure work. Use the configured systemd, container, proxy, or later Nomad/Kubernetes driver. - Which GameCult incarnation has authority to serve, write state, or represent - an admitted generation is Idunn work. + an admitted workload is Idunn work. Idunn and Odin are closely integrated but do not share authority. Idunn owns the admitted physical swarm. Odin owns the discoverable semantic topology of @@ -21,11 +21,11 @@ and health. CultMesh carries typed projections between them. - **Owner:** Idunn alone selects an exact source, admits its repository recipe under an operator binding, records the resulting artifact and process - provenance, grants process-bound route and state-write admission, and keeps - the admitted generation alive. + provenance, grants a process-bound state-write lease, separately admits + route membership, and keeps the admitted incarnation alive. - **Inputs:** root-admitted operator bindings; source-owned strict deployment declarations; exact Git objects read as the `idunn` identity; signed - deployment or lifecycle-brake state; signed generation-bound service + deployment or lifecycle-brake state; signed incarnation-bound service presence and health; Odin's observed capability topology when graph changes require semantic discovery; and observations from the configured workload and route drivers. @@ -41,12 +41,13 @@ and health. CultMesh carries typed projections between them. secrets, mounts, network, capabilities, resources, host paths, routes, placement, source refs, or rollout policy. Odin cannot promote a process or grant state writes. nginx cannot choose membership. systemd and container - runtimes cannot choose the admitted generation. Service configuration cannot + runtimes cannot choose the admitted incarnation. Service configuration cannot impersonate observed presence or readiness. Persisted shell strings and repository-supplied root programs are not executable authority. - **Shared paths:** `idunn up`, scheduled deployment, manual deployment, scaling, restart, host reboot recovery, and crash recovery use the same - source-to-recipe-to-artifact provenance and the same admission primitive. + source-to-recipe-to-artifact provenance and the same distinct write-lease and + route-membership primitives. Deployment may change that chain only while the deployment brake admits the exact transaction. Continuity may restart only the already-admitted chain and is governed by a separate lifecycle brake. @@ -57,19 +58,40 @@ and health. CultMesh carries typed projections between them. decide Ghostlight or CodexConnector deployment before either target is promoted through this design. +### Current implementation boundary + +`deployment.rs` and `deployment_plan.rs` are the deterministic contract +foundation only. They parse one strict source declaration and one root-admitted +operator binding from the exact raw blobs retained by the compiled plan, check +private source-selection facts, derive managed providers from validated Expected +documents, and content-address a sealed release. They do not yet +drive Git, runners, systemd, nginx, brakes, CultCache, CultMesh, or the legacy +Idunn supervisor. + +The full operator binding, compiled plan, source facts, and sealed release +are private Idunn control-plane state. They contain host paths and operational +bindings and must never be published as Odin topology. Only the sanitized +`ExpectedIncarnation` projection is shaped for later CultMesh publication. It +is derived only from a sealed release validated against its compiled plan and +names both content addresses and the executable artifact digest. Present and +Ready remain Odin-owned correlations over independently verified runtime +evidence; the deployment-plan module deliberately does not model them. + ## The three truths Odin exposes -For each generation, Odin keeps three distinct observations: +For each workload incarnation, Odin keeps three distinct observations: -1. **Expected** — Idunn has admitted or intends this exact generation and has - published its deployment identity, endpoints, declared capabilities, and - dependency role. -2. **Present** — that generation has established its own signed CultNet/CultMesh - runtime session. -3. **Ready** — the observed generation satisfies its signed capability and +1. **Expected** — Idunn has sealed this exact incarnation and has published its + plan and release identities, admitted runtime and signer identities, health + and optional canonical typed-MessagePack state-contract identities, + endpoints, declared capabilities, and dependency role. +2. **Present** — Idunn has published the launch-scoped activation only after its + actuator observed the exact runtime instance, and that instance has + established its own matching signed CultNet/CultMesh runtime session. +3. **Ready** — the observed incarnation satisfies its signed capability and health contract and its required dependency graph is ready. -Correlation never repairs disagreement. Generation, runtime identity, endpoint, +Correlation never repairs disagreement. Incarnation, runtime identity, endpoint, schema, capability, and dependency mismatches remain visible and block promotion. Configuration contributes only expected state; it cannot supply present or ready state. @@ -87,10 +109,10 @@ The declaration contains no host commands or privileges. It describes: - schema and target identity; - requested runner profiles; - build and test argv executed inside those runners; -- package inputs and immutable artifact outputs; +- pinned generic HTTPS inputs and immutable artifact outputs; - a constrained launch contract naming the packaged executable, literal arguments, operator-bound argument slots, and required environment names; -- health, staged-readiness, and state/schema contracts; +- one health contract and, only for stateful services, a state/schema contract; - capabilities provided, including schema and compatibility information; - bootstrap, required, optional, shared-infrastructure, private, and external operator-bound capability dependencies; @@ -101,6 +123,12 @@ Dependencies resolve by typed capability/provider compatibility. A declaration names a daemon only when identity itself is the contract; ordinary dependencies must not hard-code a provider instance. +Runtime health uses the shared `warming`, `active`, `degraded`, and `failed` +ontology. A recipe names only its health contract. It cannot redefine those +states, readiness, or operator-facing detail. Bootstrap dependencies must be +available before process start; the remaining dependency kinds retain their +typed intent without making this foundation a scheduler. + The declaration may run repository code only inside a runner sandbox admitted by the operator binding. It cannot publish a host path, Docker argument, systemd property, nginx fragment, UID, secret path, or capability grant. Idunn @@ -115,14 +143,19 @@ For one target on one fleet it owns: - canonical repository origin, admitted ref, and minimum revision; - exact runner kind, image digest, and affordances for each requested profile; -- source, cache, output, release, state, and runtime roots; -- network mode, allowed dependency egress, mounts, identities, secrets, +- source, cache, output, release, and runtime roots, plus state roots and + transition policy only when the recipe declares state; +- preconfigured runner network profiles, mounts, identities, secrets, capabilities, resource bounds, and device access; - workload driver, transient-unit namespace, private endpoint range, and stable route; +- runtime identity, expected signer identity, and trust-anchor store; +- a process-write-lease record only when the recipe declares process-bound + writable state; its sibling lock path is derived rather than configured; - route driver and its root-owned configuration destination; - rollout, drain, irreversible-cut, and retention policy; -- desired replicas and allowed placement; +- one admitted replica on one named node in v1; later placement and scaling are + delegated to an established orchestrator driver; - externally supplied capability bindings. A recipe request that has no compatible admitted binding fails closed. A @@ -134,14 +167,19 @@ does not own application build or deployment programs. ## Typed deployment state -Mutable control-plane state is CultCache. The live path uses typed records for: +Mutable control-plane state will be CultCache. Runtime integration must use +typed records for: - requested service or profile; - resolved capability graph and exact providers; - exact source and recipe digest; - runner binding and artifact digests; -- candidate process, private endpoint, and signed staged health; -- process-bound write lease and route admission; +- full materialization receipts for every pinned external input and artifact; +- candidate runtime identity, private endpoint, and signed runtime health; +- launch-scoped runtime activation, published as current only after workload- + driver observation; +- process-bound write lease; +- independently admitted route membership; - expected, present, and ready correlation; - promotion, drain, failure, and continuity results. @@ -153,8 +191,8 @@ migration artifact and declare its accepted source schemas, destination schema, and literal/operator-bound argv. The operator binding admits the state roots, backup root, and whether this rollout permits migration or a fresh-root cut. Idunn alone issues a fenced one-shot migration grant bound to the exact source, -artifact, state generation, and deployment. A target migration never receives -general deployment or lifecycle authority. +artifact, state schema generation, and deployment incarnation. A target +migration never receives general deployment or lifecycle authority. ## Initial drivers and replaceable boundary @@ -165,87 +203,108 @@ The first Yggdrasil implementation uses: - Docker only for admitted build/test/package runners; - nginx HTTP proxying for Ghostlight; - nginx stream proxying for CodexConnector's stable TCP endpoint; -- atomic root-owned files for process/write admission and generated proxy - membership; +- atomic root-owned files for process-bound write leases and separately + generated proxy membership; - graceful nginx validation and reload for route changes. -Idunn calls narrow workload, route, and admission/fencing driver ports. Those -ports express stage, start, observe, stop, validate route, publish a fenced or -process-bound admission, and promote route. They do not express GameCult -admission decisions. A later Nomad or Kubernetes driver may implement the same -consequences. Idunn must not grow general bin-packing, distributed -scheduling, service-mesh, container-format, cryptography, or consensus logic; -when those become requirements, place Idunn's admission semantics over an -established orchestrator. +Idunn calls narrow workload, route, and write-lease/fencing driver ports. Those +ports express stage, start, observe, stop, validate route, fence an incumbent, +publish a process-bound write lease, and separately promote route membership. +They do not express GameCult admission decisions. A later Nomad or Kubernetes +driver may implement the same consequences. Idunn must not grow general +bin-packing, distributed scheduling, service-mesh, container-format, +cryptography, or consensus logic; when those become requirements, place +Idunn's admission semantics over an established orchestrator. ## Candidate promotion -For a singleton generation: +For a singleton incarnation: 1. Resolve the required capability graph. Reuse a compatible admitted shared provider, especially Odin, rather than spawning a duplicate. -2. Publish the desired fleet and candidate as expected state. +2. Publish desired fleet intent. Intent is not an Expected incarnation. 3. Freeze the exact source and recipe as `idunn`, then copy and verify it into a root-owned actuation stage. The privileged driver never opens Git. -4. Build, test, and package inside the bound runners. Seal the artifact, recipe, - unit, and input digests. -5. Start the candidate through the workload driver on a private endpoint. It - has no stable route or canonical write lease. -6. Require its own signed generation-bound `staged` health and signed runtime - presence. Render and validate the proposed route before changing admission. -7. Compare-and-swap the current process/write-admission record into a named - promotion fence. No generation may write while fenced; the incumbent may - remain routed but must return a retryable unavailable result. -8. Publish the candidate backend, gracefully reload the route driver, and +4. Build, test, and package inside the bound runners. Seal the artifact, + declaration, binding, launch contract, and input digests. +5. Derive and publish the release-bound Expected incarnation from the validated + sealed release and its exact compiled plan. +6. Issue one opaque runtime-instance activation bound to the Expected digest, + pass the exact Expected and activation documents through the actuator's + isolated credential mechanism, and start the candidate privately. It has no + stable route or canonical write lease. +7. After the workload driver observes the exact native runtime and executable + artifact, publish that activation as current. Require the candidate's own + signed matching `warming` presence. Render and validate the proposed route + before changing either authority. +8. Open a named promotion transaction and separately fence the incumbent + writer. The incumbent may remain routed but its process-bound write authority + is revoked and it must return a retryable unavailable result. +9. Grant the private candidate its own process-bound write lease. Keep it off + the stable route and wait for signed `active` health and the independently + correlated Ready observation. +10. Publish the candidate backend, gracefully reload the route driver, and observe that the proxy has adopted it. Proxy lag is explicit transaction state, not readiness. -9. Compare-and-swap the fence into the candidate's process-bound write grant. - Wait for signed `active` health, then drain and stop the incumbent. +11. Clear the promotion fence only after route adoption is observed, then drain + and stop the incumbent. -The admission record is the one writer lease. A PID, endpoint, symlink, unit, -or route alone never grants writes. Outside the explicit promotion fence, the -write-admitted process and routed generation must agree. Runtimes must bind and -publish staged health without opening canonical writable state; they open or -mutate that state only after the exact process-bound admission becomes current. +The state-write lease and route membership are distinct authorities. Fencing +the incumbent does not grant the candidate or change the route. Granting the +candidate permits that exact private process to write but does not route stable +traffic. Changing the route grants no write authority. The promotion +transaction clears its fence only after the independently observed write and +route authorities name the candidate. A PID, endpoint, symlink, or unit alone +grants neither authority. Promotion persists crash-resumable phases: planned, materialized, sealed, -candidate-started, staged, fenced, route-observed, write-admitted, active, -draining, and complete. A dead Idunn cannot leave a second writer. Its successor -resumes the exact sealed transaction or restores the prior admitted generation -through the same fence; it never infers completion from a symlink or eventual -health convergence. +activation-issued, candidate-started, activation-observed, warming, +incumbent-fenced, write-lease-granted, ready-observed, route-observed, +fence-cleared, draining, and complete. A dead Idunn cannot leave a second +writer. Its successor resumes the exact sealed transaction or restores the +prior admitted incarnation through the same fence; it never infers completion +from a symlink or eventual health convergence. An irreversible state cut fails closed after the write lease moves. A reversible -cut may restore the incumbent only through the same admission primitive and -only while its artifact and state contract remain valid. +cut may restore the incumbent only through the same process-write-lease +primitive and only while its artifact and state contract remain valid. ## Continuity and outage behavior -Continuity restarts the exact sealed release, binding, endpoint, and admission -identity. It does not fetch a branch, rebuild, rerun a migration, alter a unit, -or consume the deployment brake. An explicit lifecycle brake may suspend this -actuation without changing deployment authority. +Continuity restarts the exact sealed release, binding, endpoint, runtime +identity, and route membership. Every restart receives a new runtime-instance +activation and, for a state writer, a new process-bound lease only after the new +warming presence is observed. A lease from the dead process is never reused. A +continuity restart does not fetch a branch, rebuild, rerun a migration, alter +the launch contract, or consume the deployment brake. An explicit lifecycle +brake may suspend this actuation without changing deployment authority. Idunn starts and recovers from its own durable admitted state. Odin is the first managed semantic daemon, never an Idunn bootstrap dependency. Odin's initial admission is the sole graph-bootstrap exception: Idunn uses its root-admitted local binding, publishes Odin's expected projection into durable CultMesh state, -and waits for Odin's own signed presence before admitting dependents. +and waits for Odin's observed activation and signed presence before admitting +dependents. When Odin is unavailable, Idunn continues health observation and continuity for -already admitted generations and leaves current routes in place. It does not -begin a graph-changing transaction. An already sealed transaction may continue -only from its pinned graph and expected-generation snapshot; once a promotion -fence exists, safety recovery proceeds without waiting for Odin so the fleet is -not stranded with an ambiguous writer. New deployment, dependency substitution, -or scaling waits for semantic discovery. When Odin returns, disagreement is -correlated and exposed before graph-changing work resumes. +already admitted incarnations and leaves current routes in place. It does not +begin a graph-changing transaction, and a merely sealed candidate may not start +promotion. Only a transaction whose incumbent has already been fenced may +promote when its frozen evidence already contains the exact Odin Ready receipt +for this runtime instance and signed-presence digest. Otherwise it waits, rolls +back through the same fence when reversible, or fails closed; Idunn never +manufactures Ready locally. New deployment, dependency +substitution, promotion, or scaling waits for semantic discovery. When Odin +returns, disagreement is correlated and exposed before graph-changing work +resumes. Source selection is explicit per binding: a pinned object, the captured head of -an admitted ref, or a signed release authorization. Every policy freezes one -exact commit in the plan and proves origin, reachability, recipe digest, and any -minimum floor before build. “Whatever the branch points to when root runs” is -not a selection policy. +an admitted ref, or a signed release authorization. The current deterministic +foundation retains the exact selected commit, tree, recipe blob, and Gitlink +facts, but shape validation is not proof of Git ancestry, signature authority, +or object custody. Those proofs belong to the narrow Idunn-owned source driver +that will produce these private facts. “Whatever the branch points to when root +runs” is not a selection policy. ## Garden path @@ -269,15 +328,19 @@ deployment program. The first live cut is complete only when tests and host observations prove: - exact source → recipe → artifact → process provenance; +- an issued but driver-unobserved activation cannot establish Present, and a + prior runtime instance cannot replay presence after restart; - target requests cannot grant an omitted runner or host affordance; - old command-bearing records and old target scripts are unexecutable; -- a candidate cannot write or receive the stable route before admission; -- route and write admission name the same generation and process; +- a candidate cannot write before its process-bound lease or receive the stable + route before separate route admission; +- route membership and write leases remain separate records and name the same + incarnation and process before the promotion fence clears; - expected, present, and ready disagreement blocks promotion and remains observable; - replayed or stale signed health cannot satisfy present or ready; -- external operator-bound dependencies still require observed signed presence - and readiness; configuration supplies only expected state; +- external operator-bound dependencies still require their declared observed + health/readiness contract; configuration supplies only expected state; - a compatible shared Odin is reused and a second provider is not spawned; - Idunn death during every promotion phase resumes or fails closed without a second writer; @@ -286,6 +349,7 @@ The first live cut is complete only when tests and host observations prove: - same-release crash recovery works while the deployment brake is engaged; - the lifecycle brake can stop continuity without admitting a deployment; - Odin loss preserves current continuity/routes and blocks graph changes; -- the incumbent remains routed until the candidate is signed-staged; +- the incumbent remains routed until the candidate has signed `active` health + and is correlated Ready; - the old unit, release, state root, grant, and route cannot regain authority; - Ghostlight restart preserves the exact world journal and digest identity. diff --git a/docs/idunn.md b/docs/idunn.md index 002766c..4446a61 100644 --- a/docs/idunn.md +++ b/docs/idunn.md @@ -1,495 +1,166 @@ # Idunn -Idunn is Odin's keepalive organ. +Idunn is GameCult's independent deployment-admission and continuity control +plane. It decides which exact workload incarnation may run, write canonical +state, receive traffic, and be kept alive. It does not depend on Odin or any +managed workload in order to start or recover its own durable admitted state. -Odin is the all-seer: it accepts Verse discovery, schema catalogs, translation -routes, provider surfaces, and observation projections. Idunn keeps the daemon -swarm alive from that accepted map. It is not a second Odin, not a dashboard, -and not a heroic supervisor with secret service truth in its pockets. +Systemd, container runtimes, proxies, and a future Nomad or Kubernetes driver +provide generic execution and routing. Idunn owns the GameCult-specific +decision about which source, release, runtime identity, process write lease, and +route membership are authoritative. -Idunn keeps the apples: desired daemon presence, deployment freshness, boot -recovery, crash recovery, health freshness, deploy/restart intent, operator -escalation, and continuity witness state. +The detailed contract is +[`idunn-deployment-authority.md`](idunn-deployment-authority.md). -The current deployment and runtime-admission contract is -[`idunn-deployment-authority.md`](idunn-deployment-authority.md). That contract -owns target recipes, operator bindings, capability-graph admission, -expected/present/ready correlation, candidate promotion, route admission, and -the separation between deployment and continuity. This page describes the -broader keepalive body and its existing state surfaces. +## Authority map -## Authority Map +- **Owner:** Idunn selects exact source facts under root policy, compiles the + repository declaration against an operator binding, seals materialized + inputs and artifacts, admits one runtime incarnation, separately controls its + process-bound write lease and route membership, and preserves its continuity. +- **Inputs:** the exact raw repository declaration and operator-binding blobs; + private source-driver facts; artifact and external-input materialization + receipts; separate deployment and lifecycle brakes; Odin's observed semantic + topology when a graph-changing decision needs discovery; signed runtime + presence and health; Idunn's current observed-activation projection; and + observations from narrow execution and route drivers. +- **Outputs:** private compiled plans and sealed releases; a release-bound + sanitized Expected projection for Odin/CultMesh; one launch-scoped runtime + activation published only after driver observation; process write-lease and + route decisions; continuity actions; and explicit disagreement or failure + records. +- **Derived state:** dashboards, operator summaries, proxy displays, process + listings, and Odin correlation views are projections. They do not establish + deployment, write, route, presence, or readiness authority. +- **Forbidden writers:** repositories cannot grant host privileges, identities, + trust anchors, state roots, write leases, routes, placement, or rollout + policy. Odin cannot deploy, promote, route, or grant writes. Services cannot + configure themselves Present or Ready. Proxies and process managers cannot + select the admitted incarnation. Raw command strings are not deployment + authority. +- **Shared path:** `idunn up`, scheduled deployment, operator deployment, + restart, crash recovery, and host reboot recovery all use the same admitted + source-to-release identity. Continuity may restart only that identity; it + cannot fetch, rebuild, migrate, or silently change configuration. -- Owner: Idunn owns daemon lifecycle management from its root-admitted target - catalog: bring-up after host reboot, deployment freshness, crash - recovery, health watching, deploy/restart policy, and operator escalation. -- Inputs: its admitted target catalog, Odin's accepted service records when - Odin is available, provider advertisements, `.cc` - witnesses, advertised command boundaries, CultNet/RUDP health contracts, - freshness windows, operator policy, local service manager state, and explicit - deployment/debug witnesses that cannot satisfy daemon health. -- Outputs: typed keepalive observations, deployment requests/results, restart - requests/results, release targets, deployment artifacts, state migration - plans/results, rollout plans/results, denied-action records, operator alarms, - Bifrost operator-notification requests, and an Eve/CultUI keepalive surface. -- Derived state: dashboard cells, Bifrost receipts, Discord or owner-DM - lowerings, agent summaries, and Odin service projections are - notification-only views of Idunn-owned keepalive records. -- Forbidden writers: Idunn does not decide which Verses exist, invent provider - schemas, mutate provider dashboards, own identity/session grants, or hide - restarts behind Odin refresh logic. Individual daemons should not carry - independent crash-recovery loops once Idunn owns their lifecycle path; they - publish health, surfaces, state witnesses, and command boundaries instead. - Agents are also forbidden deploy writers: they configure Idunn release - targets, command boundaries, migration commands, and rollout policy, then let - Idunn actuate and witness deployment. They do not run deploy scripts by hand. - Odin is itself an Idunn target; Odin discovery is never a prerequisite for - starting Idunn or recovering Odin. -- Shared paths: manual operator deploy/restart, scheduled deploy/restart, - degraded-health repair, boot rehydration, and future remote worker recovery - must pass through the same Idunn command primitive. -- Consequence gate: Yggdrasil keeps `deployment-brake.cc` and its pre-created - sibling `deployment-brake.cc.lock` in `/var/lib/gamecult/idunn-authority`. - The directory is `root:idunn` `0750`, both files are `root:idunn` `0640`, and - Idunn receives only a systemd `ReadOnlyPaths` view. Idunn validates under a - shared lock before spawning the privileged boundary. The root actuator then - independently reopens and validates the signed brake while remaining the sole - shared-lock holder through one synchronous deploy transaction; the child does - not inherit the lock descriptor. The root-owned operator writer takes the - lock exclusive for engage/release. A bounded release admits the exact target, - rollout request, and source revision only when the transaction starts before - its signed deadline. Admission transfers completion of that transaction to - the actuator; expiry is not a retroactive timer veto. Every later transaction - must independently revalidate the brake. -- Deletion line: any keepalive loop inside Odin, Gjallar, Eve lowerers, or - renderer code must be cut or demoted to a probe that names Idunn as the - restart owner. +## Repository declaration -## Body +A deployable repository publishes one strict declaration, normally +`deployment/idunn/recipe.toml`. It may contain: -Idunn now shares Odin's Rust body: +- literal build, test, and package argv for named runner classes; +- generic pinned HTTPS inputs with SHA-256, runner, and relative destination; +- immutable artifact outputs, optionally pinned to an expected SHA-256; +- a constrained launch contract; +- one health-contract identity; +- an optional typed state contract with state schema generation and slots; +- provided capabilities, dependency kinds, startup requirements, capacity, and + conflicts. -- `crates/odin-core/src/idunn.rs` owns the keepalive decision engine. -- `crates/odin-core/src/documents.rs` publishes typed Idunn CultMesh records - beside Odin and Gjallar records. -- `crates/idunn-daemon` is the local keepalive actuator crate and now owns the - resident Starfire-local swarm scheduler. -- `src/Idunn/README.md` is the user-facing introduction for developers, - operators, and daemon authors. -- `scripts/start-idunn-local.ps1` is now a narrow bootstrap wrapper: it ensures - one `idunn.exe` process is alive, checks the shared keepalive store for - staleness, and lets Rust own the target catalog and per-target scheduling. -- `scripts/deploy-yggdrasil-source-app.ps1` and - `scripts/health-yggdrasil-source-app.ps1` are the generic Yggdrasil source - artifact lane. They fetch the declared upstream branch, package - `origin/main` with `git archive`, run any declared daemon-owned migration - script before the deploy script, run the existing ops-owned deploy/check - scripts on Yggdrasil, and stamp a remote - `gamecult.idunn.deployment_manifest.v1` only after the remote check passes. -- `scripts/idunn-deployment-targets.ps1` is the current swarm deployment target - catalog. Every known deployable target is either `enforced`, `blocked`, - `external-owned`, or `not-runtime` with an explicit reason. -- `scripts/health-idunn-swarm-deployment-coverage.ps1` is the coverage probe - that fails when the target catalog becomes incoherent. The local Idunn - launcher runs it as `idunn-swarm-deployment-coverage` so missing deploy - ownership becomes a watched operational fault. -- `scripts/notify-idunn-operator-alarm.ps1` is the local operator crossing: - Idunn invokes it only after raising an operator alarm, and it asks Bifrost to - publish a typed `gamecult.operator_dm_request.v1` CultMesh command document - instead of learning Discord delivery itself. -- `npm run idunn:build` builds the Rust daemon. -- `npm run idunn:start -- ...` still supports the narrow one-daemon path for - manual use; RUDP health ingress stays disabled unless `--rudp-health-bind` is - supplied. -- `npm run idunn:start -- --swarm-profile starfire-local --repo-root E:\Projects\Odin --execute` - runs the singular local swarm supervisor. -- `--swarm-profile yggdrasil-local` is the Linux host-local supervisor for - Epiphany, Heimdall, Repixelizer, StreamPixels, and VoidBot. Its only command boundary is the - root-owned `/usr/local/libexec/idunn-yggdrasil` actuator. Restart commands - target the local Compose stack. For deployment, the root boundary derives the - repository, ref, daemon id, and release-authority posture from its fixed - target allowlist, then binds the caller's request identifier and source to the - signed root-owned brake. A manifest must be a direct root-owned executable - regular file under `/srv/odin/deploy-manifests`; neither it nor any ancestor - may be group/world-writable, and symlink manifests are refused. It does not - inherit Starfire paths, SSH keys, ADB authority, or Windows process ownership. -- Release authority is explicit per target. Odin, Ghostlight, and Epiphany are - source-observed targets: Idunn derives the newest commit on each admitted ref - that changes build or runtime source, freezes that exact revision into its - typed deployment request, and carries it across the narrow root actuator. - Documentation, notes, state maps, ledgers, scratch state, and root Markdown - do not impersonate a new binary generation. The actuator independently proves - that the frozen commit belongs to the admitted ref, then verifies the exact - embedded commit and deployment witness after activation. Raw branch `HEAD` is - neither release authority nor a second opinion about the selected revision. -- Targets that still require a Bifrost receipt retain that separate gate; their - receipt fields cannot leak into a source-observed request. Bifrost does not - authorize Epiphany releases. Epiphany's admitted - `GameCult/Epiphany` `refs/heads/codex/epiphany-shakedown-live` ref remains a - temporary shakedown boundary; changing it or promoting it to `main` is a - separate source-governance act. +The recipe does not configure runtime health states. GameCult runtime health +uses the shared `warming`, `active`, `degraded`, and `failed` ontology. Present +and Ready are Odin correlations over independently signed runtime evidence, not +recipe fields. -The current typed records are: +Stateless services declare no state block. Their operator binding therefore has +no state root, state-transition policy, or process write-lease record. + +## Operator binding + +The root-admitted operator binding supplies the physical policy a repository +cannot grant itself: + +- source origin, admitted ref, selection policy, checkout, and Gitlink origins; +- pinned runner images, literal-program allowlists, resources, mounts, secrets, + and preconfigured network profiles; +- workload driver, identity, isolation, release root, and runtime root; +- runtime ID, expected signer identity, and trust-anchor store; +- optional state root and state-transition policy; +- an optional process write-lease record exactly when a state slot is + process-bound writable; its sibling `.lock` path is derived; +- optional route driver and stable/private endpoint binding; +- independent deployment and lifecycle brakes; +- one replica on one admitted node in the v1 foundation. + +Route membership is not a write lease. A write lease is not route membership. +Neither may be inferred from a PID, unit, socket, symlink, or health message. + +## Deterministic release foundation + +The compiled plan retains the exact raw declaration and binding blobs and +parses those exact bytes again during validation. Its content address therefore +covers the real inputs rather than caller-supplied digests beside mutable parsed +copies. + +Source-selection facts currently preserve the private driver output: the +exact commit, source tree, recipe blob, admitted ref, and Gitlink tree entries. +The contract does not claim that shape validation proves ancestry, signatures, +or object custody. Those proofs belong to the narrow source driver that will +produce the facts. + +A sealed release binds the plan ID to sorted full artifact receipts and sorted +full external-input materialization receipts. Only a sealed release validated +against its exact plan can derive Expected. Expected includes the plan and +release IDs, runtime and signer identities, health contract, node, route, +executable artifact digest, capabilities, selected dependencies, and the +optional canonical state-contract digest computed from the typed +`StateDeclaration` MessagePack encoding. + +Expected is stable release and topology intent. Each actuator launch receives a +separate tiny `idunn.runtime_activation.v1` containing the Expected digest and +one Idunn-issued opaque runtime-instance ID. Idunn publishes that activation as +current only after the workload driver observes the matching native process and +artifact. Present requires both that Idunn observation and the service's +independent signed presence; either document alone is insufficient. + +Managed dependency candidates are derived from validated Expected documents. +External operator bindings remain expected configuration only; they cannot +impersonate signed presence or readiness. + +## Promotion and continuity + +For a routed stateful singleton, Idunn starts the candidate privately, observes +the exact actuator launch, publishes its current activation, and observes its +signed warming presence. It then fences the incumbent writer, grants the +candidate its exact process-bound write lease, and waits for signed active +health plus Ready correlation. It changes and observes route membership only +afterward. Only after the proxy has adopted the candidate may Idunn clear the +promotion fence and drain the incumbent. + +The deployment brake gates changes to source, release, configuration, schema, +unit, or authority binding. The lifecycle brake separately gates restart of an +already-admitted incarnation. Neither target brake may gate Idunn itself or an +unrelated service. + +If Odin is unavailable, Idunn preserves existing routes and continuity for +already-admitted incarnations. It starts no graph-changing deployment or +promotion. A merely sealed candidate waits. An already-fenced transaction may +promote only when its frozen evidence already contains the exact Odin Ready +receipt for this runtime instance and presence digest; otherwise it waits, +rolls back through the same fence when reversible, or fails closed. + +## Operator surface + +The intended entry points are small: ```text -idunn.desired_daemon.v1 -idunn.daemon_health.v1 -idunn.signed_health_admission.v1 -idunn.keepalive_decision.v1 -idunn.deployment_request.v2 -idunn.current_deployment_request.v1 -idunn.deployment_result.v1 -idunn.release_target.v1 -idunn.deployment_artifact.v1 -idunn.state_migration_plan.v1 -idunn.state_migration_result.v1 -idunn.rollout_plan.v1 -idunn.rollout_result.v1 -idunn.restart_request.v1 -idunn.restart_result.v1 -idunn.operator_alarm.v1 -idunn.swarm_surgery_plan.v1 -idunn.daemon_surgery_plan.v1 -idunn.daemon_transport_profile.v1 -idunn.command_boundary.v1 -idunn.runtime_transport_check.v1 -idunn.rudp_health_ingress.v1 +idunn up ghostlight +idunn up profile:aetheria +idunn up profile:full-gamecult ``` -## Invariants +Idunn ensures one compatible Odin exists, publishes the desired fleet, resolves +typed capability dependencies, admits candidates, waits for independently +observed presence and readiness, and promotes routes only when the required +graph conditions hold. -- Odin remains the accepted owner of Verse and service discovery. -- Idunn owns continuity decisions after a daemon is known. -- Individual daemons own their work and their health publication, not their - surrounding lifecycle. They must be simple to kill and simple for Idunn to - bring back. -- Providers own their own command boundaries. Idunn requests deployment or - restart through advertised authority or a named local service manager adapter. -- Host reboot recovery, crash recovery, stale deployment recovery, - stale-health recovery, and manual operator deploy/restart must share the same - Idunn command primitive. -- A repair loop is not an owner. If a daemon becomes healthy only after a later - Odin refresh or manual click, Idunn's ownership path is still incomplete. -- Restart attempts must be witnessed: requested by whom, against which service, - through which command boundary, with what result and timestamp. -- Authenticated signed health is bounded current state: Idunn stores one exact - statement per daemon, keyed by daemon id, while the admission carries its - digest and monotonic lineage. Heartbeat publication must replace that trio - atomically; it must not append one store row per pulse. Startup compacts the - former digest-keyed history through a whole-snapshot compare/exchange before - scheduler workers start. -- The keepalive store is current operational authority with bounded diagnostic - history, not an event archive. Idunn retains the latest eight decisions, - alarms, automatic deployment/restart receipts, migration results, and - rollout results per daemon, plus the latest thirty-two operator lifecycle - commands. Exact current deployment heads, their request/result chain, active - health bindings, and recent command-linked receipts are pinned regardless of - age. Startup compacts legacy history atomically; later writes reapply the - same policy before the single-file store can exceed 1 MiB for long. -- Health command exit status is not daemon awareness. Every Idunn - target must declare a daemon-owned CultNet/RUDP health contract naming what - health publication should prove and what unmarked failure means. - `idunn.desired_daemon.v1` and - `idunn.daemon_health.v1` both record that contract so later readers can - distinguish process liveness, source deployment freshness, framebuffer - composition, telemetry capture, and catalog coherence without mistaking a - temporary product/deployment probe for the real protocol surface. - `idunn.daemon_health.v1` also records `publication_source` and `transport` so - daemon-published RUDP health can be verified as daemon-owned transport - evidence. -- `idunn.desired_daemon.v1` links to - `idunn.daemon_transport_profile.v1` and `idunn.command_boundary.v1` records. - The transport profile names the target transport - `cultnet.transport.rudp.v0`, the daemon-owned witness substrate, and the cut - line that keeps old probes demoted. The command boundary names restart, - deploy, health, and alarm authority separately so Idunn can actuate only the - commands it actually owns. -- The Starfire-local shell probes are deployment/debug witnesses, not daemon - truth. A daemon is Idunn-aware when it publishes its health, command boundary, - and transport profile as typed CultNet/CultMesh documents over - `cultnet.transport.rudp.v0`. Product/debug probes are xenos-boundary - diagnostics or deployment checks only. -- Rust now shares the canonical cross-runtime `cultnet.transport.rudp.v0` - substrate in `vendor/cultnet-rs`: CNR0 packets, sessions, channels, reliable - schema frames, and timeout/retry semantics matching the TypeScript/Python - CultLib implementations. This removes "Rust cannot speak RUDP" as a substrate - excuse. It does not make any daemon fully migrated until that daemon publishes - its health and command boundary through the RUDP path and Idunn consumes that - daemon-owned publication. -- Idunn publishes `idunn.runtime_transport_check.v1` at startup. The current - check sends a CultNet hello over loopback `cultnet.transport.rudp.v0` and - records whether the acknowledgement path works in Idunn's own Rust runtime. - This proves Idunn's local substrate, not fleet migration. -- Idunn opens a RUDP health ingress only when `--rudp-health-bind` is supplied - and then publishes `idunn.rudp_health_ingress.v1`. The Starfire local - supervisor binds `0.0.0.0:17870` explicitly so host-local and WireGuard - publishers can use the configured Idunn health endpoint. That ingress - accepts raw `idunn.daemon_health` CultNet document puts and the dedicated - signed Epiphany runtime-health schema on the `schema` channel. Generic health - is observation-only. Epiphany promotion requires the separately persisted - `idunn.signed_health_admission.v1`, an exact latest - `idunn.deployment_request.v2`, a pinned host signature, current matching - health, and a fresh active admission. Each one-shot publisher gets its own RUDP session from its - UDP source address and the session is discarded after a delivered health - frame. Windows UDP `ConnectionReset`/`ConnectionAborted` reports from closed - one-shot clients are nonfatal ingress noise, not a reason to kill the worker. - The ingress does not grant deploy/restart authority; it is the daemon-owned - health publication path Idunn consumes. -- During each target cycle, fresh daemon-published RUDP health is the health - owner. Idunn accepts it only when the daemon id, health contract, - `publication_source=daemon-published`, transport `cultnet.transport.rudp.v0`, - and `max_silence_seconds` freshness window all match. If any of those fail, - Idunn publishes a missing-publication observation on the daemon key and plans - from that typed absence instead of running a local health command. -- Idunn publishes the active swarm transport migration plan as - `idunn.swarm_surgery_plan.v1`. That record names the active profile, owner, - objective, current mechanism, invariants, ordered phases, current phase, next - target, cut line, and verification layer. It is the state-surface answer to - "what surgery is Idunn doing next?" and must be lowered by Nightwing/Gjallar - before any chat summary or dashboard prose claims ownership of the plan. -- Idunn publishes per-target transport migration plans as - `idunn.daemon_surgery_plan.v1` records in the keepalive store. Each daemon - plan names severity, status, owner, objective, current mechanism, intended - CultNet/RUDP authority, cut line, ordered steps, blockers, and update time. - These records are operational state, not documentation garnish: Nightwing, - Gjallar, Odin, and future Eve lowerings should inspect them when projecting - the daemon surgery queue. -- A stale deployment is not restartable liveness. If a target reports - `stale-deployment` without deploy authority, Idunn must alarm instead of - restarting the stale artifact. If a target reports `dependency-unavailable` - or `degraded`, Idunn must alarm instead of treating local deploy/restart as - the owner. -- Daemon-owned health is evaluated before release inspection. A missing Git - checkout, unreachable upstream, or unreadable deployment witness cannot mask - fresh authenticated health and cannot prevent an unhealthy admitted body - from reaching its continuity restart path. Release inspection may refine a - healthy body into `stale-deployment`; it does not own liveness. -- Restarting an already-admitted installed body is continuity physiology and - does not consume deployment-brake authority. Artifact, configuration, - schema, unit, and authority-binding changes remain deployments and must pass - the deployment brake. A separate lifecycle brake is required if operators - need to suspend continuity actuation itself. -- Yggdrasil's `--repo-root` is Idunn-owned state, not Odin's live release. - The hosted profile uses explicit build-repository and root-manifest paths; - Idunn startup and recovery therefore do not read `/srv/odin/current`. -- Idunn should fail closed when authority is unclear. Unknown ownership, - repeated restart failure, missing command authority, or degraded health that - needs a human becomes an operator alarm. -- Operator alarms use CultMesh to request Bifrost-owned operator notification. - Bifrost is the bridge for the crossing and records the receipt. VoidBot's - `voidbot.operator-dm` command `owner.dm.send` with payload schema - `gamecult.operator_dm_request.v1` is a demoted compatibility delivery - actuator, not the owner. The owner-DM command lives in Bifrost's Verse; any - still-VoidBot delivery path must be invoked by Bifrost or documented as - migration debt. Idunn must not learn Discord token handling, DM delivery - internals, or VoidBot-specific transport. -- In the current local bridge, `--operator-alarm-command` invokes - `notify-idunn-operator-alarm.cmd`, which forwards `IDUNN_ALARM_*` - environment variables to `E:\Projects\Bifrost\tools\operator-notification.mjs - publish-idunn-alarm`. Bifrost publishes the typed CultMesh command document; - Idunn only decides that an alarm exists. -- Muninn continuity on Raven is a remote keepalive path. The long-running Raven - `muninn.exe serve` process now carries its own Idunn RUDP identity and - publishes `muninn.cultnet-rudp-remote-telemetry-health` directly; the - `muninn.exe --health` command is an explicit diagnostic publisher, not a - health owner. Idunn still restarts Muninn's idle `serve` posture - when needed. Raven is the host/body; Muninn is the local telemetry Verse - assembler. Idunn must not activate screen/audio streams as part of keepalive. - Raven media activation is a typed Muninn capture command whose target is a - `cultmesh://` URI resolved through Odin. Idunn does not install or run - standalone Raven A/V activation scripts. -- Raven is an operator-consented shared machine. Idunn restart and health - actuators for Raven must be background-only and must not open visible - terminals or interactive windows on that host. The Raven Muninn restart path - uses a hidden WScript/PowerShell trampoline; replacing it with an interactive - console launch violates the ops contract. -- Yggdrasil Gjallar deployment freshness and aggregate composition health are - part of Idunn's ops role. The daemon publishes - `gjallar.cultnet-rudp-composition-health`; Idunn's Yggdrasil actuator admits - immutable releases through the Gjallar deploy manifest and restarts - `gjallar-yggdrasil.service`. Nightwing has no Gjallar deployment or restart authority. -- Swarm-wide deployment ownership means Idunn owns the target catalog and the - freshness contract for the repo swarm. For enforced deploy targets, the - catalog must name upstream remote/branch, rollout strategy, state migration - authority, and whether zero downtime is actually available. Idunn deploys the - desired upstream revision, not arbitrary local developer `HEAD`. It does not - mean Idunn invents deploy authority for every repo immediately. A target - without a safe noninteractive deploy command must remain `blocked` or - `external-owned` with the missing authority named until a wrapper can produce - a deployment manifest and route through Idunn's typed deployment - request/result path. -- State migration is daemon-owned. Idunn may run and witness a declared - migration command before deployment, but the daemon/repo owns schema meaning, - backups, and the migrator. If migration fails, Idunn records - `idunn.state_migration_result.v1`, stops the deployment, records a failed - rollout/deployment result, and alarms instead of trying to repair state - behind the daemon's back. -- Deploy and restart scripts are Idunn actuators, not agent tools. They refuse - to run unless Idunn invokes them with `IDUNN_ACTUATOR=1` and - `IDUNN_COMMAND_AUTHORITY=idunn-daemon`. Agent work is to update the target - catalog, release target, command boundary, migration plan, and daemon - publication surfaces so Idunn can run the shared command primitive. -- Provider-health signer rotation is a root authority transaction over one - existing named trust binding. `idunn-provision - rotate-daemon-health-trust-signer` changes only that binding's public signer, - derived identity, and advancing bind time through a validated CultCache CAS; - daemon, contract, runtime, release policy, and every other binding remain - unchanged. -- Manual lifecycle requests are typed Idunn command records, not direct script - execution. Operators publish `idunn.lifecycle_command.v1` with `idunn restart - --daemon ` or `idunn redeploy --daemon `. The running supervisor - claims pending records for its target catalog, writes the corresponding - `idunn.restart_request.v1` or `idunn.deployment_request.v2`, executes through - the same guarded actuator path used by health-driven decisions, and records - the matching result document. If a target lacks restart or deploy authority, - Idunn marks the lifecycle command rejected instead of inventing authority. -- Zero downtime is a declared rollout capability, not a slogan. If a daemon - lacks hot reload, blue/green routing, rolling instances, or another named - in-place swap mechanism, Idunn records `restart-required` and verifies the - restart path honestly. -- Yggdrasil Odin, Heimdall, Ghostlight, repixelizer, and StreamPixels are - enforced through Idunn's source-selected release lane and their existing - `gamecult-ops` actuators. Heimdall and Ghostlight publish exact deployed - revisions in `/srv/heimdall/deploy/deployment.env` and - `/srv/ghostlight/deploy/deployment.env`; documentation-only commits cannot - become desired executable generations. - Odin publishes `idunn.signed_daemon_health.v1` with its root-bound Ed25519 - identity. Its immutable release pins both the Odin commit and the exact - CultLib commit, then switches them through one `/srv/odin/current` link. - Ghostlight's Linux runtime and signed-health identity are admitted. Heimdall - publishes its own daemon health and private authentication command listener; - its HTTP and loopback listener probes remain deployment witnesses rather than - release or health authority. - Bifrost is explicitly blocked as of 2026-06-09: committed Bifrost `HEAD` - expects `UserAccounts.HeimdallAccountId`, while Yggdrasil's production - database lacks that column and EF reports no pending migration. Idunn must - not claim Bifrost deployment freshness until Bifrost owns that schema - migration path. +## Current implementation boundary -## Runtime Direction - -Idunn's current Rust runtime now has two postures: - -1. One-daemon manual mode for focused probes and explicit local testing. -2. One-process swarm mode for the Starfire-local continuity graph. - -The local swarm mode owns: - -1. the built-in Starfire-local target catalog; -2. a mandatory health contract per target; -3. a typed `idunn.swarm_surgery_plan.v1` record, so Idunn's active migration - order, next target, cut line, and verification layer are explicit state; -4. a typed `idunn.daemon_surgery_plan.v1` record per target, so transport debt - is visible in the same state surface as daemon health; -5. a typed `idunn.daemon_transport_profile.v1` and - `idunn.command_boundary.v1` record per target, so debug probes and local - commands cannot pretend to be daemon-owned CultNet/RUDP truth; -6. a startup `idunn.runtime_transport_check.v1` witness proving Idunn's own - Rust RUDP loopback path; -7. a local `idunn.rudp_health_ingress.v1` listener for daemon-owned RUDP - health publication; -8. one in-process schedule per target instead of one watchdog process per target; -9. shared typed keepalive records in one CultMesh store; -10. deploy/restart/alarm execution through the same Rust decision engine; -11. recovery of fast local targets like Odin without waiting behind slow remote - Yggdrasil checks. - -Current plan surface: `idunn.swarm_surgery_plan.v1` for profile -`starfire-local` treats the Muninn Rust lanes, Odin's local provider-health -lane, Stonks daemon health, Weksa daemon health, VoidBot stack health, and -Nightwing Gjallar framebuffer composition health as completed substrate cuts. -Muninn's long-running `serve` bodies now publish -`idunn.daemon_health` over RUDP themselves; Starfire publishes to local Idunn, -while Nightwing and Raven publish to the configured Idunn RUDP health endpoint -using their target daemon ids and health contracts. The Muninn restart and -health wrappers require explicit `-IdunnRudpHealth` or `IDUNN_RUDP_HEALTH`; -there is no baked Starfire LAN default. `muninn --health` is an explicit -diagnostic publisher for the same typed health document, not live ownership. -Odin -publishes `odin.cultnet-rudp-provider-health` after each provider refresh. -Stonks publishes `stonks.cultnet-rudp-market-health` after each serialized -market refresh. Weksa publishes `weksa.cultnet-rudp-provider-health` after each -serialized provider witness refresh. VoidBot publishes -`voidbot.cultnet-rudp-stack-health` after each GameCult Local Orchestrator -pulse. Gjallar publishes `gjallar.cultnet-rudp-composition-health` from the C# -Yggdrasil aggregate compositor. Mimir Eve dashboard publishes -`mimir.cultnet-rudp-provider-health` from the Nightwing systemd broker, and the -same process publishes `nightwing.cultnet-rudp-eve-dashboard-health` for the -Nightwing dashboard service itself. The Nightwing Eve browser reference now runs -as `Mimir.EveBrowserReference`, serving -the same static lowering and publishing -`nightwing.cultnet-rudp-browser-reference-health` from its own service process. -Live Idunn cycles accept these records as health truth; missing or stale -publication becomes typed missing-publication state. -Raven's Muninn scheduled-task repair remains a separate ops invariant: -`GameCult-Muninn` is the only live Muninn scheduled task. Health fails if -obsolete activation or video-proof tasks still exist, and the live Raven -`serve` process must carry its own -`--idunn-rudp-health`, `--idunn-daemon`, and `--idunn-health-contract` -arguments. - -Next: keep moving the remaining Yggdrasil deployments off product/deck checks and -continue runtime-by-runtime until debug probes are unable to masquerade as -daemon truth. -Heimdall has now crossed the first live transport line: the Yggdrasil runtime -publishes `heimdall.cultnet-rudp-provider-health`, writes a daemon-owned -boundary witness at `/srv/heimdall/cultcache/heimdall.service.cc`, and the -deploy lane ships the required `CultLib` snapshot beside the app artifact. -Heimdall still owes Odin ingestion of that boundary store plus the later -redacted auth-document witness export, but it is no longer waiting on basic -RUDP keepalive surgery. Weksa now publishes daemon-owned provider -advertisement, operator state, Eve surface, command boundary, and transport -profile records in its provider store, accepts MiMo VoiceDesign commands over -CultNet/RUDP command documents, and records deleted product command lanes as -non-authority. Odin local discovery can ingest those records. The Weksa start -and restart wrappers require explicit `-IdunnRudpHealth` or -`WEKSA_IDUNN_RUDP_HEALTH`; there is no localhost Idunn default. Stonks now -publishes daemon-owned provider advertisement, -market snapshot, Eve surface, command boundary, and transport profile records in -its CultCache store, and Odin local discovery can ingest those records; product -routes are not provider transport. StreamPixels now has a -service-owned CultCache boundary store at -`E:\Projects\StreamPixels\.streampixels-data\cultcache\streampixels.service.cc` -containing provider advertisement, command boundary, transport profile, and an -Idunn health summary, and Odin local discovery can ingest it. The live -Yggdrasil deployment now keeps -`/srv/streampixels/env/service.env` wired for -explicit `STREAMPIXELS_IDUNN_RUDP_HEALTH` with contract -`streampixels.cultnet-rudp-service-health`, publishes the boundary store at -`/srv/streampixels/app/.streampixels-data/cultcache/streampixels.service.cc`, -and has live Idunn acceptance proof for `yggdrasil-streampixels` through the -configured RUDP route. StreamPixels now owes only the final demotion of host -checks to deployment/debug witnesses once Odin consumes the typed store. -Repixelizer now has a daemon-owned Verse runtime witness in -`src/repixelizer/verse_state.py`: the live GUI runtime writes provider -advertisement, Eve surface state, runtime config, auth projection, queue/job -records, command boundary, transport profile, and `idunn.daemon_health` into -the configured `.cc` store, and publishes Idunn RUDP health when -`GC_ACCESS_IDUNN_RUDP_HEALTH` is configured. Repixelizer product web and host -supervisor checks are deployment/debug witnesses; -absent RUDP health is a visible missing-publication state, not fallback truth. -VoidBot, Mimir, and -the Nightwing Eve runtime services still owe provider advertisement and -command-boundary RUDP publication before their renderer surfaces can be derived -from typed state alone. Gjallar consumes Odin's accepted provider-state -snapshot over CultNet/RUDP; Odin no longer hosts a browser-deck lowering bridge -for it to consume. Raven Muninn task action repair is no longer queued: the live -target is the single `GameCult-Muninn` serve task, while obsolete activation and -video-proof tasks are removed and treated as health failures if they return. - -Vili's Node daemon now has an in-process Idunn RUDP publisher for -`vili.cultnet-rudp-animation-health`, and local smoke proof shows Idunn accepts -that record over `cultnet.transport.rudp.v0`. Vili also writes -`.vili\vili.service.cc` with daemon-owned provider advertisement, operator -state, Eve surface, command boundary, and transport profile records. Odin local -provider discovery can ingest that typed store, including the Vili command -boundary and transport profile. That is now live Raven proof as well: Odin's -`scripts\restart-vili.ps1` refreshes the Raven runtime from the authoritative -local Vili and CultLib files, reinstalls the hidden `GameCult\Vili` task with -`--idunn-rudp-health` supplied by explicit `-IdunnRudpHealth`, -`VILI_IDUNN_RUDP_HEALTH`, or `IDUNN_RUDP_HEALTH`, and restarts it. Live Idunn -accepts `vili.cultnet-rudp-animation-health` through the configured RUDP route. - -No ad hoc JSON manifest, product endpoint, port socket, or browser-deck bridge -may become the live state owner. Debug projections are fine when they name the -`.cc` record, CultNet document, or CultMesh publication behind them. +`crates/idunn-daemon/src/deployment.rs` and `deployment_plan.rs` implement the +deterministic declaration, binding, plan, release, and Expected foundation. +They do not yet drive Git, runners, systemd, proxies, CultCache, CultMesh, +brakes, runtime activations, write leases, or runtime health verification. +Runtime integration must consume these contracts; it must not recreate target +catalogs, raw deployment commands, root Git inspection, or a second admission +opinion. diff --git a/vendor/cultnet-rs b/vendor/cultnet-rs index 021dca7..87d0b0f 160000 --- a/vendor/cultnet-rs +++ b/vendor/cultnet-rs @@ -1 +1 @@ -Subproject commit 021dca7f3261c9842019f0845b35022455ccf756 +Subproject commit 87d0b0f2c829ef2e7defa2bf774f1e3b9cc6a1d0