From 87fa57dd8c8a089891393b7fbdfaf6cd9eb8bb62 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 01:30:09 +0200 Subject: [PATCH 01/11] Revert "Recover fenced rollback from current activation" This reverts commit a148802cb6c24338f1ed376d23de94f18dc8411f. Rollback after fencing adopted whatever activation was projected under the shared Expected key, so a continuity abort's leftover activation could be demoted by a later deploy. The drift is closed at its source by the next commit: a continuity abort demotes its own exact activation. Rollback demotes the admitted generation's exact activation again. The doc paragraph is dropped; the 9f00e7a paragraph above it stays until B4. Co-Authored-By: Claude Sonnet 5 --- docs/deployment-authority.md | 9 -- src/control_plane.rs | 5 +- src/drivers.rs | 186 ++--------------------------------- 3 files changed, 12 insertions(+), 188 deletions(-) diff --git a/docs/deployment-authority.md b/docs/deployment-authority.md index 3b23009..c24a7f5 100644 --- a/docs/deployment-authority.md +++ b/docs/deployment-authority.md @@ -312,15 +312,6 @@ observation own current workload health. Historical receipts do not expire merely because their provider remains admitted longer than the observation window. -An Expected digest stays stable across continuity restarts, so the current -activation at that projection key can be newer than the activation cached in an -older admitted-generation receipt. During post-fencing rollback, Idunn first -stops the candidate and withdraws the lease. It then verifies any current -projected activation against Idunn's own trust anchor and the exact Expected -record, refuses if a projected write lease remains, and demotes the projection -to Expected-only. The admitted receipt does not overwrite a newer signed -activation, and no operator edits the CultCache projection by hand. - 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 diff --git a/src/control_plane.rs b/src/control_plane.rs index 99126cc..754f55b 100644 --- a/src/control_plane.rs +++ b/src/control_plane.rs @@ -5969,10 +5969,11 @@ impl Engine { if let Some(incumbent) = self.exact_incumbent(&snapshot, ¤t.value)? { let admitted_provider_anchor = self.provider_anchor_for_plan(&incumbent.value.plan)?; - let expected_sha256 = topology.demote_current_activation_to_expected_only( + let expected_sha256 = topology.demote_to_expected_only( &incumbent.value.expected, &admitted_provider_anchor, - &self.idunn_anchor, + &incumbent.value.activation, + incumbent.value.leasing.lease(), )?; ensure!( expected_sha256 == incumbent.value.expected.canonical_sha256()?, diff --git a/src/drivers.rs b/src/drivers.rs index 06c16c8..fa45b8c 100644 --- a/src/drivers.rs +++ b/src/drivers.rs @@ -4420,36 +4420,20 @@ impl CultCacheTopologyDriver { provider_anchor: &ServiceIdentityTrustAnchor, activation: &IdunnRuntimeActivationRecord, lease: Option<&IdunnProcessWriteLeaseRecord>, - ) -> Result { - self.demote_projection(expected, provider_anchor, Some(activation), lease) - } - - fn demote_projection( - &self, - expected: &IdunnExpectedIncarnationRecord, - provider_anchor: &ServiceIdentityTrustAnchor, - activation: Option<&IdunnRuntimeActivationRecord>, - lease: Option<&IdunnProcessWriteLeaseRecord>, ) -> Result { expected.validate()?; - if let Some(activation) = activation { - activation.validate()?; - ensure!( - activation.expected_projection_sha256 == expected.canonical_sha256()?, - "admitted activation does not bind the admitted Expected projection" - ); - } + activation.validate()?; + ensure!( + activation.expected_projection_sha256 == expected.canonical_sha256()?, + "admitted activation does not bind the admitted Expected projection" + ); if let Some(lease) = lease { - validate_topology_lease( - expected, - activation.context("demotion lease has no exact activation")?, - lease, - )?; + validate_topology_lease(expected, activation, lease)?; } let anchor = runtime_presence_trust_anchor(expected, provider_anchor)?; let key = incarnation_key(expected)?; self.mutate(|entries| { - let projected = ProjectedIncarnation::read(entries, expected, activation, lease)?; + let projected = ProjectedIncarnation::read(entries, expected, Some(activation), lease)?; let current_anchor = projection_entry( entries, GameCultServiceTrustAnchorRecord::TYPE, @@ -4490,55 +4474,6 @@ impl CultCacheTopologyDriver { expected.canonical_sha256() } - /// Demote the current projected activation after the owning transaction - /// has fenced the target. A continuity restart can replace the activation - /// under the same Expected key while the admitted-generation receipt still - /// carries the prior runtime instance. In that one post-fence recovery - /// path, trust the current projection only after verifying Idunn's - /// signature and exact Expected binding, and refuse while any projected - /// write lease remains. - pub fn demote_current_activation_to_expected_only( - &self, - expected: &IdunnExpectedIncarnationRecord, - provider_anchor: &ServiceIdentityTrustAnchor, - idunn_anchor: &ServiceIdentityTrustAnchor, - ) -> Result { - expected.validate()?; - let entries = self.snapshot()?; - let key = incarnation_key(expected)?; - let projected_activation = projection_entry( - &entries, - IdunnRuntimeActivationRecord::TYPE, - &key, - )? - .map(|envelope| -> Result { - ensure!( - envelope.schema_id.as_deref() == Some(IDUNN_RUNTIME_ACTIVATION_SCHEMA), - "projected activation schema is substituted" - ); - let activation = IdunnRuntimeActivationRecord::decode_canonical(&envelope.payload)?; - activation.verify_for_expected(expected, idunn_anchor)?; - Ok(activation) - }) - .transpose()?; - ensure!( - projection_entry( - &entries, - IdunnProcessWriteLeaseRecord::TYPE, - &key, - )? - .is_none(), - "cannot demote an incarnation while its projected write lease remains" - ); - - self.demote_projection( - expected, - provider_anchor, - projected_activation.as_ref(), - None, - ) - } - /// Whether the projection currently names an activation for this /// incarnation. Continuity asks so it can tell a projection that still /// describes a dead incarnation from one already demoted to Expected-only. @@ -8465,7 +8400,7 @@ mod tests { IDUNN_PROCESS_WRITE_LEASE_SCHEMA, IdunnServiceIdentity, OdinRuntimeTopologyCorrelationPurpose, OdinTopologyAuthenticationContext, OdinTopologyIdentity, authenticate_odin_runtime_topology_correlation, - enroll_service_identity_at, open_service_identity_at, verify_runtime_authority, + enroll_service_identity_at, verify_runtime_authority, }; fn digest(byte: char) -> String { @@ -10838,12 +10773,7 @@ mod tests { ); assert!(!driver.projected_activation_is_present(&incumbent)?); let idempotent_bytes = fs::read(&driver.projection_store)?; - driver.demote_to_expected_only( - &incumbent, - &provider_anchor, - &activation, - Some(&lease), - )?; + driver.demote_to_expected_only(&incumbent, &provider_anchor, &activation, Some(&lease))?; assert_eq!(fs::read(&driver.projection_store)?, idempotent_bytes); // A record under the incumbent's key that is not the incumbent's is a @@ -10907,104 +10837,6 @@ mod tests { Ok(()) } - #[test] - fn fenced_demotion_uses_the_current_verified_activation() -> Result<()> { - let temp = tempfile::tempdir()?; - let (expected, admitted_activation, warming, provider_anchor) = - authenticated_warming(temp.path())?; - let idunn = open_service_identity_at::(&temp.path().join("idunn.cc"))?; - let replacement = IdunnRuntimeActivationLaunch::issue( - &expected, - digest('a'), - 300, - &idunn, - )? - .activation() - .clone(); - assert_ne!(admitted_activation, replacement); - - let driver = topology_driver(temp.path(), "fenced-demotion"); - driver.publish_expected(&expected, &provider_anchor)?; - project_activation(&driver, &expected, &admitted_activation)?; - let key = incarnation_key(&expected)?; - upsert_record( - &driver.projection_store, - activation_envelope(&key, &replacement)?, - )?; - - assert_eq!( - driver.demote_current_activation_to_expected_only( - &expected, - &provider_anchor, - &idunn.trust_anchor()?, - )?, - expected.canonical_sha256()? - ); - assert!(!driver.projected_activation_is_present(&expected)?); - let after = SingleFileMessagePackBackingStore::new(&driver.projection_store) - .pull_all_read_only_snapshot()?; - assert!(after.iter().any(|entry| { - entry.key == key && entry.r#type == IdunnExpectedIncarnationRecord::TYPE - })); - assert!(after.iter().all(|entry| { - !(entry.key == key - && (entry.r#type == IdunnRuntimeActivationRecord::TYPE - || entry.r#type == IdunnProcessWriteLeaseRecord::TYPE)) - })); - - // Expected-only demotion is idempotent when the activation is already - // absent. - let settled = fs::read(&driver.projection_store)?; - driver.demote_current_activation_to_expected_only( - &expected, - &provider_anchor, - &idunn.trust_anchor()?, - )?; - assert_eq!(fs::read(&driver.projection_store)?, settled); - - // A record with an invalid Idunn signature is not adopted as current - // authority, even after fencing. - let mut forged = replacement; - forged.runtime_instance_id = digest('b'); - upsert_record( - &driver.projection_store, - activation_envelope(&key, &forged)?, - )?; - let before_forgery_attempt = fs::read(&driver.projection_store)?; - assert!(driver - .demote_current_activation_to_expected_only( - &expected, - &provider_anchor, - &idunn.trust_anchor()?, - ) - .is_err()); - assert_eq!(fs::read(&driver.projection_store)?, before_forgery_attempt); - - // A remaining lease means the target has not reached the demotion - // boundary. The operation leaves every byte untouched. - let incumbent_lease = lease(&expected, &admitted_activation, &warming); - upsert_record( - &driver.projection_store, - CultCacheEnvelope { - key: key.clone(), - r#type: IdunnProcessWriteLeaseRecord::TYPE.into(), - payload: incumbent_lease.canonical_bytes()?, - stored_at: "2026-09-03T00:00:00Z".into(), - schema_id: Some(IDUNN_PROCESS_WRITE_LEASE_SCHEMA.into()), - }, - )?; - let before_leased_attempt = fs::read(&driver.projection_store)?; - assert!(driver - .demote_current_activation_to_expected_only( - &expected, - &provider_anchor, - &idunn.trust_anchor()?, - ) - .is_err()); - assert_eq!(fs::read(&driver.projection_store)?, before_leased_attempt); - Ok(()) - } - /// A replaced incarnation nothing owns is withdrawn whole; the one still /// admitted, and the target's anchor, are untouched. #[test] From 44277698c3dd487d1aca84aca27168c3ea45a43e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 01:30:19 +0200 Subject: [PATCH 02/11] A continuity abort resolves its own projection (route continuity B1) A continuity candidate shares the admitted Expected key. Both abort intents marked its topology reconciliation Skipped, so a failed continuity left its candidate activation projected under the admitted key while the admitted receipt named the older one, and a later deploy's post-fence demotion refused as substituted. DeploymentTransaction::abort_topology_reconciliation is now the one rule for both intents and pre-fence validation: a deployment owes the projection when it published its Expected, a continuity owes it when it issued an activation. reconcile_failed_candidate_projection is the one resolution for both abort paths: a deployment withdraws its own key, a continuity demotes the shared key to Expected-only with its own exact activation and never withdraws the Expected. The post-fence incumbent demotion stays deployment-only and exact. Tests read the persisted topology store after the production publish/demote sequence. Co-Authored-By: Claude Sonnet 5 --- docs/deployment-authority.md | 6 + src/control_plane.rs | 332 ++++++++++++++++++++++++++++++----- 2 files changed, 290 insertions(+), 48 deletions(-) diff --git a/docs/deployment-authority.md b/docs/deployment-authority.md index c24a7f5..0ee3483 100644 --- a/docs/deployment-authority.md +++ b/docs/deployment-authority.md @@ -312,6 +312,12 @@ observation own current workload health. Historical receipts do not expire merely because their provider remains admitted longer than the observation window. +A failed continuity restart leaves its own candidate activation projected under +the shared Expected key. Its abort demotes that key to Expected-only with the +exact activation the transaction issued, so the projection never drifts from the +admitted receipt. Rollback after fencing demotes the admitted generation's exact +activation. No path adopts an activation the transaction did not issue. + 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 diff --git a/src/control_plane.rs b/src/control_plane.rs index 754f55b..6cbbee3 100644 --- a/src/control_plane.rs +++ b/src/control_plane.rs @@ -795,6 +795,22 @@ impl DeploymentTransaction { Ok(transaction) } + /// Whether an abort owes the projection a reconciliation. A deployment + /// published its own Expected key. A continuity shares the admitted key, + /// whose Expected is never withdrawn, so it owes only the demotion of the + /// activation it issued. + fn abort_topology_reconciliation(&self) -> CleanupEvidence { + let owes = match self.command_kind { + CommandKind::Deploy => self.expected_publication_sha256.is_some(), + CommandKind::Continuity => self.activation.is_some(), + }; + if owes { + CleanupEvidence::Pending + } else { + CleanupEvidence::Skipped + } + } + fn rejected(command: &DeploymentCommand, error: anyhow::Error, now: u64) -> Result { let mut transaction = Self::new(command, command.selector.clone(), 0, None, now)?; let detail = truncate(&format!("{error:#}"), 2048); @@ -1013,15 +1029,18 @@ impl DeploymentTransaction { ), "abort candidate cleanup differs from its prepared activation" ); - let topology_cleanup_required = self.command_kind == CommandKind::Deploy - && self.expected_publication_sha256.is_some(); ensure!( matches!( - (topology_cleanup_required, abort.topology_reconciliation), - (true, CleanupEvidence::Pending | CleanupEvidence::Complete) - | (false, CleanupEvidence::Skipped) + ( + self.abort_topology_reconciliation(), + abort.topology_reconciliation + ), + ( + CleanupEvidence::Pending, + CleanupEvidence::Pending | CleanupEvidence::Complete + ) | (CleanupEvidence::Skipped, CleanupEvidence::Skipped) ), - "abort topology cleanup differs from published deployment Expected" + "abort topology cleanup differs from what the transaction projected" ); ensure!( matches!( @@ -5819,13 +5838,7 @@ impl Engine { current.value.activation.is_some(), current.value.workload.is_some(), ), - topology_reconciliation: if current.value.command_kind == CommandKind::Deploy - && current.value.expected_publication_sha256.is_some() - { - CleanupEvidence::Pending - } else { - CleanupEvidence::Skipped - }, + topology_reconciliation: current.value.abort_topology_reconciliation(), source_cleanup: if current.value.command_kind == CommandKind::Deploy { CleanupEvidence::Pending } else { @@ -5947,26 +5960,27 @@ impl Engine { }); } if abort.topology_reconciliation == CleanupEvidence::Pending { - let expected = required(¤t.value.expected, "failed Expected projection")?; let snapshot = ControlSnapshot::read(&self.options.state_store)?; - // The failed candidate's records go, under its own key. Fencing - // stopped the incumbent and revoked its lease, so the incumbent is - // demoted to Expected-only under its key, which is what lets - // continuity bring it back; deployment does not restart it here. + // The failed candidate's projection is resolved first. For a + // deployment, fencing also stopped the incumbent and revoked its + // lease, so the incumbent is demoted to Expected-only under its + // key with its own exact activation, which is what lets + // continuity bring it back. A continuity candidate is the + // incumbent's key: it has nothing further to demote. let topology = self.topology(); let failed_provider_anchor = self.provider_anchor_for_plan(required( ¤t.value.plan, "failed transaction plan", )?)?; - topology - .withdraw_incarnation( - expected, - &failed_provider_anchor, - current.value.activation.as_ref(), - None, - ) - .context("withdrawing the failed candidate projection")?; - if let Some(incumbent) = self.exact_incumbent(&snapshot, ¤t.value)? { + reconcile_failed_candidate_projection( + &topology, + ¤t.value, + &failed_provider_anchor, + )?; + if let Some(incumbent) = self + .exact_incumbent(&snapshot, ¤t.value)? + .filter(|_| current.value.command_kind == CommandKind::Deploy) + { let admitted_provider_anchor = self.provider_anchor_for_plan(&incumbent.value.plan)?; let expected_sha256 = topology.demote_to_expected_only( @@ -6042,22 +6056,17 @@ impl Engine { }); } if abort.topology_reconciliation == CleanupEvidence::Pending { - let expected = required(¤t.value.expected, "failed Expected projection")?; - // Before fencing the incumbent was never touched: it is still - // running under its own key with its activation and lease. Only the - // failed candidate's records are withdrawn. The incumbent's - // projection is not demoted -- doing so would tell a live process - // it has no activation. + // Before fencing a deployment never touched its incumbent: it is + // still running under its own key with its activation and lease, + // so only the candidate's records are withdrawn. A continuity + // candidate shares the admitted key and demotes what it issued. let plan = required(¤t.value.plan, "failed transaction plan")?; let provider_anchor = self.provider_anchor_for_plan(plan)?; - self.topology() - .withdraw_incarnation( - expected, - &provider_anchor, - current.value.activation.as_ref(), - None, - ) - .context("withdrawing exact failed Expected projection")?; + reconcile_failed_candidate_projection( + &self.topology(), + ¤t.value, + &provider_anchor, + )?; return self.persist_same_phase(current, |next| { next.pre_fencing_abort .as_mut() @@ -6184,6 +6193,37 @@ fn provider_warming_advanced( && candidate_signed_presence_sha256 != prior_signed_presence_sha256 } +/// Resolve the projection a failed candidate left. A deployment candidate owns +/// its own incarnation key and withdraws it whole. A continuity candidate +/// shares the admitted key: the admitted Expected is never withdrawn, and the +/// only thing demoted is the activation this transaction issued, exactly. +fn reconcile_failed_candidate_projection( + topology: &CultCacheTopologyDriver, + transaction: &DeploymentTransaction, + provider_anchor: &ServiceIdentityTrustAnchor, +) -> Result<()> { + let expected = required(&transaction.expected, "failed Expected projection")?; + match transaction.command_kind { + CommandKind::Deploy => topology + .withdraw_incarnation( + expected, + provider_anchor, + transaction.activation.as_ref(), + None, + ) + .context("withdrawing the failed candidate projection"), + CommandKind::Continuity => topology + .demote_to_expected_only( + expected, + provider_anchor, + required(&transaction.activation, "failed continuity activation")?, + None, + ) + .map(drop) + .context("demoting the failed continuity activation"), + } +} + fn may_rollback_route_after_failed_proof(fencing: &FencingEvidence) -> bool { matches!(fencing, FencingEvidence::SkippedStateless) } @@ -6223,13 +6263,7 @@ fn post_fencing_abort_intent( transaction.activation.is_some(), transaction.workload.is_some(), ), - topology_reconciliation: if transaction.command_kind == CommandKind::Deploy - && transaction.expected_publication_sha256.is_some() - { - CleanupEvidence::Pending - } else { - CleanupEvidence::Skipped - }, + topology_reconciliation: transaction.abort_topology_reconciliation(), source_cleanup: if transaction.command_kind == CommandKind::Deploy { CleanupEvidence::Pending } else { @@ -8295,4 +8329,206 @@ mod tests { }) ); } + /// The persisted projection a continuity restart leaves behind, read at + /// the file the daemon writes. + struct ContinuityProjection { + _temp: TempDir, + topology: CultCacheTopologyDriver, + provider_anchor: ServiceIdentityTrustAnchor, + expected: IdunnExpectedIncarnationRecord, + admitted_activation: IdunnRuntimeActivationRecord, + candidate_activation: IdunnRuntimeActivationRecord, + } + + impl ContinuityProjection { + /// The production sequence: the admitted incarnation dies and is + /// demoted to Expected-only, then the continuity candidate publishes + /// its own activation under the same key once it is observed. + fn after_candidate_observed() -> Result { + let temp = TempDir::new()?; + let root = temp.path(); + let idunn = enroll_service_identity_at::(&root.join("idunn.cc"))?; + let provider = enroll_service_identity_at::( + &root.join("provider.cc"), + )?; + let provider_anchor = provider.trust_anchor()?; + let mut expected = TopologyFixture::new("ghostlight")?.expected; + expected.expected_signer_identity_id = provider.entry().identity_id.clone(); + expected.artifact_sha256 = sha256_id(&[1]); + expected.validate()?; + let topology = CultCacheTopologyDriver { + projection_store: root.join("topology.cc"), + correlation_store: root.join("correlation.cc"), + }; + let admitted = workload(1, 40, 50); + let candidate = workload(2, 41, 51); + let issue = |observation: &WorkloadObservation| -> Result<_> { + Ok(IdunnRuntimeActivationLaunch::issue( + &expected, + observation.runtime_instance_id().to_owned(), + NOW, + &idunn, + )? + .activation() + .clone()) + }; + let admitted_activation = issue(&admitted)?; + let candidate_activation = issue(&candidate)?; + assert_ne!(admitted_activation, candidate_activation); + + topology.publish_expected(&expected, &provider_anchor)?; + topology.publish_observed_activation(&expected, &admitted_activation, &admitted)?; + topology.demote_to_expected_only( + &expected, + &provider_anchor, + &admitted_activation, + None, + )?; + topology.publish_expected(&expected, &provider_anchor)?; + topology.publish_observed_activation(&expected, &candidate_activation, &candidate)?; + Ok(Self { + _temp: temp, + topology, + provider_anchor, + expected, + admitted_activation, + candidate_activation, + }) + } + + fn continuity_transaction(&self) -> Result { + let mut transaction = DeploymentTransaction::new( + &command(CommandKind::Continuity), + "ghostlight".into(), + 0, + None, + 100, + )?; + transaction.expected = Some(self.expected.clone()); + transaction.activation = Some(self.candidate_activation.clone()); + Ok(transaction) + } + + /// Types of the records projected under the shared incarnation key. + fn projected_types(&self) -> Result> { + let key = incarnation_key(&self.expected)?; + Ok( + SingleFileMessagePackBackingStore::new(&self.topology.projection_store) + .pull_all_read_only_snapshot()? + .into_iter() + .filter(|entry| entry.key == key) + .map(|entry| entry.r#type) + .collect(), + ) + } + } + + #[test] + fn a_failed_continuity_demotes_its_own_activation_and_keeps_the_expected() -> Result<()> { + let world = ContinuityProjection::after_candidate_observed()?; + assert!( + world + .projected_types()? + .contains(&IdunnRuntimeActivationRecord::TYPE.to_owned()) + ); + let transaction = world.continuity_transaction()?; + assert_eq!( + transaction.abort_topology_reconciliation(), + CleanupEvidence::Pending + ); + assert_eq!( + post_fencing_abort_intent(&transaction, "candidate died").topology_reconciliation, + CleanupEvidence::Pending + ); + + reconcile_failed_candidate_projection( + &world.topology, + &transaction, + &world.provider_anchor, + )?; + + assert_eq!( + world.projected_types()?, + vec![IdunnExpectedIncarnationRecord::TYPE.to_owned()], + "the shared key must keep its Expected and nothing else" + ); + Ok(()) + } + + #[test] + fn a_continuity_that_issued_no_activation_owes_no_projection_change() -> Result<()> { + let world = ContinuityProjection::after_candidate_observed()?; + let mut transaction = world.continuity_transaction()?; + transaction.activation = None; + assert_eq!( + transaction.abort_topology_reconciliation(), + CleanupEvidence::Skipped + ); + assert_eq!( + post_fencing_abort_intent(&transaction, "candidate never started") + .topology_reconciliation, + CleanupEvidence::Skipped + ); + Ok(()) + } + + #[test] + fn a_deploy_fencing_after_a_failed_continuity_resolves_with_the_admitted_activation() + -> Result<()> { + let world = ContinuityProjection::after_candidate_observed()?; + reconcile_failed_candidate_projection( + &world.topology, + &world.continuity_transaction()?, + &world.provider_anchor, + )?; + let settled = std::fs::read(&world.topology.projection_store)?; + + // The deploy's post-fence rollback demotes the admitted generation's + // exact activation. The failed continuity left nothing standing, so it + // resolves instead of refusing as substituted. + world.topology.demote_to_expected_only( + &world.expected, + &world.provider_anchor, + &world.admitted_activation, + None, + )?; + assert_eq!(std::fs::read(&world.topology.projection_store)?, settled); + Ok(()) + } + + #[test] + fn no_path_adopts_an_activation_the_transaction_did_not_issue() -> Result<()> { + let world = ContinuityProjection::after_candidate_observed()?; + let before = std::fs::read(&world.topology.projection_store)?; + + // The candidate's activation is still projected. The admitted + // generation's exact activation is not what stands there, so its + // demotion refuses rather than taking the newer one. + assert!( + world + .topology + .demote_to_expected_only( + &world.expected, + &world.provider_anchor, + &world.admitted_activation, + None, + ) + .is_err() + ); + + // Nor may a continuity transaction demote an activation it did not + // issue. + let mut foreign = world.continuity_transaction()?; + foreign.activation = Some(world.admitted_activation.clone()); + assert!( + reconcile_failed_candidate_projection( + &world.topology, + &foreign, + &world.provider_anchor + ) + .is_err() + ); + assert_eq!(std::fs::read(&world.topology.projection_store)?, before); + Ok(()) + } } From 4a9fe87787b165fce09797b8b938c92fb7d8a106 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 01:32:59 +0200 Subject: [PATCH 03/11] Import incarnation_key into the continuity projection tests Co-Authored-By: Claude Sonnet 5 --- src/control_plane.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/control_plane.rs b/src/control_plane.rs index 6cbbee3..5a862b2 100644 --- a/src/control_plane.rs +++ b/src/control_plane.rs @@ -6574,7 +6574,7 @@ mod tests { use tempfile::TempDir; use super::*; - use crate::drivers::SystemdWorkloadObservation; + use crate::drivers::{SystemdWorkloadObservation, incarnation_key}; /// Fixed clock for the signing fixture; correlations must land inside /// DEFAULT_TOPOLOGY_MAXIMUM_AGE_MILLIS of it to authenticate. From 9e5b7f84fd7fcd177dbb2d818f86afc603419de4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 06:11:29 +0200 Subject: [PATCH 04/11] Close the B1 transition: lift, precondition, boot reconciliation, closed history Soul found B1's rule sound and its transition unsafe. This makes the rule's old inputs impossible to reintroduce a stuck state from. - The control store's legacy lift owns the transition. A pre-B1 continuity abort that issued an activation lifts with topology_reconciliation Pending, so the one resolution demotes its own activation. A record already terminal under the old rule is reopened at Starting, since a terminal record cannot owe work. History lifts records as written. Before this, one resident record of that shape failed validation and ControlSnapshot::read refused the whole store, so Idunn could not boot. - Supervision owns the Expected-only precondition. When its pre-restart demotion fails it mints no continuity and writes next_restart_at_unix_millis on the generation's ContinuityBackoff (attempts and window untouched), so it neither restarts over an undemotable projection nor retries every tick. - Boot reconciles once: a projected activation that exactly matches the activation a failed continuity in history (or a resident terminal record) issued is demoted. Nothing is adopted; an activation no admitted generation, live transaction or failed issuer accounts for is reported and left alone. New read-only CultCacheTopologyDriver::projected_activation. - Unreadable history.cc fails closed. The continuity restart ceiling and the consumed-command check no longer read an empty history; they stop, and the fault is reported once while it lasts (ReportOnce). The undecodable-record report is a pure function, pinned. - docs/deployment-authority.md no longer says the projection never drifts. Tests: legacy fixtures written by the 9001b58 encoder for the three abort shapes (a second throwaway generator, see the fixtures README), driven through the Engine; the seeded-transaction helper now takes a command kind and an incumbent, and a Deploy carries a frozen-source receipt and a signed brake release, so Deploy commit, Deploy pre- and post-fence aborts and a continuity abort over an incumbent run through the real phase machine. Co-Authored-By: Claude Sonnet 5 --- docs/deployment-authority.md | 16 +- src/control_plane.rs | 1444 ++++++++++++++++- src/drivers.rs | 16 + tests/fixtures/idunn-control-legacy/README.md | 20 + .../idunn-control-legacy/provider-anchor.hex | 1 + .../transaction-post-fence-abort.hex | 2 + .../transaction-pre-fence-abort-terminal.hex | 2 + .../transaction-pre-fence-abort.hex | 2 + 8 files changed, 1434 insertions(+), 69 deletions(-) create mode 100644 tests/fixtures/idunn-control-legacy/provider-anchor.hex create mode 100644 tests/fixtures/idunn-control-legacy/transaction-post-fence-abort.hex create mode 100644 tests/fixtures/idunn-control-legacy/transaction-pre-fence-abort-terminal.hex create mode 100644 tests/fixtures/idunn-control-legacy/transaction-pre-fence-abort.hex diff --git a/docs/deployment-authority.md b/docs/deployment-authority.md index 0ee3483..da7f028 100644 --- a/docs/deployment-authority.md +++ b/docs/deployment-authority.md @@ -314,9 +314,19 @@ window. A failed continuity restart leaves its own candidate activation projected under the shared Expected key. Its abort demotes that key to Expected-only with the -exact activation the transaction issued, so the projection never drifts from the -admitted receipt. Rollback after fencing demotes the admitted generation's exact -activation. No path adopts an activation the transaction did not issue. +exact activation the transaction issued. Rollback after fencing demotes the +admitted generation's exact activation. No path adopts an activation the +transaction did not issue. + +A projection can still hold an activation the abort never resolved: a failure +between preparing a candidate and publishing its observation, an abort written +by an earlier Idunn, or an operator edit. Continuity therefore restarts a +generation only from an Expected-only projection: when its own demotion is +refused it mints no restart, records the deferral in the generation's +continuity backoff, and tries again after it. At boot, Idunn demotes an +activation still projected for a failed continuity in history, by that +transaction's exact activation, and only reports one no failed transaction +issued. 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 diff --git a/src/control_plane.rs b/src/control_plane.rs index cd82a0e..6c97384 100644 --- a/src/control_plane.rs +++ b/src/control_plane.rs @@ -62,6 +62,10 @@ const ODIN_RENDEZVOUS_CAPABILITY: &str = "odin.verse-rendezvous"; /// and few because each attempt holds the target against any deployment. const CONTINUITY_RESTART_ATTEMPTS: usize = 3; +/// How long continuity waits after it could not prepare a restart (the +/// projection would not demote) before trying again. +const CONTINUITY_DEFERRAL_MILLIS: u64 = 30_000; + const DEFAULT_TOPOLOGY_MAXIMUM_AGE_MILLIS: u64 = 30_000; const DEFAULT_TOPOLOGY_MAXIMUM_FUTURE_SKEW_MILLIS: u64 = 2_000; @@ -2693,13 +2697,46 @@ fn read_transaction_record(envelope: &CultCacheEnvelope) -> Result { - let value = lift_legacy_transaction(envelope)?; + let mut value = lift_legacy_transaction(envelope)?; + owe_legacy_continuity_projection(&mut value); value.validate()?; Ok(value) } } } +/// A continuity abort written before the single resolution rule recorded no +/// projection cleanup although its transaction had issued an activation, and +/// so left that activation standing. The current rule owes the demotion, so a +/// resident record of that shape lifts to `Pending`: the one resolution then +/// demotes the transaction's own activation and cleans the residue too. +/// +/// A record already terminal under the old rule is reopened at Starting (a +/// pre-fencing failure is before Fencing by definition) with its completion +/// dropped, because a terminal record cannot owe work. Only the control +/// store's read applies this: history describes what happened and is lifted +/// unchanged. +fn owe_legacy_continuity_projection(transaction: &mut DeploymentTransaction) { + if transaction.command_kind != CommandKind::Continuity || transaction.activation.is_none() { + return; + } + if let Some(abort) = transaction.pre_fencing_abort.as_mut() + && abort.topology_reconciliation == CleanupEvidence::Skipped + { + abort.topology_reconciliation = CleanupEvidence::Pending; + if transaction.completion.take().is_some() { + transaction.phase = DeploymentPhase::Starting; + transaction.phase_deadline = None; + } + } + if let Some(abort) = transaction.post_fencing_abort.as_mut() + && abort.topology_reconciliation == CleanupEvidence::Skipped + && transaction.completion.is_none() + { + abort.topology_reconciliation = CleanupEvidence::Pending; + } +} + /// Read one stored admitted generation, lifting a v2 record to the current /// shape by the same rule as `read_transaction_record`. fn read_generation_record(envelope: &CultCacheEnvelope) -> Result { @@ -2867,41 +2904,92 @@ fn archive_terminal_transaction(state_store: &Path, envelope: &CultCacheEnvelope Ok(()) } -/// Finished transactions, read leniently and for display only. -/// -/// `control.cc` keeps the byte-exact canonical check because its records still -/// gate decisions. History describes what already happened, so an unreadable -/// entry here is skipped rather than allowed to refuse the read -- that -/// asymmetry is the whole reason the two files are separate. -fn read_history_transactions(state_store: &Path) -> Vec { +/// What `history.cc` yielded: the transactions it decoded and the entries it +/// could not, each with its key and reason. +struct HistoryRead { + transactions: Vec, + undecodable: Vec<(String, String)>, +} + +impl HistoryRead { + /// What is missing from `transactions`, or `None` when nothing is. + fn report(&self) -> Option { + if self.undecodable.is_empty() { + return None; + } + let keys = self + .undecodable + .iter() + .map(|(key, error)| format!("{key} ({error})")) + .collect::>() + .join("; "); + Some(format!( + "Idunn history: {} archived transaction(s) could not be decoded and are not counted \ + by status or continuity backoff: {keys}", + self.undecodable.len() + )) + } +} + +/// Finished transactions. `control.cc` keeps the byte-exact canonical check +/// because its records still gate decisions. History describes what already +/// happened, so an undecodable entry is reported and skipped rather than +/// allowed to refuse the read -- that asymmetry is the whole reason the two +/// files are separate. A file that cannot be read at all is an error: the +/// caller decides whether an empty answer is safe. +fn read_history(state_store: &Path) -> Result { let path = history_store_path(state_store); if !path.exists() { - return Vec::new(); + return Ok(HistoryRead { + transactions: Vec::new(), + undecodable: Vec::new(), + }); } - let envelopes = match SingleFileMessagePackBackingStore::new(&path).pull_all_read_only_snapshot() - { - Ok(envelopes) => envelopes, - Err(error) => { - eprintln!( - "Idunn cannot read {}: {error:#}; every archived transaction is invisible \ - to status and to continuity backoff", - path.display() - ); - return Vec::new(); - } - }; + let envelopes = SingleFileMessagePackBackingStore::new(&path) + .pull_all_read_only_snapshot() + .with_context(|| format!("Idunn cannot read {}", path.display()))?; let (transactions, undecodable) = decode_history_transactions(envelopes); - if !undecodable.is_empty() { - for (key, error) in &undecodable { - eprintln!("Idunn history holds an undecodable transaction {key}: {error}"); + Ok(HistoryRead { + transactions, + undecodable, + }) +} + +/// History for display only (status). An unreadable file shows as empty and +/// says so; decisions use `Engine::history_for_decision`, which does not. +fn read_history_transactions(state_store: &Path) -> Vec { + match read_history(state_store) { + Ok(history) => { + if let Some(report) = history.report() { + eprintln!("{report}"); + } + history.transactions + } + Err(error) => { + eprintln!("{error:#}; every archived transaction is invisible to status"); + Vec::new() } - eprintln!( - "Idunn history: {} archived transaction(s) could not be decoded and are not counted \ - by status or continuity backoff", - undecodable.len() - ); } - transactions +} + +/// Says a fault once while it lasts. A scheduler tick that hits the same +/// unreadable file every half second must not print it every half second. +#[derive(Default)] +struct ReportOnce { + last: Mutex>, +} + +impl ReportOnce { + /// The text to print now: `report` when it differs from the last one + /// offered, nothing while the same fault stands or once it has cleared. + fn offer(&self, report: Option) -> Option { + let mut last = self.last.lock().expect("report mutex"); + if *last == report { + return None; + } + last.clone_from(&report); + report + } } /// Decode every archived transaction. An entry that fails is returned with its @@ -3382,6 +3470,7 @@ struct Engine { docker_runner: DockerRunnerDriver, systemd_workload: Arc, host_actuators: Option, + history_report: ReportOnce, } impl Engine { @@ -3436,6 +3525,7 @@ impl Engine { docker_runner: DockerRunnerDriver::default(), systemd_workload, host_actuators, + history_report: ReportOnce::default(), }) } @@ -3512,6 +3602,27 @@ impl Engine { }) } + /// History for a decision that would be wrong on an empty answer: the + /// continuity restart ceiling and the check that a command is consumed. + /// `None` means `history.cc` cannot be read, so the decision is not made; + /// a history that merely has no entries is `Some`. The fault is printed + /// once while it lasts, not on every tick. + fn history_for_decision(&self) -> Option> { + let (report, transactions) = match read_history(&self.options.state_store) { + Ok(history) => (history.report(), Some(history.transactions)), + Err(error) => ( + Some(format!( + "{error:#}; continuity and command retirement stop until it is readable" + )), + None, + ), + }; + if let Some(text) = self.history_report.offer(report) { + eprintln!("{text}"); + } + transactions + } + fn topology(&self) -> CultCacheTopologyDriver { CultCacheTopologyDriver { projection_store: self.options.topology_store.clone(), @@ -3684,6 +3795,96 @@ impl Engine { } } +/// What the boot reconciliation of failed continuity projections found. +#[derive(Debug, Default, PartialEq, Eq)] +struct ProjectionReconciliation { + /// Failed continuity transactions whose exact activation was demoted. + demoted: Vec, + /// Targets whose projection names an activation that neither the admitted + /// generation, a live transaction, nor a failed issuer accounts for. They + /// are reported and left alone. + unexplained: Vec, +} + +impl Engine { + /// Once at boot: demote the activation a failed continuity left standing, + /// where the projection still names exactly the activation that failed + /// transaction issued. A continuity abort before the single resolution + /// rule left such residue (and the lift owes the same demotion to any + /// abort still resident). The issuer is identified by exact activation, + /// from history and from resident terminal records not yet retired to it. + /// + /// Nothing is adopted: an activation with no failed issuer is never + /// demoted or kept on anyone's behalf, only reported. + fn reconcile_failed_continuity_projections(&self) -> Result { + let snapshot = ControlSnapshot::read(&self.options.state_store)?; + let mut outcome = ProjectionReconciliation::default(); + let Some(history) = self.history_for_decision() else { + return Ok(outcome); + }; + let topology = self.topology(); + let issuers = history + .iter() + .chain(snapshot.transactions.iter().map(|stored| &stored.value)) + .filter(|transaction| { + transaction.command_kind == CommandKind::Continuity + && matches!( + transaction.completion, + Some(TransactionCompletion::FailedBeforeFencing { .. }) + | Some(TransactionCompletion::FailedAfterFencing { .. }) + ) + }); + for issuer in issuers { + let (Some(expected), Some(activation), Some(plan)) = + (&issuer.expected, &issuer.activation, &issuer.plan) + else { + continue; + }; + let demoted = (|| -> Result { + if topology.projected_activation(expected)?.as_ref() != Some(activation) { + return Ok(false); + } + let provider_anchor = self.provider_anchor_for_plan(plan)?; + topology.demote_to_expected_only(expected, &provider_anchor, activation, None)?; + Ok(true) + })(); + match demoted { + Ok(true) => outcome.demoted.push(issuer.transaction_id.clone()), + Ok(false) => {} + Err(error) => eprintln!( + "Idunn could not reconcile the projection of failed continuity {}: {error:#}", + issuer.transaction_id + ), + } + } + for generation in &snapshot.admitted { + let projected = match topology.projected_activation(&generation.value.expected) { + Ok(projected) => projected, + Err(error) => { + eprintln!( + "Idunn cannot read the projected activation of {}: {error:#}", + generation.value.target + ); + continue; + } + }; + let Some(projected) = projected else { + continue; + }; + let accounted = projected == generation.value.activation + || snapshot.transactions.iter().any(|stored| { + stored.value.target == generation.value.target + && !stored.value.is_terminal() + && stored.value.activation.as_ref() == Some(&projected) + }); + if !accounted { + outcome.unexplained.push(generation.value.target.clone()); + } + } + Ok(outcome) + } +} + fn serve(options: RuntimeOptions) -> Result<()> { for path in [ &options.state_store, @@ -3710,6 +3911,20 @@ fn serve(options: RuntimeOptions) -> Result<()> { ControlSnapshot::read(&options.state_store).context("validating all Idunn records")?; let engine = Engine::open(options)?; engine.validate_durable_authority(&ControlSnapshot::read(&engine.options.state_store)?)?; + match engine.reconcile_failed_continuity_projections() { + Ok(outcome) => { + for transaction_id in &outcome.demoted { + println!("demoted the activation failed continuity {transaction_id} left projected"); + } + for target in &outcome.unexplained { + eprintln!( + "Idunn found an activation projected for {target} that no admitted generation, \ + live transaction or failed continuity accounts for; left as it is" + ); + } + } + Err(error) => eprintln!("Idunn boot projection reconciliation failed: {error:#}"), + } loop { match engine.run_scheduler_tick() { @@ -3848,7 +4063,12 @@ impl Engine { // whose transactions were retired to history before commands travelled // with them are still resident; they are not queued, they are // history that never moved. Retire them here and never freeze them. - let historical_commands = read_history_transactions(&self.options.state_store) + // With history unreadable, whether a command was consumed is unknown: + // freezing it again could run a finished deployment twice. + let Some(history) = self.history_for_decision() else { + return Ok(false); + }; + let historical_commands = history .into_iter() .map(|transaction| transaction.command_id) .collect::>(); @@ -4165,12 +4385,17 @@ impl Engine { | Some(TransactionCompletion::FailedAfterFencing { .. }) ) }; + // An unreadable history counts as zero refusals only by lying: + // the ceiling would never trip. Without it, nothing is actuated. + let Some(history) = self.history_for_decision() else { + continue; + }; let refused_restarts = snapshot .transactions .iter() .filter(|stored| is_refused_restart(&stored.value)) .count() - + read_history_transactions(&self.options.state_store) + + history .iter() .filter(|transaction| is_refused_restart(transaction)) .count(); @@ -4218,6 +4443,17 @@ impl Engine { // Demote to Expected-only, the same shape an aborted deployment // leaves, and let the restart publish its own activation once it is // observed. + let now = now_millis()?; + // A restart whose projection could not be prepared is deferred in + // the generation's own backoff, not retried every tick. + if current + .value + .continuity_backoff + .next_restart_at_unix_millis + .is_some_and(|not_before| now < not_before) + { + continue; + } let demotion = (|| -> Result<()> { let topology = self.topology(); let provider_anchor = self.provider_anchor_for_plan(¤t.value.plan)?; @@ -4232,13 +4468,21 @@ impl Engine { )?; Ok(()) })(); + // Expected-only is the precondition of a restart: a continuity + // minted over a projection that still names an activation would + // fail between preparing and publishing its own, and its abort + // could not resolve. So a failed demotion mints nothing. The + // failure is written to the generation, and the next attempt is + // not before the deferral ends. if let Err(error) = demotion { eprintln!( - "Idunn preserved admitted {} after refusing to demote its projection: {error:#}", + "Idunn deferred continuity for admitted {} after refusing to demote its projection: {error:#}", current.value.target ); + self.defer_continuity_restart(current, now)?; + progressed = true; + continue; } - let now = now_millis()?; // An engaged lifecycle brake means no continuity transaction is // minted at all. A transaction that exists and waits on the brake // owns the target, and a target owned by a parked restart accepts @@ -4286,6 +4530,29 @@ impl Engine { Ok(progressed) } + /// Record that continuity may not restart this generation before + /// `now + CONTINUITY_DEFERRAL_MILLIS`. The generation's `ContinuityBackoff` + /// owns "not before": only its `next_restart_at_unix_millis` is written, + /// so the attempts and window that count real restarts are untouched. + fn defer_continuity_restart(&self, current: &Stored, now: u64) -> Result<()> { + let mut next = current.value.clone(); + next.continuity_backoff.next_restart_at_unix_millis = + Some(now + CONTINUITY_DEFERRAL_MILLIS); + next.validate()?; + ensure!( + SingleFileMessagePackBackingStore::new(&self.options.state_store).compare_exchange( + &[CultCacheExpectedEnvelope { + r#type: AdmittedGeneration::TYPE.into(), + key: current.value.target.clone(), + current: Some(current.envelope.clone()), + }], + &[admitted_envelope(&next, now)?], + )?, + "admitted generation changed before continuity deferral CAS" + ); + Ok(()) + } + fn supervise_admitted_route(&self, current: &Stored) -> Result { let Some(expected_route) = current.value.expected.route.as_ref() else { ensure!( @@ -9541,25 +9808,107 @@ mod tests { } } - /// A Continuity transaction for an unrouted, stateless target, sitting at - /// `phase` (Warming or later) with every earlier phase's evidence in place. The plan, sealed - /// release, Expected, activation and Warming evidence are the real - /// constructions; only the workload and isolation observations are - /// borrowed from a recorded transaction. Continuity is chosen because a - /// Deploy would need a frozen source and a signed brake record, which no - /// phase past Fencing reads. + /// A Continuity transaction for an unrouted, stateless target with no + /// incumbent: the shape most Engine tests need. fn transaction_at( world: &EngineFixture, phase: DeploymentPhase, + ) -> Result { + seeded_transaction(world, phase, CommandKind::Continuity, None) + } + + /// The Odin publisher sequence a transaction seeded over `incumbent` + /// warms at; its Ready is the next one. Above anything an earlier + /// generation of the world admitted. + fn seeded_sequence(incumbent: Option<&AdmittedGeneration>) -> u64 { + if incumbent.is_some() { 14 } else { 4 } + } + + /// A released deployment brake receipt, signed by an operator identity + /// enrolled in the world: what a Deploy's `deployment_authorization` holds. + fn deployment_authorization( + world: &EngineFixture, + expected: &IdunnExpectedIncarnationRecord, + transaction_id: &str, + now: u64, + ) -> Result { + use cultnet_rs::{ + IDUNN_DEPLOYMENT_BRAKE_AUTHORITY, IDUNN_DEPLOYMENT_BRAKE_ID, + IDUNN_DEPLOYMENT_BRAKE_SCOPE, IDUNN_DEPLOYMENT_RELEASE_PURPOSE, + IdunnDeploymentBrakeReleasePurpose, enroll_service_identity_at, + }; + let signer = enroll_service_identity_at::( + &world.root.join("identities/brake-operator.cc"), + )?; + export_service_identity_trust_anchor(&signer, &world.root.join("brake-anchor.cc"))?; + let mut record = IdunnDeploymentBrakeRecord { + schema_version: IDUNN_DEPLOYMENT_BRAKE_SCHEMA.into(), + brake_id: IDUNN_DEPLOYMENT_BRAKE_ID.into(), + authority: IDUNN_DEPLOYMENT_BRAKE_AUTHORITY.into(), + runtime_id: expected.runtime_id.clone(), + status: "released".into(), + scope: IDUNN_DEPLOYMENT_BRAKE_SCOPE.into(), + reason: "test rollout".into(), + observed_at_unix_millis: now, + expires_at_unix_millis: Some(now + 600_000), + authorization_id: Some("authorization-test".into()), + authorization_purpose: Some(IDUNN_DEPLOYMENT_RELEASE_PURPOSE.into()), + authorized_release_id: Some(expected.sealed_release_id.clone()), + authorized_deployment_id: Some(transaction_id.to_owned()), + authorized_by: Some(signer.trust_anchor()?.identity_id), + authorization_issued_at_unix_millis: Some(now), + authorization_expires_at_unix_millis: Some(now + 600_000), + signature_algorithm: Some("ed25519".into()), + signature: None, + private_state_exposed: false, + updated_by: "operator/test".into(), + }; + record.signature = Some( + signer + .sign::(&rmp_serde::to_vec(&record)?) + .signature, + ); + record.validate()?; + let canonical_brake_bytes = rmp_serde::to_vec(&record)?; + Ok(DeploymentAuthorization { + authorization_id: "authorization-test".into(), + brake_sha256: sha256_id(&canonical_brake_bytes), + canonical_brake_bytes, + authorized_at_unix_millis: now, + }) + } + + /// A transaction for an unrouted, stateless target, sitting at `phase` + /// (Warming or later) with every earlier phase's evidence in place. The + /// plan, sealed release, Expected, activation and Warming evidence are the + /// real constructions; only the workload and isolation observations are + /// borrowed from a recorded transaction. + /// + /// `incumbent` is an admitted generation already in the world's store. A + /// Continuity over it restarts that generation's own release, so it shares + /// the incumbent's Expected key. A Deploy over it builds a second + /// incarnation. A Deploy carries what phases past Fencing never read but + /// validation requires: a three-field frozen-source receipt and a + /// well-formed release receipt from the brake. + fn seeded_transaction( + world: &EngineFixture, + phase: DeploymentPhase, + kind: CommandKind, + incumbent: Option<&AdmittedGeneration>, ) -> Result { use crate::deployment_plan::tests::{ BINDING, RECIPE, artifact_receipt, external_input_receipt, source, }; - let provider = enroll_service_identity_at::( - &world.root.join("identities/provider.cc"), - )?; + let provider_path = world.root.join("identities/provider.cc"); let provider_anchor = world.root.join("identities/provider-anchor.cc"); - export_service_identity_trust_anchor(&provider, &provider_anchor)?; + let provider = if provider_path.exists() { + open_service_identity_at::(&provider_path)? + } else { + let provider = + enroll_service_identity_at::(&provider_path)?; + export_service_identity_trust_anchor(&provider, &provider_anchor)?; + provider + }; let (binding_head, binding_tail) = BINDING .split_once("[route]") @@ -9585,34 +9934,60 @@ mod tests { r#"["GAMECULT_IDUNN_CANDIDATE_BIND", "GAMECULT_IDUNN_RUNTIME_BUNDLE"]"#, r#"["GAMECULT_IDUNN_RUNTIME_BUNDLE"]"#, ); - let plan = compile_deployment_plan( - recipe.as_bytes(), - binding.as_bytes(), - source(&recipe), - "service-incarnation-1", - None, - 110, - &[], - )?; - let release = SealedRelease::new( - &plan, - vec![artifact_receipt()], - vec![external_input_receipt()], - 120, - )?; + let (plan, release) = match (kind, incumbent) { + (CommandKind::Continuity, Some(incumbent)) => ( + incumbent.plan.clone(), + incumbent.sealed_release.clone(), + ), + _ => { + let incarnation = if incumbent.is_some() { + "service-incarnation-2" + } else { + "service-incarnation-1" + }; + let plan = compile_deployment_plan( + recipe.as_bytes(), + binding.as_bytes(), + source(&recipe), + incarnation, + None, + 110, + &[], + )?; + let release = SealedRelease::new( + &plan, + vec![artifact_receipt()], + vec![external_input_receipt()], + 120, + )?; + (plan, release) + } + }; let expected = release.expected_projection(&plan)?; assert!(!expected.write_lease_required && expected.route.is_none()); let now = now_millis()?; let command = DeploymentCommand { schema_version: DEPLOYMENT_COMMAND_SCHEMA.into(), - command_id: "continuity-service".into(), - kind: CommandKind::Continuity, + command_id: format!( + "{}-service{}", + match kind { + CommandKind::Deploy => "up", + CommandKind::Continuity => "continuity", + }, + if incumbent.is_some() { "-again" } else { "" } + ), + kind, selector: "service".into(), requested_by: "test".into(), requested_at_unix_millis: 100, }; - let mut transaction = DeploymentTransaction::new(&command, "service".into(), 0, None, now)?; + let mut transaction = match (kind, incumbent) { + (CommandKind::Continuity, Some(incumbent)) => { + DeploymentTransaction::from_continuity(&command, incumbent, now)? + } + _ => DeploymentTransaction::new(&command, "service".into(), 0, incumbent, now)?, + }; let activation = IdunnRuntimeActivationLaunch::issue( &expected, runtime_instance_id(&transaction.transaction_id)?, @@ -9625,12 +10000,30 @@ mod tests { .1 .workload .context("recorded transaction has no workload")?; - transaction.lifecycle_authorized_at_unix_millis = Some(now); + match kind { + CommandKind::Continuity => { + transaction.lifecycle_authorized_at_unix_millis = Some(now); + } + CommandKind::Deploy => { + transaction.frozen_source = Some(FrozenSourceReceipt { + transaction_id: transaction.transaction_id.clone(), + plan_id: plan.plan_id.clone(), + snapshot_sha256: sha256_id(b"frozen source snapshot"), + }); + transaction.deployment_authorization = Some(deployment_authorization( + world, + &expected, + &transaction.transaction_id, + now, + )?); + } + } transaction.expected_publication_sha256 = Some(expected.canonical_sha256()?); transaction.activation_publication_sha256 = Some(activation.canonical_sha256()?); match &mut workload { WorkloadObservation::Systemd(observed) => { observed.runtime_instance_id = activation.runtime_instance_id.clone(); + observed.executable_sha256 = expected.artifact_sha256.clone(); } WorkloadObservation::Host(_) => bail!("recorded workload is not a systemd unit"), } @@ -9646,7 +10039,8 @@ mod tests { transaction.workload = Some(workload); transaction.plan = Some(plan); // Odin's first word about the candidate, before it was Ready. - let warming = signed_correlation(world, &transaction, 4, false)?; + let sequence = seeded_sequence(incumbent); + let warming = signed_correlation(world, &transaction, sequence, false)?; let authenticated = world.engine.authenticate_topology_bytes( &ControlSnapshot::read(&world.state_store)?, &transaction, @@ -9657,7 +10051,7 @@ mod tests { transaction.warming = Some(WarmingEvidence::OdinTopology { evidence: TopologyEvidence::from_authenticated(&authenticated, now)?, }); - transaction.odin_publisher_sequence_cursor = 4; + transaction.odin_publisher_sequence_cursor = sequence; transaction.enter_phase(phase, now); transaction.validate()?; @@ -10564,4 +10958,922 @@ mod tests { assert_eq!(std::fs::read(&world.topology.projection_store)?, before); Ok(()) } + + // --------------------------------------------------------------------- + // B1 fix batch: the transition, the precondition, the boot reconciliation, + // history that fails closed, and the abort paths through the Engine. + // --------------------------------------------------------------------- + + /// A workload port whose process can be killed: observing it succeeds + /// until `kill`, then fails the way a dead unit does. Everything else is + /// `StillWorkload`'s. + struct SwitchWorkload { + alive: std::sync::atomic::AtomicBool, + } + + impl SwitchWorkload { + fn new() -> Arc { + Arc::new(Self { + alive: std::sync::atomic::AtomicBool::new(true), + }) + } + + fn kill(&self) { + self.alive + .store(false, std::sync::atomic::Ordering::SeqCst); + } + } + + impl WorkloadPort for SwitchWorkload { + fn install( + &self, + plan: &CompiledDeploymentPlan, + release: &crate::drivers::MaterializedRelease, + ) -> Result { + StillWorkload.install(plan, release) + } + fn prepare_activation( + &self, + plan: &CompiledDeploymentPlan, + expected: &IdunnExpectedIncarnationRecord, + launch: IdunnRuntimeActivationLaunch, + ) -> Result { + StillWorkload.prepare_activation(plan, expected, launch) + } + fn start_prepared( + &self, + plan: &CompiledDeploymentPlan, + release: &SealedRelease, + installed: &crate::drivers::InstalledReleaseObservation, + expected: &IdunnExpectedIncarnationRecord, + activation: &IdunnRuntimeActivationRecord, + ) -> Result { + StillWorkload.start_prepared(plan, release, installed, expected, activation) + } + fn discard_prepared( + &self, + _: &CompiledDeploymentPlan, + _: &IdunnExpectedIncarnationRecord, + _: &IdunnRuntimeActivationRecord, + ) -> Result<()> { + Ok(()) + } + fn observe( + &self, + _: &IdunnExpectedIncarnationRecord, + _: &IdunnRuntimeActivationRecord, + prior: &WorkloadObservation, + ) -> Result { + ensure!( + self.alive.load(std::sync::atomic::Ordering::SeqCst), + "the workload is gone" + ); + Ok(prior.clone()) + } + fn stop(&self, _: &WorkloadObservation) -> Result<()> { + Ok(()) + } + fn is_permanently_stopped(&self, _: &WorkloadObservation) -> Result { + Ok(false) + } + } + + /// Admit a generation for "service" through the real phase machine and + /// retire its transaction, leaving the world with an incumbent. + fn admit_incumbent(world: &EngineFixture) -> Result { + let seeded = transaction_at(world, DeploymentPhase::Fencing)?; + odin_reports_ready(world, &seeded, seeded_sequence(None) + 1)?; + drive(world, |transaction| { + transaction.phase == DeploymentPhase::Complete + })?; + assert!(world.engine.retire_one_terminal_transaction()?); + Ok(ControlSnapshot::read(&world.state_store)? + .admitted_for("service") + .context("commit wrote no admitted generation")? + .value + .clone()) + } + + /// Change the incumbent in the store, compare-and-swap. + fn edit_incumbent( + world: &EngineFixture, + edit: impl FnOnce(&mut AdmittedGeneration), + ) -> Result { + let snapshot = ControlSnapshot::read(&world.state_store)?; + let stored = snapshot + .admitted_for("service") + .context("no admitted generation")?; + let mut next = stored.value.clone(); + edit(&mut next); + assert!( + SingleFileMessagePackBackingStore::new(&world.state_store).compare_exchange( + &[CultCacheExpectedEnvelope { + r#type: AdmittedGeneration::TYPE.into(), + key: "service".into(), + current: Some(stored.envelope.clone()), + }], + &[admitted_envelope(&next, now_millis()?)?], + )? + ); + Ok(next) + } + + fn incumbent_envelope(world: &EngineFixture) -> Result { + Ok(ControlSnapshot::read(&world.state_store)? + .admitted_for("service") + .context("no admitted generation")? + .envelope + .clone()) + } + + /// Publish what a transaction's candidate projects: its Expected and, + /// when asked, its observed activation. + fn project_candidate( + world: &EngineFixture, + transaction: &DeploymentTransaction, + with_activation: bool, + ) -> Result<()> { + let expected = transaction.expected.as_ref().context("no Expected")?; + let anchor = world + .engine + .provider_anchor_for_plan(transaction.plan.as_ref().context("no plan")?)?; + let topology = world.engine.topology(); + topology.publish_expected(expected, &anchor)?; + if with_activation { + // The observation must name the release the Expected declares; + // the borrowed workload is patched to. + let mut workload = transaction.workload.clone().context("no workload")?; + if let WorkloadObservation::Systemd(observed) = &mut workload { + observed.executable_sha256 = expected.artifact_sha256.clone(); + } + topology.publish_observed_activation( + expected, + transaction.activation.as_ref().context("no activation")?, + &workload, + )?; + } + Ok(()) + } + + /// Publish what an admitted generation projects while it runs. + fn project_admitted(world: &EngineFixture, generation: &AdmittedGeneration) -> Result<()> { + let anchor = world.engine.provider_anchor_for_plan(&generation.plan)?; + let topology = world.engine.topology(); + topology.publish_expected(&generation.expected, &anchor)?; + topology.publish_observed_activation( + &generation.expected, + &generation.activation, + &generation.workload, + )?; + Ok(()) + } + + /// The types of the records projected under one incarnation key, sorted. + fn projected_under( + world: &EngineFixture, + expected: &IdunnExpectedIncarnationRecord, + ) -> Result> { + let path = &world.engine.options.topology_store; + if !path.exists() { + return Ok(Vec::new()); + } + let key = incarnation_key(expected)?; + let mut types = SingleFileMessagePackBackingStore::new(path) + .pull_all_read_only_snapshot()? + .into_iter() + .filter(|entry| entry.key == key) + .map(|entry| entry.r#type) + .collect::>(); + types.sort(); + Ok(types) + } + + /// One transaction by id, wherever it now lives. A failed transaction is + /// archived the moment it finishes, so it is in history, not resident. + fn record_of(world: &EngineFixture, transaction_id: &str) -> Result { + if let Some(stored) = ControlSnapshot::read(&world.state_store)? + .transactions + .into_iter() + .find(|stored| stored.value.transaction_id == transaction_id) + { + return Ok(stored.value); + } + read_history_transactions(&world.state_store) + .into_iter() + .find(|transaction| transaction.transaction_id == transaction_id) + .context("the transaction is in neither the live set nor history") + } + + fn expected_only() -> Vec { + vec![IdunnExpectedIncarnationRecord::TYPE.to_owned()] + } + + // ---- the Engine's abort paths, Deploy and incumbent ---- + + #[test] + fn a_deploy_that_fences_commits_and_retires_the_incumbent_it_replaced() -> Result<()> { + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + admit_incumbent(&world)?; + let backoff = ContinuityBackoff { + window_started_at_unix_millis: Some(1_000), + attempts: 2, + next_restart_at_unix_millis: Some(9_000), + }; + let incumbent = edit_incumbent(&world, |generation| { + generation.continuity_backoff = backoff.clone(); + })?; + + let candidate = seeded_transaction( + &world, + DeploymentPhase::Fencing, + CommandKind::Deploy, + Some(&incumbent), + )?; + odin_reports_ready(&world, &candidate, seeded_sequence(Some(&incumbent)) + 1)?; + drive(&world, |transaction| { + transaction.phase == DeploymentPhase::Complete + })?; + + let admitted = ControlSnapshot::read(&world.state_store)? + .admitted_for("service") + .context("the deploy admitted nothing")? + .value + .clone(); + assert_eq!(admitted.transaction_id, candidate.transaction_id); + assert_ne!(admitted.generation_id, incumbent.generation_id); + // The restart ceiling belongs to the target: a commit must not reset it. + assert_eq!(admitted.continuity_backoff, backoff); + assert_eq!(admitted.route_supervision, incumbent.route_supervision); + + // The commit did not stop the incumbent: it is retired after. + let committed = record_of(&world, &candidate.transaction_id)?; + let cleanup = committed.post_commit_cleanup.clone().context("no cleanup")?; + assert_eq!( + cleanup.incumbent, + IncumbentCleanupEvidence::Pending { + generation_id: incumbent.generation_id.clone(), + workload: incumbent.workload.clone(), + } + ); + assert_eq!(cleanup.source, SourceCleanupEvidence::Pending); + let frozen = world + .engine + .options + .staging_root + .join("frozen-sources") + .join(&candidate.transaction_id); + std::fs::create_dir_all(&frozen)?; + std::fs::write(frozen.join("tree"), b"frozen")?; + + drive(&world, |transaction| transaction.is_terminal())?; + let retired = record_of(&world, &candidate.transaction_id)? + .post_commit_cleanup + .context("no cleanup")?; + assert_eq!( + retired.incumbent, + IncumbentCleanupEvidence::Complete { + generation_id: incumbent.generation_id + } + ); + assert_eq!(retired.source, SourceCleanupEvidence::Complete); + assert!(!frozen.exists(), "the frozen source outlived its deploy"); + Ok(()) + } + + #[test] + fn a_deploy_post_fence_abort_cleans_up_and_restores_its_incumbent_exactly() -> Result<()> { + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + let incumbent = admit_incumbent(&world)?; + project_admitted(&world, &incumbent)?; + let candidate = seeded_transaction( + &world, + DeploymentPhase::Fencing, + CommandKind::Deploy, + Some(&incumbent), + )?; + project_candidate(&world, &candidate, true)?; + let candidate_expected = candidate.expected.clone().context("no Expected")?; + assert_eq!( + projected_under(&world, &candidate_expected)?.len(), + 2, + "the candidate did not project" + ); + let frozen = world + .engine + .options + .staging_root + .join("frozen-sources") + .join(&candidate.transaction_id); + std::fs::create_dir_all(&frozen)?; + std::fs::write(frozen.join("tree"), b"frozen")?; + let before = incumbent_envelope(&world)?; + + world + .engine + .begin_post_fencing_abort(&resident(&world)?, anyhow!("candidate refused"))?; + assert!(resident(&world)?.value.post_fencing_abort.is_some()); + drive(&world, |transaction| transaction.completion.is_some())?; + + let finished = record_of(&world, &candidate.transaction_id)?; + assert!(matches!( + finished.completion, + Some(TransactionCompletion::FailedAfterFencing { + recovery: TerminalRecovery::RestoreIncumbent, + .. + }) + )); + let abort = finished.post_fencing_abort.context("no abort evidence")?; + assert_eq!(abort.topology_reconciliation, CleanupEvidence::Complete); + assert_eq!(abort.source_cleanup, CleanupEvidence::Complete); + assert!(!frozen.exists(), "the abandoned source was not cleaned"); + assert!( + projected_under(&world, &candidate_expected)?.is_empty(), + "the abandoned candidate is still projected" + ); + // Fencing stopped the incumbent: it stands as Expected-only, with the + // exact activation it ran under withdrawn, ready for continuity. + assert_eq!(projected_under(&world, &incumbent.expected)?, expected_only()); + assert_eq!(incumbent_envelope(&world)?, before); + Ok(()) + } + + #[test] + fn a_deploy_pre_fence_abort_cleans_up_and_leaves_its_incumbent_running() -> Result<()> { + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + let incumbent = admit_incumbent(&world)?; + project_admitted(&world, &incumbent)?; + let candidate = seeded_transaction( + &world, + DeploymentPhase::Warming, + CommandKind::Deploy, + Some(&incumbent), + )?; + project_candidate(&world, &candidate, true)?; + let candidate_expected = candidate.expected.clone().context("no Expected")?; + let frozen = world + .engine + .options + .staging_root + .join("frozen-sources") + .join(&candidate.transaction_id); + std::fs::create_dir_all(&frozen)?; + std::fs::write(frozen.join("tree"), b"frozen")?; + let before = incumbent_envelope(&world)?; + + world + .engine + .begin_pre_fencing_abort(&resident(&world)?, anyhow!("candidate refused"))?; + let intent = resident(&world)?.value.pre_fencing_abort.context("no intent")?; + assert_eq!(intent.topology_reconciliation, CleanupEvidence::Pending); + assert_eq!(intent.source_cleanup, CleanupEvidence::Pending); + drive(&world, |transaction| transaction.completion.is_some())?; + + let finished = record_of(&world, &candidate.transaction_id)?; + assert!(matches!( + finished.completion, + Some(TransactionCompletion::FailedBeforeFencing { .. }) + )); + assert!(finished.is_terminal()); + assert!(!frozen.exists(), "the abandoned source was not cleaned"); + assert!(projected_under(&world, &candidate_expected)?.is_empty()); + // Before fencing a deployment never touched its incumbent. + assert_eq!( + projected_under(&world, &incumbent.expected)?, + { + let mut types = vec![ + IdunnExpectedIncarnationRecord::TYPE.to_owned(), + IdunnRuntimeActivationRecord::TYPE.to_owned(), + ]; + types.sort(); + types + } + ); + assert_eq!(incumbent_envelope(&world)?, before); + Ok(()) + } + + #[test] + fn a_continuity_abort_over_its_incumbent_demotes_only_the_activation_it_issued() -> Result<()> { + for post_fence in [false, true] { + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + let incumbent = admit_incumbent(&world)?; + let candidate = seeded_transaction( + &world, + if post_fence { + DeploymentPhase::Fencing + } else { + DeploymentPhase::Warming + }, + CommandKind::Continuity, + Some(&incumbent), + )?; + // The candidate shares the incumbent's key: same Expected, its own + // activation. + assert_eq!(candidate.expected.as_ref(), Some(&incumbent.expected)); + assert_ne!(candidate.activation.as_ref(), Some(&incumbent.activation)); + project_candidate(&world, &candidate, true)?; + let before = incumbent_envelope(&world)?; + + let stored = resident(&world)?; + if post_fence { + world + .engine + .begin_post_fencing_abort(&stored, anyhow!("candidate died"))?; + assert_eq!( + resident(&world)? + .value + .post_fencing_abort + .context("no intent")? + .topology_reconciliation, + CleanupEvidence::Pending + ); + } else { + world + .engine + .begin_pre_fencing_abort(&stored, anyhow!("candidate died"))?; + assert_eq!( + resident(&world)? + .value + .pre_fencing_abort + .context("no intent")? + .topology_reconciliation, + CleanupEvidence::Pending + ); + } + drive(&world, |transaction| transaction.completion.is_some())?; + + assert_eq!( + projected_under(&world, &incumbent.expected)?, + expected_only(), + "post_fence={post_fence}: the shared key must keep its Expected and nothing else" + ); + let finished = record_of(&world, &candidate.transaction_id)?; + assert!(finished.is_terminal()); + assert!(matches!( + finished.completion, + Some( + TransactionCompletion::FailedBeforeFencing { .. } + | TransactionCompletion::FailedAfterFencing { .. } + ) + )); + assert_eq!(incumbent_envelope(&world)?, before); + } + Ok(()) + } + + // ---- fix 1: the legacy lift owns the transition ---- + + const FIXTURE_PRE_B1_ABORTS: [(&str, &str); 3] = [ + ( + "pre-fence abort in flight", + include_str!("../tests/fixtures/idunn-control-legacy/transaction-pre-fence-abort.hex"), + ), + ( + "pre-fence abort already terminal", + include_str!( + "../tests/fixtures/idunn-control-legacy/transaction-pre-fence-abort-terminal.hex" + ), + ), + ( + "post-fence abort in flight", + include_str!("../tests/fixtures/idunn-control-legacy/transaction-post-fence-abort.hex"), + ), + ]; + const FIXTURE_PROVIDER_ANCHOR: &str = + include_str!("../tests/fixtures/idunn-control-legacy/provider-anchor.hex"); + /// Where the fixtures' plan binding names the provider trust anchor. + const FIXTURE_ANCHOR_PATH: &str = "/tmp/idunn-b1-legacy/provider-anchor.cc"; + + fn hex_bytes(text: &str) -> Vec { + let hex = text.trim(); + (0..hex.len()) + .step_by(2) + .map(|index| u8::from_str_radix(&hex[index..index + 2], 16).expect("hex fixture")) + .collect() + } + + fn write_fixture_anchor() -> Result<()> { + let path = Path::new(FIXTURE_ANCHOR_PATH); + std::fs::create_dir_all(path.parent().context("anchor path has no parent")?)?; + std::fs::write(path, hex_bytes(FIXTURE_PROVIDER_ANCHOR))?; + Ok(()) + } + + #[test] + fn a_pre_b1_continuity_abort_lifts_owing_its_own_activation_and_resolves_it() -> Result<()> { + write_fixture_anchor()?; + for (name, text) in FIXTURE_PRE_B1_ABORTS { + let envelope = fixture_envelope(text, DeploymentTransaction::TYPE)?; + + // The record is what the old rule wrote: an activation was issued + // and the abort says it owes the projection nothing. + let legacy: LegacyDeploymentTransaction = rmp_serde::from_slice(&envelope.payload)?; + assert_eq!(legacy.command_kind, CommandKind::Continuity, "{name}"); + assert!(legacy.activation.is_some(), "{name}"); + let owed = legacy + .pre_fencing_abort + .as_ref() + .map(|abort| abort.topology_reconciliation) + .or_else(|| { + legacy + .post_fencing_abort + .as_ref() + .map(|abort| abort.topology_reconciliation) + }) + .context("no abort")?; + assert_eq!(owed, CleanupEvidence::Skipped, "{name}"); + + // History describes what happened, so it lifts the record as written. + let archived = lift_legacy_transaction(&envelope)?; + let archived_owed = archived + .pre_fencing_abort + .as_ref() + .map(|abort| abort.topology_reconciliation) + .or_else(|| { + archived + .post_fencing_abort + .as_ref() + .map(|abort| abort.topology_reconciliation) + }) + .context("no abort")?; + assert_eq!(archived_owed, CleanupEvidence::Skipped, "{name}"); + + // The control store lifts it owing the demotion, and validates. + let lifted = read_transaction_record(&envelope)?; + let lifted_owed = lifted + .pre_fencing_abort + .as_ref() + .map(|abort| abort.topology_reconciliation) + .or_else(|| { + lifted + .post_fencing_abort + .as_ref() + .map(|abort| abort.topology_reconciliation) + }) + .context("no abort")?; + assert_eq!(lifted_owed, CleanupEvidence::Pending, "{name}"); + assert!(!lifted.is_terminal(), "{name}: a record that owes work is terminal"); + assert_eq!(lifted.completion, None, "{name}"); + + // Boot: the store reads, and the abort resolves. + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + let command = DeploymentCommand { + schema_version: DEPLOYMENT_COMMAND_SCHEMA.into(), + command_id: lifted.command_id.clone(), + kind: CommandKind::Continuity, + selector: "service".into(), + requested_by: "test".into(), + requested_at_unix_millis: 100, + }; + assert!( + SingleFileMessagePackBackingStore::new(&world.state_store).compare_exchange( + &[ + CultCacheExpectedEnvelope { + r#type: DeploymentCommand::TYPE.into(), + key: command.command_id.clone(), + current: None, + }, + CultCacheExpectedEnvelope { + r#type: DeploymentTransaction::TYPE.into(), + key: envelope.key.clone(), + current: None, + }, + ], + &[command_envelope(&command, 100)?, envelope.clone()], + )?, + "{name}" + ); + assert_eq!(migrate_control_store_to_current_schema(&world.state_store)?, 1); + let snapshot = ControlSnapshot::read(&world.state_store)?; + assert_eq!(snapshot.transactions.len(), 1, "{name}"); + project_candidate(&world, &lifted, true)?; + let expected = lifted.expected.clone().context("no Expected")?; + assert_eq!(projected_under(&world, &expected)?.len(), 2, "{name}"); + + for _ in 0..12 { + let Ok(current) = resident(&world) else { break }; + if current.value.completion.is_some() { + break; + } + world.engine.advance_transaction(¤t)?; + } + let finished = record_of(&world, &envelope.key)?; + assert!(finished.completion.is_some(), "{name}: the abort never resolved"); + assert_eq!( + projected_under(&world, &expected)?, + expected_only(), + "{name}: the projection was not demoted to Expected-only" + ); + } + Ok(()) + } + + // ---- fix 2: supervision owns the Expected-only precondition ---- + + #[test] + fn continuity_mints_no_restart_over_a_projection_it_cannot_demote() -> Result<()> { + let workload = SwitchWorkload::new(); + let world = EngineFixture::with_workload(workload.clone())?; + let incumbent = admit_incumbent(&world)?; + assert_eq!(incumbent.continuity_backoff, ContinuityBackoff::default()); + + // The projection names an activation that is not the incumbent's. + let anchor = world.engine.provider_anchor_for_plan(&incumbent.plan)?; + let topology = world.engine.topology(); + topology.publish_expected(&incumbent.expected, &anchor)?; + let stranger = seeded_transaction( + &world, + DeploymentPhase::Warming, + CommandKind::Continuity, + Some(&incumbent), + )?; + topology.publish_observed_activation( + &incumbent.expected, + stranger.activation.as_ref().context("no activation")?, + stranger.workload.as_ref().context("no workload")?, + )?; + // Remove the seeded stranger transaction: only the projection matters. + let seeded = resident(&world)?; + assert!( + SingleFileMessagePackBackingStore::new(&world.state_store).delete_batch_if_unchanged( + &[ + seeded.envelope.clone(), + ControlSnapshot::read(&world.state_store)? + .commands + .into_iter() + .find(|stored| stored.value.command_id == seeded.value.command_id) + .context("seeded command")? + .envelope, + ] + )? + ); + workload.kill(); + + let before = now_millis()?; + assert!(world.engine.supervise_one_admitted_generation()?); + let snapshot = ControlSnapshot::read(&world.state_store)?; + assert!( + snapshot.transactions.is_empty(), + "continuity minted a restart over a projection it could not demote" + ); + let deferred = snapshot + .admitted_for("service") + .context("no generation")? + .value + .continuity_backoff + .next_restart_at_unix_millis + .context("the failed demotion was not recorded")?; + assert!(deferred >= before + CONTINUITY_DEFERRAL_MILLIS); + + // Deferred: the next tick neither retries nor writes. + let envelope = incumbent_envelope(&world)?; + assert!(!world.engine.supervise_one_admitted_generation()?); + assert_eq!(incumbent_envelope(&world)?, envelope); + assert!(ControlSnapshot::read(&world.state_store)?.transactions.is_empty()); + + // The projection is repaired and the deferral has run out: the restart + // proceeds, from an Expected-only projection. + topology.withdraw_stale_incarnation(&incumbent.expected, &anchor)?; + project_admitted(&world, &incumbent)?; + edit_incumbent(&world, |generation| { + generation.continuity_backoff.next_restart_at_unix_millis = Some(1); + })?; + assert!(world.engine.supervise_one_admitted_generation()?); + let snapshot = ControlSnapshot::read(&world.state_store)?; + assert_eq!(snapshot.transactions.len(), 1); + assert_eq!(snapshot.transactions[0].value.command_kind, CommandKind::Continuity); + assert_eq!(projected_under(&world, &incumbent.expected)?, expected_only()); + Ok(()) + } + + // ---- fix 3: one-time boot reconciliation, by exact issuer ---- + + #[test] + fn boot_demotes_the_activation_a_failed_continuity_left_and_only_that() -> Result<()> { + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + let incumbent = admit_incumbent(&world)?; + let failed = seeded_transaction( + &world, + DeploymentPhase::Warming, + CommandKind::Continuity, + Some(&incumbent), + )?; + project_candidate(&world, &failed, true)?; + world + .engine + .begin_pre_fencing_abort(&resident(&world)?, anyhow!("candidate died"))?; + drive(&world, |transaction| transaction.completion.is_some())?; + // A failed transaction is archived the moment it finishes. + let aborted = record_of(&world, &failed.transaction_id)?; + assert!(aborted.is_terminal()); + assert!(ControlSnapshot::read(&world.state_store)?.transactions.is_empty()); + assert_eq!(projected_under(&world, &incumbent.expected)?, expected_only()); + + // Drift a pre-B1 abort left: the failed candidate's activation stands. + project_candidate(&world, &failed, true)?; + assert_eq!(projected_under(&world, &incumbent.expected)?.len(), 2); + + let outcome = world.engine.reconcile_failed_continuity_projections()?; + assert_eq!( + outcome, + ProjectionReconciliation { + demoted: vec![failed.transaction_id.clone()], + unexplained: Vec::new(), + } + ); + assert_eq!(projected_under(&world, &incumbent.expected)?, expected_only()); + + // Once: nothing is left to demote. + assert_eq!( + world.engine.reconcile_failed_continuity_projections()?, + ProjectionReconciliation::default() + ); + Ok(()) + } + + #[test] + fn boot_never_adopts_an_activation_no_failed_transaction_issued() -> Result<()> { + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + let incumbent = admit_incumbent(&world)?; + + // The incumbent's own activation is accounted for. + project_admitted(&world, &incumbent)?; + assert_eq!( + world.engine.reconcile_failed_continuity_projections()?, + ProjectionReconciliation::default() + ); + + // Some other activation, issued by nothing in history, is reported and + // left exactly as it is. + let stranger = seeded_transaction( + &world, + DeploymentPhase::Warming, + CommandKind::Continuity, + Some(&incumbent), + )?; + let anchor = world.engine.provider_anchor_for_plan(&incumbent.plan)?; + let topology = world.engine.topology(); + topology.withdraw_stale_incarnation(&incumbent.expected, &anchor)?; + project_candidate(&world, &stranger, true)?; + // A live transaction accounts for its own activation... + assert_eq!( + world.engine.reconcile_failed_continuity_projections()?, + ProjectionReconciliation::default() + ); + // ...and once it is gone, nothing does. + let seeded = resident(&world)?; + let command = ControlSnapshot::read(&world.state_store)? + .commands + .into_iter() + .find(|stored| stored.value.command_id == seeded.value.command_id) + .context("seeded command")?; + assert!( + SingleFileMessagePackBackingStore::new(&world.state_store) + .delete_batch_if_unchanged(&[seeded.envelope.clone(), command.envelope])? + ); + let projection = std::fs::read(&world.engine.options.topology_store)?; + let outcome = world.engine.reconcile_failed_continuity_projections()?; + assert_eq!( + outcome, + ProjectionReconciliation { + demoted: Vec::new(), + unexplained: vec!["service".into()], + } + ); + assert_eq!(std::fs::read(&world.engine.options.topology_store)?, projection); + Ok(()) + } + + // ---- fix 4: history that cannot be read stops actuation ---- + + /// An operator binding for the target "service", so the command queue can + /// resolve selectors. + fn write_service_binding(world: &EngineFixture) -> Result<()> { + use crate::deployment_plan::tests::BINDING; + let (head, tail) = BINDING + .split_once("[route]") + .context("binding has no route table")?; + let binding = format!( + "{head}[brakes]{}", + tail.split_once("[brakes]") + .context("binding has no brakes table")? + .1 + ); + std::fs::create_dir_all(&world.engine.options.bindings_dir)?; + std::fs::write(world.engine.options.bindings_dir.join("service.toml"), binding)?; + Ok(()) + } + + fn corrupt_history(world: &EngineFixture) -> Result<()> { + std::fs::write(history_store_path(&world.state_store), b"\xc1\xc1 torn")?; + Ok(()) + } + + #[test] + fn history_that_cannot_be_read_is_an_error_and_missing_history_is_empty() -> Result<()> { + let world = EngineFixture::new()?; + let history = read_history(&world.state_store)?; + assert!(history.transactions.is_empty() && history.report().is_none()); + + corrupt_history(&world)?; + let error = read_history(&world.state_store).err().context("torn history read")?; + assert!(format!("{error:#}").contains("history"), "{error:#}"); + assert!(world.engine.history_for_decision().is_none()); + // The display path still answers, with nothing. + assert!(read_history_transactions(&world.state_store).is_empty()); + Ok(()) + } + + #[test] + fn undecodable_history_names_what_it_is_missing() -> Result<()> { + let (finished, _) = terminal_transaction_with_command("ghostlight")?; + let good = transaction_envelope(&finished, finished.updated_at_unix_millis)?; + let mut torn = good.clone(); + torn.key = "tx-torn".into(); + torn.payload = vec![0xc1]; + let (transactions, undecodable) = decode_history_transactions(vec![good, torn]); + let history = HistoryRead { + transactions, + undecodable, + }; + let report = history.report().context("nothing reported")?; + assert!(report.contains("1 archived transaction"), "{report}"); + assert!(report.contains("tx-torn"), "{report}"); + + let complete = HistoryRead { + transactions: history.transactions, + undecodable: Vec::new(), + }; + assert_eq!(complete.report(), None); + Ok(()) + } + + #[test] + fn a_fault_is_said_once_while_it_lasts() { + let once = ReportOnce::default(); + assert_eq!(once.offer(None), None); + assert_eq!(once.offer(Some("torn".into())), Some("torn".into())); + assert_eq!(once.offer(Some("torn".into())), None); + assert_eq!(once.offer(Some("torn".into())), None); + assert_eq!(once.offer(Some("worse".into())), Some("worse".into())); + assert_eq!(once.offer(None), None); + assert_eq!(once.offer(Some("worse".into())), Some("worse".into())); + } + + #[test] + fn unreadable_history_stops_continuity_instead_of_counting_no_failures() -> Result<()> { + let workload = SwitchWorkload::new(); + let world = EngineFixture::with_workload(workload.clone())?; + admit_incumbent(&world)?; + workload.kill(); + corrupt_history(&world)?; + let envelope = incumbent_envelope(&world)?; + + // A dead workload would be restarted at once, with the ceiling counting + // zero refusals. With history unreadable nothing is actuated. + assert!(!world.engine.supervise_one_admitted_generation()?); + assert!(ControlSnapshot::read(&world.state_store)?.transactions.is_empty()); + assert_eq!(incumbent_envelope(&world)?, envelope); + + // Readable again, the same tick restarts it. + std::fs::remove_file(history_store_path(&world.state_store))?; + assert!(world.engine.supervise_one_admitted_generation()?); + assert_eq!(ControlSnapshot::read(&world.state_store)?.transactions.len(), 1); + Ok(()) + } + + #[test] + fn unreadable_history_stops_command_retirement_and_freezing() -> Result<()> { + let world = EngineFixture::new()?; + let command = DeploymentCommand { + schema_version: DEPLOYMENT_COMMAND_SCHEMA.into(), + command_id: "up-nowhere".into(), + kind: CommandKind::Deploy, + selector: "nowhere".into(), + requested_by: "test".into(), + requested_at_unix_millis: 100, + }; + assert!( + SingleFileMessagePackBackingStore::new(&world.state_store).compare_exchange( + &[CultCacheExpectedEnvelope { + r#type: DeploymentCommand::TYPE.into(), + key: command.command_id.clone(), + current: None, + }], + &[command_envelope(&command, 100)?], + )? + ); + write_service_binding(&world)?; + corrupt_history(&world)?; + + // Whether the command was consumed is unknown, so it is not acted on. + assert!(!world.engine.freeze_one_queued_command()?); + assert!(ControlSnapshot::read(&world.state_store)?.transactions.is_empty()); + + // Readable, it is acted on: the unknown selector is refused. + std::fs::remove_file(history_store_path(&world.state_store))?; + assert!(world.engine.freeze_one_queued_command()?); + assert_eq!(ControlSnapshot::read(&world.state_store)?.transactions.len(), 1); + Ok(()) + } } diff --git a/src/drivers.rs b/src/drivers.rs index 226906f..d56e3d9 100644 --- a/src/drivers.rs +++ b/src/drivers.rs @@ -4488,6 +4488,22 @@ impl CultCacheTopologyDriver { ) } + /// The activation the projection currently names under this incarnation's + /// key, if any. Read-only: it never judges whether the activation is the + /// right one, so a caller can tell an exact issuer from a substitute + /// before it demotes anything. + pub fn projected_activation( + &self, + expected: &IdunnExpectedIncarnationRecord, + ) -> Result> { + let key = incarnation_key(expected)?; + let entries = self.snapshot()?; + projection_entry(&entries, IdunnRuntimeActivationRecord::TYPE, &key)? + .map(|envelope| IdunnRuntimeActivationRecord::decode_canonical(&envelope.payload)) + .transpose() + .map_err(Into::into) + } + /// Every incarnation currently projected for one target, by its Expected. pub fn projected_incarnations( &self, diff --git a/tests/fixtures/idunn-control-legacy/README.md b/tests/fixtures/idunn-control-legacy/README.md index 07086d7..d1b00ec 100644 --- a/tests/fixtures/idunn-control-legacy/README.md +++ b/tests/fixtures/idunn-control-legacy/README.md @@ -22,3 +22,23 @@ the plan is the `deployment_plan` test recipe. No byte comes from a live store. `control_plane.rs` decodes these through `LegacyDeploymentTransaction` and `LegacyAdmittedGeneration`. The fixtures die with those structs. + +## Pre-B1 continuity aborts + +The `transaction-*-abort*` files and `provider-anchor` were printed by a second +throwaway test over `9001b58`. It built a continuity transaction that issued an +activation (the recipe and binding of the `deployment_plan` tests, a provider +identity enrolled fresh, the trust-anchor path in the binding fixed at +`/tmp/idunn-b1-legacy/provider-anchor.cc`) and gave it the aborts the base code +writes: the pre-fence abort literal of `begin_pre_fencing_abort`, and the base +`post_fencing_abort_intent`. In each, the transaction issued an activation and +its abort records `topology_reconciliation = Skipped`, because the base rule +owed a continuity no projection cleanup. The workload and Odin evidence are +borrowed from `transaction-fencing`. + +| File | What it is | +|---|---| +| `transaction-pre-fence-abort` | Warming continuity, pre-fencing abort in flight | +| `transaction-pre-fence-abort-terminal` | the same abort finished: Complete, `FailedBeforeFencing` | +| `transaction-post-fence-abort` | Fencing continuity, post-fencing abort in flight | +| `provider-anchor` | one line: the provider trust-anchor file bytes, hex. A test writes it to the fixed path so the Engine can read the plan's anchor | diff --git a/tests/fixtures/idunn-control-legacy/provider-anchor.hex b/tests/fixtures/idunn-control-legacy/provider-anchor.hex new file mode 100644 index 0000000..928d4cf --- /dev/null +++ b/tests/fixtures/idunn-control-legacy/provider-anchor.hex @@ -0,0 +1 @@ +93b263756c7463616368652e73746f72652e76319197d93167616d6563756c742e70726f76696465725f6865616c74685f6964656e746974792e74727573745f616e63686f722e7631d93167616d6563756c742e70726f76696465725f6865616c74685f6964656e746974792e74727573745f616e63686f722e7631d93467616d6563756c742e70726f76696465725f6865616c74685f6964656e746974792e74727573745f616e63686f722e76312e7631d93167616d6563756c742e70726f76696465725f6865616c74685f6964656e746974792e74727573745f616e63686f722e7631d9967b22736368656d614e616d65223a2267616d6563756c742e70726f76696465725f6865616c74685f6964656e746974792e74727573745f616e63686f722e7631222c22736368656d6156657273696f6e223a2267616d6563756c742e70726f76696465725f6865616c74685f6964656e746974792e74727573745f616e63686f722e76312e7631222c226d656d62657273223a5b5d7d91d93167616d6563756c742e70726f76696465725f6865616c74685f6964656e746974792e74727573745f616e63686f722e7631909194d92867616d6563756c742d70726f76696465722d6865616c74682d6964656e746974792d7075626c6963d93167616d6563756c742e70726f76696465725f6865616c74685f6964656e746974792e74727573745f616e63686f722e7631d923323032362d30392d32395430333a34353a31352e3031353232313330302b30303a3030c5014596d93167616d6563756c742e70726f76696465725f6865616c74685f6964656e746974792e74727573745f616e63686f722e7631d94031626661653932326138626630313132373562353536623236393135303363386366643538313234383931373134323365373736663133386463313235376337dc00205858cca9ccbb7dccb9cc8d01cccfccfccc9153ccdbcce23c224bcca757617dcce5cc8a163a6516cc9dccee2c2acce9d92d6f735f696e7374616c6c6174696f6e5f66696c655f626f756e645f636c6f6e6561626c655f626173656c696e65d923323032362d30392d32395430333a34353a31352e3031353232313330302b30303a3030d9477368613235362d63663933623766656534396235313133343736366538613937623432303065653636396338353164386464336634353366623537666664326233366630653430 diff --git a/tests/fixtures/idunn-control-legacy/transaction-post-fence-abort.hex b/tests/fixtures/idunn-control-legacy/transaction-post-fence-abort.hex new file mode 100644 index 0000000..37cd704 --- /dev/null +++ b/tests/fixtures/idunn-control-legacy/transaction-post-fence-abort.hex @@ -0,0 +1,2 @@ +idunn.deployment_transaction.v3 +dc0023bf6964756e6e2e6465706c6f796d656e745f7472616e73616374696f6e2e7633d92774782d39356138313166662d303533332d343562622d613031352d303038356132353835633061b2636f6e74696e756974792d73657276696365aa636f6e74696e75697479a77365727669636500a766656e63696e67cf0000018bcfe56800cf0000018bcfe56800c099d9216964756e6e2e636f6d70696c65645f6465706c6f796d656e745f706c616e2e7632d9477368613235362d38626532306364633335373930316463373365316162623262336365666633373835343661323962343161353535656131643633653530366562333762376330b5736572766963652d696e6361726e6174696f6e2d316e9bbf6964756e6e2e736f757263655f73656c656374696f6e5f66616374732e7631d92768747470733a2f2f6769746875622e636f6d2f47616d6543756c742f536572766963652e676974af726566732f68656164732f6d61696ed92832323232323232323232323232323232323232323232323232323232323232323232323232323232d92832323232323232323232323232323232323232323232323232323232323232323232323232323232d92833333333333333333333333333333333333333333333333333333333333333333333333333333333bc6465706c6f796d656e742f6964756e6e2f7265636970652e746f6d6cd9477368613235362d323739336466633034633331313961373962353037363965613637356538633030613938366665623331393939306631623031636364363833343563363732618091a87265662d6865616464dc04e20a736368656d61203d202267616d6563756c742e6964756e6e2e7461726765745f6465636c61726174696f6e2e7631220a746172676574203d202273657276696365220a736f757263655f7374616d705f656e7669726f6e6d656e74203d2022534552564943455f4255494c445f434f4d4d4954220a0a5b5b73746570735d5d0a6964203d20226275696c64220a7068617365203d20226275696c64220a72756e6e6572203d202272757374220a61726776203d205b22636172676f222c20226275696c64222c20222d2d6c6f636b6564225d0a0a5b5b65787465726e616c5f696e707574735d5d0a6964203d2022746f6f6c636861696e2d696e646578220a75726c203d202268747470733a2f2f6578616d706c652e696e76616c69642f746f6f6c636861696e2d696e646578220a736861323536203d202264646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464220a72756e6e6572203d202272757374220a64657374696e6174696f6e203d2022696e707574732f746f6f6c636861696e2d696e646578220a0a5b5b6172746966616374735d5d0a6964203d20226461656d6f6e220a736f757263655f6b696e64203d202272756e6e65722d6f7574707574220a72756e6e6572203d202272757374220a736f75726365203d20227461726765742f72656c656173652f73657276696365220a64657374696e6174696f6e203d202273657276696365220a65787065637465645f736861323536203d202263636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363220a65786563757461626c65203d20747275650a0a5b736572766963655d0a65786563757461626c655f6172746966616374203d20226461656d6f6e220a617267756d656e7473203d205b0a20207b206b696e64203d202262696e64696e67222c206e616d65203d202273746174655f726f6f7422207d2c0a5d0a7472616e73706f7274203d202268747470220a726f7574655f7265717569726564203d2066616c73650a72657175697265645f656e7669726f6e6d656e74203d205b2247414d4543554c545f4944554e4e5f52554e54494d455f42554e444c45225d0a0a5b736572766963652e6865616c74685d0a636f6e7472616374203d2022736572766963652e6865616c7468220a0a5b73746174655d0a736368656d615f67656e65726174696f6e203d20227631220a0a5b5b73746174652e736c6f74735d5d0a6964203d202272756e74696d652d6361636865220a72656c61746976655f70617468203d202272756e74696d652d63616368652e6363220a6b696e64203d202263756c7463616368652d66696c65220a736368656d61203d2022736572766963652e72756e74696d652d63616368652e7631220a777269746572203d20226e6f6e65220a7265636f76657279203d202272656275696c6461626c65220a73746172747570203d20226f70656e2d61742d7374617274220a0a5b5b70726f76696465735d5d0a6361706162696c697479203d2022736572766963652e72756e74696d65220a736368656d61203d2022736572766963652e72756e74696d652e7631220a636f6d7061746962696c697479203d20227631220a0adc06930a736368656d61203d202267616d6563756c742e6964756e6e2e6f70657261746f725f62696e64696e672e7632220a746172676574203d202273657276696365220a0a5b7265706f7369746f72795d0a6f726967696e203d202268747470733a2f2f6769746875622e636f6d2f47616d6543756c742f536572766963652e676974220a61646d69747465645f726566203d2022726566732f68656164732f6d61696e220a6d696e696d756d5f7265766973696f6e203d202231313131313131313131313131313131313131313131313131313131313131313131313131313131220a73656c656374696f6e203d20227265662d68656164220a636865636b6f7574203d20222f7372762f6275696c642f53657276696365220a7265636970655f70617468203d20226465706c6f796d656e742f6964756e6e2f7265636970652e746f6d6c220a0a5b72756e6e6572732e727573745d0a647269766572203d2022646f636b6572220a696d616765203d202272757374407368613235363a61616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161220a75736572203d2022313030303a31303030220a6166666f7264616e636573203d205b22736f757263652d72656164222c202261727469666163742d7772697465225d0a616c6c6f7765645f70726f6772616d73203d205b22636172676f225d0a6e6574776f726b5f70726f66696c65203d20226275696c642d646570656e64656e63792d656772657373220a6d656d6f72795f6d6562696279746573203d20323034380a6370755f71756f74615f70657263656e74203d203230300a706964735f6c696d6974203d203531320a746d7066735f6d6562696279746573203d203531320a0a5b776f726b6c6f61645d0a647269766572203d202273797374656d642d7472616e7369656e74220a73746174655f67726f7570203d202273657276696365220a756e69745f707265666978203d20226964756e6e2d73657276696365220a72656c656173655f726f6f74203d20222f7372762f736572766963652f72656c6561736573220a73746174655f726f6f74203d20222f7661722f6c69622f67616d6563756c742f73657276696365220a72756e74696d655f726f6f74203d20222f72756e2f67616d6563756c742f6964756e6e2f73657276696365220a6e6574776f726b203d2022686f73742d70726976617465220a68617264656e696e67203d2022737472696374220a6d656d6f72795f6d6562696279746573203d20313032340a6370755f71756f74615f70657263656e74203d203130300a0a5b776f726b6c6f61642e617267756d656e745f62696e64696e67735d0a73746174655f726f6f74203d20222f7661722f6c69622f67616d6563756c742f73657276696365220a0a5b776f726b6c6f61642e7365637265745f66696c65735d0a47414d4543554c545f52554e54494d455f50524553454e43455f4944454e54495459203d20222f6574632f67616d6563756c742f736572766963652f72756e74696d652d70726573656e63652d6964656e746974792e6363220a0a5b72756e74696d655f6964656e746974795d0a72756e74696d655f6964203d2022736572766963652d79676764726173696c220a65787065637465645f7369676e65725f6964656e746974795f6964203d202231626661653932326138626630313132373562353536623236393135303363386366643538313234383931373134323365373736663133386463313235376337220a74727573745f616e63686f725f73746f7265203d20222f746d702f6964756e6e2d62312d6c65676163792f70726f76696465722d616e63686f722e6363220a0a5b6272616b65735d0a6465706c6f796d656e745f73746f7265203d20222f7661722f6c69622f67616d6563756c742f6964756e6e2f736572766963652d6465706c6f796d656e742d6272616b652e6363220a6c6966656379636c655f73746f7265203d20222f7661722f6c69622f67616d6563756c742f6964756e6e2f736572766963652d6c6966656379636c652d6272616b652e6363220a0a5b726f6c6c6f75745d0a7374726174656779203d202263616e6469646174652d7468656e2d70726f6d6f7465220a647261696e5f7365636f6e6473203d2033300a72657461696e5f72656c6561736573203d20320a0a5b706c6163656d656e745d0a646573697265645f7265706c69636173203d20310a6e6f646573203d205b2279676764726173696c225d0a90c0c096b76964756e6e2e7365616c65645f72656c656173652e7631d9477368613235362d39366633373231386438333663646364303037393631343233333032353334333362316666633766323538633135353037656536376163323961643665663662d9477368613235362d386265323063646333353739303164633733653161626232623363656666333738353436613239623431613535356561316436336535303665623337623763309195a66461656d6f6ea773657276696365d9477368613235362d636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363632ac39196af746f6f6c636861696e2d696e646578d92768747470733a2f2f6578616d706c652e696e76616c69642f746f6f6c636861696e2d696e646578d9477368613235362d64646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464a472757374b6696e707574732f746f6f6c636861696e2d696e646578117892d9477368613235362d39366633373231386438333663646364303037393631343233333032353334333362316666633766323538633135353037656536376163323961643665663662ba2f7372762f736572766963652f72656c65617365732f74657374dc0012bd6964756e6e2e65787065637465645f696e6361726e6174696f6e2e7632a773657276696365d9477368613235362d38626532306364633335373930316463373365316162623262336365666633373835343661323962343161353535656131643633653530366562333762376330b5736572766963652d696e6361726e6174696f6e2d31d9477368613235362d39366633373231386438333663646364303037393631343233333032353334333362316666633766323538633135353037656536376163323961643665663662bb6769746875622e636f6d2f47616d6543756c742f53657276696365d92832323232323232323232323232323232323232323232323232323232323232323232323232323232d9477368613235362d32373933646663303463333131396137396235303736396561363735653863303061393836666562333139393930663162303163636436383334356336373261b1736572766963652d79676764726173696cd94031626661653932326138626630313132373562353536623236393135303363386366643538313234383931373134323365373736663133386463313235376337ae736572766963652e6865616c7468d9477368613235362d63636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363a27631d9477368613235362d32663837303134316366353638316566656332653234316364636435663731303831616539326162316535633534633839636438393666386335656236323731c2c09194af736572766963652e72756e74696d65b2736572766963652e72756e74696d652e7631a276310190d9477368613235362d33336163613963353639636165373831643936396632313864633036613035313134613863666239333436313634633033613263336435343033613636323666c0cf0000018bcfe568009abb6964756e6e2e72756e74696d655f61637469766174696f6e2e7632d9477368613235362d33336163613963353639636165373831643936396632313864633036613035313134613863666239333436313634633033613263336435343033613636323666b1736572766963652d79676764726173696cd9477368613235362d66353962643235306336333830383661643330396235333539373636663232326266353033366333336230616633316239633935333130353831366636396137d94066313063623131353633346366613935383966356564616332313730343339363933353834343234643736653133366434396661613236373539323266376665c420f2977384801339144d13ebd2ab001bf29fbab79f7c3948334d440db8206cf974cf0000018bcfe56800d94063653461663030623963626662316362613963363136363965323337303232323465343763623163303761346233313431626634353237383236353965646637a765643235353139c4403a548c511ff3de6fcac116b903fa6badb14deef79dd81958d71947af575fae753b11692d0272c7cb5c437300cdd0d5315e28a1e7e12f9df0a0b817951bba4700dc0033b26964756e6e2d343234322e73657276696365af4964756e6e20746573742034323432af696e766f636174696f6e2d3432343201a465786563a6616c77617973ad636f6e74726f6c2d67726f7570c3a57534323432a57534323432a0a0a0c3c3a9696e76697369626c65a3706964c3a430303737a0a0cd10920194cd1092cd1092cd1092cd109294cd1092cd1092cd1092cd109291cd10920000000000c391010807b52f6f70742f746573742f62696e2f736572766963650101d9477368613235362d34626635313232663334343535346335336264653265626238636432623765336431363030616436333163333835613564376363653233633737383534353961d9477368613235362d66353962643235306336333830383661643330396235333539373636663232326266353033366333336230616633316239633935333130353831366636396137a92f6f70742f74657374a92f72756e2f74657374d9477368613235362d6462633162346339303066666534386435373562356461356336333830343031323566363564623066653365323434393462373665613938363435376439383690d9477368613235362d30383466656430386239373861663464376431393661373434366138366235383030396536333662363131646231363231316236356139616164666632396335d9202f73797374656d2e736c6963652f6964756e6e2d343234322e73657276696365c090aa61637469766174696f6edc0020010101010101010101010101010101010101010101010101010101010101010190d9477368613235362d32393364343764383932393938373139346131303664303236326236326563363766633534393165366339633366653961326663383132643935633237376661c092ad6f64696e2d746f706f6c6f6779959139d9477368613235362d31393538316532376465376365643030666631636535306232303437653761353637633736623163626165626162653565663033663763333031376262356237ab6f64696e2d7369676e65722764c096cd10920708c0c0c091b1736b69707065642d73746174656c657373c0c0c029c0c0c0c096b163616e6469646174652072656675736564a7736b6970706564a7736b6970706564a770656e64696e67a7736b6970706564a7736b6970706564 diff --git a/tests/fixtures/idunn-control-legacy/transaction-pre-fence-abort-terminal.hex b/tests/fixtures/idunn-control-legacy/transaction-pre-fence-abort-terminal.hex new file mode 100644 index 0000000..29011d9 --- /dev/null +++ b/tests/fixtures/idunn-control-legacy/transaction-pre-fence-abort-terminal.hex @@ -0,0 +1,2 @@ +idunn.deployment_transaction.v3 +dc0023bf6964756e6e2e6465706c6f796d656e745f7472616e73616374696f6e2e7633d92774782d39356138313166662d303533332d343562622d613031352d303038356132353835633061b2636f6e74696e756974792d73657276696365aa636f6e74696e75697479a77365727669636500a8636f6d706c657465cf0000018bcfe56800cf0000018bcfe56800c099d9216964756e6e2e636f6d70696c65645f6465706c6f796d656e745f706c616e2e7632d9477368613235362d38626532306364633335373930316463373365316162623262336365666633373835343661323962343161353535656131643633653530366562333762376330b5736572766963652d696e6361726e6174696f6e2d316e9bbf6964756e6e2e736f757263655f73656c656374696f6e5f66616374732e7631d92768747470733a2f2f6769746875622e636f6d2f47616d6543756c742f536572766963652e676974af726566732f68656164732f6d61696ed92832323232323232323232323232323232323232323232323232323232323232323232323232323232d92832323232323232323232323232323232323232323232323232323232323232323232323232323232d92833333333333333333333333333333333333333333333333333333333333333333333333333333333bc6465706c6f796d656e742f6964756e6e2f7265636970652e746f6d6cd9477368613235362d323739336466633034633331313961373962353037363965613637356538633030613938366665623331393939306631623031636364363833343563363732618091a87265662d6865616464dc04e20a736368656d61203d202267616d6563756c742e6964756e6e2e7461726765745f6465636c61726174696f6e2e7631220a746172676574203d202273657276696365220a736f757263655f7374616d705f656e7669726f6e6d656e74203d2022534552564943455f4255494c445f434f4d4d4954220a0a5b5b73746570735d5d0a6964203d20226275696c64220a7068617365203d20226275696c64220a72756e6e6572203d202272757374220a61726776203d205b22636172676f222c20226275696c64222c20222d2d6c6f636b6564225d0a0a5b5b65787465726e616c5f696e707574735d5d0a6964203d2022746f6f6c636861696e2d696e646578220a75726c203d202268747470733a2f2f6578616d706c652e696e76616c69642f746f6f6c636861696e2d696e646578220a736861323536203d202264646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464220a72756e6e6572203d202272757374220a64657374696e6174696f6e203d2022696e707574732f746f6f6c636861696e2d696e646578220a0a5b5b6172746966616374735d5d0a6964203d20226461656d6f6e220a736f757263655f6b696e64203d202272756e6e65722d6f7574707574220a72756e6e6572203d202272757374220a736f75726365203d20227461726765742f72656c656173652f73657276696365220a64657374696e6174696f6e203d202273657276696365220a65787065637465645f736861323536203d202263636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363220a65786563757461626c65203d20747275650a0a5b736572766963655d0a65786563757461626c655f6172746966616374203d20226461656d6f6e220a617267756d656e7473203d205b0a20207b206b696e64203d202262696e64696e67222c206e616d65203d202273746174655f726f6f7422207d2c0a5d0a7472616e73706f7274203d202268747470220a726f7574655f7265717569726564203d2066616c73650a72657175697265645f656e7669726f6e6d656e74203d205b2247414d4543554c545f4944554e4e5f52554e54494d455f42554e444c45225d0a0a5b736572766963652e6865616c74685d0a636f6e7472616374203d2022736572766963652e6865616c7468220a0a5b73746174655d0a736368656d615f67656e65726174696f6e203d20227631220a0a5b5b73746174652e736c6f74735d5d0a6964203d202272756e74696d652d6361636865220a72656c61746976655f70617468203d202272756e74696d652d63616368652e6363220a6b696e64203d202263756c7463616368652d66696c65220a736368656d61203d2022736572766963652e72756e74696d652d63616368652e7631220a777269746572203d20226e6f6e65220a7265636f76657279203d202272656275696c6461626c65220a73746172747570203d20226f70656e2d61742d7374617274220a0a5b5b70726f76696465735d5d0a6361706162696c697479203d2022736572766963652e72756e74696d65220a736368656d61203d2022736572766963652e72756e74696d652e7631220a636f6d7061746962696c697479203d20227631220a0adc06930a736368656d61203d202267616d6563756c742e6964756e6e2e6f70657261746f725f62696e64696e672e7632220a746172676574203d202273657276696365220a0a5b7265706f7369746f72795d0a6f726967696e203d202268747470733a2f2f6769746875622e636f6d2f47616d6543756c742f536572766963652e676974220a61646d69747465645f726566203d2022726566732f68656164732f6d61696e220a6d696e696d756d5f7265766973696f6e203d202231313131313131313131313131313131313131313131313131313131313131313131313131313131220a73656c656374696f6e203d20227265662d68656164220a636865636b6f7574203d20222f7372762f6275696c642f53657276696365220a7265636970655f70617468203d20226465706c6f796d656e742f6964756e6e2f7265636970652e746f6d6c220a0a5b72756e6e6572732e727573745d0a647269766572203d2022646f636b6572220a696d616765203d202272757374407368613235363a61616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161220a75736572203d2022313030303a31303030220a6166666f7264616e636573203d205b22736f757263652d72656164222c202261727469666163742d7772697465225d0a616c6c6f7765645f70726f6772616d73203d205b22636172676f225d0a6e6574776f726b5f70726f66696c65203d20226275696c642d646570656e64656e63792d656772657373220a6d656d6f72795f6d6562696279746573203d20323034380a6370755f71756f74615f70657263656e74203d203230300a706964735f6c696d6974203d203531320a746d7066735f6d6562696279746573203d203531320a0a5b776f726b6c6f61645d0a647269766572203d202273797374656d642d7472616e7369656e74220a73746174655f67726f7570203d202273657276696365220a756e69745f707265666978203d20226964756e6e2d73657276696365220a72656c656173655f726f6f74203d20222f7372762f736572766963652f72656c6561736573220a73746174655f726f6f74203d20222f7661722f6c69622f67616d6563756c742f73657276696365220a72756e74696d655f726f6f74203d20222f72756e2f67616d6563756c742f6964756e6e2f73657276696365220a6e6574776f726b203d2022686f73742d70726976617465220a68617264656e696e67203d2022737472696374220a6d656d6f72795f6d6562696279746573203d20313032340a6370755f71756f74615f70657263656e74203d203130300a0a5b776f726b6c6f61642e617267756d656e745f62696e64696e67735d0a73746174655f726f6f74203d20222f7661722f6c69622f67616d6563756c742f73657276696365220a0a5b776f726b6c6f61642e7365637265745f66696c65735d0a47414d4543554c545f52554e54494d455f50524553454e43455f4944454e54495459203d20222f6574632f67616d6563756c742f736572766963652f72756e74696d652d70726573656e63652d6964656e746974792e6363220a0a5b72756e74696d655f6964656e746974795d0a72756e74696d655f6964203d2022736572766963652d79676764726173696c220a65787065637465645f7369676e65725f6964656e746974795f6964203d202231626661653932326138626630313132373562353536623236393135303363386366643538313234383931373134323365373736663133386463313235376337220a74727573745f616e63686f725f73746f7265203d20222f746d702f6964756e6e2d62312d6c65676163792f70726f76696465722d616e63686f722e6363220a0a5b6272616b65735d0a6465706c6f796d656e745f73746f7265203d20222f7661722f6c69622f67616d6563756c742f6964756e6e2f736572766963652d6465706c6f796d656e742d6272616b652e6363220a6c6966656379636c655f73746f7265203d20222f7661722f6c69622f67616d6563756c742f6964756e6e2f736572766963652d6c6966656379636c652d6272616b652e6363220a0a5b726f6c6c6f75745d0a7374726174656779203d202263616e6469646174652d7468656e2d70726f6d6f7465220a647261696e5f7365636f6e6473203d2033300a72657461696e5f72656c6561736573203d20320a0a5b706c6163656d656e745d0a646573697265645f7265706c69636173203d20310a6e6f646573203d205b2279676764726173696c225d0a90c0c096b76964756e6e2e7365616c65645f72656c656173652e7631d9477368613235362d39366633373231386438333663646364303037393631343233333032353334333362316666633766323538633135353037656536376163323961643665663662d9477368613235362d386265323063646333353739303164633733653161626232623363656666333738353436613239623431613535356561316436336535303665623337623763309195a66461656d6f6ea773657276696365d9477368613235362d636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363632ac39196af746f6f6c636861696e2d696e646578d92768747470733a2f2f6578616d706c652e696e76616c69642f746f6f6c636861696e2d696e646578d9477368613235362d64646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464a472757374b6696e707574732f746f6f6c636861696e2d696e646578117892d9477368613235362d39366633373231386438333663646364303037393631343233333032353334333362316666633766323538633135353037656536376163323961643665663662ba2f7372762f736572766963652f72656c65617365732f74657374dc0012bd6964756e6e2e65787065637465645f696e6361726e6174696f6e2e7632a773657276696365d9477368613235362d38626532306364633335373930316463373365316162623262336365666633373835343661323962343161353535656131643633653530366562333762376330b5736572766963652d696e6361726e6174696f6e2d31d9477368613235362d39366633373231386438333663646364303037393631343233333032353334333362316666633766323538633135353037656536376163323961643665663662bb6769746875622e636f6d2f47616d6543756c742f53657276696365d92832323232323232323232323232323232323232323232323232323232323232323232323232323232d9477368613235362d32373933646663303463333131396137396235303736396561363735653863303061393836666562333139393930663162303163636436383334356336373261b1736572766963652d79676764726173696cd94031626661653932326138626630313132373562353536623236393135303363386366643538313234383931373134323365373736663133386463313235376337ae736572766963652e6865616c7468d9477368613235362d63636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363a27631d9477368613235362d32663837303134316366353638316566656332653234316364636435663731303831616539326162316535633534633839636438393666386335656236323731c2c09194af736572766963652e72756e74696d65b2736572766963652e72756e74696d652e7631a276310190d9477368613235362d33336163613963353639636165373831643936396632313864633036613035313134613863666239333436313634633033613263336435343033613636323666c0cf0000018bcfe568009abb6964756e6e2e72756e74696d655f61637469766174696f6e2e7632d9477368613235362d33336163613963353639636165373831643936396632313864633036613035313134613863666239333436313634633033613263336435343033613636323666b1736572766963652d79676764726173696cd9477368613235362d66353962643235306336333830383661643330396235333539373636663232326266353033366333336230616633316239633935333130353831366636396137d94066313063623131353633346366613935383966356564616332313730343339363933353834343234643736653133366434396661613236373539323266376665c420f2977384801339144d13ebd2ab001bf29fbab79f7c3948334d440db8206cf974cf0000018bcfe56800d94063653461663030623963626662316362613963363136363965323337303232323465343763623163303761346233313431626634353237383236353965646637a765643235353139c4403a548c511ff3de6fcac116b903fa6badb14deef79dd81958d71947af575fae753b11692d0272c7cb5c437300cdd0d5315e28a1e7e12f9df0a0b817951bba4700dc0033b26964756e6e2d343234322e73657276696365af4964756e6e20746573742034323432af696e766f636174696f6e2d3432343201a465786563a6616c77617973ad636f6e74726f6c2d67726f7570c3a57534323432a57534323432a0a0a0c3c3a9696e76697369626c65a3706964c3a430303737a0a0cd10920194cd1092cd1092cd1092cd109294cd1092cd1092cd1092cd109291cd10920000000000c391010807b52f6f70742f746573742f62696e2f736572766963650101d9477368613235362d34626635313232663334343535346335336264653265626238636432623765336431363030616436333163333835613564376363653233633737383534353961d9477368613235362d66353962643235306336333830383661643330396235333539373636663232326266353033366333336230616633316239633935333130353831366636396137a92f6f70742f74657374a92f72756e2f74657374d9477368613235362d6462633162346339303066666534386435373562356461356336333830343031323566363564623066653365323434393462373665613938363435376439383690d9477368613235362d30383466656430386239373861663464376431393661373434366138366235383030396536333662363131646231363231316236356139616164666632396335d9202f73797374656d2e736c6963652f6964756e6e2d343234322e73657276696365c090aa61637469766174696f6edc0020010101010101010101010101010101010101010101010101010101010101010190d9477368613235362d32393364343764383932393938373139346131303664303236326236326563363766633534393165366339633366653961326663383132643935633237376661c092ad6f64696e2d746f706f6c6f6779959139d9477368613235362d31393538316532376465376365643030666631636535306232303437653761353637633736623163626165626162653565663033663763333031376262356237ab6f64696e2d7369676e65722764c0c0c0c0c0c029b163616e646964617465207265667573656492b56661696c65642d6265666f72652d66656e63696e67b163616e646964617465207265667573656494b163616e6469646174652072656675736564a8636f6d706c657465a7736b6970706564a7736b6970706564c0c0 diff --git a/tests/fixtures/idunn-control-legacy/transaction-pre-fence-abort.hex b/tests/fixtures/idunn-control-legacy/transaction-pre-fence-abort.hex new file mode 100644 index 0000000..ae345b1 --- /dev/null +++ b/tests/fixtures/idunn-control-legacy/transaction-pre-fence-abort.hex @@ -0,0 +1,2 @@ +idunn.deployment_transaction.v3 +dc0023bf6964756e6e2e6465706c6f796d656e745f7472616e73616374696f6e2e7633d92774782d39356138313166662d303533332d343562622d613031352d303038356132353835633061b2636f6e74696e756974792d73657276696365aa636f6e74696e75697479a77365727669636500a77761726d696e67cf0000018bcfe56800cf0000018bcfe56800c099d9216964756e6e2e636f6d70696c65645f6465706c6f796d656e745f706c616e2e7632d9477368613235362d38626532306364633335373930316463373365316162623262336365666633373835343661323962343161353535656131643633653530366562333762376330b5736572766963652d696e6361726e6174696f6e2d316e9bbf6964756e6e2e736f757263655f73656c656374696f6e5f66616374732e7631d92768747470733a2f2f6769746875622e636f6d2f47616d6543756c742f536572766963652e676974af726566732f68656164732f6d61696ed92832323232323232323232323232323232323232323232323232323232323232323232323232323232d92832323232323232323232323232323232323232323232323232323232323232323232323232323232d92833333333333333333333333333333333333333333333333333333333333333333333333333333333bc6465706c6f796d656e742f6964756e6e2f7265636970652e746f6d6cd9477368613235362d323739336466633034633331313961373962353037363965613637356538633030613938366665623331393939306631623031636364363833343563363732618091a87265662d6865616464dc04e20a736368656d61203d202267616d6563756c742e6964756e6e2e7461726765745f6465636c61726174696f6e2e7631220a746172676574203d202273657276696365220a736f757263655f7374616d705f656e7669726f6e6d656e74203d2022534552564943455f4255494c445f434f4d4d4954220a0a5b5b73746570735d5d0a6964203d20226275696c64220a7068617365203d20226275696c64220a72756e6e6572203d202272757374220a61726776203d205b22636172676f222c20226275696c64222c20222d2d6c6f636b6564225d0a0a5b5b65787465726e616c5f696e707574735d5d0a6964203d2022746f6f6c636861696e2d696e646578220a75726c203d202268747470733a2f2f6578616d706c652e696e76616c69642f746f6f6c636861696e2d696e646578220a736861323536203d202264646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464220a72756e6e6572203d202272757374220a64657374696e6174696f6e203d2022696e707574732f746f6f6c636861696e2d696e646578220a0a5b5b6172746966616374735d5d0a6964203d20226461656d6f6e220a736f757263655f6b696e64203d202272756e6e65722d6f7574707574220a72756e6e6572203d202272757374220a736f75726365203d20227461726765742f72656c656173652f73657276696365220a64657374696e6174696f6e203d202273657276696365220a65787065637465645f736861323536203d202263636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363220a65786563757461626c65203d20747275650a0a5b736572766963655d0a65786563757461626c655f6172746966616374203d20226461656d6f6e220a617267756d656e7473203d205b0a20207b206b696e64203d202262696e64696e67222c206e616d65203d202273746174655f726f6f7422207d2c0a5d0a7472616e73706f7274203d202268747470220a726f7574655f7265717569726564203d2066616c73650a72657175697265645f656e7669726f6e6d656e74203d205b2247414d4543554c545f4944554e4e5f52554e54494d455f42554e444c45225d0a0a5b736572766963652e6865616c74685d0a636f6e7472616374203d2022736572766963652e6865616c7468220a0a5b73746174655d0a736368656d615f67656e65726174696f6e203d20227631220a0a5b5b73746174652e736c6f74735d5d0a6964203d202272756e74696d652d6361636865220a72656c61746976655f70617468203d202272756e74696d652d63616368652e6363220a6b696e64203d202263756c7463616368652d66696c65220a736368656d61203d2022736572766963652e72756e74696d652d63616368652e7631220a777269746572203d20226e6f6e65220a7265636f76657279203d202272656275696c6461626c65220a73746172747570203d20226f70656e2d61742d7374617274220a0a5b5b70726f76696465735d5d0a6361706162696c697479203d2022736572766963652e72756e74696d65220a736368656d61203d2022736572766963652e72756e74696d652e7631220a636f6d7061746962696c697479203d20227631220a0adc06930a736368656d61203d202267616d6563756c742e6964756e6e2e6f70657261746f725f62696e64696e672e7632220a746172676574203d202273657276696365220a0a5b7265706f7369746f72795d0a6f726967696e203d202268747470733a2f2f6769746875622e636f6d2f47616d6543756c742f536572766963652e676974220a61646d69747465645f726566203d2022726566732f68656164732f6d61696e220a6d696e696d756d5f7265766973696f6e203d202231313131313131313131313131313131313131313131313131313131313131313131313131313131220a73656c656374696f6e203d20227265662d68656164220a636865636b6f7574203d20222f7372762f6275696c642f53657276696365220a7265636970655f70617468203d20226465706c6f796d656e742f6964756e6e2f7265636970652e746f6d6c220a0a5b72756e6e6572732e727573745d0a647269766572203d2022646f636b6572220a696d616765203d202272757374407368613235363a61616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161220a75736572203d2022313030303a31303030220a6166666f7264616e636573203d205b22736f757263652d72656164222c202261727469666163742d7772697465225d0a616c6c6f7765645f70726f6772616d73203d205b22636172676f225d0a6e6574776f726b5f70726f66696c65203d20226275696c642d646570656e64656e63792d656772657373220a6d656d6f72795f6d6562696279746573203d20323034380a6370755f71756f74615f70657263656e74203d203230300a706964735f6c696d6974203d203531320a746d7066735f6d6562696279746573203d203531320a0a5b776f726b6c6f61645d0a647269766572203d202273797374656d642d7472616e7369656e74220a73746174655f67726f7570203d202273657276696365220a756e69745f707265666978203d20226964756e6e2d73657276696365220a72656c656173655f726f6f74203d20222f7372762f736572766963652f72656c6561736573220a73746174655f726f6f74203d20222f7661722f6c69622f67616d6563756c742f73657276696365220a72756e74696d655f726f6f74203d20222f72756e2f67616d6563756c742f6964756e6e2f73657276696365220a6e6574776f726b203d2022686f73742d70726976617465220a68617264656e696e67203d2022737472696374220a6d656d6f72795f6d6562696279746573203d20313032340a6370755f71756f74615f70657263656e74203d203130300a0a5b776f726b6c6f61642e617267756d656e745f62696e64696e67735d0a73746174655f726f6f74203d20222f7661722f6c69622f67616d6563756c742f73657276696365220a0a5b776f726b6c6f61642e7365637265745f66696c65735d0a47414d4543554c545f52554e54494d455f50524553454e43455f4944454e54495459203d20222f6574632f67616d6563756c742f736572766963652f72756e74696d652d70726573656e63652d6964656e746974792e6363220a0a5b72756e74696d655f6964656e746974795d0a72756e74696d655f6964203d2022736572766963652d79676764726173696c220a65787065637465645f7369676e65725f6964656e746974795f6964203d202231626661653932326138626630313132373562353536623236393135303363386366643538313234383931373134323365373736663133386463313235376337220a74727573745f616e63686f725f73746f7265203d20222f746d702f6964756e6e2d62312d6c65676163792f70726f76696465722d616e63686f722e6363220a0a5b6272616b65735d0a6465706c6f796d656e745f73746f7265203d20222f7661722f6c69622f67616d6563756c742f6964756e6e2f736572766963652d6465706c6f796d656e742d6272616b652e6363220a6c6966656379636c655f73746f7265203d20222f7661722f6c69622f67616d6563756c742f6964756e6e2f736572766963652d6c6966656379636c652d6272616b652e6363220a0a5b726f6c6c6f75745d0a7374726174656779203d202263616e6469646174652d7468656e2d70726f6d6f7465220a647261696e5f7365636f6e6473203d2033300a72657461696e5f72656c6561736573203d20320a0a5b706c6163656d656e745d0a646573697265645f7265706c69636173203d20310a6e6f646573203d205b2279676764726173696c225d0a90c0c096b76964756e6e2e7365616c65645f72656c656173652e7631d9477368613235362d39366633373231386438333663646364303037393631343233333032353334333362316666633766323538633135353037656536376163323961643665663662d9477368613235362d386265323063646333353739303164633733653161626232623363656666333738353436613239623431613535356561316436336535303665623337623763309195a66461656d6f6ea773657276696365d9477368613235362d636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363632ac39196af746f6f6c636861696e2d696e646578d92768747470733a2f2f6578616d706c652e696e76616c69642f746f6f6c636861696e2d696e646578d9477368613235362d64646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464646464a472757374b6696e707574732f746f6f6c636861696e2d696e646578117892d9477368613235362d39366633373231386438333663646364303037393631343233333032353334333362316666633766323538633135353037656536376163323961643665663662ba2f7372762f736572766963652f72656c65617365732f74657374dc0012bd6964756e6e2e65787065637465645f696e6361726e6174696f6e2e7632a773657276696365d9477368613235362d38626532306364633335373930316463373365316162623262336365666633373835343661323962343161353535656131643633653530366562333762376330b5736572766963652d696e6361726e6174696f6e2d31d9477368613235362d39366633373231386438333663646364303037393631343233333032353334333362316666633766323538633135353037656536376163323961643665663662bb6769746875622e636f6d2f47616d6543756c742f53657276696365d92832323232323232323232323232323232323232323232323232323232323232323232323232323232d9477368613235362d32373933646663303463333131396137396235303736396561363735653863303061393836666562333139393930663162303163636436383334356336373261b1736572766963652d79676764726173696cd94031626661653932326138626630313132373562353536623236393135303363386366643538313234383931373134323365373736663133386463313235376337ae736572766963652e6865616c7468d9477368613235362d63636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363a27631d9477368613235362d32663837303134316366353638316566656332653234316364636435663731303831616539326162316535633534633839636438393666386335656236323731c2c09194af736572766963652e72756e74696d65b2736572766963652e72756e74696d652e7631a276310190d9477368613235362d33336163613963353639636165373831643936396632313864633036613035313134613863666239333436313634633033613263336435343033613636323666c0cf0000018bcfe568009abb6964756e6e2e72756e74696d655f61637469766174696f6e2e7632d9477368613235362d33336163613963353639636165373831643936396632313864633036613035313134613863666239333436313634633033613263336435343033613636323666b1736572766963652d79676764726173696cd9477368613235362d66353962643235306336333830383661643330396235333539373636663232326266353033366333336230616633316239633935333130353831366636396137d94066313063623131353633346366613935383966356564616332313730343339363933353834343234643736653133366434396661613236373539323266376665c420f2977384801339144d13ebd2ab001bf29fbab79f7c3948334d440db8206cf974cf0000018bcfe56800d94063653461663030623963626662316362613963363136363965323337303232323465343763623163303761346233313431626634353237383236353965646637a765643235353139c4403a548c511ff3de6fcac116b903fa6badb14deef79dd81958d71947af575fae753b11692d0272c7cb5c437300cdd0d5315e28a1e7e12f9df0a0b817951bba4700dc0033b26964756e6e2d343234322e73657276696365af4964756e6e20746573742034323432af696e766f636174696f6e2d3432343201a465786563a6616c77617973ad636f6e74726f6c2d67726f7570c3a57534323432a57534323432a0a0a0c3c3a9696e76697369626c65a3706964c3a430303737a0a0cd10920194cd1092cd1092cd1092cd109294cd1092cd1092cd1092cd109291cd10920000000000c391010807b52f6f70742f746573742f62696e2f736572766963650101d9477368613235362d34626635313232663334343535346335336264653265626238636432623765336431363030616436333163333835613564376363653233633737383534353961d9477368613235362d66353962643235306336333830383661643330396235333539373636663232326266353033366333336230616633316239633935333130353831366636396137a92f6f70742f74657374a92f72756e2f74657374d9477368613235362d6462633162346339303066666534386435373562356461356336333830343031323566363564623066653365323434393462373665613938363435376439383690d9477368613235362d30383466656430386239373861663464376431393661373434366138366235383030396536333662363131646231363231316236356139616164666632396335d9202f73797374656d2e736c6963652f6964756e6e2d343234322e73657276696365c090aa61637469766174696f6edc0020010101010101010101010101010101010101010101010101010101010101010190d9477368613235362d32393364343764383932393938373139346131303664303236326236326563363766633534393165366339633366653961326663383132643935633237376661c092ad6f64696e2d746f706f6c6f6779959139d9477368613235362d31393538316532376465376365643030666631636535306232303437653761353637633736623163626165626162653565663033663763333031376262356237ab6f64696e2d7369676e65722764c0c0c0c0c0c029c0c094b163616e6469646174652072656675736564a770656e64696e67a7736b6970706564a7736b6970706564c0c0 From ff3cd519105ce0be6a17fd63b01a3a7e2ea432fd Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 06:45:37 +0200 Subject: [PATCH 05/11] Pin the B1 fix batch's survivors cargo-mutants over the batch's diff missed the lift's gate, the unexplained projection accounting, the refusal count and the deferral clock. Tests now cover each: the lift owes only a continuity that issued an activation; a live transaction accounts for its own activation and nobody else's; three refusals in history hold the restart ceiling; the deferral lands between now and now plus its length. Co-Authored-By: Claude Sonnet 5 --- src/control_plane.rs | 86 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) diff --git a/src/control_plane.rs b/src/control_plane.rs index 6c97384..7edba23 100644 --- a/src/control_plane.rs +++ b/src/control_plane.rs @@ -11623,7 +11623,11 @@ mod tests { .continuity_backoff .next_restart_at_unix_millis .context("the failed demotion was not recorded")?; - assert!(deferred >= before + CONTINUITY_DEFERRAL_MILLIS); + let after = now_millis()?; + assert!( + (before + CONTINUITY_DEFERRAL_MILLIS..=after + CONTINUITY_DEFERRAL_MILLIS) + .contains(&deferred) + ); // Deferred: the next tick neither retries nor writes. let envelope = incumbent_envelope(&world)?; @@ -11720,6 +11724,28 @@ mod tests { world.engine.reconcile_failed_continuity_projections()?, ProjectionReconciliation::default() ); + // ...and for nobody else's. + topology.withdraw_stale_incarnation(&incumbent.expected, &anchor)?; + let mut other = stranger.clone(); + let other_activation = IdunnRuntimeActivationLaunch::issue( + &incumbent.expected, + runtime_instance_id("tx-someone-else")?, + now_millis()?, + &world.engine.idunn_signer, + )? + .activation() + .clone(); + if let Some(WorkloadObservation::Systemd(observed)) = other.workload.as_mut() { + observed.runtime_instance_id = other_activation.runtime_instance_id.clone(); + } + other.activation = Some(other_activation); + project_candidate(&world, &other, true)?; + assert_eq!( + world.engine.reconcile_failed_continuity_projections()?.unexplained, + vec!["service".to_owned()] + ); + topology.withdraw_stale_incarnation(&incumbent.expected, &anchor)?; + project_candidate(&world, &stranger, true)?; // ...and once it is gone, nothing does. let seeded = resident(&world)?; let command = ControlSnapshot::read(&world.state_store)? @@ -11876,4 +11902,62 @@ mod tests { assert_eq!(ControlSnapshot::read(&world.state_store)?.transactions.len(), 1); Ok(()) } + + #[test] + fn the_legacy_lift_owes_only_a_continuity_that_issued_an_activation() -> Result<()> { + let envelope = fixture_envelope( + FIXTURE_PRE_B1_ABORTS[0].1, + DeploymentTransaction::TYPE, + )?; + let written = lift_legacy_transaction(&envelope)?; + let owed = |transaction: &DeploymentTransaction| { + transaction + .pre_fencing_abort + .as_ref() + .map(|abort| abort.topology_reconciliation) + }; + assert_eq!(owed(&written), Some(CleanupEvidence::Skipped)); + + let mut lifted = written.clone(); + owe_legacy_continuity_projection(&mut lifted); + assert_eq!(owed(&lifted), Some(CleanupEvidence::Pending)); + + // A deployment published its own key and recorded what it owed. + let mut deploy = written.clone(); + deploy.command_kind = CommandKind::Deploy; + owe_legacy_continuity_projection(&mut deploy); + assert_eq!(owed(&deploy), Some(CleanupEvidence::Skipped)); + + // A continuity that issued nothing owes nothing. + let mut unissued = written; + unissued.activation = None; + owe_legacy_continuity_projection(&mut unissued); + assert_eq!(owed(&unissued), Some(CleanupEvidence::Skipped)); + Ok(()) + } + + #[test] + fn continuity_stops_after_three_refused_restarts_counted_from_history() -> Result<()> { + let workload = SwitchWorkload::new(); + let world = EngineFixture::with_workload(workload.clone())?; + let incumbent = admit_incumbent(&world)?; + for round in 0..CONTINUITY_RESTART_ATTEMPTS { + let failed = seeded_transaction( + &world, + DeploymentPhase::Warming, + CommandKind::Continuity, + Some(&incumbent), + )?; + world + .engine + .begin_pre_fencing_abort(&resident(&world)?, anyhow!("refused {round}"))?; + drive(&world, |transaction| transaction.completion.is_some())?; + assert!(record_of(&world, &failed.transaction_id)?.is_terminal()); + } + workload.kill(); + // Three refusals are in history and none is live: the ceiling holds. + assert!(!world.engine.supervise_one_admitted_generation()?); + assert!(ControlSnapshot::read(&world.state_store)?.transactions.is_empty()); + Ok(()) + } } From b75fbdf96cc1b58f88fa112d26070caae58e06eb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 07:17:11 +0200 Subject: [PATCH 06/11] Boot reconciliation owns legacy residue; the scheduler isolates per-record faults Soul's pass on the B1 fix batch found the lift's reopen of a terminal pre-B1 continuity abort could stop Idunn booting (the reopened record claims target authority beside a live transaction, and the store was already migrated to v4), and that one wedged abort stopped the whole scheduler. - The lift no longer reopens anything. A terminal pre-B1 continuity abort that issued an activation keeps its phase and completion and carries the typed marker CleanupEvidence::LegacySkippedBeforeB1 on its topology_reconciliation. Validation accepts that shape only for a terminal continuity abort. Boot reconciliation, already the exact-activation owner of that residue, is the only cleanup path. A pre-B1 abort still in flight lifts to Pending: it already holds its target's authority, so the lift adds no claimant. - A failed step of a pre-fence abort is recorded as a resumable error, never handed to the post-fence abort, which refuses a pre-fence phase and failed every tick. - One transaction's error no longer fails run_scheduler_tick: each candidate is resumed on its own and its fault logged, and retiring a terminal record tries the next one when an archive fails. An unreadable control store still fails the tick. - serve is boot plus the loop, so a test can run the boot sequence. Tests pin, through the Engine: the marker and no-reopen for each pre-B1 fixture; a resident terminal abort plus a live transaction plus a second resident abort for one target; a withdrawn incarnation never re-published and history keeping one copy after a crash between the archive steps; a wedged abort leaving freezing alive; an unarchivable terminal leaving resume alive; and boot demoting the residue. Co-Authored-By: Claude Sonnet 5 --- src/control_plane.rs | 611 +++++++++++++++++++++++++++++++++---------- 1 file changed, 471 insertions(+), 140 deletions(-) diff --git a/src/control_plane.rs b/src/control_plane.rs index 7edba23..48ecf07 100644 --- a/src/control_plane.rs +++ b/src/control_plane.rs @@ -751,11 +751,20 @@ enum CleanupEvidence { Pending, Skipped, Complete, + /// Set only by the legacy lift, on a terminal continuity abort written + /// before the single resolution rule: it issued an activation and recorded + /// `Skipped`. Boot reconciliation, not the record, owes that residue's + /// demotion. The marker is what lets validation accept the old shape + /// without reopening a finished transaction. + LegacySkippedBeforeB1, } impl CleanupEvidence { fn is_complete(self) -> bool { - matches!(self, Self::Skipped | Self::Complete) + matches!( + self, + Self::Skipped | Self::Complete | Self::LegacySkippedBeforeB1 + ) } } @@ -1304,7 +1313,10 @@ impl DeploymentTransaction { CleanupEvidence::Pending, CleanupEvidence::Pending | CleanupEvidence::Complete ) | (CleanupEvidence::Skipped, CleanupEvidence::Skipped) - ), + ) || (self.command_kind == CommandKind::Continuity + && self.phase == DeploymentPhase::Complete + && self.completion.is_some() + && abort.topology_reconciliation == CleanupEvidence::LegacySkippedBeforeB1), "abort topology cleanup differs from what the transaction projected" ); ensure!( @@ -2707,31 +2719,34 @@ fn read_transaction_record(envelope: &CultCacheEnvelope) -> Result Result<()> { +/// Everything the daemon does once, before its loop: lock, migrate, validate, +/// reconcile the projection. The lock is returned so the caller holds it for as +/// long as the engine runs. +fn boot(options: RuntimeOptions) -> Result<(ProcessLock, Engine)> { for path in [ &options.state_store, &options.topology_store, @@ -3900,7 +3918,7 @@ fn serve(options: RuntimeOptions) -> Result<()> { fs::create_dir_all(directory) .with_context(|| format!("creating Idunn directory {}", directory.display()))?; } - let _lock = ProcessLock::acquire(&options.state_store)?; + let lock = ProcessLock::acquire(&options.state_store)?; let migrated = migrate_control_store_to_current_schema(&options.state_store) .context("migrating Idunn control records to the current schema")?; if migrated > 0 { @@ -3925,7 +3943,11 @@ fn serve(options: RuntimeOptions) -> Result<()> { } Err(error) => eprintln!("Idunn boot projection reconciliation failed: {error:#}"), } + Ok((lock, engine)) +} +fn serve(options: RuntimeOptions) -> Result<()> { + let (_lock, engine) = boot(options)?; loop { match engine.run_scheduler_tick() { Ok(true) => continue, @@ -3944,9 +3966,6 @@ fn serve(options: RuntimeOptions) -> Result<()> { } impl Engine { - /// One pass of the scheduler, with the loop's ordering preserved exactly: - /// `Ok(true)` means "went round again immediately", which is what the - /// caller's `continue` did. /// One resident terminal transaction goes to history per tick. /// /// Transactions that finished before finished transactions travelled to @@ -3955,21 +3974,34 @@ impl Engine { /// reads. They leave the same way a transaction finishing today does. fn retire_one_terminal_transaction(&self) -> Result { let snapshot = ControlSnapshot::read(&self.options.state_store)?; - let Some(stored) = snapshot + // A record that cannot be archived (history unreadable, a torn write) + // is that record's fault: the next terminal record is still tried, and + // the tick goes on to supervise and freeze. + for stored in snapshot .transactions .iter() - .find(|stored| stored.value.is_terminal()) - else { - return Ok(false); - }; - archive_terminal_transaction(&self.options.state_store, &stored.envelope)?; - eprintln!( - "Idunn retired resident terminal transaction {} to history", - stored.value.transaction_id - ); - Ok(true) + .filter(|stored| stored.value.is_terminal()) + { + match archive_terminal_transaction(&self.options.state_store, &stored.envelope) { + Ok(()) => { + eprintln!( + "Idunn retired resident terminal transaction {} to history", + stored.value.transaction_id + ); + return Ok(true); + } + Err(error) => eprintln!( + "Idunn could not retire terminal transaction {}: {error:#}", + stored.value.transaction_id + ), + } + } + Ok(false) } + /// One pass of the scheduler. An unreadable control store is the tick's + /// fault and is returned; anything one transaction or one admitted + /// generation does wrong is logged against it and never stops the others. fn run_scheduler_tick(&self) -> Result { if self.retire_one_terminal_transaction()? { return Ok(true); @@ -4002,45 +4034,61 @@ impl Engine { if snapshot.has_earlier_authority_sibling(¤t.value) { continue; } - if let Err(error) = self.advance_transaction(current) { - let latest_snapshot = ControlSnapshot::read(&self.options.state_store)?; - let latest = latest_snapshot - .transactions - .iter() - .find(|stored| stored.value.transaction_id == current.value.transaction_id) - .context("transaction disappeared while recording an execution error")?; - if latest.value.is_terminal() { - progressed = true; - } else if latest.value.phase < DeploymentPhase::Fencing - && latest.value.pre_fencing_abort.is_none() - { - self.begin_pre_fencing_abort(latest, error)?; - } else if latest.value.post_fencing_abort.is_none() - && self.candidate_is_permanently_stopped(&latest.value)? - { - // Past the fence an error is resumable while the candidate - // can still recover. This one cannot: its transient unit - // has failed and carries Restart=no, so retrying would hold - // the target forever behind a transaction that can never - // finish. - self.begin_post_fencing_abort(latest, error)?; - } else { - self.record_resumable_error(latest, &error)?; - } - } - let after = ControlSnapshot::read(&self.options.state_store)?; - let live = after - .transactions - .iter() - .find(|stored| stored.value.transaction_id == current.value.transaction_id) - .context("transaction disappeared while checking scheduler progress")?; - if live.envelope != current.envelope { - progressed = true; + match self.resume_candidate(current) { + Ok(moved) => progressed |= moved, + Err(error) => eprintln!( + "Idunn could not resume transaction {}: {error:#}", + current.value.transaction_id + ), } } Ok(progressed) } + /// Advance one transaction, turning its failure into the durable record + /// its phase calls for. Returns whether its record changed. + fn resume_candidate(&self, current: &Stored) -> Result { + if let Err(error) = self.advance_transaction(current) { + let latest_snapshot = ControlSnapshot::read(&self.options.state_store)?; + let latest = latest_snapshot + .transactions + .iter() + .find(|stored| stored.value.transaction_id == current.value.transaction_id) + .context("transaction disappeared while recording an execution error")?; + if latest.value.is_terminal() { + return Ok(true); + } + if latest.value.phase < DeploymentPhase::Fencing { + // Before the fence an abort that cannot finish a step is + // resumable, never a post-fence abort: that path refuses a + // pre-fence phase, so choosing it only wedged the tick. + if latest.value.pre_fencing_abort.is_none() { + self.begin_pre_fencing_abort(latest, error)?; + } else { + self.record_resumable_error(latest, &error)?; + } + } else if latest.value.post_fencing_abort.is_none() + && self.candidate_is_permanently_stopped(&latest.value)? + { + // Past the fence an error is resumable while the candidate + // can still recover. This one cannot: its transient unit + // has failed and carries Restart=no, so retrying would hold + // the target forever behind a transaction that can never + // finish. + self.begin_post_fencing_abort(latest, error)?; + } else { + self.record_resumable_error(latest, &error)?; + } + } + let after = ControlSnapshot::read(&self.options.state_store)?; + let live = after + .transactions + .iter() + .find(|stored| stored.value.transaction_id == current.value.transaction_id) + .context("transaction disappeared while checking scheduler progress")?; + Ok(live.envelope != current.envelope) + } + fn freeze_one_queued_command(&self) -> Result { let snapshot = ControlSnapshot::read(&self.options.state_store)?; let live_commands = snapshot @@ -11459,8 +11507,57 @@ mod tests { Ok(()) } + fn abort_owed(transaction: &DeploymentTransaction) -> Option { + transaction + .pre_fencing_abort + .as_ref() + .map(|abort| abort.topology_reconciliation) + .or_else(|| { + transaction + .post_fencing_abort + .as_ref() + .map(|abort| abort.topology_reconciliation) + }) + } + + /// Put a continuity's record and its command in the control store as they + /// stood: `envelope` is written as given, in whatever schema it is in. + fn make_resident( + world: &EngineFixture, + transaction: &DeploymentTransaction, + envelope: CultCacheEnvelope, + ) -> Result<()> { + let command = DeploymentCommand { + schema_version: DEPLOYMENT_COMMAND_SCHEMA.into(), + command_id: transaction.command_id.clone(), + kind: CommandKind::Continuity, + selector: "service".into(), + requested_by: "test".into(), + requested_at_unix_millis: 100, + }; + assert!( + SingleFileMessagePackBackingStore::new(&world.state_store).compare_exchange( + &[ + CultCacheExpectedEnvelope { + r#type: DeploymentCommand::TYPE.into(), + key: command.command_id.clone(), + current: None, + }, + CultCacheExpectedEnvelope { + r#type: DeploymentTransaction::TYPE.into(), + key: envelope.key.clone(), + current: None, + }, + ], + &[command_envelope(&command, 100)?, envelope], + )? + ); + Ok(()) + } + #[test] - fn a_pre_b1_continuity_abort_lifts_owing_its_own_activation_and_resolves_it() -> Result<()> { + fn a_pre_b1_continuity_abort_lifts_without_reopening_and_boot_resolves_its_residue() + -> Result<()> { write_fixture_anchor()?; for (name, text) in FIXTURE_PRE_B1_ABORTS { let envelope = fixture_envelope(text, DeploymentTransaction::TYPE)?; @@ -11470,79 +11567,33 @@ mod tests { let legacy: LegacyDeploymentTransaction = rmp_serde::from_slice(&envelope.payload)?; assert_eq!(legacy.command_kind, CommandKind::Continuity, "{name}"); assert!(legacy.activation.is_some(), "{name}"); - let owed = legacy - .pre_fencing_abort - .as_ref() - .map(|abort| abort.topology_reconciliation) - .or_else(|| { - legacy - .post_fencing_abort - .as_ref() - .map(|abort| abort.topology_reconciliation) - }) - .context("no abort")?; - assert_eq!(owed, CleanupEvidence::Skipped, "{name}"); // History describes what happened, so it lifts the record as written. let archived = lift_legacy_transaction(&envelope)?; - let archived_owed = archived - .pre_fencing_abort - .as_ref() - .map(|abort| abort.topology_reconciliation) - .or_else(|| { - archived - .post_fencing_abort - .as_ref() - .map(|abort| abort.topology_reconciliation) - }) - .context("no abort")?; - assert_eq!(archived_owed, CleanupEvidence::Skipped, "{name}"); + assert_eq!(abort_owed(&archived), Some(CleanupEvidence::Skipped), "{name}"); - // The control store lifts it owing the demotion, and validates. + // The control store lifts it without reopening anything. let lifted = read_transaction_record(&envelope)?; - let lifted_owed = lifted - .pre_fencing_abort - .as_ref() - .map(|abort| abort.topology_reconciliation) - .or_else(|| { - lifted - .post_fencing_abort - .as_ref() - .map(|abort| abort.topology_reconciliation) - }) - .context("no abort")?; - assert_eq!(lifted_owed, CleanupEvidence::Pending, "{name}"); - assert!(!lifted.is_terminal(), "{name}: a record that owes work is terminal"); - assert_eq!(lifted.completion, None, "{name}"); + let terminal = archived.completion.is_some(); + if terminal { + assert_eq!( + abort_owed(&lifted), + Some(CleanupEvidence::LegacySkippedBeforeB1), + "{name}" + ); + assert!(lifted.is_terminal(), "{name}: the lift reopened a finished record"); + assert_eq!(lifted.phase, archived.phase, "{name}"); + assert_eq!(lifted.completion, archived.completion, "{name}"); + assert!(!lifted.owns_target_authority(), "{name}"); + } else { + assert_eq!(abort_owed(&lifted), Some(CleanupEvidence::Pending), "{name}"); + assert!(!lifted.is_terminal(), "{name}"); + assert_eq!(lifted.completion, None, "{name}"); + } - // Boot: the store reads, and the abort resolves. + // Boot: the store reads. let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; - let command = DeploymentCommand { - schema_version: DEPLOYMENT_COMMAND_SCHEMA.into(), - command_id: lifted.command_id.clone(), - kind: CommandKind::Continuity, - selector: "service".into(), - requested_by: "test".into(), - requested_at_unix_millis: 100, - }; - assert!( - SingleFileMessagePackBackingStore::new(&world.state_store).compare_exchange( - &[ - CultCacheExpectedEnvelope { - r#type: DeploymentCommand::TYPE.into(), - key: command.command_id.clone(), - current: None, - }, - CultCacheExpectedEnvelope { - r#type: DeploymentTransaction::TYPE.into(), - key: envelope.key.clone(), - current: None, - }, - ], - &[command_envelope(&command, 100)?, envelope.clone()], - )?, - "{name}" - ); + make_resident(&world, &lifted, envelope.clone())?; assert_eq!(migrate_control_store_to_current_schema(&world.state_store)?, 1); let snapshot = ControlSnapshot::read(&world.state_store)?; assert_eq!(snapshot.transactions.len(), 1, "{name}"); @@ -11550,15 +11601,27 @@ mod tests { let expected = lifted.expected.clone().context("no Expected")?; assert_eq!(projected_under(&world, &expected)?.len(), 2, "{name}"); - for _ in 0..12 { - let Ok(current) = resident(&world) else { break }; - if current.value.completion.is_some() { - break; + if terminal { + // A finished record owes nothing and is not touched: boot + // reconciliation demotes the residue by its exact activation. + let before = resident(&world)?.envelope; + let outcome = world.engine.reconcile_failed_continuity_projections()?; + assert_eq!(outcome.demoted, vec![lifted.transaction_id.clone()], "{name}"); + assert_eq!(resident(&world)?.envelope, before, "{name}"); + } else { + // A record in flight resolves through its own abort. + for _ in 0..12 { + let Ok(current) = resident(&world) else { break }; + if current.value.completion.is_some() { + break; + } + world.engine.advance_transaction(¤t)?; } - world.engine.advance_transaction(¤t)?; + assert!( + record_of(&world, &envelope.key)?.completion.is_some(), + "{name}: the abort never resolved" + ); } - let finished = record_of(&world, &envelope.key)?; - assert!(finished.completion.is_some(), "{name}: the abort never resolved"); assert_eq!( projected_under(&world, &expected)?, expected_only(), @@ -11568,6 +11631,274 @@ mod tests { Ok(()) } + #[test] + fn resident_terminal_pre_b1_aborts_never_claim_target_authority() -> Result<()> { + write_fixture_anchor()?; + let envelope = fixture_envelope(FIXTURE_PRE_B1_ABORTS[1].1, DeploymentTransaction::TYPE)?; + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + let live = seeded_transaction(&world, DeploymentPhase::Warming, CommandKind::Deploy, None)?; + let first = read_transaction_record(&envelope)?; + assert_eq!(first.target, live.target); + make_resident(&world, &first, envelope)?; + assert_eq!(migrate_control_store_to_current_schema(&world.state_store)?, 1); + + // A second resident abort of the same shape for the same target, + // already written as the marker the migration persists. + let mut second = first.clone(); + second.transaction_id = "tx-second-legacy".into(); + second.command_id = "continuity-second-legacy".into(); + make_resident(&world, &second, transaction_envelope(&second, 200)?)?; + + // The store reads: three records, one of them live, none of the + // finished ones claiming the target. + let snapshot = ControlSnapshot::read(&world.state_store)?; + assert_eq!(snapshot.transactions.len(), 3); + let live_before = snapshot + .transactions + .iter() + .find(|stored| stored.value.transaction_id == live.transaction_id) + .context("live transaction")? + .envelope + .clone(); + + // Reconciliation cleans the residue once, by exact activation. + let expected = first.expected.clone().context("no Expected")?; + project_candidate(&world, &first, true)?; + assert_eq!(projected_under(&world, &expected)?.len(), 2); + let outcome = world.engine.reconcile_failed_continuity_projections()?; + assert_eq!(outcome.demoted.len(), 1); + assert_eq!(projected_under(&world, &expected)?, expected_only()); + let after = ControlSnapshot::read(&world.state_store)?; + assert_eq!( + after + .transactions + .iter() + .find(|stored| stored.value.transaction_id == live.transaction_id) + .context("live transaction")? + .envelope, + live_before + ); + Ok(()) + } + + #[test] + fn boot_never_republishes_a_withdrawn_incarnation_and_history_keeps_one_copy() -> Result<()> { + write_fixture_anchor()?; + let envelope = fixture_envelope(FIXTURE_PRE_B1_ABORTS[1].1, DeploymentTransaction::TYPE)?; + let lifted = read_transaction_record(&envelope)?; + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + make_resident(&world, &lifted, envelope.clone())?; + // A crash between the two archive steps: history already holds it. + assert!( + SingleFileMessagePackBackingStore::new(&history_store_path(&world.state_store)) + .insert_entry_if_absent(envelope)? + ); + assert_eq!(migrate_control_store_to_current_schema(&world.state_store)?, 1); + + // The incarnation was withdrawn: nothing is projected for it. + let expected = lifted.expected.clone().context("no Expected")?; + assert!(projected_under(&world, &expected)?.is_empty()); + for _ in 0..3 { + world.engine.run_scheduler_tick()?; + } + assert!( + world + .engine + .reconcile_failed_continuity_projections()? + .demoted + .is_empty() + ); + assert!( + projected_under(&world, &expected)?.is_empty(), + "a withdrawn incarnation's Expected was published again" + ); + + // One copy in history, finished, and nothing resident. + let history = read_history(&world.state_store)?; + assert_eq!(history.transactions.len(), 1); + assert!(history.transactions[0].is_terminal()); + assert!(ControlSnapshot::read(&world.state_store)?.transactions.is_empty()); + Ok(()) + } + + #[test] + fn boot_runs_the_projection_reconciliation_serve_starts_from() -> Result<()> { + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + let incumbent = admit_incumbent(&world)?; + let failed = seeded_transaction( + &world, + DeploymentPhase::Warming, + CommandKind::Continuity, + Some(&incumbent), + )?; + project_candidate(&world, &failed, true)?; + world + .engine + .begin_pre_fencing_abort(&resident(&world)?, anyhow!("candidate died"))?; + drive(&world, |transaction| transaction.completion.is_some())?; + // A pre-B1 abort's residue: the failed candidate's activation stands. + project_candidate(&world, &failed, true)?; + assert_eq!(projected_under(&world, &incumbent.expected)?.len(), 2); + + let (_lock, _engine) = boot(world.engine.options.clone())?; + assert_eq!(projected_under(&world, &incumbent.expected)?, expected_only()); + Ok(()) + } + + /// A workload whose candidate can neither be stopped nor recover: an abort + /// that cannot finish its first step. + struct WedgedWorkload; + + impl WorkloadPort for WedgedWorkload { + fn install( + &self, + plan: &CompiledDeploymentPlan, + release: &crate::drivers::MaterializedRelease, + ) -> Result { + StillWorkload.install(plan, release) + } + fn prepare_activation( + &self, + plan: &CompiledDeploymentPlan, + expected: &IdunnExpectedIncarnationRecord, + launch: IdunnRuntimeActivationLaunch, + ) -> Result { + StillWorkload.prepare_activation(plan, expected, launch) + } + fn start_prepared( + &self, + plan: &CompiledDeploymentPlan, + release: &SealedRelease, + installed: &crate::drivers::InstalledReleaseObservation, + expected: &IdunnExpectedIncarnationRecord, + activation: &IdunnRuntimeActivationRecord, + ) -> Result { + StillWorkload.start_prepared(plan, release, installed, expected, activation) + } + fn discard_prepared( + &self, + plan: &CompiledDeploymentPlan, + expected: &IdunnExpectedIncarnationRecord, + activation: &IdunnRuntimeActivationRecord, + ) -> Result<()> { + StillWorkload.discard_prepared(plan, expected, activation) + } + fn observe( + &self, + expected: &IdunnExpectedIncarnationRecord, + activation: &IdunnRuntimeActivationRecord, + prior: &WorkloadObservation, + ) -> Result { + StillWorkload.observe(expected, activation, prior) + } + fn stop(&self, _: &WorkloadObservation) -> Result<()> { + bail!("the unit will not stop") + } + fn is_permanently_stopped(&self, _: &WorkloadObservation) -> Result { + Ok(true) + } + } + + #[test] + fn one_wedged_pre_fence_abort_does_not_stop_the_scheduler() -> Result<()> { + let world = EngineFixture::with_workload(Arc::new(WedgedWorkload))?; + let wedged = transaction_at(&world, DeploymentPhase::Warming)?; + world + .engine + .begin_pre_fencing_abort(&resident(&world)?, anyhow!("candidate refused"))?; + let command = DeploymentCommand { + schema_version: DEPLOYMENT_COMMAND_SCHEMA.into(), + command_id: "up-nowhere".into(), + kind: CommandKind::Deploy, + selector: "nowhere".into(), + requested_by: "test".into(), + requested_at_unix_millis: 100, + }; + assert!( + SingleFileMessagePackBackingStore::new(&world.state_store).compare_exchange( + &[CultCacheExpectedEnvelope { + r#type: DeploymentCommand::TYPE.into(), + key: command.command_id.clone(), + current: None, + }], + &[command_envelope(&command, 100)?], + )? + ); + + // Every tick answers: the wedged abort records its error and waits, + // and the rest of the scheduler goes on to freeze the queued command. + for _ in 0..6 { + world.engine.run_scheduler_tick()?; + } + let stuck = record_of(&world, &wedged.transaction_id)?; + assert!(!stuck.is_terminal()); + assert!(stuck.post_fencing_abort.is_none()); + assert!(stuck.last_error.is_some()); + assert!( + read_history_transactions(&world.state_store) + .iter() + .any(|transaction| transaction.command_id == command.command_id), + "the queued command was never frozen" + ); + Ok(()) + } + + #[test] + fn a_terminal_transaction_that_cannot_be_archived_does_not_stop_the_scheduler() -> Result<()> { + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + let live = transaction_at(&world, DeploymentPhase::Warming)?; + odin_reports_ready(&world, &live, seeded_sequence(None) + 1)?; + let (finished, command) = terminal_transaction_with_command("ghostlight")?; + assert!( + SingleFileMessagePackBackingStore::new(&world.state_store).compare_exchange( + &[ + CultCacheExpectedEnvelope { + r#type: DeploymentCommand::TYPE.into(), + key: command.command_id.clone(), + current: None, + }, + CultCacheExpectedEnvelope { + r#type: DeploymentTransaction::TYPE.into(), + key: finished.transaction_id.clone(), + current: None, + }, + ], + &[ + command_envelope(&command, 100)?, + transaction_envelope(&finished, finished.updated_at_unix_millis)?, + ], + )? + ); + corrupt_history(&world)?; + let before = ControlSnapshot::read(&world.state_store)? + .transactions + .into_iter() + .find(|stored| stored.value.transaction_id == live.transaction_id) + .context("live transaction")? + .envelope; + + // The finished record cannot be archived, and the live one still moves. + world.engine.run_scheduler_tick()?; + let after = ControlSnapshot::read(&world.state_store)?; + assert!( + after + .transactions + .iter() + .any(|stored| stored.value.transaction_id == finished.transaction_id) + ); + assert_ne!( + after + .transactions + .iter() + .find(|stored| stored.value.transaction_id == live.transaction_id) + .context("live transaction")? + .envelope, + before, + "the live transaction was not resumed" + ); + Ok(()) + } + // ---- fix 2: supervision owns the Expected-only precondition ---- #[test] From 81ec1c7f40a4b496ac8fdffadb3c43d2dd2e9d9d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 07:21:21 +0200 Subject: [PATCH 07/11] Give the wedged-abort test the operator binding a freeze needs Co-Authored-By: Claude Sonnet 5 --- src/control_plane.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/control_plane.rs b/src/control_plane.rs index 48ecf07..6904389 100644 --- a/src/control_plane.rs +++ b/src/control_plane.rs @@ -11827,6 +11827,7 @@ mod tests { // Every tick answers: the wedged abort records its error and waits, // and the rest of the scheduler goes on to freeze the queued command. + write_service_binding(&world)?; for _ in 0..6 { world.engine.run_scheduler_tick()?; } From 81478e6ddd6ab5cd8a3de52582c548e064e50b7a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 07:36:43 +0200 Subject: [PATCH 08/11] Pin the scheduler's progress report and the post-fence abort path Cargo-mutants on the previous commit missed the per-candidate progress flag and the post-fence branch selection in resume_candidate. A repeated error reports no progress; a dead candidate past the fence aborts; a wedged post-fence abort only waits. Co-Authored-By: Claude Sonnet 5 --- src/control_plane.rs | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/src/control_plane.rs b/src/control_plane.rs index 6904389..2efb9a2 100644 --- a/src/control_plane.rs +++ b/src/control_plane.rs @@ -11747,7 +11747,9 @@ mod tests { /// A workload whose candidate can neither be stopped nor recover: an abort /// that cannot finish its first step. - struct WedgedWorkload; + struct WedgedWorkload { + observe_fails: bool, + } impl WorkloadPort for WedgedWorkload { fn install( @@ -11789,6 +11791,7 @@ mod tests { activation: &IdunnRuntimeActivationRecord, prior: &WorkloadObservation, ) -> Result { + ensure!(!self.observe_fails, "the unit cannot be observed"); StillWorkload.observe(expected, activation, prior) } fn stop(&self, _: &WorkloadObservation) -> Result<()> { @@ -11801,7 +11804,9 @@ mod tests { #[test] fn one_wedged_pre_fence_abort_does_not_stop_the_scheduler() -> Result<()> { - let world = EngineFixture::with_workload(Arc::new(WedgedWorkload))?; + let world = EngineFixture::with_workload(Arc::new(WedgedWorkload { + observe_fails: false, + }))?; let wedged = transaction_at(&world, DeploymentPhase::Warming)?; world .engine @@ -11825,6 +11830,10 @@ mod tests { )? ); + // The first pass records the error and reports progress; the same + // error again changes nothing. + assert!(world.engine.resume_one_transaction()?); + assert!(!world.engine.resume_one_transaction()?); // Every tick answers: the wedged abort records its error and waits, // and the rest of the scheduler goes on to freeze the queued command. write_service_binding(&world)?; @@ -11844,6 +11853,29 @@ mod tests { Ok(()) } + #[test] + fn a_dead_candidate_past_the_fence_aborts_and_a_wedged_post_fence_abort_only_waits() -> Result<()> { + let world = EngineFixture::with_workload(Arc::new(WedgedWorkload { + observe_fails: true, + }))?; + let dead = transaction_at(&world, DeploymentPhase::AwaitingReady)?; + + // The candidate cannot be observed and can never run again, so the + // transaction abandons it after the fence. + world.engine.run_scheduler_tick()?; + assert!(record_of(&world, &dead.transaction_id)?.post_fencing_abort.is_some()); + + // Its abort cannot stop the unit: that is a resumable error, and the + // tick answers every time. + for _ in 0..3 { + world.engine.run_scheduler_tick()?; + } + let stuck = record_of(&world, &dead.transaction_id)?; + assert!(!stuck.is_terminal()); + assert!(stuck.last_error.is_some()); + Ok(()) + } + #[test] fn a_terminal_transaction_that_cannot_be_archived_does_not_stop_the_scheduler() -> Result<()> { let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; From 8998cfcf02894227c5a7f871f59457f5b8462806 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 07:56:38 +0200 Subject: [PATCH 09/11] Seed the wedged post-fence abort by hand A transaction seeded at AwaitingReady fails validation (no fencing evidence), and nothing at Fencing makes a workload error, so the post-fence abort is begun directly and the test pins that its failing step only waits. Co-Authored-By: Claude Sonnet 5 --- src/control_plane.rs | 29 ++++++++++------------------- 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/src/control_plane.rs b/src/control_plane.rs index 2efb9a2..9f3c452 100644 --- a/src/control_plane.rs +++ b/src/control_plane.rs @@ -11747,9 +11747,7 @@ mod tests { /// A workload whose candidate can neither be stopped nor recover: an abort /// that cannot finish its first step. - struct WedgedWorkload { - observe_fails: bool, - } + struct WedgedWorkload; impl WorkloadPort for WedgedWorkload { fn install( @@ -11791,7 +11789,6 @@ mod tests { activation: &IdunnRuntimeActivationRecord, prior: &WorkloadObservation, ) -> Result { - ensure!(!self.observe_fails, "the unit cannot be observed"); StillWorkload.observe(expected, activation, prior) } fn stop(&self, _: &WorkloadObservation) -> Result<()> { @@ -11804,9 +11801,7 @@ mod tests { #[test] fn one_wedged_pre_fence_abort_does_not_stop_the_scheduler() -> Result<()> { - let world = EngineFixture::with_workload(Arc::new(WedgedWorkload { - observe_fails: false, - }))?; + let world = EngineFixture::with_workload(Arc::new(WedgedWorkload))?; let wedged = transaction_at(&world, DeploymentPhase::Warming)?; world .engine @@ -11854,19 +11849,15 @@ mod tests { } #[test] - fn a_dead_candidate_past_the_fence_aborts_and_a_wedged_post_fence_abort_only_waits() -> Result<()> { - let world = EngineFixture::with_workload(Arc::new(WedgedWorkload { - observe_fails: true, - }))?; - let dead = transaction_at(&world, DeploymentPhase::AwaitingReady)?; + fn a_wedged_post_fence_abort_only_waits() -> Result<()> { + let world = EngineFixture::with_workload(Arc::new(WedgedWorkload))?; + let dead = transaction_at(&world, DeploymentPhase::Fencing)?; + world + .engine + .begin_post_fencing_abort(&resident(&world)?, anyhow!("candidate died"))?; - // The candidate cannot be observed and can never run again, so the - // transaction abandons it after the fence. - world.engine.run_scheduler_tick()?; - assert!(record_of(&world, &dead.transaction_id)?.post_fencing_abort.is_some()); - - // Its abort cannot stop the unit: that is a resumable error, and the - // tick answers every time. + // The abort cannot stop the unit. The abort is already durable, so + // that is a resumable error, and the tick answers every time. for _ in 0..3 { world.engine.run_scheduler_tick()?; } From 287aa92382ee6f7f290cee338720c7d7bc402aaf Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 08:41:25 +0200 Subject: [PATCH 10/11] B1 fix batch 3: progress means state advanced; one wedge starves no one - A tick's progress is a state change, never a last_error rewrite; freezing a queued command no longer waits on other targets' progress (still at most one freeze per tick, busy targets refused as before). - Failing transaction steps back off (process-local, doubling from the poll interval to 60s) instead of retrying every tick. - Boot reconciliation runs the resident-issuer pass with history unreadable. - Resume and retire faults are reported once per transaction and left in last_error, which status renders. - The legacy marker is a private-constructor type inside cleanup_evidence; transaction_envelope refuses a record carrying it, the schema migration writes through its own path. - Tests: changing-error wedge, backoff, dead-candidate post-fence branch, fault note, marker refusal, torn-history boot residue. Co-Authored-By: Claude Sonnet 5 --- src/control_plane.rs | 651 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 570 insertions(+), 81 deletions(-) diff --git a/src/control_plane.rs b/src/control_plane.rs index 9f3c452..fa51aa8 100644 --- a/src/control_plane.rs +++ b/src/control_plane.rs @@ -745,27 +745,133 @@ enum TransactionCompletion { }, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -enum CleanupEvidence { - Pending, - Skipped, - Complete, - /// Set only by the legacy lift, on a terminal continuity abort written - /// before the single resolution rule: it issued an activation and recorded - /// `Skipped`. Boot reconciliation, not the record, owes that residue's - /// demotion. The marker is what lets validation accept the old shape - /// without reopening a finished transaction. - LegacySkippedBeforeB1, +use cleanup_evidence::CleanupEvidence; + +/// Where the legacy marker lives, so that only the lift can make one. +/// +/// `LegacyLift` has a private field: outside this module no expression can +/// construct it, so no other code can write `CleanupEvidence::Legacy(..)`. +/// Decoding a stored record is the one other way in, and it stays here too. +/// `transaction_envelope` refuses a record carrying the marker; the schema +/// migration, which persists what the lift produced, writes through +/// `migrated_transaction_envelope`, defined here beside the only constructor. +mod cleanup_evidence { + use super::*; + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(super) struct LegacyLift(()); + + const LEGACY_MARKER: &str = "legacy-skipped-before-b1"; + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(super) enum CleanupEvidence { + Pending, + Skipped, + Complete, + /// Set only by the legacy lift, on a terminal continuity abort written + /// before the single resolution rule: it issued an activation and + /// recorded `Skipped`. Boot reconciliation, not the record, owes that + /// residue's demotion. The marker is what lets validation accept the + /// old shape without reopening a finished transaction. + Legacy(LegacyLift), + } + + impl CleanupEvidence { + pub(super) fn is_complete(self) -> bool { + !matches!(self, Self::Pending) + } + + pub(super) fn is_legacy_marker(self) -> bool { + matches!(self, Self::Legacy(_)) + } + } + + impl Serialize for CleanupEvidence { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(match self { + Self::Pending => "pending", + Self::Skipped => "skipped", + Self::Complete => "complete", + Self::Legacy(_) => LEGACY_MARKER, + }) + } + } + + impl<'de> Deserialize<'de> for CleanupEvidence { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + match text.as_str() { + "pending" => Ok(Self::Pending), + "skipped" => Ok(Self::Skipped), + "complete" => Ok(Self::Complete), + LEGACY_MARKER => Ok(Self::Legacy(LegacyLift(()))), + other => Err(serde::de::Error::unknown_variant( + other, + &["pending", "skipped", "complete", LEGACY_MARKER], + )), + } + } + } + + impl DeploymentTransaction { + pub(super) fn carries_legacy_marker(&self) -> bool { + self.pre_fencing_abort + .as_ref() + .map(|abort| abort.topology_reconciliation) + .into_iter() + .chain( + self.post_fencing_abort + .as_ref() + .map(|abort| abort.topology_reconciliation), + ) + .any(CleanupEvidence::is_legacy_marker) + } + } + + /// The envelope for a record the schema migration persists, the one write + /// path that may carry the marker. + pub(super) fn migrated_transaction_envelope( + value: &DeploymentTransaction, + now: u64, + ) -> Result { + encode_transaction(value, now) + } + +/// A continuity abort written before the single resolution rule recorded no +/// projection cleanup although its transaction had issued an activation, and +/// so left that activation standing. +/// +/// Nothing is reopened. A record already terminal keeps its terminal phase and +/// completion and is marked the legacy marker, the one shape validation +/// accepts for a terminal abort that owes nothing yet issued an activation; +/// boot reconciliation, the single owner of that residue, demotes it by exact +/// activation. A record still in flight lifts to `Pending`: it already holds +/// its target's authority (a live record claims it before and after the lift), +/// so the lift adds no claimant, and its own abort demotes the activation. +/// Only the control store's read applies this: history describes what happened +/// and is lifted unchanged. +pub(super) fn owe_legacy_continuity_projection(transaction: &mut DeploymentTransaction) { + if transaction.command_kind != CommandKind::Continuity || transaction.activation.is_none() { + return; + } + let terminal = transaction.completion.is_some(); + if let Some(abort) = transaction.pre_fencing_abort.as_mut() + && abort.topology_reconciliation == CleanupEvidence::Skipped + { + abort.topology_reconciliation = if terminal { + CleanupEvidence::Legacy(LegacyLift(())) + } else { + CleanupEvidence::Pending + }; + } + if let Some(abort) = transaction.post_fencing_abort.as_mut() + && abort.topology_reconciliation == CleanupEvidence::Skipped + && !terminal + { + abort.topology_reconciliation = CleanupEvidence::Pending; + } } -impl CleanupEvidence { - fn is_complete(self) -> bool { - matches!( - self, - Self::Skipped | Self::Complete | Self::LegacySkippedBeforeB1 - ) - } } /// Rollback of a transaction that has already fenced the incumbent. @@ -1316,7 +1422,7 @@ impl DeploymentTransaction { ) || (self.command_kind == CommandKind::Continuity && self.phase == DeploymentPhase::Complete && self.completion.is_some() - && abort.topology_reconciliation == CleanupEvidence::LegacySkippedBeforeB1), + && abort.topology_reconciliation.is_legacy_marker()), "abort topology cleanup differs from what the transaction projected" ); ensure!( @@ -2710,48 +2816,13 @@ fn read_transaction_record(envelope: &CultCacheEnvelope) -> Result { let mut value = lift_legacy_transaction(envelope)?; - owe_legacy_continuity_projection(&mut value); + cleanup_evidence::owe_legacy_continuity_projection(&mut value); value.validate()?; Ok(value) } } } -/// A continuity abort written before the single resolution rule recorded no -/// projection cleanup although its transaction had issued an activation, and -/// so left that activation standing. -/// -/// Nothing is reopened. A record already terminal keeps its terminal phase and -/// completion and is marked `LegacySkippedBeforeB1`, the one shape validation -/// accepts for a terminal abort that owes nothing yet issued an activation; -/// boot reconciliation, the single owner of that residue, demotes it by exact -/// activation. A record still in flight lifts to `Pending`: it already holds -/// its target's authority (a live record claims it before and after the lift), -/// so the lift adds no claimant, and its own abort demotes the activation. -/// Only the control store's read applies this: history describes what happened -/// and is lifted unchanged. -fn owe_legacy_continuity_projection(transaction: &mut DeploymentTransaction) { - if transaction.command_kind != CommandKind::Continuity || transaction.activation.is_none() { - return; - } - let terminal = transaction.completion.is_some(); - if let Some(abort) = transaction.pre_fencing_abort.as_mut() - && abort.topology_reconciliation == CleanupEvidence::Skipped - { - abort.topology_reconciliation = if terminal { - CleanupEvidence::LegacySkippedBeforeB1 - } else { - CleanupEvidence::Pending - }; - } - if let Some(abort) = transaction.post_fencing_abort.as_mut() - && abort.topology_reconciliation == CleanupEvidence::Skipped - && !terminal - { - abort.topology_reconciliation = CleanupEvidence::Pending; - } -} - /// Read one stored admitted generation, lifting a v2 record to the current /// shape by the same rule as `read_transaction_record`. fn read_generation_record(envelope: &CultCacheEnvelope) -> Result { @@ -2807,7 +2878,10 @@ fn migrate_control_store_to_current_schema(store_path: &Path) -> Result { for envelope in stale { let (record_type, key, mut next) = if envelope.r#type == DeploymentTransaction::TYPE { let value = read_transaction_record(&envelope)?; - let next = transaction_envelope(&value, value.updated_at_unix_millis)?; + let next = cleanup_evidence::migrated_transaction_envelope( + &value, + value.updated_at_unix_millis, + )?; (DeploymentTransaction::TYPE, value.transaction_id, next) } else { let value = read_generation_record(&envelope)?; @@ -2832,6 +2906,14 @@ fn migrate_control_store_to_current_schema(store_path: &Path) -> Result { } fn transaction_envelope(value: &DeploymentTransaction, now: u64) -> Result { + ensure!( + !value.carries_legacy_marker(), + "only the legacy lift may produce a legacy-marked record; it cannot be written as a new one" + ); + encode_transaction(value, now) +} + +fn encode_transaction(value: &DeploymentTransaction, now: u64) -> Result { value.validate()?; typed_envelope( &value.transaction_id, @@ -2987,6 +3069,15 @@ fn read_history_transactions(state_store: &Path) -> Vec { } } +/// Whether a transaction moved between two reads. An error note (`last_error`) +/// and its timestamp are commentary on a stuck step, not a step. +fn state_advanced(before: &DeploymentTransaction, after: &DeploymentTransaction) -> bool { + let mut after = after.clone(); + after.last_error.clone_from(&before.last_error); + after.updated_at_unix_millis = before.updated_at_unix_millis; + &after != before +} + /// Says a fault once while it lasts. A scheduler tick that hits the same /// unreadable file every half second must not print it every half second. #[derive(Default)] @@ -3486,8 +3577,25 @@ struct Engine { systemd_workload: Arc, host_actuators: Option, history_report: ReportOnce, + /// One `ReportOnce` per faulting record, so one wedged transaction says + /// its fault once and never drowns another's. + fault_reports: Mutex>, + /// Retry pacing for a transaction whose step keeps failing, by + /// transaction id: consecutive failures and the earliest next attempt. + /// Process-local on purpose: a restart retries at once, and no schema + /// carries a clock that only pacing reads. + resume_backoff: Mutex>, } +#[derive(Clone, Copy)] +struct ResumeBackoff { + failures: u32, + not_before_unix_millis: u64, +} + +/// Longest wait between attempts at a failing transaction step. +const RESUME_BACKOFF_CEILING_MILLIS: u64 = 60_000; + impl Engine { fn open(options: RuntimeOptions) -> Result { Self::open_with_systemd_workload( @@ -3541,6 +3649,8 @@ impl Engine { systemd_workload, host_actuators, history_report: ReportOnce::default(), + fault_reports: Mutex::default(), + resume_backoff: Mutex::default(), }) } @@ -3834,12 +3944,18 @@ impl Engine { fn reconcile_failed_continuity_projections(&self) -> Result { let snapshot = ControlSnapshot::read(&self.options.state_store)?; let mut outcome = ProjectionReconciliation::default(); - let Some(history) = self.history_for_decision() else { - return Ok(outcome); - }; + // Resident issuers need no history; only the history issuers wait on it. + let history = self.history_for_decision(); + if history.is_none() { + eprintln!( + "Idunn cannot read history at boot: failed continuities archived there are not \ + reconciled, resident ones still are" + ); + } let topology = self.topology(); let issuers = history .iter() + .flatten() .chain(snapshot.transactions.iter().map(|stored| &stored.value)) .filter(|transaction| { transaction.command_kind == CommandKind::Continuity @@ -3990,9 +4106,10 @@ impl Engine { ); return Ok(true); } - Err(error) => eprintln!( - "Idunn could not retire terminal transaction {}: {error:#}", - stored.value.transaction_id + Err(error) => self.note_fault( + "could not retire terminal transaction", + &stored.value.transaction_id, + &error, ), } } @@ -4008,7 +4125,68 @@ impl Engine { } let transaction_progress = self.resume_one_transaction()?; let continuity_progress = self.supervise_one_admitted_generation()?; - Ok(!transaction_progress && !continuity_progress && self.freeze_one_queued_command()?) + // Freezing is not gated on the others' progress: a queued command + // whose target is free must not wait behind an unrelated target's + // wedge. `freeze_command` already refuses a busy target, so this is + // still at most one freeze per tick and never a second claimant. + let froze = self.freeze_one_queued_command()?; + Ok(transaction_progress || continuity_progress || froze) + } + + /// Say a per-record fault once while it lasts and leave it in the + /// record's `last_error`, which status renders. Recording is best effort: + /// a store too broken to take the note is already in stderr. + fn note_fault(&self, what: &str, transaction_id: &str, error: &anyhow::Error) { + let detail = truncate(&format!("{error:#}"), 2048); + let offered = { + let mut reports = self.fault_reports.lock().expect("fault report mutex"); + reports + .entry(transaction_id.to_string()) + .or_default() + .offer(Some(detail.clone())) + }; + if offered.is_some() { + eprintln!("Idunn {what} {transaction_id}: {detail}"); + } + let _ = self.record_last_error(transaction_id, &detail); + } + + fn clear_fault(&self, transaction_id: &str) { + self.fault_reports + .lock() + .expect("fault report mutex") + .remove(transaction_id); + } + + /// Write `detail` as the record's `last_error`, touching nothing else and + /// not archiving: a terminal record whose archive is the fault stays put. + fn record_last_error(&self, transaction_id: &str, detail: &str) -> Result<()> { + let snapshot = ControlSnapshot::read(&self.options.state_store)?; + let Some(stored) = snapshot + .transactions + .iter() + .find(|stored| stored.value.transaction_id == transaction_id) + else { + return Ok(()); + }; + if stored.value.last_error.as_deref() == Some(detail) { + return Ok(()); + } + let mut next = stored.value.clone(); + next.last_error = Some(detail.to_string()); + let envelope = transaction_envelope(&next, next.updated_at_unix_millis)?; + ensure!( + SingleFileMessagePackBackingStore::new(&self.options.state_store).compare_exchange( + &[CultCacheExpectedEnvelope { + r#type: DeploymentTransaction::TYPE.into(), + key: transaction_id.to_string(), + current: Some(stored.envelope.clone()), + }], + &[envelope], + )?, + "transaction changed before its fault note" + ); + Ok(()) } /// Startup and every later loop use the same order: unfinished ownership @@ -4035,11 +4213,17 @@ impl Engine { continue; } match self.resume_candidate(current) { - Ok(moved) => progressed |= moved, - Err(error) => eprintln!( - "Idunn could not resume transaction {}: {error:#}", - current.value.transaction_id - ), + Ok(moved) => { + self.clear_fault(¤t.value.transaction_id); + progressed |= moved; + } + Err(error) => { + self.note_fault( + "could not resume transaction", + ¤t.value.transaction_id, + &error, + ); + } } } Ok(progressed) @@ -4047,8 +4231,32 @@ impl Engine { /// Advance one transaction, turning its failure into the durable record /// its phase calls for. Returns whether its record changed. + /// + /// "Moved" means the transaction's state advanced: a phase change, a + /// completion, or a durable abort step. Rewriting `last_error` to say the + /// same step failed again in new words is not movement, or a wedged + /// transaction would report progress every tick. fn resume_candidate(&self, current: &Stored) -> Result { - if let Err(error) = self.advance_transaction(current) { + let id = current.value.transaction_id.as_str(); + if self + .resume_backoff + .lock() + .expect("resume backoff mutex") + .get(id) + .is_some_and(|backoff| { + now_millis().is_ok_and(|now| now < backoff.not_before_unix_millis) + }) + { + return Ok(false); + } + let advanced = self.advance_transaction(current); + if advanced.is_ok() { + self.resume_backoff + .lock() + .expect("resume backoff mutex") + .remove(id); + } + if let Err(error) = advanced { let latest_snapshot = ControlSnapshot::read(&self.options.state_store)?; let latest = latest_snapshot .transactions @@ -4056,8 +4264,13 @@ impl Engine { .find(|stored| stored.value.transaction_id == current.value.transaction_id) .context("transaction disappeared while recording an execution error")?; if latest.value.is_terminal() { + self.resume_backoff + .lock() + .expect("resume backoff mutex") + .remove(id); return Ok(true); } + self.back_off(id)?; if latest.value.phase < DeploymentPhase::Fencing { // Before the fence an abort that cannot finish a step is // resumable, never a post-fence abort: that path refuses a @@ -4086,7 +4299,28 @@ impl Engine { .iter() .find(|stored| stored.value.transaction_id == current.value.transaction_id) .context("transaction disappeared while checking scheduler progress")?; - Ok(live.envelope != current.envelope) + Ok(state_advanced(¤t.value, &live.value)) + } + + /// Wait twice as long after each consecutive failure of a transaction's + /// step, from one poll interval up to a ceiling. + fn back_off(&self, transaction_id: &str) -> Result<()> { + let now = now_millis()?; + let mut all = self.resume_backoff.lock().expect("resume backoff mutex"); + let failures = all.get(transaction_id).map_or(0, |backoff| backoff.failures); + let wait = self + .options + .poll_millis + .saturating_mul(1u64 << failures.min(20)) + .min(RESUME_BACKOFF_CEILING_MILLIS); + all.insert( + transaction_id.to_string(), + ResumeBackoff { + failures: failures.saturating_add(1), + not_before_unix_millis: now.saturating_add(wait), + }, + ); + Ok(()) } fn freeze_one_queued_command(&self) -> Result { @@ -11576,9 +11810,8 @@ mod tests { let lifted = read_transaction_record(&envelope)?; let terminal = archived.completion.is_some(); if terminal { - assert_eq!( - abort_owed(&lifted), - Some(CleanupEvidence::LegacySkippedBeforeB1), + assert!( + abort_owed(&lifted).is_some_and(CleanupEvidence::is_legacy_marker), "{name}" ); assert!(lifted.is_terminal(), "{name}: the lift reopened a finished record"); @@ -11647,7 +11880,11 @@ mod tests { let mut second = first.clone(); second.transaction_id = "tx-second-legacy".into(); second.command_id = "continuity-second-legacy".into(); - make_resident(&world, &second, transaction_envelope(&second, 200)?)?; + make_resident( + &world, + &second, + cleanup_evidence::migrated_transaction_envelope(&second, 200)?, + )?; // The store reads: three records, one of them live, none of the // finished ones claiming the target. @@ -11825,9 +12062,8 @@ mod tests { )? ); - // The first pass records the error and reports progress; the same - // error again changes nothing. - assert!(world.engine.resume_one_transaction()?); + // Recording the error is not progress, and neither is repeating it. + assert!(!world.engine.resume_one_transaction()?); assert!(!world.engine.resume_one_transaction()?); // Every tick answers: the wedged abort records its error and waits, // and the rest of the scheduler goes on to freeze the queued command. @@ -11867,6 +12103,259 @@ mod tests { Ok(()) } + /// A wedged abort whose `stop()` error carries a changing counter, as + /// systemctl output with a PID or timestamp would. + struct ChangingErrorWorkload(std::sync::atomic::AtomicU32); + + impl WorkloadPort for ChangingErrorWorkload { + fn install( + &self, + plan: &CompiledDeploymentPlan, + release: &crate::drivers::MaterializedRelease, + ) -> Result { + WedgedWorkload.install(plan, release) + } + fn prepare_activation( + &self, + plan: &CompiledDeploymentPlan, + expected: &IdunnExpectedIncarnationRecord, + launch: IdunnRuntimeActivationLaunch, + ) -> Result { + WedgedWorkload.prepare_activation(plan, expected, launch) + } + fn start_prepared( + &self, + plan: &CompiledDeploymentPlan, + release: &SealedRelease, + installed: &crate::drivers::InstalledReleaseObservation, + expected: &IdunnExpectedIncarnationRecord, + activation: &IdunnRuntimeActivationRecord, + ) -> Result { + WedgedWorkload.start_prepared(plan, release, installed, expected, activation) + } + fn discard_prepared( + &self, + plan: &CompiledDeploymentPlan, + expected: &IdunnExpectedIncarnationRecord, + activation: &IdunnRuntimeActivationRecord, + ) -> Result<()> { + WedgedWorkload.discard_prepared(plan, expected, activation) + } + fn observe( + &self, + expected: &IdunnExpectedIncarnationRecord, + activation: &IdunnRuntimeActivationRecord, + prior: &WorkloadObservation, + ) -> Result { + WedgedWorkload.observe(expected, activation, prior) + } + fn stop(&self, _: &WorkloadObservation) -> Result<()> { + let n = self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + bail!("the unit will not stop (main pid {n})") + } + fn is_permanently_stopped(&self, _: &WorkloadObservation) -> Result { + Ok(true) + } + } + + fn queue_deploy_for_nowhere(world: &EngineFixture) -> Result { + let command = DeploymentCommand { + schema_version: DEPLOYMENT_COMMAND_SCHEMA.into(), + command_id: "up-nowhere".into(), + kind: CommandKind::Deploy, + selector: "nowhere".into(), + requested_by: "test".into(), + requested_at_unix_millis: 100, + }; + assert!( + SingleFileMessagePackBackingStore::new(&world.state_store).compare_exchange( + &[CultCacheExpectedEnvelope { + r#type: DeploymentCommand::TYPE.into(), + key: command.command_id.clone(), + current: None, + }], + &[command_envelope(&command, 100)?], + )? + ); + Ok(command) + } + + #[test] + fn a_wedge_whose_error_text_changes_every_tick_does_not_starve_other_targets() -> Result<()> { + let world = EngineFixture::with_workload(Arc::new(ChangingErrorWorkload( + std::sync::atomic::AtomicU32::new(0), + )))?; + transaction_at(&world, DeploymentPhase::Warming)?; + world + .engine + .begin_pre_fencing_abort(&resident(&world)?, anyhow!("candidate refused"))?; + let command = queue_deploy_for_nowhere(&world)?; + write_service_binding(&world)?; + for _ in 0..20 { + world.engine.run_scheduler_tick()?; + } + assert!( + read_history_transactions(&world.state_store) + .iter() + .any(|transaction| transaction.command_id == command.command_id), + "the queued command was starved by another target's wedge" + ); + Ok(()) + } + + #[test] + fn rewriting_last_error_is_not_progress() -> Result<()> { + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + let before = transaction_at(&world, DeploymentPhase::Warming)?; + let mut noted = before.clone(); + noted.last_error = Some("the unit will not stop (main pid 7)".into()); + noted.updated_at_unix_millis += 1; + assert!(!state_advanced(&before, ¬ed)); + let mut moved = noted.clone(); + moved.phase = DeploymentPhase::AwaitingReady; + assert!(state_advanced(&before, &moved)); + Ok(()) + } + + #[test] + fn a_failing_step_is_retried_after_a_backoff_not_every_tick() -> Result<()> { + let workload = Arc::new(ChangingErrorWorkload(std::sync::atomic::AtomicU32::new(0))); + let world = EngineFixture::with_workload(workload.clone())?; + transaction_at(&world, DeploymentPhase::Warming)?; + world + .engine + .begin_pre_fencing_abort(&resident(&world)?, anyhow!("candidate refused"))?; + for _ in 0..10 { + world.engine.run_scheduler_tick()?; + } + assert_eq!( + workload.0.load(std::sync::atomic::Ordering::SeqCst), + 1, + "the wedged step was retried inside its backoff" + ); + Ok(()) + } + + /// A candidate that fails to advance and is dead for good. + struct DeadCandidateWorkload; + + impl WorkloadPort for DeadCandidateWorkload { + fn install( + &self, + plan: &CompiledDeploymentPlan, + release: &crate::drivers::MaterializedRelease, + ) -> Result { + StillWorkload.install(plan, release) + } + fn prepare_activation( + &self, + plan: &CompiledDeploymentPlan, + expected: &IdunnExpectedIncarnationRecord, + launch: IdunnRuntimeActivationLaunch, + ) -> Result { + StillWorkload.prepare_activation(plan, expected, launch) + } + fn start_prepared( + &self, + plan: &CompiledDeploymentPlan, + release: &SealedRelease, + installed: &crate::drivers::InstalledReleaseObservation, + expected: &IdunnExpectedIncarnationRecord, + activation: &IdunnRuntimeActivationRecord, + ) -> Result { + StillWorkload.start_prepared(plan, release, installed, expected, activation) + } + fn discard_prepared( + &self, + plan: &CompiledDeploymentPlan, + expected: &IdunnExpectedIncarnationRecord, + activation: &IdunnRuntimeActivationRecord, + ) -> Result<()> { + StillWorkload.discard_prepared(plan, expected, activation) + } + fn observe( + &self, + _: &IdunnExpectedIncarnationRecord, + _: &IdunnRuntimeActivationRecord, + _: &WorkloadObservation, + ) -> Result { + bail!("the candidate is gone") + } + fn stop(&self, _: &WorkloadObservation) -> Result<()> { + Ok(()) + } + fn is_permanently_stopped(&self, _: &WorkloadObservation) -> Result { + Ok(true) + } + } + + #[test] + fn a_permanently_dead_candidate_past_the_fence_begins_its_post_fence_abort() -> Result<()> { + let world = EngineFixture::with_workload(Arc::new(DeadCandidateWorkload))?; + let dead = transaction_at(&world, DeploymentPhase::Fencing)?; + assert!(record_of(&world, &dead.transaction_id)?.post_fencing_abort.is_none()); + for _ in 0..8 { + world.engine.resume_one_transaction()?; + } + assert!( + record_of(&world, &dead.transaction_id)? + .post_fencing_abort + .is_some(), + "a dead candidate past the fence was retried instead of aborted" + ); + Ok(()) + } + + #[test] + fn a_resume_fault_is_reported_once_and_left_in_the_record() -> Result<()> { + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + let live = transaction_at(&world, DeploymentPhase::Warming)?; + let error = anyhow!("store hiccup 1"); + world + .engine + .note_fault("could not resume transaction", &live.transaction_id, &error); + assert_eq!( + record_of(&world, &live.transaction_id)?.last_error.as_deref(), + Some("store hiccup 1") + ); + let reports = world.engine.fault_reports.lock().unwrap(); + assert_eq!(reports.len(), 1); + assert!(reports[&live.transaction_id].offer(Some("store hiccup 1".into())).is_none()); + Ok(()) + } + + #[test] + fn a_new_record_cannot_carry_the_legacy_marker() -> Result<()> { + write_fixture_anchor()?; + let envelope = fixture_envelope(FIXTURE_PRE_B1_ABORTS[1].1, DeploymentTransaction::TYPE)?; + let lifted = read_transaction_record(&envelope)?; + assert!(lifted.carries_legacy_marker()); + let error = error_text(transaction_envelope(&lifted, 1).map(|_| ())); + assert!(error.contains("legacy lift"), "{error}"); + // The migration's own path still writes it, and it reads back. + let migrated = cleanup_evidence::migrated_transaction_envelope(&lifted, 1)?; + assert!(read_transaction_record(&migrated)?.carries_legacy_marker()); + Ok(()) + } + + #[test] + fn unreadable_history_does_not_skip_resident_residue_at_boot() -> Result<()> { + write_fixture_anchor()?; + let envelope = fixture_envelope(FIXTURE_PRE_B1_ABORTS[1].1, DeploymentTransaction::TYPE)?; + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + let first = read_transaction_record(&envelope)?; + make_resident(&world, &first, envelope)?; + assert_eq!(migrate_control_store_to_current_schema(&world.state_store)?, 1); + let expected = first.expected.clone().context("no Expected")?; + project_candidate(&world, &first, true)?; + assert_eq!(projected_under(&world, &expected)?.len(), 2); + corrupt_history(&world)?; + let outcome = world.engine.reconcile_failed_continuity_projections()?; + assert_eq!(outcome.demoted.len(), 1); + assert_eq!(projected_under(&world, &expected)?, expected_only()); + Ok(()) + } + #[test] fn a_terminal_transaction_that_cannot_be_archived_does_not_stop_the_scheduler() -> Result<()> { let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; @@ -12274,19 +12763,19 @@ mod tests { assert_eq!(owed(&written), Some(CleanupEvidence::Skipped)); let mut lifted = written.clone(); - owe_legacy_continuity_projection(&mut lifted); + cleanup_evidence::owe_legacy_continuity_projection(&mut lifted); assert_eq!(owed(&lifted), Some(CleanupEvidence::Pending)); // A deployment published its own key and recorded what it owed. let mut deploy = written.clone(); deploy.command_kind = CommandKind::Deploy; - owe_legacy_continuity_projection(&mut deploy); + cleanup_evidence::owe_legacy_continuity_projection(&mut deploy); assert_eq!(owed(&deploy), Some(CleanupEvidence::Skipped)); // A continuity that issued nothing owes nothing. let mut unissued = written; unissued.activation = None; - owe_legacy_continuity_projection(&mut unissued); + cleanup_evidence::owe_legacy_continuity_projection(&mut unissued); assert_eq!(owed(&unissued), Some(CleanupEvidence::Skipped)); Ok(()) } From 5743a25389a0b4de14064c2e47b7bb4cc363236b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 10:28:34 +0200 Subject: [PATCH 11/11] B1 fix batch 4: faults re-arm only on recovery; notes reach marked records - Fault reports clear only when a step ran and succeeded, not on a backoff skip or a handled failure. - Fault notes are written through cleanup_evidence::last_error_envelope, so an unretirable pre-B1 terminal record shows its fault; a failed note is printed with the fault instead of swallowed. - backoff_wait and is_waiting are pure and unit-tested; tick and resume return values are pinned. - migrate_transaction_record is the migration's only entry; the encoder that can write a marker is private to cleanup_evidence. Co-Authored-By: Claude Sonnet 5 --- src/control_plane.rs | 178 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 148 insertions(+), 30 deletions(-) diff --git a/src/control_plane.rs b/src/control_plane.rs index fa51aa8..ac38edf 100644 --- a/src/control_plane.rs +++ b/src/control_plane.rs @@ -754,7 +754,9 @@ use cleanup_evidence::CleanupEvidence; /// Decoding a stored record is the one other way in, and it stays here too. /// `transaction_envelope` refuses a record carrying the marker; the schema /// migration, which persists what the lift produced, writes through -/// `migrated_transaction_envelope`, defined here beside the only constructor. +/// `migrate_transaction_record`, and a fault note on an existing record through +/// `last_error_envelope`; both are defined here beside the only constructor, +/// and the encoder they share is private to this module. mod cleanup_evidence { use super::*; @@ -828,13 +830,26 @@ mod cleanup_evidence { } } - /// The envelope for a record the schema migration persists, the one write - /// path that may carry the marker. - pub(super) fn migrated_transaction_envelope( + /// The schema migration's one entry point: read a stored v2, v3 or v4 + /// transaction (lifting older ones) and return its key and current-shape + /// envelope. The record may carry the marker the lift just set. + pub(super) fn migrate_transaction_record( + envelope: &CultCacheEnvelope, + ) -> Result<(String, CultCacheEnvelope)> { + let value = read_transaction_record(envelope)?; + let next = encode_transaction(&value, value.updated_at_unix_millis)?; + Ok((value.transaction_id, next)) + } + + /// The envelope for an existing record with only its `last_error` set. The + /// record may already carry the marker; this cannot add one. + pub(super) fn last_error_envelope( value: &DeploymentTransaction, - now: u64, + detail: &str, ) -> Result { - encode_transaction(value, now) + let mut next = value.clone(); + next.last_error = Some(detail.to_string()); + encode_transaction(&next, next.updated_at_unix_millis) } /// A continuity abort written before the single resolution rule recorded no @@ -2877,12 +2892,8 @@ fn migrate_control_store_to_current_schema(store_path: &Path) -> Result { let mut migrated = 0; for envelope in stale { let (record_type, key, mut next) = if envelope.r#type == DeploymentTransaction::TYPE { - let value = read_transaction_record(&envelope)?; - let next = cleanup_evidence::migrated_transaction_envelope( - &value, - value.updated_at_unix_millis, - )?; - (DeploymentTransaction::TYPE, value.transaction_id, next) + let (key, next) = cleanup_evidence::migrate_transaction_record(&envelope)?; + (DeploymentTransaction::TYPE, key, next) } else { let value = read_generation_record(&envelope)?; let next = admitted_envelope(&value, value.admitted_at_unix_millis)?; @@ -3069,6 +3080,19 @@ fn read_history_transactions(state_store: &Path) -> Vec { } } +/// How long to wait after `failures` consecutive failures: one poll interval +/// after the first, doubling each time, never past the ceiling. +fn backoff_wait(poll_millis: u64, failures: u32) -> u64 { + poll_millis + .saturating_mul(1u64 << failures.min(20)) + .min(RESUME_BACKOFF_CEILING_MILLIS) +} + +/// Whether an attempt due at `not_before` must still wait at `now`. +fn is_waiting(now: u64, not_before: u64) -> bool { + now < not_before +} + /// Whether a transaction moved between two reads. An error note (`last_error`) /// and its timestamp are commentary on a stuck step, not a step. fn state_advanced(before: &DeploymentTransaction, after: &DeploymentTransaction) -> bool { @@ -4145,10 +4169,13 @@ impl Engine { .or_default() .offer(Some(detail.clone())) }; + let recorded = self.record_last_error(transaction_id, &detail); if offered.is_some() { eprintln!("Idunn {what} {transaction_id}: {detail}"); + if let Err(error) = recorded { + eprintln!("Idunn could not leave that in the record of {transaction_id}: {error:#}"); + } } - let _ = self.record_last_error(transaction_id, &detail); } fn clear_fault(&self, transaction_id: &str) { @@ -4172,9 +4199,7 @@ impl Engine { if stored.value.last_error.as_deref() == Some(detail) { return Ok(()); } - let mut next = stored.value.clone(); - next.last_error = Some(detail.to_string()); - let envelope = transaction_envelope(&next, next.updated_at_unix_millis)?; + let envelope = cleanup_evidence::last_error_envelope(&stored.value, detail)?; ensure!( SingleFileMessagePackBackingStore::new(&self.options.state_store).compare_exchange( &[CultCacheExpectedEnvelope { @@ -4213,10 +4238,7 @@ impl Engine { continue; } match self.resume_candidate(current) { - Ok(moved) => { - self.clear_fault(¤t.value.transaction_id); - progressed |= moved; - } + Ok(moved) => progressed |= moved, Err(error) => { self.note_fault( "could not resume transaction", @@ -4244,17 +4266,20 @@ impl Engine { .expect("resume backoff mutex") .get(id) .is_some_and(|backoff| { - now_millis().is_ok_and(|now| now < backoff.not_before_unix_millis) + now_millis().is_ok_and(|now| is_waiting(now, backoff.not_before_unix_millis)) }) { return Ok(false); } let advanced = self.advance_transaction(current); if advanced.is_ok() { + // The step ran and succeeded: the fault, if any, has recovered, so + // a later failure is news. A skipped or failed attempt clears nothing. self.resume_backoff .lock() .expect("resume backoff mutex") .remove(id); + self.clear_fault(id); } if let Err(error) = advanced { let latest_snapshot = ControlSnapshot::read(&self.options.state_store)?; @@ -4308,11 +4333,7 @@ impl Engine { let now = now_millis()?; let mut all = self.resume_backoff.lock().expect("resume backoff mutex"); let failures = all.get(transaction_id).map_or(0, |backoff| backoff.failures); - let wait = self - .options - .poll_millis - .saturating_mul(1u64 << failures.min(20)) - .min(RESUME_BACKOFF_CEILING_MILLIS); + let wait = backoff_wait(self.options.poll_millis, failures); all.insert( transaction_id.to_string(), ResumeBackoff { @@ -11883,7 +11904,7 @@ mod tests { make_resident( &world, &second, - cleanup_evidence::migrated_transaction_envelope(&second, 200)?, + cleanup_evidence::last_error_envelope(&second, "second")?, )?; // The store reads: three records, one of them live, none of the @@ -12105,7 +12126,7 @@ mod tests { /// A wedged abort whose `stop()` error carries a changing counter, as /// systemctl output with a PID or timestamp would. - struct ChangingErrorWorkload(std::sync::atomic::AtomicU32); + struct ChangingErrorWorkload(std::sync::atomic::AtomicU32, std::sync::atomic::AtomicBool); impl WorkloadPort for ChangingErrorWorkload { fn install( @@ -12151,6 +12172,9 @@ mod tests { } fn stop(&self, _: &WorkloadObservation) -> Result<()> { let n = self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + if self.1.load(std::sync::atomic::Ordering::SeqCst) { + return Ok(()); + } bail!("the unit will not stop (main pid {n})") } fn is_permanently_stopped(&self, _: &WorkloadObservation) -> Result { @@ -12184,6 +12208,7 @@ mod tests { fn a_wedge_whose_error_text_changes_every_tick_does_not_starve_other_targets() -> Result<()> { let world = EngineFixture::with_workload(Arc::new(ChangingErrorWorkload( std::sync::atomic::AtomicU32::new(0), + std::sync::atomic::AtomicBool::new(false), )))?; transaction_at(&world, DeploymentPhase::Warming)?; world @@ -12219,7 +12244,10 @@ mod tests { #[test] fn a_failing_step_is_retried_after_a_backoff_not_every_tick() -> Result<()> { - let workload = Arc::new(ChangingErrorWorkload(std::sync::atomic::AtomicU32::new(0))); + let workload = Arc::new(ChangingErrorWorkload( + std::sync::atomic::AtomicU32::new(0), + std::sync::atomic::AtomicBool::new(false), + )); let world = EngineFixture::with_workload(workload.clone())?; transaction_at(&world, DeploymentPhase::Warming)?; world @@ -12333,7 +12361,7 @@ mod tests { let error = error_text(transaction_envelope(&lifted, 1).map(|_| ())); assert!(error.contains("legacy lift"), "{error}"); // The migration's own path still writes it, and it reads back. - let migrated = cleanup_evidence::migrated_transaction_envelope(&lifted, 1)?; + let (_, migrated) = cleanup_evidence::migrate_transaction_record(&envelope)?; assert!(read_transaction_record(&migrated)?.carries_legacy_marker()); Ok(()) } @@ -12356,6 +12384,96 @@ mod tests { Ok(()) } + #[test] + fn backoff_doubles_caps_and_waits_exactly() { + assert_eq!(backoff_wait(500, 0), 500); + assert_eq!(backoff_wait(500, 1), 1000); + assert_eq!(backoff_wait(500, 2), 2000); + assert_eq!(backoff_wait(500, 3), 4000); + assert_eq!(backoff_wait(500, 30), RESUME_BACKOFF_CEILING_MILLIS); + assert_eq!(backoff_wait(u64::MAX, 5), RESUME_BACKOFF_CEILING_MILLIS); + assert!(is_waiting(9, 10)); + assert!(!is_waiting(10, 10)); + assert!(!is_waiting(11, 10)); + } + + #[test] + fn a_persistent_fault_is_reported_once_and_again_only_after_recovery() -> Result<()> { + let workload = Arc::new(ChangingErrorWorkload( + std::sync::atomic::AtomicU32::new(0), + std::sync::atomic::AtomicBool::new(false), + )); + let world = EngineFixture::with_workload(workload.clone())?; + let wedged = transaction_at(&world, DeploymentPhase::Warming)?; + world + .engine + .begin_pre_fencing_abort(&resident(&world)?, anyhow!("candidate refused"))?; + let id = wedged.transaction_id; + let expire = || { + world.engine.resume_backoff.lock().unwrap().clear(); + }; + let reported = || world.engine.fault_reports.lock().unwrap().contains_key(&id); + // A fault already reported for this transaction (an Err from the + // resume itself); a handled, still-failing step must not re-arm it. + world + .engine + .note_fault("could not resume transaction", &id, &anyhow!("store hiccup")); + assert!(reported()); + world.engine.resume_one_transaction()?; + assert!(reported(), "a failing handled step re-armed the report"); + // Skipped inside the backoff: the fault is still the same fault. + world.engine.resume_one_transaction()?; + assert!(reported(), "a backoff skip re-armed the report"); + // Still failing after the backoff expires: still the same fault. + expire(); + world.engine.resume_one_transaction()?; + assert!(reported()); + // A real recovery clears it. + workload.1.store(true, std::sync::atomic::Ordering::SeqCst); + expire(); + world.engine.resume_one_transaction()?; + assert!(!reported(), "a step that ran and succeeded left the fault armed"); + Ok(()) + } + + #[test] + fn an_unretirable_legacy_marked_record_shows_its_fault_in_the_record() -> Result<()> { + write_fixture_anchor()?; + let envelope = fixture_envelope(FIXTURE_PRE_B1_ABORTS[1].1, DeploymentTransaction::TYPE)?; + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + let first = read_transaction_record(&envelope)?; + make_resident(&world, &first, envelope)?; + assert_eq!(migrate_control_store_to_current_schema(&world.state_store)?, 1); + assert!(record_of(&world, &first.transaction_id)?.carries_legacy_marker()); + corrupt_history(&world)?; + assert!(!world.engine.retire_one_terminal_transaction()?); + let noted = record_of(&world, &first.transaction_id)?; + assert!( + noted.last_error.is_some() && noted.last_error != first.last_error, + "the retire fault never reached the record" + ); + assert!(noted.carries_legacy_marker()); + Ok(()) + } + + #[test] + fn a_tick_that_only_freezes_or_only_advances_reports_progress() -> Result<()> { + // Only a freeze. + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + queue_deploy_for_nowhere(&world)?; + write_service_binding(&world)?; + assert!(world.engine.run_scheduler_tick()?, "a freeze-only tick reported no progress"); + + // Only a phase advance. + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + transaction_at(&world, DeploymentPhase::Fencing)?; + assert!(world.engine.resume_one_transaction()?, "a real advance reported none"); + let world = EngineFixture::with_workload(Arc::new(StillWorkload))?; + transaction_at(&world, DeploymentPhase::Fencing)?; + assert!(world.engine.run_scheduler_tick()?); + Ok(()) + } + #[test] fn a_terminal_transaction_that_cannot_be_archived_does_not_stop_the_scheduler() -> Result<()> { let world = EngineFixture::with_workload(Arc::new(StillWorkload))?;