diff --git a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs index 06473d4..25cf845 100644 --- a/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs +++ b/crates/ghostlight-dungeon/src/bin/ghostlight-strategic-smoke.rs @@ -17,7 +17,7 @@ async fn main() -> anyhow::Result<()> { kernel::{CommandResult, WorldKernel}, model_runtime::ModelRuntimeSelection, persistence::CampaignStore, - scheduler::propose_resolution_wave, + scheduler::{ResolutionWavePipelineFailure, propose_resolution_wave}, turn::SnapshotPermit, }; use std::{path::PathBuf, sync::Arc, time::Instant}; @@ -172,22 +172,48 @@ async fn main() -> anyhow::Result<()> { .await { Ok(output) => break output, - Err(error) if rejected_pulses.len() < max_rejected_pulses_per_wave => { + Err(error) => { let pulse = rejected_pulses.len() + 1; + let rejected_stage_receipt_hashes = error + .downcast_ref::() + .map(|failure| { + store.persist_model_stage_receipts(&failure.stage_receipts)?; + Ok::<_, anyhow::Error>( + failure + .stage_receipts + .iter() + .map(|receipt| receipt.storage_key().to_owned()) + .collect::>(), + ) + }) + .transpose()? + .unwrap_or_default(); std::fs::write( root.join(format!( "wave-{wave_index:02}-rejected-pulse-{pulse:02}.txt" )), error.to_string(), )?; - rejected_pulses.push(serde_json::json!({ + let rejected_pulse = serde_json::json!({ "pulse":pulse, "world_revision":campaign.revision, "resolution_epoch":campaign.resolution_policy.resolution_epoch, "error":error.to_string(), - })); + "rejected_stage_receipt_hashes":rejected_stage_receipt_hashes, + }); + if rejected_pulses.len() < max_rejected_pulses_per_wave { + rejected_pulses.push(rejected_pulse); + } else { + std::fs::write( + root.join(format!("wave-{wave_index:02}-terminal-failure.json")), + serde_json::to_vec_pretty(&serde_json::json!({ + "rejected_pulses":rejected_pulses, + "terminal_failure":rejected_pulse, + }))?, + )?; + return Err(error); + } } - Err(error) => return Err(error), } }; std::fs::write( @@ -227,14 +253,13 @@ async fn main() -> anyhow::Result<()> { "strategic wave {wave_index} resolved no material offscreen change: direct transitions were empty and every selected activity outcome was no_material_change" ); } - for stage in &output.stages { - store.insert( - "persona_stage_receipt.v1", - "ghostlight.persona_stage_receipt.v1", - stage.receipt.storage_key(), - &stage.receipt, - )?; - } + store.persist_model_stage_receipts( + &output + .stages + .iter() + .map(|stage| stage.receipt.clone()) + .collect::>(), + )?; let committed = kernel .command(WorldCommand::AdvanceStrategicTick { expected_revision: campaign.revision, diff --git a/crates/ghostlight-dungeon/src/persona.rs b/crates/ghostlight-dungeon/src/persona.rs index 2de134a..aaf4972 100644 --- a/crates/ghostlight-dungeon/src/persona.rs +++ b/crates/ghostlight-dungeon/src/persona.rs @@ -177,6 +177,35 @@ pub struct CellTerminalBundle { pub stage_receipts: Vec, } +#[derive(Clone, Debug)] +pub struct CellPipelineFailure { + pub diagnostic: String, + pub stage_receipts: Vec, +} + +impl std::fmt::Display for CellPipelineFailure { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.diagnostic) + } +} + +impl std::error::Error for CellPipelineFailure {} + +fn cell_pipeline_failure( + error: anyhow::Error, + mut prior_stage_receipts: Vec, +) -> anyhow::Error { + if let Some(failure) = error.downcast_ref::() { + prior_stage_receipts.extend(failure.stage_receipts.clone()); + } else if let Some(omission) = error.downcast_ref::() { + prior_stage_receipts.extend(omission.stage_receipts.clone()); + } + anyhow::Error::new(CellPipelineFailure { + diagnostic: format!("{error:#}").chars().take(4_000).collect(), + stage_receipts: prior_stage_receipts, + }) +} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] #[serde(deny_unknown_fields)] struct CellAppraisalProposal { @@ -338,6 +367,30 @@ struct CellActionVerificationRun { verdict: CellActionEffectVerdict, } +#[derive(Debug)] +struct CellEffectVerifierWaveFailure { + diagnostics: Vec, + completed_stage_receipts: Vec, +} + +impl std::fmt::Display for CellEffectVerifierWaveFailure { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + formatter, + "cell effect verifier wave failed: {}", + self.diagnostics.join("; ") + ) + } +} + +impl std::error::Error for CellEffectVerifierWaveFailure {} + +#[derive(Debug)] +struct CellEffectVerifierTaskFailure { + diagnostic: String, + completed_stage_receipt: Option, +} + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)] #[serde(rename_all = "snake_case")] enum CellEffectMatchResult { @@ -1190,12 +1243,20 @@ impl CellProjectionEngine { Ok(bundle) => Ok(bundle), Err(error) => { let Some(omission) = error.downcast_ref::() else { - return Err(error); + return Err(cell_pipeline_failure(error, Vec::new())); }; let mut prior_receipts = omission.stage_receipts.clone(); - let mut bundle = self.execute_once(slice, true).await.context( - "cell Persona supplied no explicit decision after one same-snapshot retry", - )?; + let mut bundle = match self.execute_once(slice, true).await { + Ok(bundle) => bundle, + Err(error) => { + return Err(cell_pipeline_failure( + error.context( + "cell Persona supplied no explicit decision after one same-snapshot retry", + ), + prior_receipts, + )); + } + }; prior_receipts.append(&mut bundle.stage_receipts); bundle.stage_receipts = prior_receipts; Ok(bundle) @@ -1263,9 +1324,13 @@ impl CellProjectionEngine { }; let mut projector_receipts = Vec::new(); let (projected_narrative, active_subject_ids, projector_receipt) = loop { - let mut projected = run_validated_stage(self.model.as_ref(), &projection_request) + let mut projected = match run_validated_stage(self.model.as_ref(), &projection_request) .await - .context("cell projector model stage failed")?; + .context("cell projector model stage failed") + { + Ok(projected) => projected, + Err(error) => return Err(cell_pipeline_failure(error, projector_receipts)), + }; let proposal = projected .structured .clone() @@ -1287,8 +1352,15 @@ impl CellProjectionEngine { )); } Err(error) => { - return Err(anyhow!( - "cell Projector failed perspective binding after one correction: {error}" + projected.receipt.validation_result = "semantic_invalid".into(); + projected.receipt.local_validation_error = + Some(error.to_string().chars().take(1_000).collect()); + projector_receipts.push(projected.receipt); + return Err(cell_pipeline_failure( + anyhow!( + "cell Projector failed perspective binding after one correction: {error}" + ), + projector_receipts, )); } } @@ -1304,7 +1376,8 @@ impl CellProjectionEngine { }; self.permit .require(&slice.cell_id, &slice.snapshot_binding, "cell_persona") - .await?; + .await + .map_err(|error| cell_pipeline_failure(error, projector_receipts.clone()))?; let persona_domain_guidance = if require_explicit_decision { format!( "{} Your previous response supplied no explicit strategic decision. Respond naturally again from this same lived moment, but make every voiced constituent end with either one concrete present-tense attempt or an explicit choice to hold or wait. Do not invent new perceptions, permissions, contacts, resources, or completed consequences.", @@ -1313,7 +1386,7 @@ impl CellProjectionEngine { } else { cell_persona_mode_guidance(&slice.mode).to_owned() }; - let persona = run_validated_stage( + let persona = match run_validated_stage( self.model.as_ref(), &ModelStageRequest { stage: "cell_persona".into(), @@ -1332,14 +1405,24 @@ impl CellProjectionEngine { }, ) .await - .context("cell Persona model stage failed")?; + .context("cell Persona model stage failed") + { + Ok(persona) => persona, + Err(error) => return Err(cell_pipeline_failure(error, projector_receipts)), + }; + let mut stage_receipts = projector_receipts; + stage_receipts.push(persona.receipt.clone()); self.permit .require(&slice.cell_id, &slice.snapshot_binding, "cell_interpreter") - .await?; - let mut schema = serde_json::to_value(schema_for!(CellAppraisalProposal))?; - constrain_cell_proposal_schema(&mut schema, &slice, &active_subject_ids)?; + .await + .map_err(|error| cell_pipeline_failure(error, stage_receipts.clone()))?; + let mut schema = serde_json::to_value(schema_for!(CellAppraisalProposal)) + .map_err(|error| cell_pipeline_failure(error.into(), stage_receipts.clone()))?; + constrain_cell_proposal_schema(&mut schema, &slice, &active_subject_ids) + .map_err(|error| cell_pipeline_failure(error, stage_receipts.clone()))?; let interpreter_context = - serde_json::to_string(&cell_interpreter_context(&slice, &active_subject_ids))?; + serde_json::to_string(&cell_interpreter_context(&slice, &active_subject_ids)) + .map_err(|error| cell_pipeline_failure(error.into(), stage_receipts.clone()))?; let permission_guidance = format!( concat!( "Emit at most {} exact constituent- or named-member-attributed attempts. Priority is an urgency score from 0 to 100 where higher numbers resolve first. ", @@ -1379,12 +1462,16 @@ impl CellProjectionEngine { temperature: Some(0.0), max_output_tokens: Some(1_600), }; - let mut stage_receipts = projector_receipts; - stage_receipts.push(persona.receipt); for attempt in 0..3 { - let mut interpreted = run_validated_stage(self.model.as_ref(), &request) + let mut interpreted = match run_validated_stage(self.model.as_ref(), &request) .await - .context("cell interpreter model stage failed")?; + .context("cell interpreter model stage failed") + { + Ok(interpreted) => interpreted, + Err(error) => { + return Err(cell_pipeline_failure(error, stage_receipts)); + } + }; let proposal = interpreted .structured .clone() @@ -1411,7 +1498,10 @@ impl CellProjectionEngine { &slice.snapshot_binding, "cell_effect_verifier", ) - .await?; + .await + .map_err(|error| { + cell_pipeline_failure(error, stage_receipts.clone()) + })?; let mut verifications = run_cell_effect_verifier_wave( self.model.clone(), &self.interpreter_model, @@ -1421,7 +1511,16 @@ impl CellProjectionEngine { &campaign_policy, &appraisal.actions, ) - .await?; + .await + .map_err(|error| { + let mut completed = stage_receipts.clone(); + if let Some(failure) = + error.downcast_ref::() + { + completed.extend(failure.completed_stage_receipts.clone()); + } + cell_pipeline_failure(error, completed) + })?; let rejected_action_indices = verifications .iter() .filter_map(|verification| { @@ -1504,14 +1603,18 @@ impl CellProjectionEngine { &appraisal.actions, &rejected_action_indices, ); - return Err(anyhow!( - "cell effect verifier rejected the appraisal after two corrections: {error}; rejected_actions={rejected_actions}" + return Err(cell_pipeline_failure( + anyhow!( + "cell effect verifier rejected the appraisal after two corrections: {error}; rejected_actions={rejected_actions}" + ), + stage_receipts, )); } } self.permit .require(&slice.cell_id, &slice.snapshot_binding, "cell_terminal") - .await?; + .await + .map_err(|error| cell_pipeline_failure(error, stage_receipts.clone()))?; return Ok(CellTerminalBundle { lived_stream: lived, persona_output: persona.narrative, @@ -1547,8 +1650,15 @@ impl CellProjectionEngine { append_cell_correction(&mut request, &error, &rejected_appraisal); } Err(error) => { - return Err(anyhow!( - "cell interpreter failed semantic validation after two corrections: {error}" + interpreted.receipt.validation_result = "semantic_invalid".into(); + interpreted.receipt.local_validation_error = + Some(error.to_string().chars().take(1_000).collect()); + stage_receipts.push(interpreted.receipt); + return Err(cell_pipeline_failure( + anyhow!( + "cell interpreter failed semantic validation after two corrections: {error}" + ), + stage_receipts, )); } } @@ -1614,24 +1724,45 @@ async fn run_cell_effect_verifier_wave( }; let model = model.clone(); jobs.spawn(async move { - let output = run_validated_stage(model.as_ref(), &request) - .await - .map_err(|error| { - anyhow!("cell effect verifier action {action_index} failed: {error}") + let output = match run_validated_stage(model.as_ref(), &request).await { + Ok(output) => output, + Err(error) => { + return Err(CellEffectVerifierTaskFailure { + diagnostic: format!( + "cell effect verifier action {action_index} failed: {error}" + ), + completed_stage_receipt: None, + }); + } + }; + let verification = output + .structured + .clone() + .ok_or_else(|| anyhow!("cell effect verifier produced no typed verdict")) + .and_then(|value| serde_json::from_value::(value).map_err(Into::into)) + .and_then(|verification| { + validate_effect_verification(&verification, 1)?; + Ok(verification) + }) + .map_err(|error: anyhow::Error| { + let diagnostic = format!( + "cell effect verifier action {action_index} failed local validation: {error}" + ); + let mut receipt = output.receipt.clone(); + receipt.validation_result = "semantic_invalid".into(); + receipt.local_validation_error = + Some(diagnostic.chars().take(1_000).collect()); + CellEffectVerifierTaskFailure { + diagnostic, + completed_stage_receipt: Some(receipt), + } })?; - let verification: CellEffectVerification = serde_json::from_value( - output - .structured - .clone() - .ok_or_else(|| anyhow!("cell effect verifier produced no typed verdict"))?, - )?; - validate_effect_verification(&verification, 1)?; let verdict = verification .verdicts .into_iter() .next() .expect("one-action verifier schema and validator require one verdict"); - Ok::<_, anyhow::Error>(CellActionVerificationRun { + Ok::<_, CellEffectVerifierTaskFailure>(CellActionVerificationRun { action_index, output, verdict, @@ -1640,9 +1771,27 @@ async fn run_cell_effect_verifier_wave( } let mut verified = Vec::with_capacity(actions.len()); + let mut diagnostics = Vec::new(); + let mut failed_stage_receipts = Vec::new(); while let Some(result) = jobs.join_next().await { - verified - .push(result.map_err(|error| anyhow!("cell effect verifier task failed: {error}"))??); + match result { + Ok(Ok(verification)) => verified.push(verification), + Ok(Err(failure)) => { + diagnostics.push(failure.diagnostic); + failed_stage_receipts.extend(failure.completed_stage_receipt); + } + Err(error) => diagnostics.push(format!("cell effect verifier task failed: {error}")), + } + } + if !diagnostics.is_empty() { + return Err(anyhow::Error::new(CellEffectVerifierWaveFailure { + diagnostics, + completed_stage_receipts: verified + .into_iter() + .map(|verification| verification.output.receipt) + .chain(failed_stage_receipts) + .collect(), + })); } verified.sort_by_key(|verification| verification.action_index); Ok(verified) diff --git a/crates/ghostlight-dungeon/src/scheduler.rs b/crates/ghostlight-dungeon/src/scheduler.rs index 3ab1927..de77f36 100644 --- a/crates/ghostlight-dungeon/src/scheduler.rs +++ b/crates/ghostlight-dungeon/src/scheduler.rs @@ -3,12 +3,15 @@ use crate::{ AgencyAxis, AgencySubjectKind, Campaign, GestaltIndividuation, GestaltMemberDelta, ResolutionDemand, ResolutionWaveCommit, SimulationCell, StrategicGestaltIndividuation, }, - model::{MODEL_FAST, ModelPort, ModelStageOutput, ModelStageRequest, run_validated_stage}, + model::{ + MODEL_FAST, ModelPort, ModelStageOutput, ModelStageReceipt, ModelStageRequest, + run_validated_stage, + }, outcome::{activity_outcome_binding, resolve_activity_outcomes}, persona::{ CellActivityTargetSlice, CellConstituentSlice, CellMemberSlice, - CellMigrationDestinationSlice, CellPerceivedEventSlice, CellProjectionEngine, - ExecutionPermit, PermittedCellSlice, + CellMigrationDestinationSlice, CellPerceivedEventSlice, CellPipelineFailure, + CellProjectionEngine, ExecutionPermit, PermittedCellSlice, }, resolution::{ cell_action_digest, cell_action_limit, default_demand, plan_cover, plan_receipt, @@ -91,10 +94,41 @@ pub struct StrategicResolutionOutput { #[derive(Clone, Debug, Serialize)] pub struct PrivateCellTrace { pub cell_id: String, + pub pipeline_attempts: usize, + pub rejected_pipeline_errors: Vec, + pub rejected_pipeline_receipt_hashes: Vec, + pub terminal_pipeline_receipt_hashes: Vec, pub lived_stream: String, pub persona_output: String, } +#[derive(Clone, Debug)] +pub struct ResolutionWavePipelineFailure { + pub cell_errors: Vec, + pub stage_receipts: Vec, +} + +impl std::fmt::Display for ResolutionWavePipelineFailure { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + formatter, + "resolution wave rejected after {} cell pipeline failure(s): {}", + self.cell_errors.len(), + self.cell_errors.join("; ") + ) + } +} + +impl std::error::Error for ResolutionWavePipelineFailure {} + +#[derive(Debug)] +struct CellPipelineExhaustion { + diagnostic: String, + stage_receipts: Vec, +} + +const MAX_CELL_PIPELINE_ATTEMPTS: usize = 3; + pub async fn propose_resolution_wave( model: Arc, permit: Arc, @@ -141,40 +175,128 @@ pub async fn propose_resolution_wave_with_policy( jobs.spawn(async move { let cell_id = cell.id; let subject_ids = cell.subject_ids; - let _permit = semaphore - .acquire_owned() - .await - .map_err(|_| anyhow!("provider concurrency gate closed"))?; - let terminal = engine.execute(slice).await.with_context(|| { - format!( - "simulation cell {cell_id} subjects {} pipeline failed", - serde_json::to_string(&subject_ids).unwrap_or_else(|_| "[unavailable]".into()) - ) - })?; - Ok::<_, anyhow::Error>((cell_id, terminal)) + let mut rejected_pipeline_errors = Vec::new(); + let mut rejected_pipeline_receipts = Vec::new(); + let terminal = loop { + let Ok(_provider_slot) = semaphore.clone().acquire_owned().await else { + return Err(CellPipelineExhaustion { + diagnostic: "provider concurrency gate closed".into(), + stage_receipts: rejected_pipeline_receipts, + }); + }; + match engine.execute(slice.clone()).await { + Ok(terminal) => break terminal, + Err(error) + if rejected_pipeline_errors.len() + 1 < MAX_CELL_PIPELINE_ATTEMPTS => + { + if let Some(failure) = error.downcast_ref::() { + rejected_pipeline_receipts.extend(failure.stage_receipts.clone()); + } + rejected_pipeline_errors + .push(format!("{error:#}").chars().take(1_000).collect()); + } + Err(error) => { + if let Some(failure) = error.downcast_ref::() { + rejected_pipeline_receipts.extend(failure.stage_receipts.clone()); + } + rejected_pipeline_errors + .push(format!("{error:#}").chars().take(1_000).collect()); + let terminal_error = rejected_pipeline_errors + .last() + .cloned() + .unwrap_or_else(|| "unknown cell pipeline failure".into()); + return Err(CellPipelineExhaustion { + diagnostic: format!( + "simulation cell {cell_id} subjects {} pipeline failed after {} attempts: {terminal_error}", + serde_json::to_string(&subject_ids) + .unwrap_or_else(|_| "[unavailable]".into()), + MAX_CELL_PIPELINE_ATTEMPTS + ), + stage_receipts: rejected_pipeline_receipts, + }); + } + } + }; + Ok::<_, CellPipelineExhaustion>(( + cell_id, + terminal, + rejected_pipeline_errors, + rejected_pipeline_receipts, + )) }); } let mut terminals = Vec::new(); + let mut cell_failures = Vec::new(); while let Some(result) = jobs.join_next().await { - terminals.push(result.map_err(|error| anyhow!("cell Persona task failed: {error}"))??); + match result { + Ok(Ok(terminal)) => terminals.push(terminal), + Ok(Err(failure)) => cell_failures.push(failure), + Err(error) => cell_failures.push(CellPipelineExhaustion { + diagnostic: format!("cell Persona task failed: {error}"), + stage_receipts: Vec::new(), + }), + } + } + if !cell_failures.is_empty() { + let mut stage_receipts = stages + .iter() + .map(|stage| stage.receipt.clone()) + .chain( + terminals + .iter() + .flat_map(|(_, terminal, _, rejected_receipts)| { + rejected_receipts + .iter() + .chain(terminal.stage_receipts.iter()) + .cloned() + }), + ) + .collect::>(); + stage_receipts.extend( + cell_failures + .iter() + .flat_map(|failure| failure.stage_receipts.iter().cloned()), + ); + return Err(anyhow::Error::new(ResolutionWavePipelineFailure { + cell_errors: cell_failures + .into_iter() + .map(|failure| failure.diagnostic) + .collect(), + stage_receipts, + })); } terminals.sort_by(|left, right| left.0.cmp(&right.0)); let appraisals = terminals .iter() - .map(|(_, terminal)| terminal.appraisal.clone()) + .map(|(_, terminal, _, _)| terminal.appraisal.clone()) .collect(); let private_cell_traces = terminals .iter() - .map(|(cell_id, terminal)| PrivateCellTrace { - cell_id: cell_id.clone(), - lived_stream: terminal.lived_stream.text.clone(), - persona_output: terminal.persona_output.clone(), - }) + .map( + |(cell_id, terminal, rejected_pipeline_errors, rejected_pipeline_receipts)| { + PrivateCellTrace { + cell_id: cell_id.clone(), + pipeline_attempts: rejected_pipeline_errors.len() + 1, + rejected_pipeline_errors: rejected_pipeline_errors.clone(), + rejected_pipeline_receipt_hashes: rejected_pipeline_receipts + .iter() + .map(|receipt| receipt.storage_key().to_owned()) + .collect(), + terminal_pipeline_receipt_hashes: terminal + .stage_receipts + .iter() + .map(|receipt| receipt.storage_key().to_owned()) + .collect(), + lived_stream: terminal.lived_stream.text.clone(), + persona_output: terminal.persona_output.clone(), + } + }, + ) .collect(); - for (_, terminal) in terminals { + let mut committed_stages = stages.clone(); + for (_, terminal, _, rejected_pipeline_receipts) in terminals { stages.extend( - terminal - .stage_receipts + rejected_pipeline_receipts .into_iter() .map(|receipt| ModelStageOutput { narrative: String::new(), @@ -182,8 +304,19 @@ pub async fn propose_resolution_wave_with_policy( receipt, }), ); + let terminal_stages = terminal + .stage_receipts + .into_iter() + .map(|receipt| ModelStageOutput { + narrative: String::new(), + structured: None, + receipt, + }) + .collect::>(); + committed_stages.extend(terminal_stages.clone()); + stages.extend(terminal_stages); } - let cell_model_receipt_hashes = distinct_model_receipt_hashes(&stages); + let cell_model_receipt_hashes = distinct_model_receipt_hashes(&committed_stages); let mut wave = ResolutionWaveCommit { schema: "ghostlight.resolution_wave_commit.v1".into(), world_revision: campaign.revision, @@ -231,6 +364,7 @@ pub async fn propose_resolution_wave_with_policy( ) .await?; } + committed_stages.extend(outcome_stages.clone()); stages.extend(outcome_stages); wave.activity_outcomes = activity_outcomes; let individuation_candidate_digests = @@ -267,9 +401,10 @@ pub async fn propose_resolution_wave_with_policy( ) .await?; } + committed_stages.extend(individuation_stages.clone()); stages.extend(individuation_stages); wave.strategic_individuations = strategic_individuations; - wave.model_receipt_hashes = distinct_model_receipt_hashes(&stages); + wave.model_receipt_hashes = distinct_model_receipt_hashes(&committed_stages); validate_and_resolve_wave(campaign, &wave)?; let aggregate_receipt_hash = format!( "sha256:{:x}", @@ -1316,7 +1451,10 @@ mod tests { use crate::model::ModelPort; use crate::persona::AllowAllPermit; use async_trait::async_trait; - use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{ + Mutex, + atomic::{AtomicUsize, Ordering}, + }; struct CellFixtureModel { active: AtomicUsize, @@ -1324,6 +1462,12 @@ mod tests { malformed_cell: bool, } + struct TransientCellFixtureModel { + fixture: CellFixtureModel, + target_binding: Mutex>, + failures_remaining: AtomicUsize, + } + struct PersonFixtureModel; #[test] @@ -1477,6 +1621,39 @@ mod tests { } } + #[async_trait] + impl ModelPort for TransientCellFixtureModel { + async fn run(&self, request: &ModelStageRequest) -> Result { + if request.stage == "cell_persona" { + let target_binding = { + let mut target = self.target_binding.lock().unwrap(); + target + .get_or_insert_with(|| request.snapshot_binding.clone()) + .clone() + }; + if request.snapshot_binding == target_binding + && self + .failures_remaining + .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |remaining| { + if remaining > 0 { + Some(remaining - 1) + } else { + None + } + }) + .is_ok() + { + return Err(anyhow!("transient fixture cell failure")); + } + } + self.fixture.run(request).await + } + + fn provider(&self) -> &'static str { + "fixture" + } + } + #[async_trait] impl ModelPort for PersonFixtureModel { async fn run(&self, request: &ModelStageRequest) -> Result { @@ -2050,6 +2227,78 @@ mod tests { output.wave.model_receipt_hashes ); assert!(model.maximum.load(Ordering::SeqCst) <= 2); + assert!( + output + .private_cell_traces + .iter() + .all(|trace| trace.pipeline_attempts == 1 + && trace.rejected_pipeline_errors.is_empty()) + ); + validate_and_resolve_wave(&campaign, &output.wave).unwrap(); + } + + #[tokio::test] + async fn one_transient_cell_failure_retries_only_that_same_snapshot() { + let mut campaign = crate::resolution::tests::campaign(6, 2); + campaign.resolution_policy.provider_parallelism = 2; + let model = Arc::new(TransientCellFixtureModel { + fixture: CellFixtureModel { + active: AtomicUsize::new(0), + maximum: AtomicUsize::new(0), + malformed_cell: false, + }, + target_binding: Mutex::new(None), + failures_remaining: AtomicUsize::new(2), + }); + + let output = propose_resolution_wave(model.clone(), Arc::new(AllowAllPermit), &campaign) + .await + .unwrap(); + + assert_eq!(output.wave.cover.cells.len(), 2); + let retried = output + .private_cell_traces + .iter() + .filter(|trace| trace.pipeline_attempts == 2) + .collect::>(); + assert_eq!(retried.len(), 1); + assert_eq!(retried[0].rejected_pipeline_errors.len(), 1); + assert_eq!(retried[0].rejected_pipeline_receipt_hashes.len(), 1); + assert!(retried[0].rejected_pipeline_errors[0].contains( + "cell Persona model stage failed: model stage cell_persona provider failed twice against the same snapshot" + )); + assert!(output.stages.iter().any(|stage| { + retried[0] + .rejected_pipeline_receipt_hashes + .contains(&stage.receipt.storage_key().to_owned()) + })); + assert!( + retried[0] + .rejected_pipeline_receipt_hashes + .iter() + .filter(|hash| output.wave.model_receipt_hashes.contains(hash)) + .all(|hash| retried[0].terminal_pipeline_receipt_hashes.contains(hash)) + ); + let dir = tempfile::tempdir().unwrap(); + let store = + crate::persistence::CampaignStore::open(dir.path().join("campaign.cc")).unwrap(); + let receipts = output + .stages + .iter() + .map(|stage| stage.receipt.clone()) + .collect::>(); + store.persist_model_stage_receipts(&receipts).unwrap(); + store.persist_model_stage_receipts(&receipts).unwrap(); + assert_eq!( + store.keys("persona_stage_receipt.v1").unwrap().len(), + receipts + .iter() + .map(ModelStageReceipt::storage_key) + .collect::>() + .len() + ); + assert_eq!(model.failures_remaining.load(Ordering::SeqCst), 0); + assert!(model.fixture.maximum.load(Ordering::SeqCst) <= 2); validate_and_resolve_wave(&campaign, &output.wave).unwrap(); } @@ -2161,10 +2410,35 @@ mod tests { maximum: AtomicUsize::new(0), malformed_cell: true, }); + let error = match propose_resolution_wave(model, Arc::new(AllowAllPermit), &campaign).await + { + Ok(_) => panic!("permanently malformed cells must reject the wave"), + Err(error) => error, + }; + let failure = error + .downcast_ref::() + .expect("exhausted cell retries must preserve wave failure evidence"); + assert!(!failure.cell_errors.is_empty()); assert!( - propose_resolution_wave(model, Arc::new(AllowAllPermit), &campaign) - .await - .is_err() + failure + .cell_errors + .iter() + .all(|error| error.contains("pipeline failed after 3 attempts")) + ); + assert!(failure.stage_receipts.len() >= 7); + assert!( + failure + .stage_receipts + .iter() + .any(|receipt| receipt.stage == "resolution_demand") + ); + assert!( + failure + .stage_receipts + .iter() + .filter(|receipt| receipt.stage == "cell_projector") + .count() + >= 3 ); assert_eq!(campaign, before); }